@mux/mux-player 3.13.1-canary.2 → 3.13.1-canary.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,19 +1,19 @@
1
- "use strict";(()=>{var Q1=Object.defineProperty;var X1=Object.getPrototypeOf;var Z1=Reflect.get;var nE=i=>{throw TypeError(i)};var J1=(i,e,t)=>e in i?Q1(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var Ie=(i,e,t)=>J1(i,typeof e!="symbol"?e+"":e,t),jf=(i,e,t)=>e.has(i)||nE("Cannot "+t);var w=(i,e,t)=>(jf(i,e,"read from private field"),t?t.call(i):e.get(i)),oe=(i,e,t)=>e.has(i)?nE("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),ee=(i,e,t,s)=>(jf(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),Ne=(i,e,t)=>(jf(i,e,"access private method"),t);var wd=(i,e,t)=>Z1(X1(i),t,e);var Vn=class{addEventListener(){}removeEventListener(){}dispatchEvent(e){return!0}};if(typeof DocumentFragment=="undefined"){class i extends Vn{}globalThis.DocumentFragment=i}var So=class extends Vn{},zf=class extends Vn{},eI={get(i){},define(i,e,t){},getName(i){return null},upgrade(i){},whenDefined(i){return Promise.resolve(So)}},Io,Qf=class{constructor(e,t={}){oe(this,Io);ee(this,Io,t==null?void 0:t.detail)}get detail(){return w(this,Io)}initCustomEvent(){}};Io=new WeakMap;function tI(i,e){return new So}var aE={document:{createElement:tI},DocumentFragment,customElements:eI,CustomEvent:Qf,EventTarget:Vn,HTMLElement:So,HTMLVideoElement:zf},oE=typeof window=="undefined"||typeof globalThis.customElements=="undefined",Md=oE?aE:globalThis,pN=oE?aE.document:globalThis.document;var iI=Object.create,gE=Object.defineProperty,sI=Object.getOwnPropertyDescriptor,rI=Object.getOwnPropertyNames,nI=Object.getPrototypeOf,aI=Object.prototype.hasOwnProperty,vE=function(i,e){return function(){return i&&(e=i(i=0)),e}},Yt=function(i,e){return function(){return e||i((e={exports:{}}).exports,e),e.exports}},oI=function(i,e,t,s){if(e&&typeof e=="object"||typeof e=="function")for(var r=rI(e),n=0,a=r.length,o;n<a;n++)o=r[n],!aI.call(i,o)&&o!==t&&gE(i,o,{get:function(l){return e[l]}.bind(null,o),enumerable:!(s=sI(e,o))||s.enumerable});return i},mi=function(i,e,t){return t=i!=null?iI(nI(i)):{},oI(e||!i||!i.__esModule?gE(t,"default",{value:i,enumerable:!0}):t,i)},ji=Yt(function(i,e){var t;typeof window!="undefined"?t=window:typeof global!="undefined"?t=global:typeof self!="undefined"?t=self:t={},e.exports=t});function Yr(i,e){return e!=null&&typeof Symbol!="undefined"&&e[Symbol.hasInstance]?!!e[Symbol.hasInstance](i):Yr(i,e)}var jr=vE(function(){jr()});function EE(i){"@swc/helpers - typeof";return i&&typeof Symbol!="undefined"&&i.constructor===Symbol?"symbol":typeof i}var yE=vE(function(){}),TE=Yt(function(i,e){var t=Array.prototype.slice;e.exports=s;function s(r,n){for(("length"in r)||(r=[r]),r=t.call(r);r.length;){var a=r.shift(),o=n(a);if(o)return o;a.childNodes&&a.childNodes.length&&(r=t.call(a.childNodes).concat(r))}}}),lI=Yt(function(i,e){jr(),e.exports=t;function t(s,r){if(!Yr(this,t))return new t(s,r);this.data=s,this.nodeValue=s,this.length=s.length,this.ownerDocument=r||null}t.prototype.nodeType=8,t.prototype.nodeName="#comment",t.prototype.toString=function(){return"[object Comment]"}}),dI=Yt(function(i,e){jr(),e.exports=t;function t(s,r){if(!Yr(this,t))return new t(s);this.data=s||"",this.length=this.data.length,this.ownerDocument=r||null}t.prototype.type="DOMTextNode",t.prototype.nodeType=3,t.prototype.nodeName="#text",t.prototype.toString=function(){return this.data},t.prototype.replaceData=function(s,r,n){var a=this.data,o=a.substring(0,s),l=a.substring(s+r,a.length);this.data=o+n+l,this.length=this.data.length}}),bE=Yt(function(i,e){e.exports=t;function t(s){var r=this,n=s.type;s.target||(s.target=r),r.listeners||(r.listeners={});var a=r.listeners[n];if(a)return a.forEach(function(o){s.currentTarget=r,typeof o=="function"?o(s):o.handleEvent(s)});r.parentNode&&r.parentNode.dispatchEvent(s)}}),_E=Yt(function(i,e){e.exports=t;function t(s,r){var n=this;n.listeners||(n.listeners={}),n.listeners[s]||(n.listeners[s]=[]),n.listeners[s].indexOf(r)===-1&&n.listeners[s].push(r)}}),AE=Yt(function(i,e){e.exports=t;function t(s,r){var n=this;if(n.listeners&&n.listeners[s]){var a=n.listeners[s],o=a.indexOf(r);o!==-1&&a.splice(o,1)}}}),uI=Yt(function(i,e){yE(),e.exports=s;var t=["area","base","br","col","embed","hr","img","input","keygen","link","menuitem","meta","param","source","track","wbr"];function s(h){switch(h.nodeType){case 3:return u(h.data);case 8:return"<!--"+h.data+"-->";default:return r(h)}}function r(h){var f=[],m=h.tagName;return h.namespaceURI==="http://www.w3.org/1999/xhtml"&&(m=m.toLowerCase()),f.push("<"+m+d(h)+o(h)),t.indexOf(m)>-1?f.push(" />"):(f.push(">"),h.childNodes.length?f.push.apply(f,h.childNodes.map(s)):h.textContent||h.innerText?f.push(u(h.textContent||h.innerText)):h.innerHTML&&f.push(h.innerHTML),f.push("</"+m+">")),f.join("")}function n(h,f){var m=EE(h[f]);return f==="style"&&Object.keys(h.style).length>0?!0:h.hasOwnProperty(f)&&(m==="string"||m==="boolean"||m==="number")&&f!=="nodeName"&&f!=="className"&&f!=="tagName"&&f!=="textContent"&&f!=="innerText"&&f!=="namespaceURI"&&f!=="innerHTML"}function a(h){if(typeof h=="string")return h;var f="";return Object.keys(h).forEach(function(m){var p=h[m];m=m.replace(/[A-Z]/g,function(g){return"-"+g.toLowerCase()}),f+=m+":"+p+";"}),f}function o(h){var f=h.dataset,m=[];for(var p in f)m.push({name:"data-"+p,value:f[p]});return m.length?l(m):""}function l(h){var f=[];return h.forEach(function(m){var p=m.name,g=m.value;p==="style"&&(g=a(g)),f.push(p+'="'+c(g)+'"')}),f.length?" "+f.join(" "):""}function d(h){var f=[];for(var m in h)n(h,m)&&f.push({name:m,value:h[m]});for(var p in h._attributes)for(var g in h._attributes[p]){var v=h._attributes[p][g],T=(v.prefix?v.prefix+":":"")+g;f.push({name:T,value:v.value})}return h.className&&f.push({name:"class",value:h.className}),f.length?l(f):""}function u(h){var f="";return typeof h=="string"?f=h:h&&(f=h.toString()),f.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function c(h){return u(h).replace(/"/g,"&quot;")}}),SE=Yt(function(i,e){jr();var t=TE(),s=bE(),r=_E(),n=AE(),a=uI(),o="http://www.w3.org/1999/xhtml";e.exports=l;function l(d,u,c){if(!Yr(this,l))return new l(d);var h=c===void 0?o:c||null;this.tagName=h===o?String(d).toUpperCase():d,this.nodeName=this.tagName,this.className="",this.dataset={},this.childNodes=[],this.parentNode=null,this.style={},this.ownerDocument=u||null,this.namespaceURI=h,this._attributes={},this.tagName==="INPUT"&&(this.type="text")}l.prototype.type="DOMElement",l.prototype.nodeType=1,l.prototype.appendChild=function(d){return d.parentNode&&d.parentNode.removeChild(d),this.childNodes.push(d),d.parentNode=this,d},l.prototype.replaceChild=function(d,u){d.parentNode&&d.parentNode.removeChild(d);var c=this.childNodes.indexOf(u);return u.parentNode=null,this.childNodes[c]=d,d.parentNode=this,u},l.prototype.removeChild=function(d){var u=this.childNodes.indexOf(d);return this.childNodes.splice(u,1),d.parentNode=null,d},l.prototype.insertBefore=function(d,u){d.parentNode&&d.parentNode.removeChild(d);var c=u==null?-1:this.childNodes.indexOf(u);return c>-1?this.childNodes.splice(c,0,d):this.childNodes.push(d),d.parentNode=this,d},l.prototype.setAttributeNS=function(d,u,c){var h=null,f=u,m=u.indexOf(":");if(m>-1&&(h=u.substr(0,m),f=u.substr(m+1)),this.tagName==="INPUT"&&u==="type")this.type=c;else{var p=this._attributes[d]||(this._attributes[d]={});p[f]={value:c,prefix:h}}},l.prototype.getAttributeNS=function(d,u){var c=this._attributes[d],h=c&&c[u]&&c[u].value;return this.tagName==="INPUT"&&u==="type"?this.type:typeof h!="string"?null:h},l.prototype.removeAttributeNS=function(d,u){var c=this._attributes[d];c&&delete c[u]},l.prototype.hasAttributeNS=function(d,u){var c=this._attributes[d];return!!c&&u in c},l.prototype.setAttribute=function(d,u){return this.setAttributeNS(null,d,u)},l.prototype.getAttribute=function(d){return this.getAttributeNS(null,d)},l.prototype.removeAttribute=function(d){return this.removeAttributeNS(null,d)},l.prototype.hasAttribute=function(d){return this.hasAttributeNS(null,d)},l.prototype.removeEventListener=n,l.prototype.addEventListener=r,l.prototype.dispatchEvent=s,l.prototype.focus=function(){},l.prototype.toString=function(){return a(this)},l.prototype.getElementsByClassName=function(d){var u=d.split(" "),c=[];return t(this,function(h){if(h.nodeType===1){var f=h.className||"",m=f.split(" ");u.every(function(p){return m.indexOf(p)!==-1})&&c.push(h)}}),c},l.prototype.getElementsByTagName=function(d){d=d.toLowerCase();var u=[];return t(this.childNodes,function(c){c.nodeType===1&&(d==="*"||c.tagName.toLowerCase()===d)&&u.push(c)}),u},l.prototype.contains=function(d){return t(this,function(u){return d===u})||!1}}),cI=Yt(function(i,e){jr();var t=SE();e.exports=s;function s(r){if(!Yr(this,s))return new s;this.childNodes=[],this.parentNode=null,this.ownerDocument=r||null}s.prototype.type="DocumentFragment",s.prototype.nodeType=11,s.prototype.nodeName="#document-fragment",s.prototype.appendChild=t.prototype.appendChild,s.prototype.replaceChild=t.prototype.replaceChild,s.prototype.removeChild=t.prototype.removeChild,s.prototype.toString=function(){return this.childNodes.map(function(r){return String(r)}).join("")}}),hI=Yt(function(i,e){e.exports=t;function t(s){}t.prototype.initEvent=function(s,r,n){this.type=s,this.bubbles=r,this.cancelable=n},t.prototype.preventDefault=function(){}}),fI=Yt(function(i,e){jr();var t=TE(),s=lI(),r=dI(),n=SE(),a=cI(),o=hI(),l=bE(),d=_E(),u=AE();e.exports=c;function c(){if(!Yr(this,c))return new c;this.head=this.createElement("head"),this.body=this.createElement("body"),this.documentElement=this.createElement("html"),this.documentElement.appendChild(this.head),this.documentElement.appendChild(this.body),this.childNodes=[this.documentElement],this.nodeType=9}var h=c.prototype;h.createTextNode=function(f){return new r(f,this)},h.createElementNS=function(f,m){var p=f===null?null:String(f);return new n(m,this,p)},h.createElement=function(f){return new n(f,this)},h.createDocumentFragment=function(){return new a(this)},h.createEvent=function(f){return new o(f)},h.createComment=function(f){return new s(f,this)},h.getElementById=function(f){f=String(f);var m=t(this.childNodes,function(p){if(String(p.id)===f)return p});return m||null},h.getElementsByClassName=n.prototype.getElementsByClassName,h.getElementsByTagName=n.prototype.getElementsByTagName,h.contains=n.prototype.contains,h.removeEventListener=u,h.addEventListener=d,h.dispatchEvent=l}),mI=Yt(function(i,e){var t=fI();e.exports=new t}),IE=Yt(function(i,e){var t=typeof global!="undefined"?global:typeof window!="undefined"?window:{},s=mI(),r;typeof document!="undefined"?r=document:(r=t["__GLOBAL_DOCUMENT_CACHE@4"],r||(r=t["__GLOBAL_DOCUMENT_CACHE@4"]=s)),e.exports=r});function pI(i){if(Array.isArray(i))return i}function gI(i,e){var t=i==null?null:typeof Symbol!="undefined"&&i[Symbol.iterator]||i["@@iterator"];if(t!=null){var s=[],r=!0,n=!1,a,o;try{for(t=t.call(i);!(r=(a=t.next()).done)&&(s.push(a.value),!(e&&s.length===e));r=!0);}catch(l){n=!0,o=l}finally{try{!r&&t.return!=null&&t.return()}finally{if(n)throw o}}return s}}function vI(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
2
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function sm(i,e){(e==null||e>i.length)&&(e=i.length);for(var t=0,s=new Array(e);t<e;t++)s[t]=i[t];return s}function LE(i,e){if(i){if(typeof i=="string")return sm(i,e);var t=Object.prototype.toString.call(i).slice(8,-1);if(t==="Object"&&i.constructor&&(t=i.constructor.name),t==="Map"||t==="Set")return Array.from(t);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return sm(i,e)}}function Is(i,e){return pI(i)||gI(i,e)||LE(i,e)||vI()}var xo=mi(ji()),lE=mi(ji()),EI=mi(ji()),yI={now:function(){var i=EI.default.performance,e=i&&i.timing,t=e&&e.navigationStart,s=typeof t=="number"&&typeof i.now=="function"?t+i.now():Date.now();return Math.round(s)}},It=yI,Do=function(){var i,e,t;if(typeof((i=lE.default.crypto)===null||i===void 0?void 0:i.getRandomValues)=="function"){t=new Uint8Array(32),lE.default.crypto.getRandomValues(t);for(var s=0;s<32;s++)t[s]=t[s]%16}else{t=[];for(var r=0;r<32;r++)t[r]=Math.random()*16|0}var n=0;e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(l){var d=l==="x"?t[n]:t[n]&3|8;return n++,d.toString(16)});var a=It.now(),o=a==null?void 0:a.toString(16).substring(3);return o?e.substring(0,28)+o:e},RE=function(){return("000000"+(Math.random()*Math.pow(36,6)<<0).toString(36)).slice(-6)},Ri=function(i){if(i&&typeof i.nodeName!="undefined")return i.muxId||(i.muxId=RE()),i.muxId;var e;try{e=document.querySelector(i)}catch{}return e&&!e.muxId&&(e.muxId=i),(e==null?void 0:e.muxId)||i},Nd=function(i){var e;i&&typeof i.nodeName!="undefined"?(e=i,i=Ri(e)):e=document.querySelector(i);var t=e&&e.nodeName?e.nodeName.toLowerCase():"";return[e,i,t]};function TI(i){if(Array.isArray(i))return sm(i)}function bI(i){if(typeof Symbol!="undefined"&&i[Symbol.iterator]!=null||i["@@iterator"]!=null)return Array.from(i)}function _I(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
3
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function xi(i){return TI(i)||bI(i)||LE(i)||_I()}var Wr={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},AI=function(i){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:3,t,s,r,n,a,o=i?[console,i]:[console],l=(t=console.trace).bind.apply(t,xi(o)),d=(s=console.info).bind.apply(s,xi(o)),u=(r=console.debug).bind.apply(r,xi(o)),c=(n=console.warn).bind.apply(n,xi(o)),h=(a=console.error).bind.apply(a,xi(o)),f=e;return{trace:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];if(!(f>Wr.TRACE))return l.apply(void 0,xi(p))},debug:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];if(!(f>Wr.DEBUG))return u.apply(void 0,xi(p))},info:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];if(!(f>Wr.INFO))return d.apply(void 0,xi(p))},warn:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];if(!(f>Wr.WARN))return c.apply(void 0,xi(p))},error:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];if(!(f>Wr.ERROR))return h.apply(void 0,xi(p))},get level(){return f},set level(m){m!==this.level&&(f=m!=null?m:e)}}},Ve=AI("[mux]"),Xf=mi(ji());function rm(){var i=Xf.default.doNotTrack||Xf.default.navigator&&Xf.default.navigator.doNotTrack;return i==="1"}function ue(i){if(i===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return i}jr();function ft(i,e){if(!Yr(i,e))throw new TypeError("Cannot call a class as a function")}function dE(i,e){for(var t=0;t<e.length;t++){var s=e[t];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(i,s.key,s)}}function Di(i,e,t){return e&&dE(i.prototype,e),t&&dE(i,t),i}function Y(i,e,t){return e in i?Object.defineProperty(i,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):i[e]=t,i}function qn(i){return qn=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},qn(i)}function SI(i,e){for(;!Object.prototype.hasOwnProperty.call(i,e)&&(i=qn(i),i!==null););return i}function Od(i,e,t){return typeof Reflect!="undefined"&&Reflect.get?Od=Reflect.get:Od=function(s,r,n){var a=SI(s,r);if(a){var o=Object.getOwnPropertyDescriptor(a,r);return o.get?o.get.call(n||s):o.value}},Od(i,e,t||i)}function nm(i,e){return nm=Object.setPrototypeOf||function(t,s){return t.__proto__=s,t},nm(i,e)}function II(i,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");i.prototype=Object.create(e&&e.prototype,{constructor:{value:i,writable:!0,configurable:!0}}),e&&nm(i,e)}function LI(i,e){if(i==null)return{};var t={},s=Object.keys(i),r,n;for(n=0;n<s.length;n++)r=s[n],!(e.indexOf(r)>=0)&&(t[r]=i[r]);return t}function RI(i,e){if(i==null)return{};var t=LI(i,e),s,r;if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(i);for(r=0;r<n.length;r++)s=n[r],!(e.indexOf(s)>=0)&&Object.prototype.propertyIsEnumerable.call(i,s)&&(t[s]=i[s])}return t}function xI(){if(typeof Reflect=="undefined"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}yE();function kI(i,e){return e&&(EE(e)==="object"||typeof e=="function")?e:ue(i)}function DI(i){var e=xI();return function(){var t=qn(i),s;if(e){var r=qn(this).constructor;s=Reflect.construct(t,arguments,r)}else s=t.apply(this,arguments);return kI(this,s)}}var ki=function(i){return Co(i)[0]},Co=function(i){if(typeof i!="string"||i==="")return["localhost"];var e=/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/,t=i.match(e)||[],s=t[4],r;return s&&(r=(s.match(/[^\.]+\.[^\.]+$/)||[])[0]),[s,r]},Zf=mi(ji()),CI={exists:function(){var i=Zf.default.performance,e=i&&i.timing;return e!==void 0},domContentLoadedEventEnd:function(){var i=Zf.default.performance,e=i&&i.timing;return e&&e.domContentLoadedEventEnd},navigationStart:function(){var i=Zf.default.performance,e=i&&i.timing;return e&&e.navigationStart}},Ud=CI;function yt(i,e,t){t=t===void 0?1:t,i[e]=i[e]||0,i[e]+=t}function Fd(i){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{},s=Object.keys(t);typeof Object.getOwnPropertySymbols=="function"&&(s=s.concat(Object.getOwnPropertySymbols(t).filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable}))),s.forEach(function(r){Y(i,r,t[r])})}return i}function wI(i,e){var t=Object.keys(i);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(i);e&&(s=s.filter(function(r){return Object.getOwnPropertyDescriptor(i,r).enumerable})),t.push.apply(t,s)}return t}function om(i,e){return e=e!=null?e:{},Object.getOwnPropertyDescriptors?Object.defineProperties(i,Object.getOwnPropertyDescriptors(e)):wI(Object(e)).forEach(function(t){Object.defineProperty(i,t,Object.getOwnPropertyDescriptor(e,t))}),i}var MI=["x-cdn","content-type"],xE=["x-request-id","cf-ray","x-amz-cf-id","x-akamai-request-id"],PI=MI.concat(xE);function lm(i){i=i||"";var e={},t=i.trim().split(/[\r\n]+/);return t.forEach(function(s){if(s){var r=s.split(": "),n=r.shift();n&&(PI.indexOf(n.toLowerCase())>=0||n.toLowerCase().indexOf("x-litix-")===0)&&(e[n]=r.join(": "))}}),e}function Bd(i){if(i){var e=xE.find(function(t){return i[t]!==void 0});return e?i[e]:void 0}}var OI=function(i){var e={};for(var t in i){var s=i[t],r=s["DATA-ID"].search("io.litix.data.");if(r!==-1){var n=s["DATA-ID"].replace("io.litix.data.","");e[n]=s.VALUE}}return e},kE=OI,Pd=function(i){if(!i)return{};var e=Ud.navigationStart(),t=i.loading,s=t?t.start:i.trequest,r=t?t.first:i.tfirst,n=t?t.end:i.tload;return{bytesLoaded:i.total,requestStart:Math.round(e+s),responseStart:Math.round(e+r),responseEnd:Math.round(e+n)}},Lo=function(i){if(!(!i||typeof i.getAllResponseHeaders!="function"))return lm(i.getAllResponseHeaders())},NI=function(i,e,t){var s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{},r=arguments.length>4?arguments[4]:void 0,n=i.log,a=i.utils.secondsToMs,o=function(v){var T=parseInt(r.version),y;return T===1&&v.programDateTime!==null&&(y=v.programDateTime),T===0&&v.pdt!==null&&(y=v.pdt),y};if(!Ud.exists()){n.warn("performance timing not supported. Not tracking HLS.js.");return}var l=function(v,T){return i.emit(e,v,T)},d=function(v,T){var y=T.levels,b=T.audioTracks,A=T.url,R=T.stats,I=T.networkDetails,x=T.sessionData,D={},S={};y.forEach(function(U,j){D[j]={width:U.width,height:U.height,bitrate:U.bitrate,attrs:U.attrs}}),b.forEach(function(U,j){S[j]={name:U.name,language:U.lang,bitrate:U.bitrate}});var C=Pd(R),P=C.bytesLoaded,N=C.requestStart,$=C.responseStart,H=C.responseEnd;l("requestcompleted",om(Fd({},kE(x)),{request_event_type:v,request_bytes_loaded:P,request_start:N,request_response_start:$,request_response_end:H,request_type:"manifest",request_hostname:ki(A),request_response_headers:Lo(I),request_rendition_lists:{media:D,audio:S,video:{}}}))};t.on(r.Events.MANIFEST_LOADED,d);var u=function(v,T){var y=T.details,b=T.level,A=T.networkDetails,R=T.stats,I=Pd(R),x=I.bytesLoaded,D=I.requestStart,S=I.responseStart,C=I.responseEnd,P=y.fragments[y.fragments.length-1],N=o(P)+a(P.duration);l("requestcompleted",{request_event_type:v,request_bytes_loaded:x,request_start:D,request_response_start:S,request_response_end:C,request_current_level:b,request_type:"manifest",request_hostname:ki(y.url),request_response_headers:Lo(A),video_holdback:y.holdBack&&a(y.holdBack),video_part_holdback:y.partHoldBack&&a(y.partHoldBack),video_part_target_duration:y.partTarget&&a(y.partTarget),video_target_duration:y.targetduration&&a(y.targetduration),video_source_is_live:y.live,player_manifest_newest_program_time:isNaN(N)?void 0:N})};t.on(r.Events.LEVEL_LOADED,u);var c=function(v,T){var y=T.details,b=T.networkDetails,A=T.stats,R=Pd(A),I=R.bytesLoaded,x=R.requestStart,D=R.responseStart,S=R.responseEnd;l("requestcompleted",{request_event_type:v,request_bytes_loaded:I,request_start:x,request_response_start:D,request_response_end:S,request_type:"manifest",request_hostname:ki(y.url),request_response_headers:Lo(b)})};t.on(r.Events.AUDIO_TRACK_LOADED,c);var h=function(v,T){var y=T.stats,b=T.networkDetails,A=T.frag;y=y||A.stats;var R=Pd(y),I=R.bytesLoaded,x=R.requestStart,D=R.responseStart,S=R.responseEnd,C=b?Lo(b):void 0,P={request_event_type:v,request_bytes_loaded:I,request_start:x,request_response_start:D,request_response_end:S,request_hostname:b?ki(b.responseURL):void 0,request_id:C?Bd(C):void 0,request_response_headers:C,request_media_duration:A.duration,request_url:b==null?void 0:b.responseURL};A.type==="main"?(P.request_type="media",P.request_current_level=A.level,P.request_video_width=(t.levels[A.level]||{}).width,P.request_video_height=(t.levels[A.level]||{}).height,P.request_labeled_bitrate=(t.levels[A.level]||{}).bitrate):P.request_type=A.type,l("requestcompleted",P)};t.on(r.Events.FRAG_LOADED,h);var f=function(v,T){var y=T.frag,b=y.start,A=o(y),R={currentFragmentPDT:A,currentFragmentStart:a(b)};l("fragmentchange",R)};t.on(r.Events.FRAG_CHANGED,f);var m=function(v,T){var y=T.type,b=T.details,A=T.response,R=T.fatal,I=T.frag,x=T.networkDetails,D=(I==null?void 0:I.url)||T.url||"",S=x?Lo(x):void 0;if((b===r.ErrorDetails.MANIFEST_LOAD_ERROR||b===r.ErrorDetails.MANIFEST_LOAD_TIMEOUT||b===r.ErrorDetails.FRAG_LOAD_ERROR||b===r.ErrorDetails.FRAG_LOAD_TIMEOUT||b===r.ErrorDetails.LEVEL_LOAD_ERROR||b===r.ErrorDetails.LEVEL_LOAD_TIMEOUT||b===r.ErrorDetails.AUDIO_TRACK_LOAD_ERROR||b===r.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT||b===r.ErrorDetails.SUBTITLE_LOAD_ERROR||b===r.ErrorDetails.SUBTITLE_LOAD_TIMEOUT||b===r.ErrorDetails.KEY_LOAD_ERROR||b===r.ErrorDetails.KEY_LOAD_TIMEOUT)&&l("requestfailed",{request_error:b,request_url:D,request_hostname:ki(D),request_id:S?Bd(S):void 0,request_type:b===r.ErrorDetails.FRAG_LOAD_ERROR||b===r.ErrorDetails.FRAG_LOAD_TIMEOUT?"media":b===r.ErrorDetails.AUDIO_TRACK_LOAD_ERROR||b===r.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT?"audio":b===r.ErrorDetails.SUBTITLE_LOAD_ERROR||b===r.ErrorDetails.SUBTITLE_LOAD_TIMEOUT?"subtitle":b===r.ErrorDetails.KEY_LOAD_ERROR||b===r.ErrorDetails.KEY_LOAD_TIMEOUT?"encryption":"manifest",request_error_code:A==null?void 0:A.code,request_error_text:A==null?void 0:A.text}),R){var C,P="".concat(D?"url: ".concat(D,`
1
+ "use strict";(()=>{var Q1=Object.defineProperty;var X1=Object.getPrototypeOf;var Z1=Reflect.get;var nE=i=>{throw TypeError(i)};var J1=(i,e,t)=>e in i?Q1(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var Ie=(i,e,t)=>J1(i,typeof e!="symbol"?e+"":e,t),jf=(i,e,t)=>e.has(i)||nE("Cannot "+t);var w=(i,e,t)=>(jf(i,e,"read from private field"),t?t.call(i):e.get(i)),oe=(i,e,t)=>e.has(i)?nE("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),ee=(i,e,t,s)=>(jf(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),Ne=(i,e,t)=>(jf(i,e,"access private method"),t);var wd=(i,e,t)=>Z1(X1(i),t,e);var Vn=class{addEventListener(){}removeEventListener(){}dispatchEvent(e){return!0}};if(typeof DocumentFragment=="undefined"){class i extends Vn{}globalThis.DocumentFragment=i}var So=class extends Vn{},zf=class extends Vn{},eI={get(i){},define(i,e,t){},getName(i){return null},upgrade(i){},whenDefined(i){return Promise.resolve(So)}},Io,Qf=class{constructor(e,t={}){oe(this,Io);ee(this,Io,t==null?void 0:t.detail)}get detail(){return w(this,Io)}initCustomEvent(){}};Io=new WeakMap;function tI(i,e){return new So}var aE={document:{createElement:tI},DocumentFragment,customElements:eI,CustomEvent:Qf,EventTarget:Vn,HTMLElement:So,HTMLVideoElement:zf},oE=typeof window=="undefined"||typeof globalThis.customElements=="undefined",Md=oE?aE:globalThis,pN=oE?aE.document:globalThis.document;var iI=Object.create,gE=Object.defineProperty,sI=Object.getOwnPropertyDescriptor,rI=Object.getOwnPropertyNames,nI=Object.getPrototypeOf,aI=Object.prototype.hasOwnProperty,vE=function(i,e){return function(){return i&&(e=i(i=0)),e}},Yt=function(i,e){return function(){return e||i((e={exports:{}}).exports,e),e.exports}},oI=function(i,e,t,s){if(e&&typeof e=="object"||typeof e=="function")for(var r=rI(e),n=0,a=r.length,o;n<a;n++)o=r[n],!aI.call(i,o)&&o!==t&&gE(i,o,{get:function(l){return e[l]}.bind(null,o),enumerable:!(s=sI(e,o))||s.enumerable});return i},mi=function(i,e,t){return t=i!=null?iI(nI(i)):{},oI(e||!i||!i.__esModule?gE(t,"default",{value:i,enumerable:!0}):t,i)},ji=Yt(function(i,e){var t;typeof window!="undefined"?t=window:typeof global!="undefined"?t=global:typeof self!="undefined"?t=self:t={},e.exports=t});function Yr(i,e){return e!=null&&typeof Symbol!="undefined"&&e[Symbol.hasInstance]?!!e[Symbol.hasInstance](i):Yr(i,e)}var jr=vE(function(){jr()});function EE(i){"@swc/helpers - typeof";return i&&typeof Symbol!="undefined"&&i.constructor===Symbol?"symbol":typeof i}var yE=vE(function(){}),bE=Yt(function(i,e){var t=Array.prototype.slice;e.exports=s;function s(r,n){for(("length"in r)||(r=[r]),r=t.call(r);r.length;){var a=r.shift(),o=n(a);if(o)return o;a.childNodes&&a.childNodes.length&&(r=t.call(a.childNodes).concat(r))}}}),lI=Yt(function(i,e){jr(),e.exports=t;function t(s,r){if(!Yr(this,t))return new t(s,r);this.data=s,this.nodeValue=s,this.length=s.length,this.ownerDocument=r||null}t.prototype.nodeType=8,t.prototype.nodeName="#comment",t.prototype.toString=function(){return"[object Comment]"}}),dI=Yt(function(i,e){jr(),e.exports=t;function t(s,r){if(!Yr(this,t))return new t(s);this.data=s||"",this.length=this.data.length,this.ownerDocument=r||null}t.prototype.type="DOMTextNode",t.prototype.nodeType=3,t.prototype.nodeName="#text",t.prototype.toString=function(){return this.data},t.prototype.replaceData=function(s,r,n){var a=this.data,o=a.substring(0,s),l=a.substring(s+r,a.length);this.data=o+n+l,this.length=this.data.length}}),TE=Yt(function(i,e){e.exports=t;function t(s){var r=this,n=s.type;s.target||(s.target=r),r.listeners||(r.listeners={});var a=r.listeners[n];if(a)return a.forEach(function(o){s.currentTarget=r,typeof o=="function"?o(s):o.handleEvent(s)});r.parentNode&&r.parentNode.dispatchEvent(s)}}),_E=Yt(function(i,e){e.exports=t;function t(s,r){var n=this;n.listeners||(n.listeners={}),n.listeners[s]||(n.listeners[s]=[]),n.listeners[s].indexOf(r)===-1&&n.listeners[s].push(r)}}),AE=Yt(function(i,e){e.exports=t;function t(s,r){var n=this;if(n.listeners&&n.listeners[s]){var a=n.listeners[s],o=a.indexOf(r);o!==-1&&a.splice(o,1)}}}),uI=Yt(function(i,e){yE(),e.exports=s;var t=["area","base","br","col","embed","hr","img","input","keygen","link","menuitem","meta","param","source","track","wbr"];function s(h){switch(h.nodeType){case 3:return u(h.data);case 8:return"<!--"+h.data+"-->";default:return r(h)}}function r(h){var f=[],m=h.tagName;return h.namespaceURI==="http://www.w3.org/1999/xhtml"&&(m=m.toLowerCase()),f.push("<"+m+d(h)+o(h)),t.indexOf(m)>-1?f.push(" />"):(f.push(">"),h.childNodes.length?f.push.apply(f,h.childNodes.map(s)):h.textContent||h.innerText?f.push(u(h.textContent||h.innerText)):h.innerHTML&&f.push(h.innerHTML),f.push("</"+m+">")),f.join("")}function n(h,f){var m=EE(h[f]);return f==="style"&&Object.keys(h.style).length>0?!0:h.hasOwnProperty(f)&&(m==="string"||m==="boolean"||m==="number")&&f!=="nodeName"&&f!=="className"&&f!=="tagName"&&f!=="textContent"&&f!=="innerText"&&f!=="namespaceURI"&&f!=="innerHTML"}function a(h){if(typeof h=="string")return h;var f="";return Object.keys(h).forEach(function(m){var p=h[m];m=m.replace(/[A-Z]/g,function(g){return"-"+g.toLowerCase()}),f+=m+":"+p+";"}),f}function o(h){var f=h.dataset,m=[];for(var p in f)m.push({name:"data-"+p,value:f[p]});return m.length?l(m):""}function l(h){var f=[];return h.forEach(function(m){var p=m.name,g=m.value;p==="style"&&(g=a(g)),f.push(p+'="'+c(g)+'"')}),f.length?" "+f.join(" "):""}function d(h){var f=[];for(var m in h)n(h,m)&&f.push({name:m,value:h[m]});for(var p in h._attributes)for(var g in h._attributes[p]){var v=h._attributes[p][g],b=(v.prefix?v.prefix+":":"")+g;f.push({name:b,value:v.value})}return h.className&&f.push({name:"class",value:h.className}),f.length?l(f):""}function u(h){var f="";return typeof h=="string"?f=h:h&&(f=h.toString()),f.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function c(h){return u(h).replace(/"/g,"&quot;")}}),SE=Yt(function(i,e){jr();var t=bE(),s=TE(),r=_E(),n=AE(),a=uI(),o="http://www.w3.org/1999/xhtml";e.exports=l;function l(d,u,c){if(!Yr(this,l))return new l(d);var h=c===void 0?o:c||null;this.tagName=h===o?String(d).toUpperCase():d,this.nodeName=this.tagName,this.className="",this.dataset={},this.childNodes=[],this.parentNode=null,this.style={},this.ownerDocument=u||null,this.namespaceURI=h,this._attributes={},this.tagName==="INPUT"&&(this.type="text")}l.prototype.type="DOMElement",l.prototype.nodeType=1,l.prototype.appendChild=function(d){return d.parentNode&&d.parentNode.removeChild(d),this.childNodes.push(d),d.parentNode=this,d},l.prototype.replaceChild=function(d,u){d.parentNode&&d.parentNode.removeChild(d);var c=this.childNodes.indexOf(u);return u.parentNode=null,this.childNodes[c]=d,d.parentNode=this,u},l.prototype.removeChild=function(d){var u=this.childNodes.indexOf(d);return this.childNodes.splice(u,1),d.parentNode=null,d},l.prototype.insertBefore=function(d,u){d.parentNode&&d.parentNode.removeChild(d);var c=u==null?-1:this.childNodes.indexOf(u);return c>-1?this.childNodes.splice(c,0,d):this.childNodes.push(d),d.parentNode=this,d},l.prototype.setAttributeNS=function(d,u,c){var h=null,f=u,m=u.indexOf(":");if(m>-1&&(h=u.substr(0,m),f=u.substr(m+1)),this.tagName==="INPUT"&&u==="type")this.type=c;else{var p=this._attributes[d]||(this._attributes[d]={});p[f]={value:c,prefix:h}}},l.prototype.getAttributeNS=function(d,u){var c=this._attributes[d],h=c&&c[u]&&c[u].value;return this.tagName==="INPUT"&&u==="type"?this.type:typeof h!="string"?null:h},l.prototype.removeAttributeNS=function(d,u){var c=this._attributes[d];c&&delete c[u]},l.prototype.hasAttributeNS=function(d,u){var c=this._attributes[d];return!!c&&u in c},l.prototype.setAttribute=function(d,u){return this.setAttributeNS(null,d,u)},l.prototype.getAttribute=function(d){return this.getAttributeNS(null,d)},l.prototype.removeAttribute=function(d){return this.removeAttributeNS(null,d)},l.prototype.hasAttribute=function(d){return this.hasAttributeNS(null,d)},l.prototype.removeEventListener=n,l.prototype.addEventListener=r,l.prototype.dispatchEvent=s,l.prototype.focus=function(){},l.prototype.toString=function(){return a(this)},l.prototype.getElementsByClassName=function(d){var u=d.split(" "),c=[];return t(this,function(h){if(h.nodeType===1){var f=h.className||"",m=f.split(" ");u.every(function(p){return m.indexOf(p)!==-1})&&c.push(h)}}),c},l.prototype.getElementsByTagName=function(d){d=d.toLowerCase();var u=[];return t(this.childNodes,function(c){c.nodeType===1&&(d==="*"||c.tagName.toLowerCase()===d)&&u.push(c)}),u},l.prototype.contains=function(d){return t(this,function(u){return d===u})||!1}}),cI=Yt(function(i,e){jr();var t=SE();e.exports=s;function s(r){if(!Yr(this,s))return new s;this.childNodes=[],this.parentNode=null,this.ownerDocument=r||null}s.prototype.type="DocumentFragment",s.prototype.nodeType=11,s.prototype.nodeName="#document-fragment",s.prototype.appendChild=t.prototype.appendChild,s.prototype.replaceChild=t.prototype.replaceChild,s.prototype.removeChild=t.prototype.removeChild,s.prototype.toString=function(){return this.childNodes.map(function(r){return String(r)}).join("")}}),hI=Yt(function(i,e){e.exports=t;function t(s){}t.prototype.initEvent=function(s,r,n){this.type=s,this.bubbles=r,this.cancelable=n},t.prototype.preventDefault=function(){}}),fI=Yt(function(i,e){jr();var t=bE(),s=lI(),r=dI(),n=SE(),a=cI(),o=hI(),l=TE(),d=_E(),u=AE();e.exports=c;function c(){if(!Yr(this,c))return new c;this.head=this.createElement("head"),this.body=this.createElement("body"),this.documentElement=this.createElement("html"),this.documentElement.appendChild(this.head),this.documentElement.appendChild(this.body),this.childNodes=[this.documentElement],this.nodeType=9}var h=c.prototype;h.createTextNode=function(f){return new r(f,this)},h.createElementNS=function(f,m){var p=f===null?null:String(f);return new n(m,this,p)},h.createElement=function(f){return new n(f,this)},h.createDocumentFragment=function(){return new a(this)},h.createEvent=function(f){return new o(f)},h.createComment=function(f){return new s(f,this)},h.getElementById=function(f){f=String(f);var m=t(this.childNodes,function(p){if(String(p.id)===f)return p});return m||null},h.getElementsByClassName=n.prototype.getElementsByClassName,h.getElementsByTagName=n.prototype.getElementsByTagName,h.contains=n.prototype.contains,h.removeEventListener=u,h.addEventListener=d,h.dispatchEvent=l}),mI=Yt(function(i,e){var t=fI();e.exports=new t}),IE=Yt(function(i,e){var t=typeof global!="undefined"?global:typeof window!="undefined"?window:{},s=mI(),r;typeof document!="undefined"?r=document:(r=t["__GLOBAL_DOCUMENT_CACHE@4"],r||(r=t["__GLOBAL_DOCUMENT_CACHE@4"]=s)),e.exports=r});function pI(i){if(Array.isArray(i))return i}function gI(i,e){var t=i==null?null:typeof Symbol!="undefined"&&i[Symbol.iterator]||i["@@iterator"];if(t!=null){var s=[],r=!0,n=!1,a,o;try{for(t=t.call(i);!(r=(a=t.next()).done)&&(s.push(a.value),!(e&&s.length===e));r=!0);}catch(l){n=!0,o=l}finally{try{!r&&t.return!=null&&t.return()}finally{if(n)throw o}}return s}}function vI(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
2
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function sm(i,e){(e==null||e>i.length)&&(e=i.length);for(var t=0,s=new Array(e);t<e;t++)s[t]=i[t];return s}function LE(i,e){if(i){if(typeof i=="string")return sm(i,e);var t=Object.prototype.toString.call(i).slice(8,-1);if(t==="Object"&&i.constructor&&(t=i.constructor.name),t==="Map"||t==="Set")return Array.from(t);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return sm(i,e)}}function Is(i,e){return pI(i)||gI(i,e)||LE(i,e)||vI()}var xo=mi(ji()),lE=mi(ji()),EI=mi(ji()),yI={now:function(){var i=EI.default.performance,e=i&&i.timing,t=e&&e.navigationStart,s=typeof t=="number"&&typeof i.now=="function"?t+i.now():Date.now();return Math.round(s)}},It=yI,Do=function(){var i,e,t;if(typeof((i=lE.default.crypto)===null||i===void 0?void 0:i.getRandomValues)=="function"){t=new Uint8Array(32),lE.default.crypto.getRandomValues(t);for(var s=0;s<32;s++)t[s]=t[s]%16}else{t=[];for(var r=0;r<32;r++)t[r]=Math.random()*16|0}var n=0;e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(l){var d=l==="x"?t[n]:t[n]&3|8;return n++,d.toString(16)});var a=It.now(),o=a==null?void 0:a.toString(16).substring(3);return o?e.substring(0,28)+o:e},RE=function(){return("000000"+(Math.random()*Math.pow(36,6)<<0).toString(36)).slice(-6)},Ri=function(i){if(i&&typeof i.nodeName!="undefined")return i.muxId||(i.muxId=RE()),i.muxId;var e;try{e=document.querySelector(i)}catch{}return e&&!e.muxId&&(e.muxId=i),(e==null?void 0:e.muxId)||i},Nd=function(i){var e;i&&typeof i.nodeName!="undefined"?(e=i,i=Ri(e)):e=document.querySelector(i);var t=e&&e.nodeName?e.nodeName.toLowerCase():"";return[e,i,t]};function bI(i){if(Array.isArray(i))return sm(i)}function TI(i){if(typeof Symbol!="undefined"&&i[Symbol.iterator]!=null||i["@@iterator"]!=null)return Array.from(i)}function _I(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
3
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function xi(i){return bI(i)||TI(i)||LE(i)||_I()}var Wr={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},AI=function(i){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:3,t,s,r,n,a,o=i?[console,i]:[console],l=(t=console.trace).bind.apply(t,xi(o)),d=(s=console.info).bind.apply(s,xi(o)),u=(r=console.debug).bind.apply(r,xi(o)),c=(n=console.warn).bind.apply(n,xi(o)),h=(a=console.error).bind.apply(a,xi(o)),f=e;return{trace:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];if(!(f>Wr.TRACE))return l.apply(void 0,xi(p))},debug:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];if(!(f>Wr.DEBUG))return u.apply(void 0,xi(p))},info:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];if(!(f>Wr.INFO))return d.apply(void 0,xi(p))},warn:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];if(!(f>Wr.WARN))return c.apply(void 0,xi(p))},error:function(){for(var m=arguments.length,p=new Array(m),g=0;g<m;g++)p[g]=arguments[g];if(!(f>Wr.ERROR))return h.apply(void 0,xi(p))},get level(){return f},set level(m){m!==this.level&&(f=m!=null?m:e)}}},Ve=AI("[mux]"),Xf=mi(ji());function rm(){var i=Xf.default.doNotTrack||Xf.default.navigator&&Xf.default.navigator.doNotTrack;return i==="1"}function ue(i){if(i===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return i}jr();function ft(i,e){if(!Yr(i,e))throw new TypeError("Cannot call a class as a function")}function dE(i,e){for(var t=0;t<e.length;t++){var s=e[t];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(i,s.key,s)}}function Di(i,e,t){return e&&dE(i.prototype,e),t&&dE(i,t),i}function Y(i,e,t){return e in i?Object.defineProperty(i,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):i[e]=t,i}function qn(i){return qn=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},qn(i)}function SI(i,e){for(;!Object.prototype.hasOwnProperty.call(i,e)&&(i=qn(i),i!==null););return i}function Od(i,e,t){return typeof Reflect!="undefined"&&Reflect.get?Od=Reflect.get:Od=function(s,r,n){var a=SI(s,r);if(a){var o=Object.getOwnPropertyDescriptor(a,r);return o.get?o.get.call(n||s):o.value}},Od(i,e,t||i)}function nm(i,e){return nm=Object.setPrototypeOf||function(t,s){return t.__proto__=s,t},nm(i,e)}function II(i,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");i.prototype=Object.create(e&&e.prototype,{constructor:{value:i,writable:!0,configurable:!0}}),e&&nm(i,e)}function LI(i,e){if(i==null)return{};var t={},s=Object.keys(i),r,n;for(n=0;n<s.length;n++)r=s[n],!(e.indexOf(r)>=0)&&(t[r]=i[r]);return t}function RI(i,e){if(i==null)return{};var t=LI(i,e),s,r;if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(i);for(r=0;r<n.length;r++)s=n[r],!(e.indexOf(s)>=0)&&Object.prototype.propertyIsEnumerable.call(i,s)&&(t[s]=i[s])}return t}function xI(){if(typeof Reflect=="undefined"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}yE();function kI(i,e){return e&&(EE(e)==="object"||typeof e=="function")?e:ue(i)}function DI(i){var e=xI();return function(){var t=qn(i),s;if(e){var r=qn(this).constructor;s=Reflect.construct(t,arguments,r)}else s=t.apply(this,arguments);return kI(this,s)}}var ki=function(i){return Co(i)[0]},Co=function(i){if(typeof i!="string"||i==="")return["localhost"];var e=/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/,t=i.match(e)||[],s=t[4],r;return s&&(r=(s.match(/[^\.]+\.[^\.]+$/)||[])[0]),[s,r]},Zf=mi(ji()),CI={exists:function(){var i=Zf.default.performance,e=i&&i.timing;return e!==void 0},domContentLoadedEventEnd:function(){var i=Zf.default.performance,e=i&&i.timing;return e&&e.domContentLoadedEventEnd},navigationStart:function(){var i=Zf.default.performance,e=i&&i.timing;return e&&e.navigationStart}},Ud=CI;function yt(i,e,t){t=t===void 0?1:t,i[e]=i[e]||0,i[e]+=t}function Fd(i){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{},s=Object.keys(t);typeof Object.getOwnPropertySymbols=="function"&&(s=s.concat(Object.getOwnPropertySymbols(t).filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable}))),s.forEach(function(r){Y(i,r,t[r])})}return i}function wI(i,e){var t=Object.keys(i);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(i);e&&(s=s.filter(function(r){return Object.getOwnPropertyDescriptor(i,r).enumerable})),t.push.apply(t,s)}return t}function om(i,e){return e=e!=null?e:{},Object.getOwnPropertyDescriptors?Object.defineProperties(i,Object.getOwnPropertyDescriptors(e)):wI(Object(e)).forEach(function(t){Object.defineProperty(i,t,Object.getOwnPropertyDescriptor(e,t))}),i}var MI=["x-cdn","content-type"],xE=["x-request-id","cf-ray","x-amz-cf-id","x-akamai-request-id"],PI=MI.concat(xE);function lm(i){i=i||"";var e={},t=i.trim().split(/[\r\n]+/);return t.forEach(function(s){if(s){var r=s.split(": "),n=r.shift();n&&(PI.indexOf(n.toLowerCase())>=0||n.toLowerCase().indexOf("x-litix-")===0)&&(e[n]=r.join(": "))}}),e}function Bd(i){if(i){var e=xE.find(function(t){return i[t]!==void 0});return e?i[e]:void 0}}var OI=function(i){var e={};for(var t in i){var s=i[t],r=s["DATA-ID"].search("io.litix.data.");if(r!==-1){var n=s["DATA-ID"].replace("io.litix.data.","");e[n]=s.VALUE}}return e},kE=OI,Pd=function(i){if(!i)return{};var e=Ud.navigationStart(),t=i.loading,s=t?t.start:i.trequest,r=t?t.first:i.tfirst,n=t?t.end:i.tload;return{bytesLoaded:i.total,requestStart:Math.round(e+s),responseStart:Math.round(e+r),responseEnd:Math.round(e+n)}},Lo=function(i){if(!(!i||typeof i.getAllResponseHeaders!="function"))return lm(i.getAllResponseHeaders())},NI=function(i,e,t){var s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{},r=arguments.length>4?arguments[4]:void 0,n=i.log,a=i.utils.secondsToMs,o=function(v){var b=parseInt(r.version),y;return b===1&&v.programDateTime!==null&&(y=v.programDateTime),b===0&&v.pdt!==null&&(y=v.pdt),y};if(!Ud.exists()){n.warn("performance timing not supported. Not tracking HLS.js.");return}var l=function(v,b){return i.emit(e,v,b)},d=function(v,b){var y=b.levels,T=b.audioTracks,A=b.url,R=b.stats,I=b.networkDetails,x=b.sessionData,D={},S={};y.forEach(function(U,j){D[j]={width:U.width,height:U.height,bitrate:U.bitrate,attrs:U.attrs}}),T.forEach(function(U,j){S[j]={name:U.name,language:U.lang,bitrate:U.bitrate}});var C=Pd(R),P=C.bytesLoaded,N=C.requestStart,$=C.responseStart,H=C.responseEnd;l("requestcompleted",om(Fd({},kE(x)),{request_event_type:v,request_bytes_loaded:P,request_start:N,request_response_start:$,request_response_end:H,request_type:"manifest",request_hostname:ki(A),request_response_headers:Lo(I),request_rendition_lists:{media:D,audio:S,video:{}}}))};t.on(r.Events.MANIFEST_LOADED,d);var u=function(v,b){var y=b.details,T=b.level,A=b.networkDetails,R=b.stats,I=Pd(R),x=I.bytesLoaded,D=I.requestStart,S=I.responseStart,C=I.responseEnd,P=y.fragments[y.fragments.length-1],N=o(P)+a(P.duration);l("requestcompleted",{request_event_type:v,request_bytes_loaded:x,request_start:D,request_response_start:S,request_response_end:C,request_current_level:T,request_type:"manifest",request_hostname:ki(y.url),request_response_headers:Lo(A),video_holdback:y.holdBack&&a(y.holdBack),video_part_holdback:y.partHoldBack&&a(y.partHoldBack),video_part_target_duration:y.partTarget&&a(y.partTarget),video_target_duration:y.targetduration&&a(y.targetduration),video_source_is_live:y.live,player_manifest_newest_program_time:isNaN(N)?void 0:N})};t.on(r.Events.LEVEL_LOADED,u);var c=function(v,b){var y=b.details,T=b.networkDetails,A=b.stats,R=Pd(A),I=R.bytesLoaded,x=R.requestStart,D=R.responseStart,S=R.responseEnd;l("requestcompleted",{request_event_type:v,request_bytes_loaded:I,request_start:x,request_response_start:D,request_response_end:S,request_type:"manifest",request_hostname:ki(y.url),request_response_headers:Lo(T)})};t.on(r.Events.AUDIO_TRACK_LOADED,c);var h=function(v,b){var y=b.stats,T=b.networkDetails,A=b.frag;y=y||A.stats;var R=Pd(y),I=R.bytesLoaded,x=R.requestStart,D=R.responseStart,S=R.responseEnd,C=T?Lo(T):void 0,P={request_event_type:v,request_bytes_loaded:I,request_start:x,request_response_start:D,request_response_end:S,request_hostname:T?ki(T.responseURL):void 0,request_id:C?Bd(C):void 0,request_response_headers:C,request_media_duration:A.duration,request_url:T==null?void 0:T.responseURL};A.type==="main"?(P.request_type="media",P.request_current_level=A.level,P.request_video_width=(t.levels[A.level]||{}).width,P.request_video_height=(t.levels[A.level]||{}).height,P.request_labeled_bitrate=(t.levels[A.level]||{}).bitrate):P.request_type=A.type,l("requestcompleted",P)};t.on(r.Events.FRAG_LOADED,h);var f=function(v,b){var y=b.frag,T=y.start,A=o(y),R={currentFragmentPDT:A,currentFragmentStart:a(T)};l("fragmentchange",R)};t.on(r.Events.FRAG_CHANGED,f);var m=function(v,b){var y=b.type,T=b.details,A=b.response,R=b.fatal,I=b.frag,x=b.networkDetails,D=(I==null?void 0:I.url)||b.url||"",S=x?Lo(x):void 0;if((T===r.ErrorDetails.MANIFEST_LOAD_ERROR||T===r.ErrorDetails.MANIFEST_LOAD_TIMEOUT||T===r.ErrorDetails.FRAG_LOAD_ERROR||T===r.ErrorDetails.FRAG_LOAD_TIMEOUT||T===r.ErrorDetails.LEVEL_LOAD_ERROR||T===r.ErrorDetails.LEVEL_LOAD_TIMEOUT||T===r.ErrorDetails.AUDIO_TRACK_LOAD_ERROR||T===r.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT||T===r.ErrorDetails.SUBTITLE_LOAD_ERROR||T===r.ErrorDetails.SUBTITLE_LOAD_TIMEOUT||T===r.ErrorDetails.KEY_LOAD_ERROR||T===r.ErrorDetails.KEY_LOAD_TIMEOUT)&&l("requestfailed",{request_error:T,request_url:D,request_hostname:ki(D),request_id:S?Bd(S):void 0,request_type:T===r.ErrorDetails.FRAG_LOAD_ERROR||T===r.ErrorDetails.FRAG_LOAD_TIMEOUT?"media":T===r.ErrorDetails.AUDIO_TRACK_LOAD_ERROR||T===r.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT?"audio":T===r.ErrorDetails.SUBTITLE_LOAD_ERROR||T===r.ErrorDetails.SUBTITLE_LOAD_TIMEOUT?"subtitle":T===r.ErrorDetails.KEY_LOAD_ERROR||T===r.ErrorDetails.KEY_LOAD_TIMEOUT?"encryption":"manifest",request_error_code:A==null?void 0:A.code,request_error_text:A==null?void 0:A.text}),R){var C,P="".concat(D?"url: ".concat(D,`
4
4
  `):"")+"".concat(A&&(A.code||A.text)?"response: ".concat(A.code,", ").concat(A.text,`
5
- `):"")+"".concat(T.reason?"failure reason: ".concat(T.reason,`
6
- `):"")+"".concat(T.level?"level: ".concat(T.level,`
7
- `):"")+"".concat(T.parent?"parent stream controller: ".concat(T.parent,`
8
- `):"")+"".concat(T.buffer?"buffer length: ".concat(T.buffer,`
9
- `):"")+"".concat(T.error?"error: ".concat(T.error,`
10
- `):"")+"".concat(T.event?"event: ".concat(T.event,`
11
- `):"")+"".concat(T.err?"error message: ".concat((C=T.err)===null||C===void 0?void 0:C.message,`
12
- `):"");l("error",{player_error_code:y,player_error_message:b,player_error_context:P})}};t.on(r.Events.ERROR,m);var p=function(v,T){var y=T.frag,b=y&&y._url||"";l("requestcanceled",{request_event_type:v,request_url:b,request_type:"media",request_hostname:ki(b)})};t.on(r.Events.FRAG_LOAD_EMERGENCY_ABORTED,p);var g=function(v,T){var y=T.level,b=t.levels[y];if(b&&b.attrs&&b.attrs.BANDWIDTH){var A=b.attrs.BANDWIDTH,R,I=parseFloat(b.attrs["FRAME-RATE"]);isNaN(I)||(R=I),A?l("renditionchange",{video_source_fps:R,video_source_bitrate:A,video_source_width:b.width,video_source_height:b.height,video_source_rendition_name:b.name,video_source_codec:b==null?void 0:b.videoCodec}):n.warn("missing BANDWIDTH from HLS manifest parsed by HLS.js")}};t.on(r.Events.LEVEL_SWITCHED,g),t._stopMuxMonitor=function(){t.off(r.Events.MANIFEST_LOADED,d),t.off(r.Events.LEVEL_LOADED,u),t.off(r.Events.AUDIO_TRACK_LOADED,c),t.off(r.Events.FRAG_LOADED,h),t.off(r.Events.FRAG_CHANGED,f),t.off(r.Events.ERROR,m),t.off(r.Events.FRAG_LOAD_EMERGENCY_ABORTED,p),t.off(r.Events.LEVEL_SWITCHED,g),t.off(r.Events.DESTROYING,t._stopMuxMonitor),delete t._stopMuxMonitor},t.on(r.Events.DESTROYING,t._stopMuxMonitor)},UI=function(i){i&&typeof i._stopMuxMonitor=="function"&&i._stopMuxMonitor()},uE=function(i,e){if(!i||!i.requestEndDate)return{};var t=ki(i.url),s=i.url,r=i.bytesLoaded,n=new Date(i.requestStartDate).getTime(),a=new Date(i.firstByteDate).getTime(),o=new Date(i.requestEndDate).getTime(),l=isNaN(i.duration)?0:i.duration,d=typeof e.getMetricsFor=="function"?e.getMetricsFor(i.mediaType).HttpList:e.getDashMetrics().getHttpRequests(i.mediaType),u;d.length>0&&(u=lm(d[d.length-1]._responseHeaders||""));var c=u?Bd(u):void 0;return{requestStart:n,requestResponseStart:a,requestResponseEnd:o,requestBytesLoaded:r,requestResponseHeaders:u,requestMediaDuration:l,requestHostname:t,requestUrl:s,requestId:c}},FI=function(i,e){var t=e.getQualityFor(i),s=e.getCurrentTrackFor(i).bitrateList;return s?{currentLevel:t,renditionWidth:s[t].width||null,renditionHeight:s[t].height||null,renditionBitrate:s[t].bandwidth}:{}},BI=function(i){var e;return(e=i.match(/.*codecs\*?="(.*)"/))===null||e===void 0?void 0:e[1]},$I=function(i){try{var e,t,s=(t=i.getVersion)===null||t===void 0||(e=t.call(i))===null||e===void 0?void 0:e.split(".").map(function(r){return parseInt(r)})[0];return s}catch{return!1}},HI=function(i,e,t){var s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{},r=i.log;if(!t||!t.on){r.warn("Invalid dash.js player reference. Monitoring blocked.");return}var n=$I(t),a=function(y,b){return i.emit(e,y,b)},o=function(y){var b=y.type,A=y.data,R=(A||{}).url;a("requestcompleted",{request_event_type:b,request_start:0,request_response_start:0,request_response_end:0,request_bytes_loaded:-1,request_type:"manifest",request_hostname:ki(R),request_url:R})};t.on("manifestLoaded",o);var l={},d=function(y){if(typeof y.getRequests!="function")return null;var b=y.getRequests({state:"executed"});return b.length===0?null:b[b.length-1]},u=function(y){var b=y.type,A=y.fragmentModel,R=y.chunk,I=d(A);c({type:b,request:I,chunk:R})},c=function(y){var b=y.type,A=y.chunk,R=y.request,I=(A||{}).mediaInfo,x=I||{},D=x.type,S=x.bitrateList;S=S||[];var C={};S.forEach(function(V,G){C[G]={},C[G].width=V.width,C[G].height=V.height,C[G].bitrate=V.bandwidth,C[G].attrs={}}),D==="video"?l.video=C:D==="audio"?l.audio=C:l.media=C;var P=uE(R,t),N=P.requestStart,$=P.requestResponseStart,H=P.requestResponseEnd,U=P.requestResponseHeaders,j=P.requestMediaDuration,q=P.requestHostname,Z=P.requestUrl,re=P.requestId;a("requestcompleted",{request_event_type:b,request_start:N,request_response_start:$,request_response_end:H,request_bytes_loaded:-1,request_type:D+"_init",request_response_headers:U,request_hostname:q,request_id:re,request_url:Z,request_media_duration:j,request_rendition_lists:l})};n>=4?t.on("initFragmentLoaded",c):t.on("initFragmentLoaded",u);var h=function(y){var b=y.type,A=y.fragmentModel,R=y.chunk,I=d(A);f({type:b,request:I,chunk:R})},f=function(y){var b=y.type,A=y.chunk,R=y.request,I=A||{},x=I.mediaInfo,D=I.start,S=x||{},C=S.type,P=uE(R,t),N=P.requestStart,$=P.requestResponseStart,H=P.requestResponseEnd,U=P.requestBytesLoaded,j=P.requestResponseHeaders,q=P.requestMediaDuration,Z=P.requestHostname,re=P.requestUrl,V=P.requestId,G=FI(C,t),ce=G.currentLevel,Se=G.renditionWidth,he=G.renditionHeight,Te=G.renditionBitrate;a("requestcompleted",{request_event_type:b,request_start:N,request_response_start:$,request_response_end:H,request_bytes_loaded:U,request_type:C,request_response_headers:j,request_hostname:Z,request_id:V,request_url:re,request_media_start_time:D,request_media_duration:q,request_current_level:ce,request_labeled_bitrate:Te,request_video_width:Se,request_video_height:he})};n>=4?t.on("mediaFragmentLoaded",f):t.on("mediaFragmentLoaded",h);var m={video:void 0,audio:void 0,totalBitrate:void 0},p=function(){if(m.video&&typeof m.video.bitrate=="number"){if(!(m.video.width&&m.video.height)){r.warn("have bitrate info for video but missing width/height");return}var y=m.video.bitrate;if(m.audio&&typeof m.audio.bitrate=="number"&&(y+=m.audio.bitrate),y!==m.totalBitrate)return m.totalBitrate=y,{video_source_bitrate:y,video_source_height:m.video.height,video_source_width:m.video.width,video_source_codec:BI(m.video.codec)}}},g=function(y,b,A){if(typeof y.newQuality!="number"){r.warn("missing evt.newQuality in qualityChangeRendered event",y);return}var R=y.mediaType;if(R==="audio"||R==="video"){var I=t.getBitrateInfoListFor(R).find(function(D){var S=D.qualityIndex;return S===y.newQuality});if(!(I&&typeof I.bitrate=="number")){r.warn("missing bitrate info for ".concat(R));return}m[R]=om(Fd({},I),{codec:t.getCurrentTrackFor(R).codec});var x=p();x&&a("renditionchange",x)}};t.on("qualityChangeRendered",g);var v=function(y){var b=y.request,A=y.mediaType;b=b||{},a("requestcanceled",{request_event_type:b.type+"_"+b.action,request_url:b.url,request_type:A,request_hostname:ki(b.url)})};t.on("fragmentLoadingAbandoned",v);var T=function(y){var b=y.error,A,R,I=(b==null||(A=b.data)===null||A===void 0?void 0:A.request)||{},x=(b==null||(R=b.data)===null||R===void 0?void 0:R.response)||{};(b==null?void 0:b.code)===27&&a("requestfailed",{request_error:I.type+"_"+I.action,request_url:I.url,request_hostname:ki(I.url),request_type:I.mediaType,request_error_code:x.status,request_error_text:x.statusText});var D="".concat(I!=null&&I.url?"url: ".concat(I.url,`
5
+ `):"")+"".concat(b.reason?"failure reason: ".concat(b.reason,`
6
+ `):"")+"".concat(b.level?"level: ".concat(b.level,`
7
+ `):"")+"".concat(b.parent?"parent stream controller: ".concat(b.parent,`
8
+ `):"")+"".concat(b.buffer?"buffer length: ".concat(b.buffer,`
9
+ `):"")+"".concat(b.error?"error: ".concat(b.error,`
10
+ `):"")+"".concat(b.event?"event: ".concat(b.event,`
11
+ `):"")+"".concat(b.err?"error message: ".concat((C=b.err)===null||C===void 0?void 0:C.message,`
12
+ `):"");l("error",{player_error_code:y,player_error_message:T,player_error_context:P})}};t.on(r.Events.ERROR,m);var p=function(v,b){var y=b.frag,T=y&&y._url||"";l("requestcanceled",{request_event_type:v,request_url:T,request_type:"media",request_hostname:ki(T)})};t.on(r.Events.FRAG_LOAD_EMERGENCY_ABORTED,p);var g=function(v,b){var y=b.level,T=t.levels[y];if(T&&T.attrs&&T.attrs.BANDWIDTH){var A=T.attrs.BANDWIDTH,R,I=parseFloat(T.attrs["FRAME-RATE"]);isNaN(I)||(R=I),A?l("renditionchange",{video_source_fps:R,video_source_bitrate:A,video_source_width:T.width,video_source_height:T.height,video_source_rendition_name:T.name,video_source_codec:T==null?void 0:T.videoCodec}):n.warn("missing BANDWIDTH from HLS manifest parsed by HLS.js")}};t.on(r.Events.LEVEL_SWITCHED,g),t._stopMuxMonitor=function(){t.off(r.Events.MANIFEST_LOADED,d),t.off(r.Events.LEVEL_LOADED,u),t.off(r.Events.AUDIO_TRACK_LOADED,c),t.off(r.Events.FRAG_LOADED,h),t.off(r.Events.FRAG_CHANGED,f),t.off(r.Events.ERROR,m),t.off(r.Events.FRAG_LOAD_EMERGENCY_ABORTED,p),t.off(r.Events.LEVEL_SWITCHED,g),t.off(r.Events.DESTROYING,t._stopMuxMonitor),delete t._stopMuxMonitor},t.on(r.Events.DESTROYING,t._stopMuxMonitor)},UI=function(i){i&&typeof i._stopMuxMonitor=="function"&&i._stopMuxMonitor()},uE=function(i,e){if(!i||!i.requestEndDate)return{};var t=ki(i.url),s=i.url,r=i.bytesLoaded,n=new Date(i.requestStartDate).getTime(),a=new Date(i.firstByteDate).getTime(),o=new Date(i.requestEndDate).getTime(),l=isNaN(i.duration)?0:i.duration,d=typeof e.getMetricsFor=="function"?e.getMetricsFor(i.mediaType).HttpList:e.getDashMetrics().getHttpRequests(i.mediaType),u;d.length>0&&(u=lm(d[d.length-1]._responseHeaders||""));var c=u?Bd(u):void 0;return{requestStart:n,requestResponseStart:a,requestResponseEnd:o,requestBytesLoaded:r,requestResponseHeaders:u,requestMediaDuration:l,requestHostname:t,requestUrl:s,requestId:c}},FI=function(i,e){var t=e.getQualityFor(i),s=e.getCurrentTrackFor(i).bitrateList;return s?{currentLevel:t,renditionWidth:s[t].width||null,renditionHeight:s[t].height||null,renditionBitrate:s[t].bandwidth}:{}},BI=function(i){var e;return(e=i.match(/.*codecs\*?="(.*)"/))===null||e===void 0?void 0:e[1]},$I=function(i){try{var e,t,s=(t=i.getVersion)===null||t===void 0||(e=t.call(i))===null||e===void 0?void 0:e.split(".").map(function(r){return parseInt(r)})[0];return s}catch{return!1}},HI=function(i,e,t){var s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{},r=i.log;if(!t||!t.on){r.warn("Invalid dash.js player reference. Monitoring blocked.");return}var n=$I(t),a=function(y,T){return i.emit(e,y,T)},o=function(y){var T=y.type,A=y.data,R=(A||{}).url;a("requestcompleted",{request_event_type:T,request_start:0,request_response_start:0,request_response_end:0,request_bytes_loaded:-1,request_type:"manifest",request_hostname:ki(R),request_url:R})};t.on("manifestLoaded",o);var l={},d=function(y){if(typeof y.getRequests!="function")return null;var T=y.getRequests({state:"executed"});return T.length===0?null:T[T.length-1]},u=function(y){var T=y.type,A=y.fragmentModel,R=y.chunk,I=d(A);c({type:T,request:I,chunk:R})},c=function(y){var T=y.type,A=y.chunk,R=y.request,I=(A||{}).mediaInfo,x=I||{},D=x.type,S=x.bitrateList;S=S||[];var C={};S.forEach(function(V,G){C[G]={},C[G].width=V.width,C[G].height=V.height,C[G].bitrate=V.bandwidth,C[G].attrs={}}),D==="video"?l.video=C:D==="audio"?l.audio=C:l.media=C;var P=uE(R,t),N=P.requestStart,$=P.requestResponseStart,H=P.requestResponseEnd,U=P.requestResponseHeaders,j=P.requestMediaDuration,q=P.requestHostname,Z=P.requestUrl,re=P.requestId;a("requestcompleted",{request_event_type:T,request_start:N,request_response_start:$,request_response_end:H,request_bytes_loaded:-1,request_type:D+"_init",request_response_headers:U,request_hostname:q,request_id:re,request_url:Z,request_media_duration:j,request_rendition_lists:l})};n>=4?t.on("initFragmentLoaded",c):t.on("initFragmentLoaded",u);var h=function(y){var T=y.type,A=y.fragmentModel,R=y.chunk,I=d(A);f({type:T,request:I,chunk:R})},f=function(y){var T=y.type,A=y.chunk,R=y.request,I=A||{},x=I.mediaInfo,D=I.start,S=x||{},C=S.type,P=uE(R,t),N=P.requestStart,$=P.requestResponseStart,H=P.requestResponseEnd,U=P.requestBytesLoaded,j=P.requestResponseHeaders,q=P.requestMediaDuration,Z=P.requestHostname,re=P.requestUrl,V=P.requestId,G=FI(C,t),ce=G.currentLevel,Se=G.renditionWidth,he=G.renditionHeight,be=G.renditionBitrate;a("requestcompleted",{request_event_type:T,request_start:N,request_response_start:$,request_response_end:H,request_bytes_loaded:U,request_type:C,request_response_headers:j,request_hostname:Z,request_id:V,request_url:re,request_media_start_time:D,request_media_duration:q,request_current_level:ce,request_labeled_bitrate:be,request_video_width:Se,request_video_height:he})};n>=4?t.on("mediaFragmentLoaded",f):t.on("mediaFragmentLoaded",h);var m={video:void 0,audio:void 0,totalBitrate:void 0},p=function(){if(m.video&&typeof m.video.bitrate=="number"){if(!(m.video.width&&m.video.height)){r.warn("have bitrate info for video but missing width/height");return}var y=m.video.bitrate;if(m.audio&&typeof m.audio.bitrate=="number"&&(y+=m.audio.bitrate),y!==m.totalBitrate)return m.totalBitrate=y,{video_source_bitrate:y,video_source_height:m.video.height,video_source_width:m.video.width,video_source_codec:BI(m.video.codec)}}},g=function(y,T,A){if(typeof y.newQuality!="number"){r.warn("missing evt.newQuality in qualityChangeRendered event",y);return}var R=y.mediaType;if(R==="audio"||R==="video"){var I=t.getBitrateInfoListFor(R).find(function(D){var S=D.qualityIndex;return S===y.newQuality});if(!(I&&typeof I.bitrate=="number")){r.warn("missing bitrate info for ".concat(R));return}m[R]=om(Fd({},I),{codec:t.getCurrentTrackFor(R).codec});var x=p();x&&a("renditionchange",x)}};t.on("qualityChangeRendered",g);var v=function(y){var T=y.request,A=y.mediaType;T=T||{},a("requestcanceled",{request_event_type:T.type+"_"+T.action,request_url:T.url,request_type:A,request_hostname:ki(T.url)})};t.on("fragmentLoadingAbandoned",v);var b=function(y){var T=y.error,A,R,I=(T==null||(A=T.data)===null||A===void 0?void 0:A.request)||{},x=(T==null||(R=T.data)===null||R===void 0?void 0:R.response)||{};(T==null?void 0:T.code)===27&&a("requestfailed",{request_error:I.type+"_"+I.action,request_url:I.url,request_hostname:ki(I.url),request_type:I.mediaType,request_error_code:x.status,request_error_text:x.statusText});var D="".concat(I!=null&&I.url?"url: ".concat(I.url,`
13
13
  `):"")+"".concat(x!=null&&x.status||x!=null&&x.statusText?"response: ".concat(x==null?void 0:x.status,", ").concat(x==null?void 0:x.statusText,`
14
- `):"");a("error",{player_error_code:b==null?void 0:b.code,player_error_message:b==null?void 0:b.message,player_error_context:D})};t.on("error",T),t._stopMuxMonitor=function(){t.off("manifestLoaded",o),t.off("initFragmentLoaded",c),t.off("mediaFragmentLoaded",f),t.off("qualityChangeRendered",g),t.off("error",T),t.off("fragmentLoadingAbandoned",v),delete t._stopMuxMonitor}},GI=function(i){i&&typeof i._stopMuxMonitor=="function"&&i._stopMuxMonitor()},cE=0,KI=function(){"use strict";function i(){ft(this,i),Y(this,"_listeners",void 0)}return Di(i,[{key:"on",value:function(e,t,s){return t._eventEmitterGuid=t._eventEmitterGuid||++cE,this._listeners=this._listeners||{},this._listeners[e]=this._listeners[e]||[],s&&(t=t.bind(s)),this._listeners[e].push(t),t}},{key:"off",value:function(e,t){var s=this._listeners&&this._listeners[e];s&&s.forEach(function(r,n){r._eventEmitterGuid===t._eventEmitterGuid&&s.splice(n,1)})}},{key:"one",value:function(e,t,s){var r=this;t._eventEmitterGuid=t._eventEmitterGuid||++cE;var n=function(){r.off(e,n),t.apply(s||this,arguments)};n._eventEmitterGuid=t._eventEmitterGuid,this.on(e,n)}},{key:"emit",value:function(e,t){var s=this;if(this._listeners){t=t||{};var r=this._listeners["before"+e]||[],n=this._listeners["before*"]||[],a=this._listeners[e]||[],o=this._listeners["after"+e]||[],l=function(d,u){d=d.slice(),d.forEach(function(c){c.call(s,{type:e},u)})};l(r,t),l(n,t),l(a,t),l(o,t)}}}]),i}(),VI=KI,Jf=mi(ji()),WI=function(){"use strict";function i(e){var t=this;ft(this,i),Y(this,"_playbackHeartbeatInterval",void 0),Y(this,"_playheadShouldBeProgressing",void 0),Y(this,"pm",void 0),this.pm=e,this._playbackHeartbeatInterval=null,this._playheadShouldBeProgressing=!1,e.on("playing",function(){t._playheadShouldBeProgressing=!0}),e.on("play",this._startPlaybackHeartbeatInterval.bind(this)),e.on("playing",this._startPlaybackHeartbeatInterval.bind(this)),e.on("adbreakstart",this._startPlaybackHeartbeatInterval.bind(this)),e.on("adplay",this._startPlaybackHeartbeatInterval.bind(this)),e.on("adplaying",this._startPlaybackHeartbeatInterval.bind(this)),e.on("devicewake",this._startPlaybackHeartbeatInterval.bind(this)),e.on("viewstart",this._startPlaybackHeartbeatInterval.bind(this)),e.on("rebufferstart",this._startPlaybackHeartbeatInterval.bind(this)),e.on("pause",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("ended",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("viewend",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("error",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("aderror",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("adpause",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("adended",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("adbreakend",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("seeked",function(){e.data.player_is_paused?t._stopPlaybackHeartbeatInterval():t._startPlaybackHeartbeatInterval()}),e.on("timeupdate",function(){t._playbackHeartbeatInterval!==null&&e.emit("playbackheartbeat")}),e.on("devicesleep",function(s,r){t._playbackHeartbeatInterval!==null&&(Jf.default.clearInterval(t._playbackHeartbeatInterval),e.emit("playbackheartbeatend",{viewer_time:r.viewer_time}),t._playbackHeartbeatInterval=null)})}return Di(i,[{key:"_startPlaybackHeartbeatInterval",value:function(){var e=this;this._playbackHeartbeatInterval===null&&(this.pm.emit("playbackheartbeat"),this._playbackHeartbeatInterval=Jf.default.setInterval(function(){e.pm.emit("playbackheartbeat")},this.pm.playbackHeartbeatTime))}},{key:"_stopPlaybackHeartbeatInterval",value:function(){this._playheadShouldBeProgressing=!1,this._playbackHeartbeatInterval!==null&&(Jf.default.clearInterval(this._playbackHeartbeatInterval),this.pm.emit("playbackheartbeatend"),this._playbackHeartbeatInterval=null)}}]),i}(),qI=WI,YI=function i(e){"use strict";var t=this;ft(this,i),Y(this,"viewErrored",void 0),e.on("viewinit",function(){t.viewErrored=!1}),e.on("error",function(s,r){try{var n=e.errorTranslator({player_error_code:r.player_error_code,player_error_message:r.player_error_message,player_error_context:r.player_error_context,player_error_severity:r.player_error_severity,player_error_business_exception:r.player_error_business_exception});n&&(e.data.player_error_code=n.player_error_code||r.player_error_code,e.data.player_error_message=n.player_error_message||r.player_error_message,e.data.player_error_context=n.player_error_context||r.player_error_context,e.data.player_error_severity=n.player_error_severity||r.player_error_severity,e.data.player_error_business_exception=n.player_error_business_exception||r.player_error_business_exception,t.viewErrored=!0)}catch(a){e.mux.log.warn("Exception in error translator callback.",a),t.viewErrored=!0}}),e.on("aftererror",function(){var s,r,n,a,o;(s=e.data)===null||s===void 0||delete s.player_error_code,(r=e.data)===null||r===void 0||delete r.player_error_message,(n=e.data)===null||n===void 0||delete n.player_error_context,(a=e.data)===null||a===void 0||delete a.player_error_severity,(o=e.data)===null||o===void 0||delete o.player_error_business_exception})},jI=YI,zI=function(){"use strict";function i(e){ft(this,i),Y(this,"_watchTimeTrackerLastCheckedTime",void 0),Y(this,"pm",void 0),this.pm=e,this._watchTimeTrackerLastCheckedTime=null,e.on("playbackheartbeat",this._updateWatchTime.bind(this)),e.on("playbackheartbeatend",this._clearWatchTimeState.bind(this))}return Di(i,[{key:"_updateWatchTime",value:function(e,t){var s=t.viewer_time;this._watchTimeTrackerLastCheckedTime===null&&(this._watchTimeTrackerLastCheckedTime=s),yt(this.pm.data,"view_watch_time",s-this._watchTimeTrackerLastCheckedTime),this._watchTimeTrackerLastCheckedTime=s}},{key:"_clearWatchTimeState",value:function(e,t){this._updateWatchTime(e,t),this._watchTimeTrackerLastCheckedTime=null}}]),i}(),QI=zI,XI=function(){"use strict";function i(e){var t=this;ft(this,i),Y(this,"_playbackTimeTrackerLastPlayheadPosition",void 0),Y(this,"_lastTime",void 0),Y(this,"_isAdPlaying",void 0),Y(this,"_callbackUpdatePlaybackTime",void 0),Y(this,"pm",void 0),this.pm=e,this._playbackTimeTrackerLastPlayheadPosition=-1,this._lastTime=It.now(),this._isAdPlaying=!1,this._callbackUpdatePlaybackTime=null,e.on("viewinit",function(){t.pm.data.view_playing_time_ms_cumulative=0});var s=this._startPlaybackTimeTracking.bind(this);e.on("playing",s),e.on("adplaying",s),e.on("seeked",s),e.on("rebufferend",s);var r=this._stopPlaybackTimeTracking.bind(this);e.on("playbackheartbeatend",r),e.on("seeking",r),e.on("rebufferstart",r),e.on("adplaying",function(){t._isAdPlaying=!0}),e.on("adended",function(){t._isAdPlaying=!1}),e.on("adpause",function(){t._isAdPlaying=!1}),e.on("adbreakstart",function(){t._isAdPlaying=!1}),e.on("adbreakend",function(){t._isAdPlaying=!1}),e.on("adplay",function(){t._isAdPlaying=!1}),e.on("viewinit",function(){t._playbackTimeTrackerLastPlayheadPosition=-1,t._lastTime=It.now(),t._isAdPlaying=!1,t._callbackUpdatePlaybackTime=null})}return Di(i,[{key:"_startPlaybackTimeTracking",value:function(){this._callbackUpdatePlaybackTime===null&&(this._callbackUpdatePlaybackTime=this._updatePlaybackTime.bind(this),this._playbackTimeTrackerLastPlayheadPosition=this.pm.data.player_playhead_time,this._lastTime=It.now(),this.pm.on("playbackheartbeat",this._callbackUpdatePlaybackTime))}},{key:"_stopPlaybackTimeTracking",value:function(){this._callbackUpdatePlaybackTime&&(this._updatePlaybackTime(),this.pm.off("playbackheartbeat",this._callbackUpdatePlaybackTime),this._callbackUpdatePlaybackTime=null,this._playbackTimeTrackerLastPlayheadPosition=-1)}},{key:"_updatePlaybackTime",value:function(){var e=this.pm.data.player_playhead_time||0,t=It.now(),s=t-this._lastTime,r=-1;this._playbackTimeTrackerLastPlayheadPosition>=0&&e>this._playbackTimeTrackerLastPlayheadPosition?r=e-this._playbackTimeTrackerLastPlayheadPosition:this._isAdPlaying&&(r=s),r>0&&r<=1e3&&yt(this.pm.data,"view_content_playback_time",r),this._callbackUpdatePlaybackTime!==null&&s>0&&s<=1e3&&(this._isAdPlaying&&yt(this.pm.data,"ad_playing_time_ms_cumulative",s),yt(this.pm.data,"view_playing_time_ms_cumulative",s)),this._playbackTimeTrackerLastPlayheadPosition=e,this._lastTime=t}}]),i}(),ZI=XI,JI=function(){"use strict";function i(e){ft(this,i),Y(this,"pm",void 0),this.pm=e;var t=this._updatePlayheadTime.bind(this);e.on("playbackheartbeat",t),e.on("playbackheartbeatend",t),e.on("timeupdate",t),e.on("destroy",function(){e.off("timeupdate",t)})}return Di(i,[{key:"_updateMaxPlayheadPosition",value:function(){this.pm.data.view_max_playhead_position=typeof this.pm.data.view_max_playhead_position=="undefined"?this.pm.data.player_playhead_time:Math.max(this.pm.data.view_max_playhead_position,this.pm.data.player_playhead_time)}},{key:"_updatePlayheadTime",value:function(e,t){var s=this,r=function(){s.pm.currentFragmentPDT&&s.pm.currentFragmentStart&&(s.pm.data.player_program_time=s.pm.currentFragmentPDT+s.pm.data.player_playhead_time-s.pm.currentFragmentStart)};if(t&&t.player_playhead_time)this.pm.data.player_playhead_time=t.player_playhead_time,r(),this._updateMaxPlayheadPosition();else if(this.pm.getPlayheadTime){var n=this.pm.getPlayheadTime();typeof n!="undefined"&&(this.pm.data.player_playhead_time=n,r(),this._updateMaxPlayheadPosition())}}}]),i}(),eL=JI,hE=5*60*1e3,tL=function i(e){"use strict";if(ft(this,i),!e.disableRebufferTracking){var t,s=function(n,a){r(a),t=void 0},r=function(n){if(t){var a=n.viewer_time-t;yt(e.data,"view_rebuffer_duration",a),t=n.viewer_time,e.data.view_rebuffer_duration>hE&&(e.emit("viewend"),e.send("viewend"),e.mux.log.warn("Ending view after rebuffering for longer than ".concat(hE,"ms, future events will be ignored unless a programchange or videochange occurs.")))}e.data.view_watch_time>=0&&e.data.view_rebuffer_count>0&&(e.data.view_rebuffer_frequency=e.data.view_rebuffer_count/e.data.view_watch_time,e.data.view_rebuffer_percentage=e.data.view_rebuffer_duration/e.data.view_watch_time)};e.on("playbackheartbeat",function(n,a){return r(a)}),e.on("rebufferstart",function(n,a){t||(yt(e.data,"view_rebuffer_count",1),t=a.viewer_time,e.one("rebufferend",s))}),e.on("viewinit",function(){t=void 0,e.off("rebufferend",s)})}},iL=tL,sL=function(){"use strict";function i(e){var t=this;ft(this,i),Y(this,"_lastCheckedTime",void 0),Y(this,"_lastPlayheadTime",void 0),Y(this,"_lastPlayheadTimeUpdatedTime",void 0),Y(this,"_rebuffering",void 0),Y(this,"pm",void 0),this.pm=e,!(e.disableRebufferTracking||e.disablePlayheadRebufferTracking)&&(this._lastCheckedTime=null,this._lastPlayheadTime=null,this._lastPlayheadTimeUpdatedTime=null,e.on("playbackheartbeat",this._checkIfRebuffering.bind(this)),e.on("playbackheartbeatend",this._cleanupRebufferTracker.bind(this)),e.on("seeking",function(){t._cleanupRebufferTracker(null,{viewer_time:It.now()})}))}return Di(i,[{key:"_checkIfRebuffering",value:function(e,t){if(this.pm.seekingTracker.isSeeking||this.pm.adTracker.isAdBreak||!this.pm.playbackHeartbeat._playheadShouldBeProgressing){this._cleanupRebufferTracker(e,t);return}if(this._lastCheckedTime===null){this._prepareRebufferTrackerState(t.viewer_time);return}if(this._lastPlayheadTime!==this.pm.data.player_playhead_time){this._cleanupRebufferTracker(e,t,!0);return}var s=t.viewer_time-this._lastPlayheadTimeUpdatedTime;typeof this.pm.sustainedRebufferThreshold=="number"&&s>=this.pm.sustainedRebufferThreshold&&(this._rebuffering||(this._rebuffering=!0,this.pm.emit("rebufferstart",{viewer_time:this._lastPlayheadTimeUpdatedTime}))),this._lastCheckedTime=t.viewer_time}},{key:"_clearRebufferTrackerState",value:function(){this._lastCheckedTime=null,this._lastPlayheadTime=null,this._lastPlayheadTimeUpdatedTime=null}},{key:"_prepareRebufferTrackerState",value:function(e){this._lastCheckedTime=e,this._lastPlayheadTime=this.pm.data.player_playhead_time,this._lastPlayheadTimeUpdatedTime=e}},{key:"_cleanupRebufferTracker",value:function(e,t){var s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;if(this._rebuffering)this._rebuffering=!1,this.pm.emit("rebufferend",{viewer_time:t.viewer_time});else{if(this._lastCheckedTime===null)return;var r=this.pm.data.player_playhead_time-this._lastPlayheadTime,n=t.viewer_time-this._lastPlayheadTimeUpdatedTime;typeof this.pm.minimumRebufferDuration=="number"&&r>0&&n-r>this.pm.minimumRebufferDuration&&(this._lastCheckedTime=null,this.pm.emit("rebufferstart",{viewer_time:this._lastPlayheadTimeUpdatedTime}),this.pm.emit("rebufferend",{viewer_time:this._lastPlayheadTimeUpdatedTime+n-r}))}s?this._prepareRebufferTrackerState(t.viewer_time):this._clearRebufferTrackerState()}}]),i}(),rL=sL,nL=function(){"use strict";function i(e){var t=this;ft(this,i),Y(this,"pm",void 0),this.pm=e,e.on("viewinit",function(){var s=e.data,r=s.view_id;if(!s.view_program_changed){var n=function(a,o){var l=o.viewer_time;(a.type==="playing"&&typeof e.data.view_time_to_first_frame=="undefined"||a.type==="adplaying"&&(typeof e.data.view_time_to_first_frame=="undefined"||t._inPrerollPosition()))&&t.calculateTimeToFirstFrame(l||It.now(),r)};e.one("playing",n),e.one("adplaying",n),e.one("viewend",function(){e.off("playing",n),e.off("adplaying",n)})}})}return Di(i,[{key:"_inPrerollPosition",value:function(){return typeof this.pm.data.view_content_playback_time=="undefined"||this.pm.data.view_content_playback_time<=1e3}},{key:"calculateTimeToFirstFrame",value:function(e,t){t===this.pm.data.view_id&&(this.pm.watchTimeTracker._updateWatchTime(null,{viewer_time:e}),this.pm.data.view_time_to_first_frame=this.pm.data.view_watch_time,(this.pm.data.player_autoplay_on||this.pm.data.video_is_autoplay)&&this.pm.pageLoadInitTime&&(this.pm.data.view_aggregate_startup_time=this.pm.data.view_start+this.pm.data.view_watch_time-this.pm.pageLoadInitTime))}}]),i}(),aL=nL,oL=function i(e){"use strict";var t=this;ft(this,i),Y(this,"_lastPlayerHeight",void 0),Y(this,"_lastPlayerWidth",void 0),Y(this,"_lastPlayheadPosition",void 0),Y(this,"_lastSourceHeight",void 0),Y(this,"_lastSourceWidth",void 0),e.on("viewinit",function(){t._lastPlayheadPosition=-1});var s=["pause","rebufferstart","seeking","error","adbreakstart","hb","renditionchange","orientationchange","viewend","playbackmodechange"],r=["playing","hb","renditionchange","orientationchange","playbackmodechange"];s.forEach(function(n){e.on(n,function(){if(t._lastPlayheadPosition>=0&&e.data.player_playhead_time>=0&&t._lastPlayerWidth>=0&&t._lastSourceWidth>0&&t._lastPlayerHeight>=0&&t._lastSourceHeight>0){var a=e.data.player_playhead_time-t._lastPlayheadPosition;if(a<0){t._lastPlayheadPosition=-1;return}var o=Math.min(t._lastPlayerWidth/t._lastSourceWidth,t._lastPlayerHeight/t._lastSourceHeight),l=Math.max(0,o-1),d=Math.max(0,1-o);e.data.view_max_upscale_percentage=Math.max(e.data.view_max_upscale_percentage||0,l),e.data.view_max_downscale_percentage=Math.max(e.data.view_max_downscale_percentage||0,d),yt(e.data,"view_total_content_playback_time",a),yt(e.data,"view_total_upscaling",l*a),yt(e.data,"view_total_downscaling",d*a)}t._lastPlayheadPosition=-1})}),r.forEach(function(n){e.on(n,function(){t._lastPlayheadPosition=e.data.player_playhead_time,t._lastPlayerWidth=e.data.player_width,t._lastPlayerHeight=e.data.player_height,t._lastSourceWidth=e.data.video_source_width,t._lastSourceHeight=e.data.video_source_height})})},lL=oL,dL=2e3,uL=function i(e){"use strict";var t=this;ft(this,i),Y(this,"isSeeking",void 0),this.isSeeking=!1;var s=-1,r=function(){var n=It.now(),a=(e.data.viewer_time||n)-(s||n);yt(e.data,"view_seek_duration",a),e.data.view_max_seek_time=Math.max(e.data.view_max_seek_time||0,a),t.isSeeking=!1,s=-1};e.on("seeking",function(n,a){if(Object.assign(e.data,a),t.isSeeking&&a.viewer_time-s<=dL){s=a.viewer_time;return}t.isSeeking&&r(),t.isSeeking=!0,s=a.viewer_time,yt(e.data,"view_seek_count",1),e.send("seeking")}),e.on("seeked",function(){r()}),e.on("viewend",function(){t.isSeeking&&(r(),e.send("seeked")),t.isSeeking=!1,s=-1})},cL=uL,fE=function(i,e){i.push(e),i.sort(function(t,s){return t.viewer_time-s.viewer_time})},hL=["adbreakstart","adrequest","adresponse","adplay","adplaying","adpause","adended","adbreakend","aderror","adclicked","adskipped"],fL=function(){"use strict";function i(e){var t=this;ft(this,i),Y(this,"_adHasPlayed",void 0),Y(this,"_adRequests",void 0),Y(this,"_adResponses",void 0),Y(this,"_currentAdRequestNumber",void 0),Y(this,"_currentAdResponseNumber",void 0),Y(this,"_prerollPlayTime",void 0),Y(this,"_wouldBeNewAdPlay",void 0),Y(this,"isAdBreak",void 0),Y(this,"pm",void 0),this.pm=e,e.on("viewinit",function(){t.isAdBreak=!1,t._currentAdRequestNumber=0,t._currentAdResponseNumber=0,t._adRequests=[],t._adResponses=[],t._adHasPlayed=!1,t._wouldBeNewAdPlay=!0,t._prerollPlayTime=void 0}),hL.forEach(function(r){return e.on(r,t._updateAdData.bind(t))});var s=function(){t.isAdBreak=!1};e.on("adbreakstart",function(){t.isAdBreak=!0}),e.on("play",s),e.on("playing",s),e.on("viewend",s),e.on("adrequest",function(r,n){n=Object.assign({ad_request_id:"generatedAdRequestId"+t._currentAdRequestNumber++},n),fE(t._adRequests,n),yt(e.data,"view_ad_request_count"),t.inPrerollPosition()&&(e.data.view_preroll_requested=!0,t._adHasPlayed||yt(e.data,"view_preroll_request_count"))}),e.on("adresponse",function(r,n){n=Object.assign({ad_request_id:"generatedAdRequestId"+t._currentAdResponseNumber++},n),fE(t._adResponses,n);var a=t.findAdRequest(n.ad_request_id);a&&yt(e.data,"view_ad_request_time",Math.max(0,n.viewer_time-a.viewer_time))}),e.on("adplay",function(r,n){t._adHasPlayed=!0,t._wouldBeNewAdPlay&&(t._wouldBeNewAdPlay=!1,yt(e.data,"view_ad_played_count")),t.inPrerollPosition()&&!e.data.view_preroll_played&&(e.data.view_preroll_played=!0,t._adRequests.length>0&&(e.data.view_preroll_request_time=Math.max(0,n.viewer_time-t._adRequests[0].viewer_time)),e.data.view_start&&(e.data.view_startup_preroll_request_time=Math.max(0,n.viewer_time-e.data.view_start)),t._prerollPlayTime=n.viewer_time)}),e.on("adplaying",function(r,n){t.inPrerollPosition()&&typeof e.data.view_preroll_load_time=="undefined"&&typeof t._prerollPlayTime!="undefined"&&(e.data.view_preroll_load_time=n.viewer_time-t._prerollPlayTime,e.data.view_startup_preroll_load_time=n.viewer_time-t._prerollPlayTime)}),e.on("adclicked",function(r,n){t._wouldBeNewAdPlay||yt(e.data,"view_ad_clicked_count")}),e.on("adskipped",function(r,n){t._wouldBeNewAdPlay||yt(e.data,"view_ad_skipped_count")}),e.on("adended",function(){t._wouldBeNewAdPlay=!0}),e.on("aderror",function(){t._wouldBeNewAdPlay=!0})}return Di(i,[{key:"inPrerollPosition",value:function(){return typeof this.pm.data.view_content_playback_time=="undefined"||this.pm.data.view_content_playback_time<=1e3}},{key:"findAdRequest",value:function(e){for(var t=0;t<this._adRequests.length;t++)if(this._adRequests[t].ad_request_id===e)return this._adRequests[t]}},{key:"_updateAdData",value:function(e,t){if(this.inPrerollPosition()){if(!this.pm.data.view_preroll_ad_tag_hostname&&t.ad_tag_url){var s=Is(Co(t.ad_tag_url),2),r=s[0],n=s[1];this.pm.data.view_preroll_ad_tag_domain=n,this.pm.data.view_preroll_ad_tag_hostname=r}if(!this.pm.data.view_preroll_ad_asset_hostname&&t.ad_asset_url){var a=Is(Co(t.ad_asset_url),2),o=a[0],l=a[1];this.pm.data.view_preroll_ad_asset_domain=l,this.pm.data.view_preroll_ad_asset_hostname=o}this.pm.data.ad_type="preroll"}this.pm.data.ad_asset_url=t==null?void 0:t.ad_asset_url,this.pm.data.ad_tag_url=t==null?void 0:t.ad_tag_url,this.pm.data.ad_creative_id=t==null?void 0:t.ad_creative_id,this.pm.data.ad_id=t==null?void 0:t.ad_id,this.pm.data.ad_universal_id=t==null?void 0:t.ad_universal_id,t!=null&&t.ad_type&&(this.pm.data.ad_type=t==null?void 0:t.ad_type)}}]),i}(),mL=fL,pL=function i(e){"use strict";var t=this;ft(this,i),Y(this,"lastWallClockTime",void 0);var s=function(){t.lastWallClockTime=It.now(),e.on("before*",r)},r=function(n){var a=It.now(),o=t.lastWallClockTime;t.lastWallClockTime=a,a-o>3e4&&(e.emit("devicesleep",{viewer_time:o}),Object.assign(e.data,{viewer_time:o}),e.send("devicesleep"),e.emit("devicewake",{viewer_time:a}),Object.assign(e.data,{viewer_time:a}),e.send("devicewake"))};e.one("playbackheartbeat",s),e.on("playbackheartbeatend",function(){e.off("before*",r),e.one("playbackheartbeat",s)})},gL=pL,em=mi(ji()),DE=function(i){return i()}(function(){var i=function(){for(var t=0,s={};t<arguments.length;t++){var r=arguments[t];for(var n in r)s[n]=r[n]}return s};function e(t){function s(r,n,a){var o;if(typeof document!="undefined"){if(arguments.length>1){if(a=i({path:"/"},s.defaults,a),typeof a.expires=="number"){var l=new Date;l.setMilliseconds(l.getMilliseconds()+a.expires*864e5),a.expires=l}try{o=JSON.stringify(n),/^[\{\[]/.test(o)&&(n=o)}catch{}return t.write?n=t.write(n,r):n=encodeURIComponent(String(n)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent),r=encodeURIComponent(String(r)),r=r.replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent),r=r.replace(/[\(\)]/g,escape),document.cookie=[r,"=",n,a.expires?"; expires="+a.expires.toUTCString():"",a.path?"; path="+a.path:"",a.domain?"; domain="+a.domain:"",a.secure?"; secure":""].join("")}r||(o={});for(var d=document.cookie?document.cookie.split("; "):[],u=/(%[0-9A-Z]{2})+/g,c=0;c<d.length;c++){var h=d[c].split("="),f=h.slice(1).join("=");f.charAt(0)==='"'&&(f=f.slice(1,-1));try{var m=h[0].replace(u,decodeURIComponent);if(f=t.read?t.read(f,m):t(f,m)||f.replace(u,decodeURIComponent),this.json)try{f=JSON.parse(f)}catch{}if(r===m){o=f;break}r||(o[m]=f)}catch{}}return o}}return s.set=s,s.get=function(r){return s.call(s,r)},s.getJSON=function(){return s.apply({json:!0},[].slice.call(arguments))},s.defaults={},s.remove=function(r,n){s(r,"",i(n,{expires:-1}))},s.withConverter=e,s}return e(function(){})}),CE="muxData",vL=function(i){return Object.entries(i).map(function(e){var t=Is(e,2),s=t[0],r=t[1];return"".concat(s,"=").concat(r)}).join("&")},EL=function(i){return i.split("&").reduce(function(e,t){var s=Is(t.split("="),2),r=s[0],n=s[1],a=+n,o=n&&a==n?a:n;return e[r]=o,e},{})},wE=function(){var i;try{i=EL(DE.get(CE)||"")}catch{i={}}return i},ME=function(i){try{DE.set(CE,vL(i),{expires:365})}catch{}},yL=function(){var i=wE();return i.mux_viewer_id=i.mux_viewer_id||Do(),i.msn=i.msn||Math.random(),ME(i),{mux_viewer_id:i.mux_viewer_id,mux_sample_number:i.msn}},TL=function(){var i=wE(),e=It.now();return i.session_start&&(i.sst=i.session_start,delete i.session_start),i.session_id&&(i.sid=i.session_id,delete i.session_id),i.session_expires&&(i.sex=i.session_expires,delete i.session_expires),(!i.sex||i.sex<e)&&(i.sid=Do(),i.sst=e),i.sex=e+25*60*1e3,ME(i),{session_id:i.sid,session_start:i.sst,session_expires:i.sex}};function bL(i,e){var t=e.beaconCollectionDomain,s=e.beaconDomain;if(t)return"https://"+t;i=i||"inferred";var r=s||"litix.io";return i.match(/^[a-z0-9]+$/)?"https://"+i+"."+r:"https://img.litix.io/a.gif"}var _L=mi(ji()),PE=function(){var i;switch(OE()){case"cellular":i="cellular";break;case"ethernet":i="wired";break;case"wifi":i="wifi";break;case void 0:break;default:i="other"}return i},OE=function(){var i=_L.default.navigator,e=i&&(i.connection||i.mozConnection||i.webkitConnection);return e&&e.type};PE.getConnectionFromAPI=OE;var AL=PE,SL={a:"env",b:"beacon",c:"custom",d:"ad",e:"event",f:"experiment",i:"internal",m:"mux",n:"response",p:"player",q:"request",r:"retry",s:"session",t:"timestamp",u:"viewer",v:"video",w:"page",x:"view",y:"sub"},IL=NE(SL),LL={ad:"ad",af:"affiliate",ag:"aggregate",ap:"api",al:"application",ao:"audio",ar:"architecture",as:"asset",au:"autoplay",av:"average",bi:"bitrate",bn:"brand",br:"break",bw:"browser",by:"bytes",bz:"business",ca:"cached",cb:"cancel",cc:"codec",cd:"code",cg:"category",ch:"changed",ci:"client",ck:"clicked",cl:"canceled",cm:"cmcd",cn:"config",co:"count",ce:"counter",cp:"complete",cq:"creator",cr:"creative",cs:"captions",ct:"content",cu:"current",cv:"cumulative",cx:"connection",cz:"context",da:"data",dg:"downscaling",dm:"domain",dn:"cdn",do:"downscale",dr:"drm",dp:"dropped",du:"duration",dv:"device",dy:"dynamic",eb:"enabled",ec:"encoding",ed:"edge",en:"end",eg:"engine",em:"embed",er:"error",ep:"experiments",es:"errorcode",et:"errortext",ee:"event",ev:"events",ex:"expires",ez:"exception",fa:"failed",fi:"first",fm:"family",ft:"format",fp:"fps",fq:"frequency",fr:"frame",fs:"fullscreen",ha:"has",hb:"holdback",he:"headers",ho:"host",hn:"hostname",ht:"height",id:"id",ii:"init",in:"instance",ip:"ip",is:"is",ke:"key",la:"language",lb:"labeled",le:"level",li:"live",ld:"loaded",lo:"load",ls:"lists",lt:"latency",ma:"max",md:"media",me:"message",mf:"manifest",mi:"mime",ml:"midroll",mm:"min",mn:"manufacturer",mo:"model",mp:"mode",ms:"ms",mx:"mux",ne:"newest",nm:"name",no:"number",on:"on",or:"origin",os:"os",pa:"paused",pb:"playback",pd:"producer",pe:"percentage",pf:"played",pg:"program",ph:"playhead",pi:"plugin",pl:"preroll",pn:"playing",po:"poster",pp:"pip",pr:"preload",ps:"position",pt:"part",pv:"previous",py:"property",px:"pop",pz:"plan",ra:"rate",rd:"requested",re:"rebuffer",rf:"rendition",rg:"range",rm:"remote",ro:"ratio",rp:"response",rq:"request",rs:"requests",sa:"sample",sd:"skipped",se:"session",sh:"shift",sk:"seek",sm:"stream",so:"source",sq:"sequence",sr:"series",ss:"status",st:"start",su:"startup",sv:"server",sw:"software",sy:"severity",ta:"tag",tc:"tech",te:"text",tg:"target",th:"throughput",ti:"time",tl:"total",to:"to",tt:"title",ty:"type",ug:"upscaling",un:"universal",up:"upscale",ur:"url",us:"user",va:"variant",vd:"viewed",vi:"video",ve:"version",vw:"view",vr:"viewer",wd:"width",wa:"watch",wt:"waiting"},mE=NE(LL);function NE(i){var e={};for(var t in i)i.hasOwnProperty(t)&&(e[i[t]]=t);return e}function am(i){var e={},t={};return Object.keys(i).forEach(function(s){var r=!1;if(i.hasOwnProperty(s)&&i[s]!==void 0){var n=s.split("_"),a=n[0],o=IL[a];o||(Ve.info("Data key word `"+n[0]+"` not expected in "+s),o=a+"_"),n.splice(1).forEach(function(l){l==="url"&&(r=!0),mE[l]?o+=mE[l]:Number.isInteger(Number(l))?o+=l:(Ve.info("Data key word `"+l+"` not expected in "+s),o+="_"+l+"_")}),r?t[o]=i[s]:e[o]=i[s]}}),Object.assign(e,t)}var qr=mi(ji()),RL=mi(IE()),xL={maxBeaconSize:300,maxQueueLength:3600,baseTimeBetweenBeacons:1e4,maxPayloadKBSize:500},kL=56*1024,DL=["hb","requestcompleted","requestfailed","requestcanceled"],CL="https://img.litix.io",Ls=function(i){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this._beaconUrl=i||CL,this._eventQueue=[],this._postInFlight=!1,this._resendAfterPost=!1,this._failureCount=0,this._sendTimeout=!1,this._options=Object.assign({},xL,e)};Ls.prototype.queueEvent=function(i,e){var t=Object.assign({},e);return this._eventQueue.length<=this._options.maxQueueLength||i==="eventrateexceeded"?(this._eventQueue.push(t),this._sendTimeout||this._startBeaconSending(),this._eventQueue.length<=this._options.maxQueueLength):!1};Ls.prototype.flushEvents=function(){var i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(i&&this._eventQueue.length===1){this._eventQueue.pop();return}this._eventQueue.length&&this._sendBeaconQueue(),this._startBeaconSending()};Ls.prototype.destroy=function(){var i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;this.destroyed=!0,i?this._clearBeaconQueue():this.flushEvents(),qr.default.clearTimeout(this._sendTimeout)};Ls.prototype._clearBeaconQueue=function(){var i=this._eventQueue.length>this._options.maxBeaconSize?this._eventQueue.length-this._options.maxBeaconSize:0,e=this._eventQueue.slice(i);i>0&&Object.assign(e[e.length-1],am({mux_view_message:"event queue truncated"}));var t=this._createPayload(e);UE(this._beaconUrl,t,!0,function(){})};Ls.prototype._sendBeaconQueue=function(){var i=this;if(this._postInFlight){this._resendAfterPost=!0;return}var e=this._eventQueue.slice(0,this._options.maxBeaconSize);this._eventQueue=this._eventQueue.slice(this._options.maxBeaconSize),this._postInFlight=!0;var t=this._createPayload(e),s=It.now();UE(this._beaconUrl,t,!1,function(r,n){n?(i._eventQueue=e.concat(i._eventQueue),i._failureCount+=1,Ve.info("Error sending beacon: "+n)):i._failureCount=0,i._roundTripTime=It.now()-s,i._postInFlight=!1,i._resendAfterPost&&(i._resendAfterPost=!1,i._eventQueue.length>0&&i._sendBeaconQueue())})};Ls.prototype._getNextBeaconTime=function(){if(!this._failureCount)return this._options.baseTimeBetweenBeacons;var i=Math.pow(2,this._failureCount-1);return i=i*Math.random(),(1+i)*this._options.baseTimeBetweenBeacons};Ls.prototype._startBeaconSending=function(){var i=this;qr.default.clearTimeout(this._sendTimeout),!this.destroyed&&(this._sendTimeout=qr.default.setTimeout(function(){i._eventQueue.length&&i._sendBeaconQueue(),i._startBeaconSending()},this._getNextBeaconTime()))};Ls.prototype._createPayload=function(i){var e=this,t={transmission_timestamp:Math.round(It.now())};this._roundTripTime&&(t.rtt_ms=Math.round(this._roundTripTime));var s,r,n,a=function(){s=JSON.stringify({metadata:t,events:r||i}),n=s.length/1024},o=function(){return n<=e._options.maxPayloadKBSize};return a(),o()||(Ve.info("Payload size is too big ("+n+" kb). Removing unnecessary events."),r=i.filter(function(l){return DL.indexOf(l.e)===-1}),a()),o()||(Ve.info("Payload size still too big ("+n+" kb). Cropping fields.."),r.forEach(function(l){for(var d in l){var u=l[d],c=50*1024;typeof u=="string"&&u.length>c&&(l[d]=u.substring(0,c))}}),a()),s};var wL=typeof RL.default.exitPictureInPicture=="function"?function(i){return i.length<=kL}:function(i){return!1},UE=function(i,e,t,s){if(t&&navigator&&navigator.sendBeacon&&navigator.sendBeacon(i,e)){s();return}if(qr.default.fetch){qr.default.fetch(i,{method:"POST",body:e,headers:{"Content-Type":"text/plain"},keepalive:wL(e)}).then(function(n){return s(null,n.ok?null:"Error")}).catch(function(n){return s(null,n)});return}if(qr.default.XMLHttpRequest){var r=new qr.default.XMLHttpRequest;r.onreadystatechange=function(){if(r.readyState===4)return s(null,r.status!==200?"error":void 0)},r.open("POST",i),r.setRequestHeader("Content-Type","text/plain"),r.send(e);return}s()},ML=Ls,PL=["env_key","view_id","view_sequence_number","player_sequence_number","beacon_domain","player_playhead_time","viewer_time","mux_api_version","event","video_id","player_instance_id","player_error_code","player_error_message","player_error_context","player_error_severity","player_error_business_exception","view_playing_time_ms_cumulative","ad_playing_time_ms_cumulative"],OL=["adplay","adplaying","adpause","adfirstquartile","admidpoint","adthirdquartile","adended","adresponse","adrequest"],NL=["ad_id","ad_creative_id","ad_universal_id"],UL=["viewstart","error","ended","viewend"],FL=10*60*1e3,BL=function(){"use strict";function i(e,t){var s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};ft(this,i);var r,n,a,o,l,d,u,c,h,f,m,p;Y(this,"mux",void 0),Y(this,"envKey",void 0),Y(this,"options",void 0),Y(this,"eventQueue",void 0),Y(this,"sampleRate",void 0),Y(this,"disableCookies",void 0),Y(this,"respectDoNotTrack",void 0),Y(this,"previousBeaconData",void 0),Y(this,"lastEventTime",void 0),Y(this,"rateLimited",void 0),Y(this,"pageLevelData",void 0),Y(this,"viewerData",void 0),this.mux=e,this.envKey=t,this.options=s,this.previousBeaconData=null,this.lastEventTime=0,this.rateLimited=!1,this.eventQueue=new ML(bL(this.envKey,this.options));var g;this.sampleRate=(g=this.options.sampleRate)!==null&&g!==void 0?g:1;var v;this.disableCookies=(v=this.options.disableCookies)!==null&&v!==void 0?v:!1;var T;this.respectDoNotTrack=(T=this.options.respectDoNotTrack)!==null&&T!==void 0?T:!1,this.previousBeaconData=null,this.lastEventTime=0,this.rateLimited=!1,this.pageLevelData={mux_api_version:this.mux.API_VERSION,mux_embed:this.mux.NAME,mux_embed_version:this.mux.VERSION,viewer_application_name:(r=this.options.platform)===null||r===void 0?void 0:r.name,viewer_application_version:(n=this.options.platform)===null||n===void 0?void 0:n.version,viewer_application_engine:(a=this.options.platform)===null||a===void 0?void 0:a.layout,viewer_device_name:(o=this.options.platform)===null||o===void 0?void 0:o.product,viewer_device_category:"",viewer_device_manufacturer:(l=this.options.platform)===null||l===void 0?void 0:l.manufacturer,viewer_os_family:(u=this.options.platform)===null||u===void 0||(d=u.os)===null||d===void 0?void 0:d.family,viewer_os_architecture:(h=this.options.platform)===null||h===void 0||(c=h.os)===null||c===void 0?void 0:c.architecture,viewer_os_version:(m=this.options.platform)===null||m===void 0||(f=m.os)===null||f===void 0?void 0:f.version,viewer_connection_type:AL(),page_url:em.default===null||em.default===void 0||(p=em.default.location)===null||p===void 0?void 0:p.href},this.viewerData=this.disableCookies?{}:yL()}return Di(i,[{key:"send",value:function(e,t){if(!(!e||!(t!=null&&t.view_id))){if(this.respectDoNotTrack&&rm())return Ve.info("Not sending `"+e+"` because Do Not Track is enabled");if(!t||typeof t!="object")return Ve.error("A data object was expected in send() but was not provided");var s=this.disableCookies?{}:TL(),r=om(Fd({},this.pageLevelData,t,s,this.viewerData),{event:e,env_key:this.envKey});r.user_id&&(r.viewer_user_id=r.user_id,delete r.user_id);var n,a=((n=r.mux_sample_number)!==null&&n!==void 0?n:0)>=this.sampleRate,o=this._deduplicateBeaconData(e,r),l=am(o);if(this.lastEventTime=this.mux.utils.now(),a)return Ve.info("Not sending event due to sample rate restriction",e,r,l);if(this.envKey||Ve.info("Missing environment key (envKey) - beacons will be dropped if the video source is not a valid mux video URL",e,r,l),!this.rateLimited)if(Ve.info("Sending event",e,r,l),this.rateLimited=!this.eventQueue.queueEvent(e,l),this.mux.WINDOW_UNLOADING&&e==="viewend")this.eventQueue.destroy(!0);else{if(this.mux.WINDOW_HIDDEN&&e==="hb")this.eventQueue.flushEvents(!0);else if(UL.indexOf(e)>=0){if(e==="error"&&t.player_error_severity==="warning")return;this.eventQueue.flushEvents()}if(this.rateLimited)return r.event="eventrateexceeded",l=am(r),this.eventQueue.queueEvent(r.event,l),Ve.error("Beaconing disabled due to rate limit.")}}}},{key:"destroy",value:function(){this.eventQueue.destroy(!1)}},{key:"_deduplicateBeaconData",value:function(e,t){var s=this,r={},n=t.view_id;if(n==="-1"||e==="viewstart"||e==="viewend"||!this.previousBeaconData||this.mux.utils.now()-this.lastEventTime>=FL)r=Fd({},t),n&&(this.previousBeaconData=r),n&&e==="viewend"&&(this.previousBeaconData=null);else{var a=e.indexOf("request")===0;Object.entries(t).forEach(function(o){var l=Is(o,2),d=l[0],u=l[1];s.previousBeaconData&&(u!==s.previousBeaconData[d]||PL.indexOf(d)>-1||s.objectHasChanged(a,d,u,s.previousBeaconData[d])||s.eventRequiresKey(e,d))&&(r[d]=u,s.previousBeaconData[d]=u)})}return r}},{key:"objectHasChanged",value:function(e,t,s,r){return!e||t.indexOf("request_")!==0?!1:t==="request_response_headers"||typeof s!="object"||typeof r!="object"?!0:Object.keys(s||{}).length!==Object.keys(r||{}).length}},{key:"eventRequiresKey",value:function(e,t){return!!(e==="renditionchange"&&t.indexOf("video_source_")===0||NL.includes(t)&&OL.includes(e))}}]),i}(),$L=function i(e){"use strict";ft(this,i);var t=0,s=0,r=0,n=0,a=0,o=0,l=0,d=function(h,f){var m=f.request_start,p=f.request_response_start,g=f.request_response_end,v=f.request_bytes_loaded;n++;var T,y;if(p?(T=p-(m!=null?m:0),y=(g!=null?g:0)-p):y=(g!=null?g:0)-(m!=null?m:0),y>0&&v&&v>0){var b=v/y*8e3;a++,s+=v,r+=y,e.data.view_min_request_throughput=Math.min(e.data.view_min_request_throughput||1/0,b),e.data.view_average_request_throughput=s/r*8e3,e.data.view_request_count=n,T>0&&(t+=T,e.data.view_max_request_latency=Math.max(e.data.view_max_request_latency||0,T),e.data.view_average_request_latency=t/a)}},u=function(h,f){n++,o++,e.data.view_request_count=n,e.data.view_request_failed_count=o},c=function(h,f){n++,l++,e.data.view_request_count=n,e.data.view_request_canceled_count=l};e.on("requestcompleted",d),e.on("requestfailed",u),e.on("requestcanceled",c)},HL=$L,GL=60*60*1e3,KL=function i(e){"use strict";var t=this;ft(this,i),Y(this,"_lastEventTime",void 0),e.on("before*",function(s,r){var n=r.viewer_time,a=It.now(),o=t._lastEventTime;if(t._lastEventTime=a,o&&a-o>GL){var l=Object.keys(e.data).reduce(function(u,c){return c.indexOf("video_")===0?Object.assign(u,Y({},c,e.data[c])):u},{});e.mux.log.info("Received event after at least an hour inactivity, creating a new view");var d=e.playbackHeartbeat._playheadShouldBeProgressing;e._resetView(Object.assign({viewer_time:n},l)),e.playbackHeartbeat._playheadShouldBeProgressing=d,e.playbackHeartbeat._playheadShouldBeProgressing&&s.type!=="play"&&s.type!=="adbreakstart"&&(e.emit("play",{viewer_time:n}),s.type!=="playing"&&e.emit("playing",{viewer_time:n}))}})},VL=KL,WL=function i(e){"use strict";ft(this,i);var t=function(o){var l=qL(o),d=YL(o);if(l!=null&&!pE(l,n)&&a<=d){n=l,a=d;var u={video_cdn:l};e.emit("cdnchange",u)}},s=null,r=null,n=null,a=0;e.on("viewinit",function(){s=null,r=null,n=null,a=0}),e.on("beforecdnchange",function(o,l){var d=l==null?void 0:l.video_cdn;d&&(typeof l.video_previous_cdn=="undefined"||l.video_previous_cdn===null)&&(pE(d,r)?l.video_previous_cdn=s!=null?s:void 0:(l.video_previous_cdn=r!=null?r:void 0,s=r,r=d))}),e.on("requestcompleted",function(o,l){t(l)})};function pE(i,e){return(i==null?void 0:i.toLowerCase())===(e==null?void 0:e.toLowerCase())}function qL(i){var e;return i!=null&&i.request_type&&(i.request_type==="media"||i.request_type==="video")&&!((e=i.request_response_headers)===null||e===void 0)&&e["x-cdn"]?i.request_response_headers["x-cdn"]:i!=null&&i.video_cdn?i.video_cdn:null}function YL(i){return i!=null&&i.request_start?i.request_start:i!=null&&i.viewer_time?i.viewer_time:Date.now()}var jL=WL,zL=function(i){try{return JSON.parse(i),!0}catch{return!1}},QL=function i(e){"use strict";var t=this;ft(this,i),Y(this,"_emittingAutomaticEvent",!1),Y(this,"_hasInitialized",!1),Y(this,"_currentMode","standard"),e.on("viewstart",function(){t._hasInitialized||(t._hasInitialized=!0,t._currentMode=e.data.player_playback_mode||"standard",t._emittingAutomaticEvent=!0,e.emit("playbackmodechange",{player_playback_mode:t._currentMode,player_playback_mode_data:"{}"}),t._emittingAutomaticEvent=!1)}),e.on("viewend",function(){t._hasInitialized=!1}),e.on("playbackmodechange",function(s,r){t._emittingAutomaticEvent||(r.player_playback_mode_data?zL(r.player_playback_mode_data)||(e.mux.log.warn("Invalid JSON string for player_playback_mode_data"),r.player_playback_mode_data="{}"):r.player_playback_mode_data="{}",e.data.player_playback_mode_data=r.player_playback_mode_data,e.data.player_playback_mode=r.player_playback_mode,t._currentMode=r.player_playback_mode)})},XL=QL,ZL=function(){"use strict";function i(e){ft(this,i),Y(this,"pm",void 0),Y(this,"_currentRangeStart",void 0),Y(this,"_lastPlayheadTime",void 0),this.pm=e,this._currentRangeStart=null,this._lastPlayheadTime=null,e.on("playbackheartbeat",this._updatePlaybackRange.bind(this)),e.on("playbackheartbeatend",this._endPlaybackRange.bind(this))}return Di(i,[{key:"_updateLastRangeEnd",value:function(){var e=this.pm.data.video_playback_ranges;if(e&&e.length>0){var t=this.pm.data.player_playhead_time||0;e[e.length-1][1]=t}}},{key:"_updatePlaybackRange",value:function(){var e,t=this.pm.data.player_playhead_time||0;if(!(!this.pm.disableAdPlaybackRangeFiltering&&!((e=this.pm.adTracker)===null||e===void 0)&&e.isAdBreak&&this._lastPlayheadTime!==null&&t<this._lastPlayheadTime)){if(this._lastPlayheadTime!==null&&this._currentRangeStart!==null){var s=Math.abs(t-this._lastPlayheadTime);if(s>1e3){var r=this.pm.data.video_playback_ranges;r&&r.length>0&&(r[r.length-1][1]=this._lastPlayheadTime),this._currentRangeStart=null}}if(this._currentRangeStart===null){var n=this.pm.data.video_playback_ranges||[];n.length>0&&n[n.length-1][1]===t?this._currentRangeStart=n[n.length-1][0]:(this._currentRangeStart=t,n.push([t,t])),this.pm.data.video_playback_ranges=n}else this._updateLastRangeEnd();this._lastPlayheadTime=t}}},{key:"_endPlaybackRange",value:function(){this._currentRangeStart!==null&&(this._updateLastRangeEnd(),this._currentRangeStart=null,this._lastPlayheadTime=null)}}]),i}(),JL=ZL,eR=["viewstart","ended","loadstart","pause","play","playing","ratechange","waiting","adplay","adpause","adended","aderror","adplaying","adrequest","adresponse","adbreakstart","adbreakend","adfirstquartile","admidpoint","adthirdquartile","rebufferstart","rebufferend","seeked","error","hb","requestcompleted","requestfailed","requestcanceled","renditionchange","cdnchange","playbackmodechange"],tR=new Set(["requestcompleted","requestfailed","requestcanceled"]),iR=function(i){"use strict";II(t,i);var e=DI(t);function t(s,r,n){ft(this,t);var a;a=e.call(this),Y(ue(a),"pageLoadEndTime",void 0),Y(ue(a),"pageLoadInitTime",void 0),Y(ue(a),"_destroyed",void 0),Y(ue(a),"_heartBeatTimeout",void 0),Y(ue(a),"adTracker",void 0),Y(ue(a),"dashjs",void 0),Y(ue(a),"data",void 0),Y(ue(a),"disablePlayheadRebufferTracking",void 0),Y(ue(a),"disableRebufferTracking",void 0),Y(ue(a),"disableAdPlaybackRangeFiltering",void 0),Y(ue(a),"errorTracker",void 0),Y(ue(a),"errorTranslator",void 0),Y(ue(a),"emitTranslator",void 0),Y(ue(a),"getAdData",void 0),Y(ue(a),"getPlayheadTime",void 0),Y(ue(a),"getStateData",void 0),Y(ue(a),"stateDataTranslator",void 0),Y(ue(a),"hlsjs",void 0),Y(ue(a),"id",void 0),Y(ue(a),"longResumeTracker",void 0),Y(ue(a),"minimumRebufferDuration",void 0),Y(ue(a),"mux",void 0),Y(ue(a),"playbackEventDispatcher",void 0),Y(ue(a),"playbackHeartbeat",void 0),Y(ue(a),"playbackHeartbeatTime",void 0),Y(ue(a),"playheadTime",void 0),Y(ue(a),"seekingTracker",void 0),Y(ue(a),"sustainedRebufferThreshold",void 0),Y(ue(a),"watchTimeTracker",void 0),Y(ue(a),"currentFragmentPDT",void 0),Y(ue(a),"currentFragmentStart",void 0),a.pageLoadInitTime=Ud.navigationStart(),a.pageLoadEndTime=Ud.domContentLoadedEventEnd();var o={debug:!1,minimumRebufferDuration:250,sustainedRebufferThreshold:1e3,playbackHeartbeatTime:25,beaconDomain:"litix.io",sampleRate:1,disableCookies:!1,respectDoNotTrack:!1,disableRebufferTracking:!1,disablePlayheadRebufferTracking:!1,disableAdPlaybackRangeFiltering:!1,errorTranslator:function(h){return h},emitTranslator:function(){for(var h=arguments.length,f=new Array(h),m=0;m<h;m++)f[m]=arguments[m];return f},stateDataTranslator:function(h){return h}};a.mux=s,a.id=r,n!=null&&n.beaconDomain&&a.mux.log.warn("The `beaconDomain` setting has been deprecated in favor of `beaconCollectionDomain`. Please change your integration to use `beaconCollectionDomain` instead of `beaconDomain`."),n=Object.assign(o,n),n.data=n.data||{},n.data.property_key&&(n.data.env_key=n.data.property_key,delete n.data.property_key),Ve.level=n.debug?Wr.DEBUG:Wr.WARN,a.getPlayheadTime=n.getPlayheadTime,a.getStateData=n.getStateData||function(){return{}},a.getAdData=n.getAdData||function(){},a.minimumRebufferDuration=n.minimumRebufferDuration,a.sustainedRebufferThreshold=n.sustainedRebufferThreshold,a.playbackHeartbeatTime=n.playbackHeartbeatTime,a.disableRebufferTracking=n.disableRebufferTracking,a.disableRebufferTracking&&a.mux.log.warn("Disabling rebuffer tracking. This should only be used in specific circumstances as a last resort when your player is known to unreliably track rebuffering."),a.disablePlayheadRebufferTracking=n.disablePlayheadRebufferTracking,a.disableAdPlaybackRangeFiltering=n.disableAdPlaybackRangeFiltering,a.errorTranslator=n.errorTranslator,a.emitTranslator=n.emitTranslator,a.stateDataTranslator=n.stateDataTranslator,a.playbackEventDispatcher=new BL(s,n.data.env_key,n),a.data={player_instance_id:Do(),mux_sample_rate:n.sampleRate,beacon_domain:n.beaconCollectionDomain||n.beaconDomain},a.data.view_sequence_number=1,a.data.player_sequence_number=1;var l=function(){typeof this.data.view_start=="undefined"&&(this.data.view_start=this.mux.utils.now(),this.emit("viewstart"),this.emit("renditionchange"))}.bind(ue(a));if(a.on("viewinit",function(h,f){this._resetVideoData(),this._resetViewData(),this._resetErrorData(),this._updateStateData(),Object.assign(this.data,f),this._initializeViewData(),this.one("play",l),this.one("adbreakstart",l)}),a.on("videochange",function(h,f){this._resetView(f)}),a.on("programchange",function(h,f){this.data.player_is_paused&&this.mux.log.warn("The `programchange` event is intended to be used when the content changes mid playback without the video source changing, however the video is not currently playing. If the video source is changing please use the videochange event otherwise you will lose startup time information."),this._resetView(Object.assign(f,{view_program_changed:!0})),l(),this.emit("play"),this.emit("playing")}),a.on("fragmentchange",function(h,f){this.currentFragmentPDT=f.currentFragmentPDT,this.currentFragmentStart=f.currentFragmentStart}),a.on("destroy",a.destroy),typeof window!="undefined"&&typeof window.addEventListener=="function"&&typeof window.removeEventListener=="function"){var d=function(){var h=typeof a.data.view_start!="undefined";a.mux.WINDOW_HIDDEN=document.visibilityState==="hidden",h&&a.mux.WINDOW_HIDDEN&&(a.data.player_is_paused||a.emit("hb"))};window.addEventListener("visibilitychange",d,!1);var u=function(h){h.persisted||a.destroy()};window.addEventListener("pagehide",u,!1),a.on("destroy",function(){window.removeEventListener("visibilitychange",d),window.removeEventListener("pagehide",u)})}a.on("playerready",function(h,f){Object.assign(this.data,f)}),eR.forEach(function(h){a.on(h,function(f,m){h.indexOf("ad")!==0&&this._updateStateData(),Object.assign(this.data,m),this._sanitizeData()}),a.on("after"+h,function(){(h!=="error"||this.errorTracker.viewErrored)&&this.send(h)})}),a.on("viewend",function(h,f){Object.assign(a.data,f)});var c=function(h){var f=this.mux.utils.now();this.data.player_init_time&&(this.data.player_startup_time=f-this.data.player_init_time),this.pageLoadInitTime=this.data.page_load_init_time||this.pageLoadInitTime,this.pageLoadEndTime=this.data.page_load_end_time||this.pageLoadEndTime,!this.mux.PLAYER_TRACKED&&this.pageLoadInitTime&&(this.mux.PLAYER_TRACKED=!0,(this.data.player_init_time||this.pageLoadEndTime)&&(this.data.page_load_time=Math.min(this.data.player_init_time||1/0,this.pageLoadEndTime||1/0)-this.pageLoadInitTime)),this.send("playerready"),delete this.data.player_startup_time,delete this.data.page_load_time};return a.one("playerready",c),a.longResumeTracker=new VL(ue(a)),a.errorTracker=new jI(ue(a)),new gL(ue(a)),a.seekingTracker=new cL(ue(a)),a.playheadTime=new eL(ue(a)),a.playbackHeartbeat=new qI(ue(a)),new lL(ue(a)),a.watchTimeTracker=new QI(ue(a)),new ZI(ue(a)),new JL(ue(a)),a.adTracker=new mL(ue(a)),new rL(ue(a)),new iL(ue(a)),new aL(ue(a)),new HL(ue(a)),new jL(ue(a)),new XL(ue(a)),n.hlsjs&&a.addHLSJS(n),n.dashjs&&a.addDashJS(n),a.emit("viewinit",n.data),a}return Di(t,[{key:"emit",value:function(s,r){var n,a=Object.assign({viewer_time:this.mux.utils.now()},r),o=[s,a];if(this.emitTranslator)try{o=this.emitTranslator(s,a)}catch(l){this.mux.log.warn("Exception in emit translator callback.",l)}o!=null&&o.length&&(n=Od(qn(t.prototype),"emit",this)).call.apply(n,[this].concat(xi(o)))}},{key:"destroy",value:function(){this._destroyed||(this._destroyed=!0,typeof this.data.view_start!="undefined"&&(this.emit("viewend"),this.send("viewend")),this.playbackEventDispatcher.destroy(),this.removeHLSJS(),this.removeDashJS(),window.clearTimeout(this._heartBeatTimeout))}},{key:"send",value:function(s){if(this.data.view_id){var r=Object.assign({},this.data),n=["player_program_time","player_manifest_newest_program_time","player_live_edge_program_time","player_program_time","video_holdback","video_part_holdback","video_target_duration","video_part_target_duration"];if(r.video_source_is_live===void 0&&(r.player_source_duration===1/0||r.video_source_duration===1/0?r.video_source_is_live=!0:(r.player_source_duration>0||r.video_source_duration>0)&&(r.video_source_is_live=!1)),r.video_source_is_live||n.forEach(function(d){r[d]=void 0}),r.video_source_url=r.video_source_url||r.player_source_url,r.video_source_url){var a=Is(Co(r.video_source_url),2),o=a[0],l=a[1];r.video_source_domain=l,r.video_source_hostname=o}delete r.ad_request_id,r.video_playback_ranges&&(r.video_playback_range=JSON.stringify(r.video_playback_ranges.filter(function(d){return d[0]!==d[1]}).map(function(d){return"".concat(d[0],":").concat(d[1])})),delete r.video_playback_ranges),this.playbackEventDispatcher.send(s,r),this.data.view_sequence_number++,this.data.player_sequence_number++,tR.has(s)||this._restartHeartBeat(),s==="viewend"&&delete this.data.view_id}}},{key:"_resetView",value:function(s){this.emit("viewend"),this.send("viewend"),this.emit("viewinit",s)}},{key:"_updateStateData",value:function(){var s,r=this.getStateData();if(typeof this.stateDataTranslator=="function")try{r=this.stateDataTranslator(r)}catch(o){this.mux.log.warn("Exception in stateDataTranslator translator callback.",o)}if(!((s=this.data)===null||s===void 0)&&s.video_cdn&&r!=null&&r.video_cdn){var n=r.video_cdn,a=RI(r,["video_cdn"]);r=a}Object.assign(this.data,r),this.playheadTime._updatePlayheadTime(),this._sanitizeData()}},{key:"_sanitizeData",value:function(){var s=this,r=["player_width","player_height","video_source_width","video_source_height","player_playhead_time","video_source_bitrate"];r.forEach(function(a){var o=parseInt(s.data[a],10);s.data[a]=isNaN(o)?void 0:o});var n=["player_source_url","video_source_url"];n.forEach(function(a){if(s.data[a]){var o=s.data[a].toLowerCase();(o.indexOf("data:")===0||o.indexOf("blob:")===0)&&(s.data[a]="MSE style URL")}})}},{key:"_resetVideoData",value:function(){var s=this;Object.keys(this.data).forEach(function(r){r.indexOf("video_")===0&&delete s.data[r]})}},{key:"_resetViewData",value:function(){var s=this;Object.keys(this.data).forEach(function(r){r.indexOf("view_")===0&&delete s.data[r]}),this.data.view_sequence_number=1}},{key:"_resetErrorData",value:function(){delete this.data.player_error_code,delete this.data.player_error_message,delete this.data.player_error_context,delete this.data.player_error_severity,delete this.data.player_error_business_exception}},{key:"_initializeViewData",value:function(){var s=this,r=this.data.view_id=Do(),n=function(){r===s.data.view_id&&yt(s.data,"player_view_count",1)};this.data.player_is_paused?this.one("play",n):n()}},{key:"_restartHeartBeat",value:function(){var s=this;window.clearTimeout(this._heartBeatTimeout),this._heartBeatTimeout=window.setTimeout(function(){s.data.player_is_paused||s.emit("hb")},1e4)}},{key:"addHLSJS",value:function(s){if(!s.hlsjs){this.mux.log.warn("You must pass a valid hlsjs instance in order to track it.");return}if(this.hlsjs){this.mux.log.warn("An instance of HLS.js is already being monitored for this player.");return}this.hlsjs=s.hlsjs,NI(this.mux,this.id,s.hlsjs,{},s.Hls||window.Hls)}},{key:"removeHLSJS",value:function(){this.hlsjs&&(UI(this.hlsjs),this.hlsjs=void 0)}},{key:"addDashJS",value:function(s){if(!s.dashjs){this.mux.log.warn("You must pass a valid dashjs instance in order to track it.");return}if(this.dashjs){this.mux.log.warn("An instance of Dash.js is already being monitored for this player.");return}this.dashjs=s.dashjs,HI(this.mux,this.id,s.dashjs)}},{key:"removeDashJS",value:function(){this.dashjs&&(GI(this.dashjs),this.dashjs=void 0)}}]),t}(VI),sR=iR,Ro=mi(IE());function tm(){return Ro.default&&!!(Ro.default.fullscreenElement||Ro.default.webkitFullscreenElement||Ro.default.mozFullScreenElement||Ro.default.msFullscreenElement)}var rR=["loadstart","pause","play","playing","seeking","seeked","timeupdate","ratechange","stalled","waiting","error","ended"],nR={1:"MEDIA_ERR_ABORTED",2:"MEDIA_ERR_NETWORK",3:"MEDIA_ERR_DECODE",4:"MEDIA_ERR_SRC_NOT_SUPPORTED"};function aR(i,e,t){var s=Is(Nd(e),3),r=s[0],n=s[1],a=s[2],o=i.log,l=i.utils.getComputedStyle,d=i.utils.secondsToMs,u={automaticErrorTracking:!0};if(r){if(a!=="video"&&a!=="audio")return o.error("The element of `"+n+"` was not a media element.")}else return o.error("No element was found with the `"+n+"` query selector.");r.mux&&(r.mux.destroy(),delete r.mux,o.warn("Already monitoring this video element, replacing existing event listeners"));var c={getPlayheadTime:function(){return d(r.currentTime)},getStateData:function(){var f,m,p,g=((f=(m=this).getPlayheadTime)===null||f===void 0?void 0:f.call(m))||d(r.currentTime),v=this.hlsjs&&this.hlsjs.url,T=this.dashjs&&typeof this.dashjs.getSource=="function"&&this.dashjs.getSource(),y={player_is_paused:r.paused,player_width:parseInt(l(r,"width")),player_height:parseInt(l(r,"height")),player_autoplay_on:r.autoplay,player_preload_on:r.preload,player_language_code:r.lang,player_is_fullscreen:tm(),video_poster_url:r.poster,video_source_url:v||T||r.currentSrc,video_source_duration:d(r.duration),video_source_height:r.videoHeight,video_source_width:r.videoWidth,view_dropped_frame_count:r==null||(p=r.getVideoPlaybackQuality)===null||p===void 0?void 0:p.call(r).droppedVideoFrames};if(r.getStartDate&&g>0){var b=r.getStartDate();if(b&&typeof b.getTime=="function"&&b.getTime()){var A=b.getTime();if(y.player_program_time=A+g,r.seekable.length>0){var R=A+r.seekable.end(r.seekable.length-1);y.player_live_edge_program_time=R}}}return y}};t=Object.assign(u,t,c),t.data=Object.assign({player_software:"HTML5 Video Element",player_mux_plugin_name:"VideoElementMonitor",player_mux_plugin_version:i.VERSION},t.data),r.mux=r.mux||{},r.mux.deleted=!1,r.mux.emit=function(f,m){i.emit(n,f,m)},r.mux.updateData=function(f){r.mux.emit("hb",f)};var h=function(){o.error("The monitor for this video element has already been destroyed.")};r.mux.destroy=function(){Object.keys(r.mux.listeners).forEach(function(f){r.removeEventListener(f,r.mux.listeners[f],!1)}),delete r.mux.listeners,r.mux.fullscreenChangeListener&&(document.removeEventListener("fullscreenchange",r.mux.fullscreenChangeListener,!1),delete r.mux.fullscreenChangeListener),r.mux.destroy=h,r.mux.swapElement=h,r.mux.emit=h,r.mux.addHLSJS=h,r.mux.addDashJS=h,r.mux.removeHLSJS=h,r.mux.removeDashJS=h,r.mux.updateData=h,r.mux.setEmitTranslator=h,r.mux.setStateDataTranslator=h,r.mux.setGetPlayheadTime=h,r.mux.deleted=!0,i.emit(n,"destroy")},r.mux.swapElement=function(f){var m=Is(Nd(f),3),p=m[0],g=m[1],v=m[2];if(p){if(v!=="video"&&v!=="audio")return i.log.error("The element of `"+g+"` was not a media element.")}else return i.log.error("No element was found with the `"+g+"` query selector.");p.muxId=r.muxId,delete r.muxId,p.mux=p.mux||{},p.mux.listeners=Object.assign({},r.mux.listeners),delete r.mux.listeners,Object.keys(p.mux.listeners).forEach(function(T){r.removeEventListener(T,p.mux.listeners[T],!1),p.addEventListener(T,p.mux.listeners[T],!1)}),p.mux.fullscreenChangeListener=r.mux.fullscreenChangeListener,delete r.mux.fullscreenChangeListener,p.mux.swapElement=r.mux.swapElement,p.mux.destroy=r.mux.destroy,delete r.mux,r=p},r.mux.addHLSJS=function(f){i.addHLSJS(n,f)},r.mux.addDashJS=function(f){i.addDashJS(n,f)},r.mux.removeHLSJS=function(){i.removeHLSJS(n)},r.mux.removeDashJS=function(){i.removeDashJS(n)},r.mux.setEmitTranslator=function(f){i.setEmitTranslator(n,f)},r.mux.setStateDataTranslator=function(f){i.setStateDataTranslator(n,f)},r.mux.setGetPlayheadTime=function(f){f||(f=t.getPlayheadTime),i.setGetPlayheadTime(n,f)},i.init(n,t),i.emit(n,"playerready"),r.paused||(i.emit(n,"play"),r.readyState>2&&i.emit(n,"playing")),r.mux.listeners={},rR.forEach(function(f){f==="error"&&!t.automaticErrorTracking||(r.mux.listeners[f]=function(){var m={};if(f==="error"){if(!r.error||r.error.code===1)return;m.player_error_code=r.error.code,m.player_error_message=nR[r.error.code]||r.error.message}i.emit(n,f,m)},r.addEventListener(f,r.mux.listeners[f],!1))}),r.mux.listeners.enterpictureinpicture=function(){i.emit(n,"playbackmodechange",{player_playback_mode:"pip",player_playback_mode_data:"{}"})},r.mux.listeners.leavepictureinpicture=function(){var f=tm()?"fullscreen":"standard";i.emit(n,"playbackmodechange",{player_playback_mode:f,player_playback_mode_data:"{}"})},r.addEventListener("enterpictureinpicture",r.mux.listeners.enterpictureinpicture,!1),r.addEventListener("leavepictureinpicture",r.mux.listeners.leavepictureinpicture,!1),r.mux.fullscreenChangeListener=function(){var f=tm(),m=document.fullscreenElement;if(f&&(m===r||m!=null&&m.contains(r)))i.emit(n,"playbackmodechange",{player_playback_mode:"fullscreen",player_playback_mode_data:"{}"});else if(!f){var p=document.pictureInPictureElement===r,g=p?"pip":"standard";i.emit(n,"playbackmodechange",{player_playback_mode:g,player_playback_mode_data:"{}"})}},document.addEventListener("fullscreenchange",r.mux.fullscreenChangeListener,!1)}function oR(i,e,t,s){var r=s;if(i&&typeof i[e]=="function")try{r=i[e].apply(i,t)}catch(n){Ve.info("safeCall error",n)}return r}var ko=mi(ji()),Wn;ko.default&&ko.default.WeakMap&&(Wn=new WeakMap);function lR(i,e){if(!i||!e||!ko.default||typeof ko.default.getComputedStyle!="function")return"";var t;return Wn&&Wn.has(i)&&(t=Wn.get(i)),t||(t=ko.default.getComputedStyle(i,null),Wn&&Wn.set(i,t)),t.getPropertyValue(e)}function dR(i){return Math.floor(i*1e3)}var Vr={TARGET_DURATION:"#EXT-X-TARGETDURATION",PART_INF:"#EXT-X-PART-INF",SERVER_CONTROL:"#EXT-X-SERVER-CONTROL",INF:"#EXTINF",PROGRAM_DATE_TIME:"#EXT-X-PROGRAM-DATE-TIME",VERSION:"#EXT-X-VERSION",SESSION_DATA:"#EXT-X-SESSION-DATA"},$d=function(i){return this.buffer="",this.manifest={segments:[],serverControl:{},sessionData:{}},this.currentUri={},this.process(i),this.manifest};$d.prototype.process=function(i){var e;for(this.buffer+=i,e=this.buffer.indexOf(`
14
+ `):"");a("error",{player_error_code:T==null?void 0:T.code,player_error_message:T==null?void 0:T.message,player_error_context:D})};t.on("error",b),t._stopMuxMonitor=function(){t.off("manifestLoaded",o),t.off("initFragmentLoaded",c),t.off("mediaFragmentLoaded",f),t.off("qualityChangeRendered",g),t.off("error",b),t.off("fragmentLoadingAbandoned",v),delete t._stopMuxMonitor}},GI=function(i){i&&typeof i._stopMuxMonitor=="function"&&i._stopMuxMonitor()},cE=0,KI=function(){"use strict";function i(){ft(this,i),Y(this,"_listeners",void 0)}return Di(i,[{key:"on",value:function(e,t,s){return t._eventEmitterGuid=t._eventEmitterGuid||++cE,this._listeners=this._listeners||{},this._listeners[e]=this._listeners[e]||[],s&&(t=t.bind(s)),this._listeners[e].push(t),t}},{key:"off",value:function(e,t){var s=this._listeners&&this._listeners[e];s&&s.forEach(function(r,n){r._eventEmitterGuid===t._eventEmitterGuid&&s.splice(n,1)})}},{key:"one",value:function(e,t,s){var r=this;t._eventEmitterGuid=t._eventEmitterGuid||++cE;var n=function(){r.off(e,n),t.apply(s||this,arguments)};n._eventEmitterGuid=t._eventEmitterGuid,this.on(e,n)}},{key:"emit",value:function(e,t){var s=this;if(this._listeners){t=t||{};var r=this._listeners["before"+e]||[],n=this._listeners["before*"]||[],a=this._listeners[e]||[],o=this._listeners["after"+e]||[],l=function(d,u){d=d.slice(),d.forEach(function(c){c.call(s,{type:e},u)})};l(r,t),l(n,t),l(a,t),l(o,t)}}}]),i}(),VI=KI,Jf=mi(ji()),WI=function(){"use strict";function i(e){var t=this;ft(this,i),Y(this,"_playbackHeartbeatInterval",void 0),Y(this,"_playheadShouldBeProgressing",void 0),Y(this,"pm",void 0),this.pm=e,this._playbackHeartbeatInterval=null,this._playheadShouldBeProgressing=!1,e.on("playing",function(){t._playheadShouldBeProgressing=!0}),e.on("play",this._startPlaybackHeartbeatInterval.bind(this)),e.on("playing",this._startPlaybackHeartbeatInterval.bind(this)),e.on("adbreakstart",this._startPlaybackHeartbeatInterval.bind(this)),e.on("adplay",this._startPlaybackHeartbeatInterval.bind(this)),e.on("adplaying",this._startPlaybackHeartbeatInterval.bind(this)),e.on("devicewake",this._startPlaybackHeartbeatInterval.bind(this)),e.on("viewstart",this._startPlaybackHeartbeatInterval.bind(this)),e.on("rebufferstart",this._startPlaybackHeartbeatInterval.bind(this)),e.on("pause",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("ended",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("viewend",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("error",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("aderror",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("adpause",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("adended",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("adbreakend",this._stopPlaybackHeartbeatInterval.bind(this)),e.on("seeked",function(){e.data.player_is_paused?t._stopPlaybackHeartbeatInterval():t._startPlaybackHeartbeatInterval()}),e.on("timeupdate",function(){t._playbackHeartbeatInterval!==null&&e.emit("playbackheartbeat")}),e.on("devicesleep",function(s,r){t._playbackHeartbeatInterval!==null&&(Jf.default.clearInterval(t._playbackHeartbeatInterval),e.emit("playbackheartbeatend",{viewer_time:r.viewer_time}),t._playbackHeartbeatInterval=null)})}return Di(i,[{key:"_startPlaybackHeartbeatInterval",value:function(){var e=this;this._playbackHeartbeatInterval===null&&(this.pm.emit("playbackheartbeat"),this._playbackHeartbeatInterval=Jf.default.setInterval(function(){e.pm.emit("playbackheartbeat")},this.pm.playbackHeartbeatTime))}},{key:"_stopPlaybackHeartbeatInterval",value:function(){this._playheadShouldBeProgressing=!1,this._playbackHeartbeatInterval!==null&&(Jf.default.clearInterval(this._playbackHeartbeatInterval),this.pm.emit("playbackheartbeatend"),this._playbackHeartbeatInterval=null)}}]),i}(),qI=WI,YI=function i(e){"use strict";var t=this;ft(this,i),Y(this,"viewErrored",void 0),e.on("viewinit",function(){t.viewErrored=!1}),e.on("error",function(s,r){try{var n=e.errorTranslator({player_error_code:r.player_error_code,player_error_message:r.player_error_message,player_error_context:r.player_error_context,player_error_severity:r.player_error_severity,player_error_business_exception:r.player_error_business_exception});n&&(e.data.player_error_code=n.player_error_code||r.player_error_code,e.data.player_error_message=n.player_error_message||r.player_error_message,e.data.player_error_context=n.player_error_context||r.player_error_context,e.data.player_error_severity=n.player_error_severity||r.player_error_severity,e.data.player_error_business_exception=n.player_error_business_exception||r.player_error_business_exception,t.viewErrored=!0)}catch(a){e.mux.log.warn("Exception in error translator callback.",a),t.viewErrored=!0}}),e.on("aftererror",function(){var s,r,n,a,o;(s=e.data)===null||s===void 0||delete s.player_error_code,(r=e.data)===null||r===void 0||delete r.player_error_message,(n=e.data)===null||n===void 0||delete n.player_error_context,(a=e.data)===null||a===void 0||delete a.player_error_severity,(o=e.data)===null||o===void 0||delete o.player_error_business_exception})},jI=YI,zI=function(){"use strict";function i(e){ft(this,i),Y(this,"_watchTimeTrackerLastCheckedTime",void 0),Y(this,"pm",void 0),this.pm=e,this._watchTimeTrackerLastCheckedTime=null,e.on("playbackheartbeat",this._updateWatchTime.bind(this)),e.on("playbackheartbeatend",this._clearWatchTimeState.bind(this))}return Di(i,[{key:"_updateWatchTime",value:function(e,t){var s=t.viewer_time;this._watchTimeTrackerLastCheckedTime===null&&(this._watchTimeTrackerLastCheckedTime=s),yt(this.pm.data,"view_watch_time",s-this._watchTimeTrackerLastCheckedTime),this._watchTimeTrackerLastCheckedTime=s}},{key:"_clearWatchTimeState",value:function(e,t){this._updateWatchTime(e,t),this._watchTimeTrackerLastCheckedTime=null}}]),i}(),QI=zI,XI=function(){"use strict";function i(e){var t=this;ft(this,i),Y(this,"_playbackTimeTrackerLastPlayheadPosition",void 0),Y(this,"_lastTime",void 0),Y(this,"_isAdPlaying",void 0),Y(this,"_callbackUpdatePlaybackTime",void 0),Y(this,"pm",void 0),this.pm=e,this._playbackTimeTrackerLastPlayheadPosition=-1,this._lastTime=It.now(),this._isAdPlaying=!1,this._callbackUpdatePlaybackTime=null,e.on("viewinit",function(){t.pm.data.view_playing_time_ms_cumulative=0});var s=this._startPlaybackTimeTracking.bind(this);e.on("playing",s),e.on("adplaying",s),e.on("seeked",s),e.on("rebufferend",s);var r=this._stopPlaybackTimeTracking.bind(this);e.on("playbackheartbeatend",r),e.on("seeking",r),e.on("rebufferstart",r),e.on("adplaying",function(){t._isAdPlaying=!0}),e.on("adended",function(){t._isAdPlaying=!1}),e.on("adpause",function(){t._isAdPlaying=!1}),e.on("adbreakstart",function(){t._isAdPlaying=!1}),e.on("adbreakend",function(){t._isAdPlaying=!1}),e.on("adplay",function(){t._isAdPlaying=!1}),e.on("viewinit",function(){t._playbackTimeTrackerLastPlayheadPosition=-1,t._lastTime=It.now(),t._isAdPlaying=!1,t._callbackUpdatePlaybackTime=null})}return Di(i,[{key:"_startPlaybackTimeTracking",value:function(){this._callbackUpdatePlaybackTime===null&&(this._callbackUpdatePlaybackTime=this._updatePlaybackTime.bind(this),this._playbackTimeTrackerLastPlayheadPosition=this.pm.data.player_playhead_time,this._lastTime=It.now(),this.pm.on("playbackheartbeat",this._callbackUpdatePlaybackTime))}},{key:"_stopPlaybackTimeTracking",value:function(){this._callbackUpdatePlaybackTime&&(this._updatePlaybackTime(),this.pm.off("playbackheartbeat",this._callbackUpdatePlaybackTime),this._callbackUpdatePlaybackTime=null,this._playbackTimeTrackerLastPlayheadPosition=-1)}},{key:"_updatePlaybackTime",value:function(){var e=this.pm.data.player_playhead_time||0,t=It.now(),s=t-this._lastTime,r=-1;this._playbackTimeTrackerLastPlayheadPosition>=0&&e>this._playbackTimeTrackerLastPlayheadPosition?r=e-this._playbackTimeTrackerLastPlayheadPosition:this._isAdPlaying&&(r=s),r>0&&r<=1e3&&yt(this.pm.data,"view_content_playback_time",r),this._callbackUpdatePlaybackTime!==null&&s>0&&s<=1e3&&(this._isAdPlaying&&yt(this.pm.data,"ad_playing_time_ms_cumulative",s),yt(this.pm.data,"view_playing_time_ms_cumulative",s)),this._playbackTimeTrackerLastPlayheadPosition=e,this._lastTime=t}}]),i}(),ZI=XI,JI=function(){"use strict";function i(e){ft(this,i),Y(this,"pm",void 0),this.pm=e;var t=this._updatePlayheadTime.bind(this);e.on("playbackheartbeat",t),e.on("playbackheartbeatend",t),e.on("timeupdate",t),e.on("destroy",function(){e.off("timeupdate",t)})}return Di(i,[{key:"_updateMaxPlayheadPosition",value:function(){this.pm.data.view_max_playhead_position=typeof this.pm.data.view_max_playhead_position=="undefined"?this.pm.data.player_playhead_time:Math.max(this.pm.data.view_max_playhead_position,this.pm.data.player_playhead_time)}},{key:"_updatePlayheadTime",value:function(e,t){var s=this,r=function(){s.pm.currentFragmentPDT&&s.pm.currentFragmentStart&&(s.pm.data.player_program_time=s.pm.currentFragmentPDT+s.pm.data.player_playhead_time-s.pm.currentFragmentStart)};if(t&&t.player_playhead_time)this.pm.data.player_playhead_time=t.player_playhead_time,r(),this._updateMaxPlayheadPosition();else if(this.pm.getPlayheadTime){var n=this.pm.getPlayheadTime();typeof n!="undefined"&&(this.pm.data.player_playhead_time=n,r(),this._updateMaxPlayheadPosition())}}}]),i}(),eL=JI,hE=5*60*1e3,tL=function i(e){"use strict";if(ft(this,i),!e.disableRebufferTracking){var t,s=function(n,a){r(a),t=void 0},r=function(n){if(t){var a=n.viewer_time-t;yt(e.data,"view_rebuffer_duration",a),t=n.viewer_time,e.data.view_rebuffer_duration>hE&&(e.emit("viewend"),e.send("viewend"),e.mux.log.warn("Ending view after rebuffering for longer than ".concat(hE,"ms, future events will be ignored unless a programchange or videochange occurs.")))}e.data.view_watch_time>=0&&e.data.view_rebuffer_count>0&&(e.data.view_rebuffer_frequency=e.data.view_rebuffer_count/e.data.view_watch_time,e.data.view_rebuffer_percentage=e.data.view_rebuffer_duration/e.data.view_watch_time)};e.on("playbackheartbeat",function(n,a){return r(a)}),e.on("rebufferstart",function(n,a){t||(yt(e.data,"view_rebuffer_count",1),t=a.viewer_time,e.one("rebufferend",s))}),e.on("viewinit",function(){t=void 0,e.off("rebufferend",s)})}},iL=tL,sL=function(){"use strict";function i(e){var t=this;ft(this,i),Y(this,"_lastCheckedTime",void 0),Y(this,"_lastPlayheadTime",void 0),Y(this,"_lastPlayheadTimeUpdatedTime",void 0),Y(this,"_rebuffering",void 0),Y(this,"pm",void 0),this.pm=e,!(e.disableRebufferTracking||e.disablePlayheadRebufferTracking)&&(this._lastCheckedTime=null,this._lastPlayheadTime=null,this._lastPlayheadTimeUpdatedTime=null,e.on("playbackheartbeat",this._checkIfRebuffering.bind(this)),e.on("playbackheartbeatend",this._cleanupRebufferTracker.bind(this)),e.on("seeking",function(){t._cleanupRebufferTracker(null,{viewer_time:It.now()})}))}return Di(i,[{key:"_checkIfRebuffering",value:function(e,t){if(this.pm.seekingTracker.isSeeking||this.pm.adTracker.isAdBreak||!this.pm.playbackHeartbeat._playheadShouldBeProgressing){this._cleanupRebufferTracker(e,t);return}if(this._lastCheckedTime===null){this._prepareRebufferTrackerState(t.viewer_time);return}if(this._lastPlayheadTime!==this.pm.data.player_playhead_time){this._cleanupRebufferTracker(e,t,!0);return}var s=t.viewer_time-this._lastPlayheadTimeUpdatedTime;typeof this.pm.sustainedRebufferThreshold=="number"&&s>=this.pm.sustainedRebufferThreshold&&(this._rebuffering||(this._rebuffering=!0,this.pm.emit("rebufferstart",{viewer_time:this._lastPlayheadTimeUpdatedTime}))),this._lastCheckedTime=t.viewer_time}},{key:"_clearRebufferTrackerState",value:function(){this._lastCheckedTime=null,this._lastPlayheadTime=null,this._lastPlayheadTimeUpdatedTime=null}},{key:"_prepareRebufferTrackerState",value:function(e){this._lastCheckedTime=e,this._lastPlayheadTime=this.pm.data.player_playhead_time,this._lastPlayheadTimeUpdatedTime=e}},{key:"_cleanupRebufferTracker",value:function(e,t){var s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;if(this._rebuffering)this._rebuffering=!1,this.pm.emit("rebufferend",{viewer_time:t.viewer_time});else{if(this._lastCheckedTime===null)return;var r=this.pm.data.player_playhead_time-this._lastPlayheadTime,n=t.viewer_time-this._lastPlayheadTimeUpdatedTime;typeof this.pm.minimumRebufferDuration=="number"&&r>0&&n-r>this.pm.minimumRebufferDuration&&(this._lastCheckedTime=null,this.pm.emit("rebufferstart",{viewer_time:this._lastPlayheadTimeUpdatedTime}),this.pm.emit("rebufferend",{viewer_time:this._lastPlayheadTimeUpdatedTime+n-r}))}s?this._prepareRebufferTrackerState(t.viewer_time):this._clearRebufferTrackerState()}}]),i}(),rL=sL,nL=function(){"use strict";function i(e){var t=this;ft(this,i),Y(this,"pm",void 0),this.pm=e,e.on("viewinit",function(){var s=e.data,r=s.view_id;if(!s.view_program_changed){var n=function(a,o){var l=o.viewer_time;(a.type==="playing"&&typeof e.data.view_time_to_first_frame=="undefined"||a.type==="adplaying"&&(typeof e.data.view_time_to_first_frame=="undefined"||t._inPrerollPosition()))&&t.calculateTimeToFirstFrame(l||It.now(),r)};e.one("playing",n),e.one("adplaying",n),e.one("viewend",function(){e.off("playing",n),e.off("adplaying",n)})}})}return Di(i,[{key:"_inPrerollPosition",value:function(){return typeof this.pm.data.view_content_playback_time=="undefined"||this.pm.data.view_content_playback_time<=1e3}},{key:"calculateTimeToFirstFrame",value:function(e,t){t===this.pm.data.view_id&&(this.pm.watchTimeTracker._updateWatchTime(null,{viewer_time:e}),this.pm.data.view_time_to_first_frame=this.pm.data.view_watch_time,(this.pm.data.player_autoplay_on||this.pm.data.video_is_autoplay)&&this.pm.pageLoadInitTime&&(this.pm.data.view_aggregate_startup_time=this.pm.data.view_start+this.pm.data.view_watch_time-this.pm.pageLoadInitTime))}}]),i}(),aL=nL,oL=function i(e){"use strict";var t=this;ft(this,i),Y(this,"_lastPlayerHeight",void 0),Y(this,"_lastPlayerWidth",void 0),Y(this,"_lastPlayheadPosition",void 0),Y(this,"_lastSourceHeight",void 0),Y(this,"_lastSourceWidth",void 0),e.on("viewinit",function(){t._lastPlayheadPosition=-1});var s=["pause","rebufferstart","seeking","error","adbreakstart","hb","renditionchange","orientationchange","viewend","playbackmodechange"],r=["playing","hb","renditionchange","orientationchange","playbackmodechange"];s.forEach(function(n){e.on(n,function(){if(t._lastPlayheadPosition>=0&&e.data.player_playhead_time>=0&&t._lastPlayerWidth>=0&&t._lastSourceWidth>0&&t._lastPlayerHeight>=0&&t._lastSourceHeight>0){var a=e.data.player_playhead_time-t._lastPlayheadPosition;if(a<0){t._lastPlayheadPosition=-1;return}var o=Math.min(t._lastPlayerWidth/t._lastSourceWidth,t._lastPlayerHeight/t._lastSourceHeight),l=Math.max(0,o-1),d=Math.max(0,1-o);e.data.view_max_upscale_percentage=Math.max(e.data.view_max_upscale_percentage||0,l),e.data.view_max_downscale_percentage=Math.max(e.data.view_max_downscale_percentage||0,d),yt(e.data,"view_total_content_playback_time",a),yt(e.data,"view_total_upscaling",l*a),yt(e.data,"view_total_downscaling",d*a)}t._lastPlayheadPosition=-1})}),r.forEach(function(n){e.on(n,function(){t._lastPlayheadPosition=e.data.player_playhead_time,t._lastPlayerWidth=e.data.player_width,t._lastPlayerHeight=e.data.player_height,t._lastSourceWidth=e.data.video_source_width,t._lastSourceHeight=e.data.video_source_height})})},lL=oL,dL=2e3,uL=function i(e){"use strict";var t=this;ft(this,i),Y(this,"isSeeking",void 0),this.isSeeking=!1;var s=-1,r=function(){var n=It.now(),a=(e.data.viewer_time||n)-(s||n);yt(e.data,"view_seek_duration",a),e.data.view_max_seek_time=Math.max(e.data.view_max_seek_time||0,a),t.isSeeking=!1,s=-1};e.on("seeking",function(n,a){if(Object.assign(e.data,a),t.isSeeking&&a.viewer_time-s<=dL){s=a.viewer_time;return}t.isSeeking&&r(),t.isSeeking=!0,s=a.viewer_time,yt(e.data,"view_seek_count",1),e.send("seeking")}),e.on("seeked",function(){r()}),e.on("viewend",function(){t.isSeeking&&(r(),e.send("seeked")),t.isSeeking=!1,s=-1})},cL=uL,fE=function(i,e){i.push(e),i.sort(function(t,s){return t.viewer_time-s.viewer_time})},hL=["adbreakstart","adrequest","adresponse","adplay","adplaying","adpause","adended","adbreakend","aderror","adclicked","adskipped"],fL=function(){"use strict";function i(e){var t=this;ft(this,i),Y(this,"_adHasPlayed",void 0),Y(this,"_adRequests",void 0),Y(this,"_adResponses",void 0),Y(this,"_currentAdRequestNumber",void 0),Y(this,"_currentAdResponseNumber",void 0),Y(this,"_prerollPlayTime",void 0),Y(this,"_wouldBeNewAdPlay",void 0),Y(this,"isAdBreak",void 0),Y(this,"pm",void 0),this.pm=e,e.on("viewinit",function(){t.isAdBreak=!1,t._currentAdRequestNumber=0,t._currentAdResponseNumber=0,t._adRequests=[],t._adResponses=[],t._adHasPlayed=!1,t._wouldBeNewAdPlay=!0,t._prerollPlayTime=void 0}),hL.forEach(function(r){return e.on(r,t._updateAdData.bind(t))});var s=function(){t.isAdBreak=!1};e.on("adbreakstart",function(){t.isAdBreak=!0}),e.on("play",s),e.on("playing",s),e.on("viewend",s),e.on("adrequest",function(r,n){n=Object.assign({ad_request_id:"generatedAdRequestId"+t._currentAdRequestNumber++},n),fE(t._adRequests,n),yt(e.data,"view_ad_request_count"),t.inPrerollPosition()&&(e.data.view_preroll_requested=!0,t._adHasPlayed||yt(e.data,"view_preroll_request_count"))}),e.on("adresponse",function(r,n){n=Object.assign({ad_request_id:"generatedAdRequestId"+t._currentAdResponseNumber++},n),fE(t._adResponses,n);var a=t.findAdRequest(n.ad_request_id);a&&yt(e.data,"view_ad_request_time",Math.max(0,n.viewer_time-a.viewer_time))}),e.on("adplay",function(r,n){t._adHasPlayed=!0,t._wouldBeNewAdPlay&&(t._wouldBeNewAdPlay=!1,yt(e.data,"view_ad_played_count")),t.inPrerollPosition()&&!e.data.view_preroll_played&&(e.data.view_preroll_played=!0,t._adRequests.length>0&&(e.data.view_preroll_request_time=Math.max(0,n.viewer_time-t._adRequests[0].viewer_time)),e.data.view_start&&(e.data.view_startup_preroll_request_time=Math.max(0,n.viewer_time-e.data.view_start)),t._prerollPlayTime=n.viewer_time)}),e.on("adplaying",function(r,n){t.inPrerollPosition()&&typeof e.data.view_preroll_load_time=="undefined"&&typeof t._prerollPlayTime!="undefined"&&(e.data.view_preroll_load_time=n.viewer_time-t._prerollPlayTime,e.data.view_startup_preroll_load_time=n.viewer_time-t._prerollPlayTime)}),e.on("adclicked",function(r,n){t._wouldBeNewAdPlay||yt(e.data,"view_ad_clicked_count")}),e.on("adskipped",function(r,n){t._wouldBeNewAdPlay||yt(e.data,"view_ad_skipped_count")}),e.on("adended",function(){t._wouldBeNewAdPlay=!0}),e.on("aderror",function(){t._wouldBeNewAdPlay=!0})}return Di(i,[{key:"inPrerollPosition",value:function(){return typeof this.pm.data.view_content_playback_time=="undefined"||this.pm.data.view_content_playback_time<=1e3}},{key:"findAdRequest",value:function(e){for(var t=0;t<this._adRequests.length;t++)if(this._adRequests[t].ad_request_id===e)return this._adRequests[t]}},{key:"_updateAdData",value:function(e,t){if(this.inPrerollPosition()){if(!this.pm.data.view_preroll_ad_tag_hostname&&t.ad_tag_url){var s=Is(Co(t.ad_tag_url),2),r=s[0],n=s[1];this.pm.data.view_preroll_ad_tag_domain=n,this.pm.data.view_preroll_ad_tag_hostname=r}if(!this.pm.data.view_preroll_ad_asset_hostname&&t.ad_asset_url){var a=Is(Co(t.ad_asset_url),2),o=a[0],l=a[1];this.pm.data.view_preroll_ad_asset_domain=l,this.pm.data.view_preroll_ad_asset_hostname=o}this.pm.data.ad_type="preroll"}this.pm.data.ad_asset_url=t==null?void 0:t.ad_asset_url,this.pm.data.ad_tag_url=t==null?void 0:t.ad_tag_url,this.pm.data.ad_creative_id=t==null?void 0:t.ad_creative_id,this.pm.data.ad_id=t==null?void 0:t.ad_id,this.pm.data.ad_universal_id=t==null?void 0:t.ad_universal_id,t!=null&&t.ad_type&&(this.pm.data.ad_type=t==null?void 0:t.ad_type)}}]),i}(),mL=fL,pL=function i(e){"use strict";var t=this;ft(this,i),Y(this,"lastWallClockTime",void 0);var s=function(){t.lastWallClockTime=It.now(),e.on("before*",r)},r=function(n){var a=It.now(),o=t.lastWallClockTime;t.lastWallClockTime=a,a-o>3e4&&(e.emit("devicesleep",{viewer_time:o}),Object.assign(e.data,{viewer_time:o}),e.send("devicesleep"),e.emit("devicewake",{viewer_time:a}),Object.assign(e.data,{viewer_time:a}),e.send("devicewake"))};e.one("playbackheartbeat",s),e.on("playbackheartbeatend",function(){e.off("before*",r),e.one("playbackheartbeat",s)})},gL=pL,em=mi(ji()),DE=function(i){return i()}(function(){var i=function(){for(var t=0,s={};t<arguments.length;t++){var r=arguments[t];for(var n in r)s[n]=r[n]}return s};function e(t){function s(r,n,a){var o;if(typeof document!="undefined"){if(arguments.length>1){if(a=i({path:"/"},s.defaults,a),typeof a.expires=="number"){var l=new Date;l.setMilliseconds(l.getMilliseconds()+a.expires*864e5),a.expires=l}try{o=JSON.stringify(n),/^[\{\[]/.test(o)&&(n=o)}catch{}return t.write?n=t.write(n,r):n=encodeURIComponent(String(n)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent),r=encodeURIComponent(String(r)),r=r.replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent),r=r.replace(/[\(\)]/g,escape),document.cookie=[r,"=",n,a.expires?"; expires="+a.expires.toUTCString():"",a.path?"; path="+a.path:"",a.domain?"; domain="+a.domain:"",a.secure?"; secure":""].join("")}r||(o={});for(var d=document.cookie?document.cookie.split("; "):[],u=/(%[0-9A-Z]{2})+/g,c=0;c<d.length;c++){var h=d[c].split("="),f=h.slice(1).join("=");f.charAt(0)==='"'&&(f=f.slice(1,-1));try{var m=h[0].replace(u,decodeURIComponent);if(f=t.read?t.read(f,m):t(f,m)||f.replace(u,decodeURIComponent),this.json)try{f=JSON.parse(f)}catch{}if(r===m){o=f;break}r||(o[m]=f)}catch{}}return o}}return s.set=s,s.get=function(r){return s.call(s,r)},s.getJSON=function(){return s.apply({json:!0},[].slice.call(arguments))},s.defaults={},s.remove=function(r,n){s(r,"",i(n,{expires:-1}))},s.withConverter=e,s}return e(function(){})}),CE="muxData",vL=function(i){return Object.entries(i).map(function(e){var t=Is(e,2),s=t[0],r=t[1];return"".concat(s,"=").concat(r)}).join("&")},EL=function(i){return i.split("&").reduce(function(e,t){var s=Is(t.split("="),2),r=s[0],n=s[1],a=+n,o=n&&a==n?a:n;return e[r]=o,e},{})},wE=function(){var i;try{i=EL(DE.get(CE)||"")}catch{i={}}return i},ME=function(i){try{DE.set(CE,vL(i),{expires:365})}catch{}},yL=function(){var i=wE();return i.mux_viewer_id=i.mux_viewer_id||Do(),i.msn=i.msn||Math.random(),ME(i),{mux_viewer_id:i.mux_viewer_id,mux_sample_number:i.msn}},bL=function(){var i=wE(),e=It.now();return i.session_start&&(i.sst=i.session_start,delete i.session_start),i.session_id&&(i.sid=i.session_id,delete i.session_id),i.session_expires&&(i.sex=i.session_expires,delete i.session_expires),(!i.sex||i.sex<e)&&(i.sid=Do(),i.sst=e),i.sex=e+25*60*1e3,ME(i),{session_id:i.sid,session_start:i.sst,session_expires:i.sex}};function TL(i,e){var t=e.beaconCollectionDomain,s=e.beaconDomain;if(t)return"https://"+t;i=i||"inferred";var r=s||"litix.io";return i.match(/^[a-z0-9]+$/)?"https://"+i+"."+r:"https://img.litix.io/a.gif"}var _L=mi(ji()),PE=function(){var i;switch(OE()){case"cellular":i="cellular";break;case"ethernet":i="wired";break;case"wifi":i="wifi";break;case void 0:break;default:i="other"}return i},OE=function(){var i=_L.default.navigator,e=i&&(i.connection||i.mozConnection||i.webkitConnection);return e&&e.type};PE.getConnectionFromAPI=OE;var AL=PE,SL={a:"env",b:"beacon",c:"custom",d:"ad",e:"event",f:"experiment",i:"internal",m:"mux",n:"response",p:"player",q:"request",r:"retry",s:"session",t:"timestamp",u:"viewer",v:"video",w:"page",x:"view",y:"sub"},IL=NE(SL),LL={ad:"ad",af:"affiliate",ag:"aggregate",ap:"api",al:"application",ao:"audio",ar:"architecture",as:"asset",au:"autoplay",av:"average",bi:"bitrate",bn:"brand",br:"break",bw:"browser",by:"bytes",bz:"business",ca:"cached",cb:"cancel",cc:"codec",cd:"code",cg:"category",ch:"changed",ci:"client",ck:"clicked",cl:"canceled",cm:"cmcd",cn:"config",co:"count",ce:"counter",cp:"complete",cq:"creator",cr:"creative",cs:"captions",ct:"content",cu:"current",cv:"cumulative",cx:"connection",cz:"context",da:"data",dg:"downscaling",dm:"domain",dn:"cdn",do:"downscale",dr:"drm",dp:"dropped",du:"duration",dv:"device",dy:"dynamic",eb:"enabled",ec:"encoding",ed:"edge",en:"end",eg:"engine",em:"embed",er:"error",ep:"experiments",es:"errorcode",et:"errortext",ee:"event",ev:"events",ex:"expires",ez:"exception",fa:"failed",fi:"first",fm:"family",ft:"format",fp:"fps",fq:"frequency",fr:"frame",fs:"fullscreen",ha:"has",hb:"holdback",he:"headers",ho:"host",hn:"hostname",ht:"height",id:"id",ii:"init",in:"instance",ip:"ip",is:"is",ke:"key",la:"language",lb:"labeled",le:"level",li:"live",ld:"loaded",lo:"load",ls:"lists",lt:"latency",ma:"max",md:"media",me:"message",mf:"manifest",mi:"mime",ml:"midroll",mm:"min",mn:"manufacturer",mo:"model",mp:"mode",ms:"ms",mx:"mux",ne:"newest",nm:"name",no:"number",on:"on",or:"origin",os:"os",pa:"paused",pb:"playback",pd:"producer",pe:"percentage",pf:"played",pg:"program",ph:"playhead",pi:"plugin",pl:"preroll",pn:"playing",po:"poster",pp:"pip",pr:"preload",ps:"position",pt:"part",pv:"previous",py:"property",px:"pop",pz:"plan",ra:"rate",rd:"requested",re:"rebuffer",rf:"rendition",rg:"range",rm:"remote",ro:"ratio",rp:"response",rq:"request",rs:"requests",sa:"sample",sd:"skipped",se:"session",sh:"shift",sk:"seek",sm:"stream",so:"source",sq:"sequence",sr:"series",ss:"status",st:"start",su:"startup",sv:"server",sw:"software",sy:"severity",ta:"tag",tc:"tech",te:"text",tg:"target",th:"throughput",ti:"time",tl:"total",to:"to",tt:"title",ty:"type",ug:"upscaling",un:"universal",up:"upscale",ur:"url",us:"user",va:"variant",vd:"viewed",vi:"video",ve:"version",vw:"view",vr:"viewer",wd:"width",wa:"watch",wt:"waiting"},mE=NE(LL);function NE(i){var e={};for(var t in i)i.hasOwnProperty(t)&&(e[i[t]]=t);return e}function am(i){var e={},t={};return Object.keys(i).forEach(function(s){var r=!1;if(i.hasOwnProperty(s)&&i[s]!==void 0){var n=s.split("_"),a=n[0],o=IL[a];o||(Ve.info("Data key word `"+n[0]+"` not expected in "+s),o=a+"_"),n.splice(1).forEach(function(l){l==="url"&&(r=!0),mE[l]?o+=mE[l]:Number.isInteger(Number(l))?o+=l:(Ve.info("Data key word `"+l+"` not expected in "+s),o+="_"+l+"_")}),r?t[o]=i[s]:e[o]=i[s]}}),Object.assign(e,t)}var qr=mi(ji()),RL=mi(IE()),xL={maxBeaconSize:300,maxQueueLength:3600,baseTimeBetweenBeacons:1e4,maxPayloadKBSize:500},kL=56*1024,DL=["hb","requestcompleted","requestfailed","requestcanceled"],CL="https://img.litix.io",Ls=function(i){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this._beaconUrl=i||CL,this._eventQueue=[],this._postInFlight=!1,this._resendAfterPost=!1,this._failureCount=0,this._sendTimeout=!1,this._options=Object.assign({},xL,e)};Ls.prototype.queueEvent=function(i,e){var t=Object.assign({},e);return this._eventQueue.length<=this._options.maxQueueLength||i==="eventrateexceeded"?(this._eventQueue.push(t),this._sendTimeout||this._startBeaconSending(),this._eventQueue.length<=this._options.maxQueueLength):!1};Ls.prototype.flushEvents=function(){var i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;if(i&&this._eventQueue.length===1){this._eventQueue.pop();return}this._eventQueue.length&&this._sendBeaconQueue(),this._startBeaconSending()};Ls.prototype.destroy=function(){var i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;this.destroyed=!0,i?this._clearBeaconQueue():this.flushEvents(),qr.default.clearTimeout(this._sendTimeout)};Ls.prototype._clearBeaconQueue=function(){var i=this._eventQueue.length>this._options.maxBeaconSize?this._eventQueue.length-this._options.maxBeaconSize:0,e=this._eventQueue.slice(i);i>0&&Object.assign(e[e.length-1],am({mux_view_message:"event queue truncated"}));var t=this._createPayload(e);UE(this._beaconUrl,t,!0,function(){})};Ls.prototype._sendBeaconQueue=function(){var i=this;if(this._postInFlight){this._resendAfterPost=!0;return}var e=this._eventQueue.slice(0,this._options.maxBeaconSize);this._eventQueue=this._eventQueue.slice(this._options.maxBeaconSize),this._postInFlight=!0;var t=this._createPayload(e),s=It.now();UE(this._beaconUrl,t,!1,function(r,n){n?(i._eventQueue=e.concat(i._eventQueue),i._failureCount+=1,Ve.info("Error sending beacon: "+n)):i._failureCount=0,i._roundTripTime=It.now()-s,i._postInFlight=!1,i._resendAfterPost&&(i._resendAfterPost=!1,i._eventQueue.length>0&&i._sendBeaconQueue())})};Ls.prototype._getNextBeaconTime=function(){if(!this._failureCount)return this._options.baseTimeBetweenBeacons;var i=Math.pow(2,this._failureCount-1);return i=i*Math.random(),(1+i)*this._options.baseTimeBetweenBeacons};Ls.prototype._startBeaconSending=function(){var i=this;qr.default.clearTimeout(this._sendTimeout),!this.destroyed&&(this._sendTimeout=qr.default.setTimeout(function(){i._eventQueue.length&&i._sendBeaconQueue(),i._startBeaconSending()},this._getNextBeaconTime()))};Ls.prototype._createPayload=function(i){var e=this,t={transmission_timestamp:Math.round(It.now())};this._roundTripTime&&(t.rtt_ms=Math.round(this._roundTripTime));var s,r,n,a=function(){s=JSON.stringify({metadata:t,events:r||i}),n=s.length/1024},o=function(){return n<=e._options.maxPayloadKBSize};return a(),o()||(Ve.info("Payload size is too big ("+n+" kb). Removing unnecessary events."),r=i.filter(function(l){return DL.indexOf(l.e)===-1}),a()),o()||(Ve.info("Payload size still too big ("+n+" kb). Cropping fields.."),r.forEach(function(l){for(var d in l){var u=l[d],c=50*1024;typeof u=="string"&&u.length>c&&(l[d]=u.substring(0,c))}}),a()),s};var wL=typeof RL.default.exitPictureInPicture=="function"?function(i){return i.length<=kL}:function(i){return!1},UE=function(i,e,t,s){if(t&&navigator&&navigator.sendBeacon&&navigator.sendBeacon(i,e)){s();return}if(qr.default.fetch){qr.default.fetch(i,{method:"POST",body:e,headers:{"Content-Type":"text/plain"},keepalive:wL(e)}).then(function(n){return s(null,n.ok?null:"Error")}).catch(function(n){return s(null,n)});return}if(qr.default.XMLHttpRequest){var r=new qr.default.XMLHttpRequest;r.onreadystatechange=function(){if(r.readyState===4)return s(null,r.status!==200?"error":void 0)},r.open("POST",i),r.setRequestHeader("Content-Type","text/plain"),r.send(e);return}s()},ML=Ls,PL=["env_key","view_id","view_sequence_number","player_sequence_number","beacon_domain","player_playhead_time","viewer_time","mux_api_version","event","video_id","player_instance_id","player_error_code","player_error_message","player_error_context","player_error_severity","player_error_business_exception","view_playing_time_ms_cumulative","ad_playing_time_ms_cumulative"],OL=["adplay","adplaying","adpause","adfirstquartile","admidpoint","adthirdquartile","adended","adresponse","adrequest"],NL=["ad_id","ad_creative_id","ad_universal_id"],UL=["viewstart","error","ended","viewend"],FL=10*60*1e3,BL=function(){"use strict";function i(e,t){var s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};ft(this,i);var r,n,a,o,l,d,u,c,h,f,m,p;Y(this,"mux",void 0),Y(this,"envKey",void 0),Y(this,"options",void 0),Y(this,"eventQueue",void 0),Y(this,"sampleRate",void 0),Y(this,"disableCookies",void 0),Y(this,"respectDoNotTrack",void 0),Y(this,"previousBeaconData",void 0),Y(this,"lastEventTime",void 0),Y(this,"rateLimited",void 0),Y(this,"pageLevelData",void 0),Y(this,"viewerData",void 0),this.mux=e,this.envKey=t,this.options=s,this.previousBeaconData=null,this.lastEventTime=0,this.rateLimited=!1,this.eventQueue=new ML(TL(this.envKey,this.options));var g;this.sampleRate=(g=this.options.sampleRate)!==null&&g!==void 0?g:1;var v;this.disableCookies=(v=this.options.disableCookies)!==null&&v!==void 0?v:!1;var b;this.respectDoNotTrack=(b=this.options.respectDoNotTrack)!==null&&b!==void 0?b:!1,this.previousBeaconData=null,this.lastEventTime=0,this.rateLimited=!1,this.pageLevelData={mux_api_version:this.mux.API_VERSION,mux_embed:this.mux.NAME,mux_embed_version:this.mux.VERSION,viewer_application_name:(r=this.options.platform)===null||r===void 0?void 0:r.name,viewer_application_version:(n=this.options.platform)===null||n===void 0?void 0:n.version,viewer_application_engine:(a=this.options.platform)===null||a===void 0?void 0:a.layout,viewer_device_name:(o=this.options.platform)===null||o===void 0?void 0:o.product,viewer_device_category:"",viewer_device_manufacturer:(l=this.options.platform)===null||l===void 0?void 0:l.manufacturer,viewer_os_family:(u=this.options.platform)===null||u===void 0||(d=u.os)===null||d===void 0?void 0:d.family,viewer_os_architecture:(h=this.options.platform)===null||h===void 0||(c=h.os)===null||c===void 0?void 0:c.architecture,viewer_os_version:(m=this.options.platform)===null||m===void 0||(f=m.os)===null||f===void 0?void 0:f.version,viewer_connection_type:AL(),page_url:em.default===null||em.default===void 0||(p=em.default.location)===null||p===void 0?void 0:p.href},this.viewerData=this.disableCookies?{}:yL()}return Di(i,[{key:"send",value:function(e,t){if(!(!e||!(t!=null&&t.view_id))){if(this.respectDoNotTrack&&rm())return Ve.info("Not sending `"+e+"` because Do Not Track is enabled");if(!t||typeof t!="object")return Ve.error("A data object was expected in send() but was not provided");var s=this.disableCookies?{}:bL(),r=om(Fd({},this.pageLevelData,t,s,this.viewerData),{event:e,env_key:this.envKey});r.user_id&&(r.viewer_user_id=r.user_id,delete r.user_id);var n,a=((n=r.mux_sample_number)!==null&&n!==void 0?n:0)>=this.sampleRate,o=this._deduplicateBeaconData(e,r),l=am(o);if(this.lastEventTime=this.mux.utils.now(),a)return Ve.info("Not sending event due to sample rate restriction",e,r,l);if(this.envKey||Ve.info("Missing environment key (envKey) - beacons will be dropped if the video source is not a valid mux video URL",e,r,l),!this.rateLimited)if(Ve.info("Sending event",e,r,l),this.rateLimited=!this.eventQueue.queueEvent(e,l),this.mux.WINDOW_UNLOADING&&e==="viewend")this.eventQueue.destroy(!0);else{if(this.mux.WINDOW_HIDDEN&&e==="hb")this.eventQueue.flushEvents(!0);else if(UL.indexOf(e)>=0){if(e==="error"&&t.player_error_severity==="warning")return;this.eventQueue.flushEvents()}if(this.rateLimited)return r.event="eventrateexceeded",l=am(r),this.eventQueue.queueEvent(r.event,l),Ve.error("Beaconing disabled due to rate limit.")}}}},{key:"destroy",value:function(){this.eventQueue.destroy(!1)}},{key:"_deduplicateBeaconData",value:function(e,t){var s=this,r={},n=t.view_id;if(n==="-1"||e==="viewstart"||e==="viewend"||!this.previousBeaconData||this.mux.utils.now()-this.lastEventTime>=FL)r=Fd({},t),n&&(this.previousBeaconData=r),n&&e==="viewend"&&(this.previousBeaconData=null);else{var a=e.indexOf("request")===0;Object.entries(t).forEach(function(o){var l=Is(o,2),d=l[0],u=l[1];s.previousBeaconData&&(u!==s.previousBeaconData[d]||PL.indexOf(d)>-1||s.objectHasChanged(a,d,u,s.previousBeaconData[d])||s.eventRequiresKey(e,d))&&(r[d]=u,s.previousBeaconData[d]=u)})}return r}},{key:"objectHasChanged",value:function(e,t,s,r){return!e||t.indexOf("request_")!==0?!1:t==="request_response_headers"||typeof s!="object"||typeof r!="object"?!0:Object.keys(s||{}).length!==Object.keys(r||{}).length}},{key:"eventRequiresKey",value:function(e,t){return!!(e==="renditionchange"&&t.indexOf("video_source_")===0||NL.includes(t)&&OL.includes(e))}}]),i}(),$L=function i(e){"use strict";ft(this,i);var t=0,s=0,r=0,n=0,a=0,o=0,l=0,d=function(h,f){var m=f.request_start,p=f.request_response_start,g=f.request_response_end,v=f.request_bytes_loaded;n++;var b,y;if(p?(b=p-(m!=null?m:0),y=(g!=null?g:0)-p):y=(g!=null?g:0)-(m!=null?m:0),y>0&&v&&v>0){var T=v/y*8e3;a++,s+=v,r+=y,e.data.view_min_request_throughput=Math.min(e.data.view_min_request_throughput||1/0,T),e.data.view_average_request_throughput=s/r*8e3,e.data.view_request_count=n,b>0&&(t+=b,e.data.view_max_request_latency=Math.max(e.data.view_max_request_latency||0,b),e.data.view_average_request_latency=t/a)}},u=function(h,f){n++,o++,e.data.view_request_count=n,e.data.view_request_failed_count=o},c=function(h,f){n++,l++,e.data.view_request_count=n,e.data.view_request_canceled_count=l};e.on("requestcompleted",d),e.on("requestfailed",u),e.on("requestcanceled",c)},HL=$L,GL=60*60*1e3,KL=function i(e){"use strict";var t=this;ft(this,i),Y(this,"_lastEventTime",void 0),e.on("before*",function(s,r){var n=r.viewer_time,a=It.now(),o=t._lastEventTime;if(t._lastEventTime=a,o&&a-o>GL){var l=Object.keys(e.data).reduce(function(u,c){return c.indexOf("video_")===0?Object.assign(u,Y({},c,e.data[c])):u},{});e.mux.log.info("Received event after at least an hour inactivity, creating a new view");var d=e.playbackHeartbeat._playheadShouldBeProgressing;e._resetView(Object.assign({viewer_time:n},l)),e.playbackHeartbeat._playheadShouldBeProgressing=d,e.playbackHeartbeat._playheadShouldBeProgressing&&s.type!=="play"&&s.type!=="adbreakstart"&&(e.emit("play",{viewer_time:n}),s.type!=="playing"&&e.emit("playing",{viewer_time:n}))}})},VL=KL,WL=function i(e){"use strict";ft(this,i);var t=function(o){var l=qL(o),d=YL(o);if(l!=null&&!pE(l,n)&&a<=d){n=l,a=d;var u={video_cdn:l};e.emit("cdnchange",u)}},s=null,r=null,n=null,a=0;e.on("viewinit",function(){s=null,r=null,n=null,a=0}),e.on("beforecdnchange",function(o,l){var d=l==null?void 0:l.video_cdn;d&&(typeof l.video_previous_cdn=="undefined"||l.video_previous_cdn===null)&&(pE(d,r)?l.video_previous_cdn=s!=null?s:void 0:(l.video_previous_cdn=r!=null?r:void 0,s=r,r=d))}),e.on("requestcompleted",function(o,l){t(l)})};function pE(i,e){return(i==null?void 0:i.toLowerCase())===(e==null?void 0:e.toLowerCase())}function qL(i){var e;return i!=null&&i.request_type&&(i.request_type==="media"||i.request_type==="video")&&!((e=i.request_response_headers)===null||e===void 0)&&e["x-cdn"]?i.request_response_headers["x-cdn"]:i!=null&&i.video_cdn?i.video_cdn:null}function YL(i){return i!=null&&i.request_start?i.request_start:i!=null&&i.viewer_time?i.viewer_time:Date.now()}var jL=WL,zL=function(i){try{return JSON.parse(i),!0}catch{return!1}},QL=function i(e){"use strict";var t=this;ft(this,i),Y(this,"_emittingAutomaticEvent",!1),Y(this,"_hasInitialized",!1),Y(this,"_currentMode","standard"),e.on("viewstart",function(){t._hasInitialized||(t._hasInitialized=!0,t._currentMode=e.data.player_playback_mode||"standard",t._emittingAutomaticEvent=!0,e.emit("playbackmodechange",{player_playback_mode:t._currentMode,player_playback_mode_data:"{}"}),t._emittingAutomaticEvent=!1)}),e.on("viewend",function(){t._hasInitialized=!1}),e.on("playbackmodechange",function(s,r){t._emittingAutomaticEvent||(r.player_playback_mode_data?zL(r.player_playback_mode_data)||(e.mux.log.warn("Invalid JSON string for player_playback_mode_data"),r.player_playback_mode_data="{}"):r.player_playback_mode_data="{}",e.data.player_playback_mode_data=r.player_playback_mode_data,e.data.player_playback_mode=r.player_playback_mode,t._currentMode=r.player_playback_mode)})},XL=QL,ZL=function(){"use strict";function i(e){ft(this,i),Y(this,"pm",void 0),Y(this,"_currentRangeStart",void 0),Y(this,"_lastPlayheadTime",void 0),this.pm=e,this._currentRangeStart=null,this._lastPlayheadTime=null,e.on("playbackheartbeat",this._updatePlaybackRange.bind(this)),e.on("playbackheartbeatend",this._endPlaybackRange.bind(this))}return Di(i,[{key:"_updateLastRangeEnd",value:function(){var e=this.pm.data.video_playback_ranges;if(e&&e.length>0){var t=this.pm.data.player_playhead_time||0;e[e.length-1][1]=t}}},{key:"_updatePlaybackRange",value:function(){var e,t=this.pm.data.player_playhead_time||0;if(!(!this.pm.disableAdPlaybackRangeFiltering&&!((e=this.pm.adTracker)===null||e===void 0)&&e.isAdBreak&&this._lastPlayheadTime!==null&&t<this._lastPlayheadTime)){if(this._lastPlayheadTime!==null&&this._currentRangeStart!==null){var s=Math.abs(t-this._lastPlayheadTime);if(s>1e3){var r=this.pm.data.video_playback_ranges;r&&r.length>0&&(r[r.length-1][1]=this._lastPlayheadTime),this._currentRangeStart=null}}if(this._currentRangeStart===null){var n=this.pm.data.video_playback_ranges||[];n.length>0&&n[n.length-1][1]===t?this._currentRangeStart=n[n.length-1][0]:(this._currentRangeStart=t,n.push([t,t])),this.pm.data.video_playback_ranges=n}else this._updateLastRangeEnd();this._lastPlayheadTime=t}}},{key:"_endPlaybackRange",value:function(){this._currentRangeStart!==null&&(this._updateLastRangeEnd(),this._currentRangeStart=null,this._lastPlayheadTime=null)}}]),i}(),JL=ZL,eR=["viewstart","ended","loadstart","pause","play","playing","ratechange","waiting","adplay","adpause","adended","aderror","adplaying","adrequest","adresponse","adbreakstart","adbreakend","adfirstquartile","admidpoint","adthirdquartile","rebufferstart","rebufferend","seeked","error","hb","requestcompleted","requestfailed","requestcanceled","renditionchange","cdnchange","playbackmodechange"],tR=new Set(["requestcompleted","requestfailed","requestcanceled"]),iR=function(i){"use strict";II(t,i);var e=DI(t);function t(s,r,n){ft(this,t);var a;a=e.call(this),Y(ue(a),"pageLoadEndTime",void 0),Y(ue(a),"pageLoadInitTime",void 0),Y(ue(a),"_destroyed",void 0),Y(ue(a),"_heartBeatTimeout",void 0),Y(ue(a),"adTracker",void 0),Y(ue(a),"dashjs",void 0),Y(ue(a),"data",void 0),Y(ue(a),"disablePlayheadRebufferTracking",void 0),Y(ue(a),"disableRebufferTracking",void 0),Y(ue(a),"disableAdPlaybackRangeFiltering",void 0),Y(ue(a),"errorTracker",void 0),Y(ue(a),"errorTranslator",void 0),Y(ue(a),"emitTranslator",void 0),Y(ue(a),"getAdData",void 0),Y(ue(a),"getPlayheadTime",void 0),Y(ue(a),"getStateData",void 0),Y(ue(a),"stateDataTranslator",void 0),Y(ue(a),"hlsjs",void 0),Y(ue(a),"id",void 0),Y(ue(a),"longResumeTracker",void 0),Y(ue(a),"minimumRebufferDuration",void 0),Y(ue(a),"mux",void 0),Y(ue(a),"playbackEventDispatcher",void 0),Y(ue(a),"playbackHeartbeat",void 0),Y(ue(a),"playbackHeartbeatTime",void 0),Y(ue(a),"playheadTime",void 0),Y(ue(a),"seekingTracker",void 0),Y(ue(a),"sustainedRebufferThreshold",void 0),Y(ue(a),"watchTimeTracker",void 0),Y(ue(a),"currentFragmentPDT",void 0),Y(ue(a),"currentFragmentStart",void 0),a.pageLoadInitTime=Ud.navigationStart(),a.pageLoadEndTime=Ud.domContentLoadedEventEnd();var o={debug:!1,minimumRebufferDuration:250,sustainedRebufferThreshold:1e3,playbackHeartbeatTime:25,beaconDomain:"litix.io",sampleRate:1,disableCookies:!1,respectDoNotTrack:!1,disableRebufferTracking:!1,disablePlayheadRebufferTracking:!1,disableAdPlaybackRangeFiltering:!1,errorTranslator:function(h){return h},emitTranslator:function(){for(var h=arguments.length,f=new Array(h),m=0;m<h;m++)f[m]=arguments[m];return f},stateDataTranslator:function(h){return h}};a.mux=s,a.id=r,n!=null&&n.beaconDomain&&a.mux.log.warn("The `beaconDomain` setting has been deprecated in favor of `beaconCollectionDomain`. Please change your integration to use `beaconCollectionDomain` instead of `beaconDomain`."),n=Object.assign(o,n),n.data=n.data||{},n.data.property_key&&(n.data.env_key=n.data.property_key,delete n.data.property_key),Ve.level=n.debug?Wr.DEBUG:Wr.WARN,a.getPlayheadTime=n.getPlayheadTime,a.getStateData=n.getStateData||function(){return{}},a.getAdData=n.getAdData||function(){},a.minimumRebufferDuration=n.minimumRebufferDuration,a.sustainedRebufferThreshold=n.sustainedRebufferThreshold,a.playbackHeartbeatTime=n.playbackHeartbeatTime,a.disableRebufferTracking=n.disableRebufferTracking,a.disableRebufferTracking&&a.mux.log.warn("Disabling rebuffer tracking. This should only be used in specific circumstances as a last resort when your player is known to unreliably track rebuffering."),a.disablePlayheadRebufferTracking=n.disablePlayheadRebufferTracking,a.disableAdPlaybackRangeFiltering=n.disableAdPlaybackRangeFiltering,a.errorTranslator=n.errorTranslator,a.emitTranslator=n.emitTranslator,a.stateDataTranslator=n.stateDataTranslator,a.playbackEventDispatcher=new BL(s,n.data.env_key,n),a.data={player_instance_id:Do(),mux_sample_rate:n.sampleRate,beacon_domain:n.beaconCollectionDomain||n.beaconDomain},a.data.view_sequence_number=1,a.data.player_sequence_number=1;var l=function(){typeof this.data.view_start=="undefined"&&(this.data.view_start=this.mux.utils.now(),this.emit("viewstart"),this.emit("renditionchange"))}.bind(ue(a));if(a.on("viewinit",function(h,f){this._resetVideoData(),this._resetViewData(),this._resetErrorData(),this._updateStateData(),Object.assign(this.data,f),this._initializeViewData(),this.one("play",l),this.one("adbreakstart",l)}),a.on("videochange",function(h,f){this._resetView(f)}),a.on("programchange",function(h,f){this.data.player_is_paused&&this.mux.log.warn("The `programchange` event is intended to be used when the content changes mid playback without the video source changing, however the video is not currently playing. If the video source is changing please use the videochange event otherwise you will lose startup time information."),this._resetView(Object.assign(f,{view_program_changed:!0})),l(),this.emit("play"),this.emit("playing")}),a.on("fragmentchange",function(h,f){this.currentFragmentPDT=f.currentFragmentPDT,this.currentFragmentStart=f.currentFragmentStart}),a.on("destroy",a.destroy),typeof window!="undefined"&&typeof window.addEventListener=="function"&&typeof window.removeEventListener=="function"){var d=function(){var h=typeof a.data.view_start!="undefined";a.mux.WINDOW_HIDDEN=document.visibilityState==="hidden",h&&a.mux.WINDOW_HIDDEN&&(a.data.player_is_paused||a.emit("hb"))};window.addEventListener("visibilitychange",d,!1);var u=function(h){h.persisted||a.destroy()};window.addEventListener("pagehide",u,!1),a.on("destroy",function(){window.removeEventListener("visibilitychange",d),window.removeEventListener("pagehide",u)})}a.on("playerready",function(h,f){Object.assign(this.data,f)}),eR.forEach(function(h){a.on(h,function(f,m){h.indexOf("ad")!==0&&this._updateStateData(),Object.assign(this.data,m),this._sanitizeData()}),a.on("after"+h,function(){(h!=="error"||this.errorTracker.viewErrored)&&this.send(h)})}),a.on("viewend",function(h,f){Object.assign(a.data,f)});var c=function(h){var f=this.mux.utils.now();this.data.player_init_time&&(this.data.player_startup_time=f-this.data.player_init_time),this.pageLoadInitTime=this.data.page_load_init_time||this.pageLoadInitTime,this.pageLoadEndTime=this.data.page_load_end_time||this.pageLoadEndTime,!this.mux.PLAYER_TRACKED&&this.pageLoadInitTime&&(this.mux.PLAYER_TRACKED=!0,(this.data.player_init_time||this.pageLoadEndTime)&&(this.data.page_load_time=Math.min(this.data.player_init_time||1/0,this.pageLoadEndTime||1/0)-this.pageLoadInitTime)),this.send("playerready"),delete this.data.player_startup_time,delete this.data.page_load_time};return a.one("playerready",c),a.longResumeTracker=new VL(ue(a)),a.errorTracker=new jI(ue(a)),new gL(ue(a)),a.seekingTracker=new cL(ue(a)),a.playheadTime=new eL(ue(a)),a.playbackHeartbeat=new qI(ue(a)),new lL(ue(a)),a.watchTimeTracker=new QI(ue(a)),new ZI(ue(a)),new JL(ue(a)),a.adTracker=new mL(ue(a)),new rL(ue(a)),new iL(ue(a)),new aL(ue(a)),new HL(ue(a)),new jL(ue(a)),new XL(ue(a)),n.hlsjs&&a.addHLSJS(n),n.dashjs&&a.addDashJS(n),a.emit("viewinit",n.data),a}return Di(t,[{key:"emit",value:function(s,r){var n,a=Object.assign({viewer_time:this.mux.utils.now()},r),o=[s,a];if(this.emitTranslator)try{o=this.emitTranslator(s,a)}catch(l){this.mux.log.warn("Exception in emit translator callback.",l)}o!=null&&o.length&&(n=Od(qn(t.prototype),"emit",this)).call.apply(n,[this].concat(xi(o)))}},{key:"destroy",value:function(){this._destroyed||(this._destroyed=!0,typeof this.data.view_start!="undefined"&&(this.emit("viewend"),this.send("viewend")),this.playbackEventDispatcher.destroy(),this.removeHLSJS(),this.removeDashJS(),window.clearTimeout(this._heartBeatTimeout))}},{key:"send",value:function(s){if(this.data.view_id){var r=Object.assign({},this.data),n=["player_program_time","player_manifest_newest_program_time","player_live_edge_program_time","player_program_time","video_holdback","video_part_holdback","video_target_duration","video_part_target_duration"];if(r.video_source_is_live===void 0&&(r.player_source_duration===1/0||r.video_source_duration===1/0?r.video_source_is_live=!0:(r.player_source_duration>0||r.video_source_duration>0)&&(r.video_source_is_live=!1)),r.video_source_is_live||n.forEach(function(d){r[d]=void 0}),r.video_source_url=r.video_source_url||r.player_source_url,r.video_source_url){var a=Is(Co(r.video_source_url),2),o=a[0],l=a[1];r.video_source_domain=l,r.video_source_hostname=o}delete r.ad_request_id,r.video_playback_ranges&&(r.video_playback_range=JSON.stringify(r.video_playback_ranges.filter(function(d){return d[0]!==d[1]}).map(function(d){return"".concat(d[0],":").concat(d[1])})),delete r.video_playback_ranges),this.playbackEventDispatcher.send(s,r),this.data.view_sequence_number++,this.data.player_sequence_number++,tR.has(s)||this._restartHeartBeat(),s==="viewend"&&delete this.data.view_id}}},{key:"_resetView",value:function(s){this.emit("viewend"),this.send("viewend"),this.emit("viewinit",s)}},{key:"_updateStateData",value:function(){var s,r=this.getStateData();if(typeof this.stateDataTranslator=="function")try{r=this.stateDataTranslator(r)}catch(o){this.mux.log.warn("Exception in stateDataTranslator translator callback.",o)}if(!((s=this.data)===null||s===void 0)&&s.video_cdn&&r!=null&&r.video_cdn){var n=r.video_cdn,a=RI(r,["video_cdn"]);r=a}Object.assign(this.data,r),this.playheadTime._updatePlayheadTime(),this._sanitizeData()}},{key:"_sanitizeData",value:function(){var s=this,r=["player_width","player_height","video_source_width","video_source_height","player_playhead_time","video_source_bitrate"];r.forEach(function(a){var o=parseInt(s.data[a],10);s.data[a]=isNaN(o)?void 0:o});var n=["player_source_url","video_source_url"];n.forEach(function(a){if(s.data[a]){var o=s.data[a].toLowerCase();(o.indexOf("data:")===0||o.indexOf("blob:")===0)&&(s.data[a]="MSE style URL")}})}},{key:"_resetVideoData",value:function(){var s=this;Object.keys(this.data).forEach(function(r){r.indexOf("video_")===0&&delete s.data[r]})}},{key:"_resetViewData",value:function(){var s=this;Object.keys(this.data).forEach(function(r){r.indexOf("view_")===0&&delete s.data[r]}),this.data.view_sequence_number=1}},{key:"_resetErrorData",value:function(){delete this.data.player_error_code,delete this.data.player_error_message,delete this.data.player_error_context,delete this.data.player_error_severity,delete this.data.player_error_business_exception}},{key:"_initializeViewData",value:function(){var s=this,r=this.data.view_id=Do(),n=function(){r===s.data.view_id&&yt(s.data,"player_view_count",1)};this.data.player_is_paused?this.one("play",n):n()}},{key:"_restartHeartBeat",value:function(){var s=this;window.clearTimeout(this._heartBeatTimeout),this._heartBeatTimeout=window.setTimeout(function(){s.data.player_is_paused||s.emit("hb")},1e4)}},{key:"addHLSJS",value:function(s){if(!s.hlsjs){this.mux.log.warn("You must pass a valid hlsjs instance in order to track it.");return}if(this.hlsjs){this.mux.log.warn("An instance of HLS.js is already being monitored for this player.");return}this.hlsjs=s.hlsjs,NI(this.mux,this.id,s.hlsjs,{},s.Hls||window.Hls)}},{key:"removeHLSJS",value:function(){this.hlsjs&&(UI(this.hlsjs),this.hlsjs=void 0)}},{key:"addDashJS",value:function(s){if(!s.dashjs){this.mux.log.warn("You must pass a valid dashjs instance in order to track it.");return}if(this.dashjs){this.mux.log.warn("An instance of Dash.js is already being monitored for this player.");return}this.dashjs=s.dashjs,HI(this.mux,this.id,s.dashjs)}},{key:"removeDashJS",value:function(){this.dashjs&&(GI(this.dashjs),this.dashjs=void 0)}}]),t}(VI),sR=iR,Ro=mi(IE());function tm(){return Ro.default&&!!(Ro.default.fullscreenElement||Ro.default.webkitFullscreenElement||Ro.default.mozFullScreenElement||Ro.default.msFullscreenElement)}var rR=["loadstart","pause","play","playing","seeking","seeked","timeupdate","ratechange","stalled","waiting","error","ended"],nR={1:"MEDIA_ERR_ABORTED",2:"MEDIA_ERR_NETWORK",3:"MEDIA_ERR_DECODE",4:"MEDIA_ERR_SRC_NOT_SUPPORTED"};function aR(i,e,t){var s=Is(Nd(e),3),r=s[0],n=s[1],a=s[2],o=i.log,l=i.utils.getComputedStyle,d=i.utils.secondsToMs,u={automaticErrorTracking:!0};if(r){if(a!=="video"&&a!=="audio")return o.error("The element of `"+n+"` was not a media element.")}else return o.error("No element was found with the `"+n+"` query selector.");r.mux&&(r.mux.destroy(),delete r.mux,o.warn("Already monitoring this video element, replacing existing event listeners"));var c={getPlayheadTime:function(){return d(r.currentTime)},getStateData:function(){var f,m,p,g=((f=(m=this).getPlayheadTime)===null||f===void 0?void 0:f.call(m))||d(r.currentTime),v=this.hlsjs&&this.hlsjs.url,b=this.dashjs&&typeof this.dashjs.getSource=="function"&&this.dashjs.getSource(),y={player_is_paused:r.paused,player_width:parseInt(l(r,"width")),player_height:parseInt(l(r,"height")),player_autoplay_on:r.autoplay,player_preload_on:r.preload,player_language_code:r.lang,player_is_fullscreen:tm(),video_poster_url:r.poster,video_source_url:v||b||r.currentSrc,video_source_duration:d(r.duration),video_source_height:r.videoHeight,video_source_width:r.videoWidth,view_dropped_frame_count:r==null||(p=r.getVideoPlaybackQuality)===null||p===void 0?void 0:p.call(r).droppedVideoFrames};if(r.getStartDate&&g>0){var T=r.getStartDate();if(T&&typeof T.getTime=="function"&&T.getTime()){var A=T.getTime();if(y.player_program_time=A+g,r.seekable.length>0){var R=A+r.seekable.end(r.seekable.length-1);y.player_live_edge_program_time=R}}}return y}};t=Object.assign(u,t,c),t.data=Object.assign({player_software:"HTML5 Video Element",player_mux_plugin_name:"VideoElementMonitor",player_mux_plugin_version:i.VERSION},t.data),r.mux=r.mux||{},r.mux.deleted=!1,r.mux.emit=function(f,m){i.emit(n,f,m)},r.mux.updateData=function(f){r.mux.emit("hb",f)};var h=function(){o.error("The monitor for this video element has already been destroyed.")};r.mux.destroy=function(){Object.keys(r.mux.listeners).forEach(function(f){r.removeEventListener(f,r.mux.listeners[f],!1)}),delete r.mux.listeners,r.mux.fullscreenChangeListener&&(document.removeEventListener("fullscreenchange",r.mux.fullscreenChangeListener,!1),delete r.mux.fullscreenChangeListener),r.mux.destroy=h,r.mux.swapElement=h,r.mux.emit=h,r.mux.addHLSJS=h,r.mux.addDashJS=h,r.mux.removeHLSJS=h,r.mux.removeDashJS=h,r.mux.updateData=h,r.mux.setEmitTranslator=h,r.mux.setStateDataTranslator=h,r.mux.setGetPlayheadTime=h,r.mux.deleted=!0,i.emit(n,"destroy")},r.mux.swapElement=function(f){var m=Is(Nd(f),3),p=m[0],g=m[1],v=m[2];if(p){if(v!=="video"&&v!=="audio")return i.log.error("The element of `"+g+"` was not a media element.")}else return i.log.error("No element was found with the `"+g+"` query selector.");p.muxId=r.muxId,delete r.muxId,p.mux=p.mux||{},p.mux.listeners=Object.assign({},r.mux.listeners),delete r.mux.listeners,Object.keys(p.mux.listeners).forEach(function(b){r.removeEventListener(b,p.mux.listeners[b],!1),p.addEventListener(b,p.mux.listeners[b],!1)}),p.mux.fullscreenChangeListener=r.mux.fullscreenChangeListener,delete r.mux.fullscreenChangeListener,p.mux.swapElement=r.mux.swapElement,p.mux.destroy=r.mux.destroy,delete r.mux,r=p},r.mux.addHLSJS=function(f){i.addHLSJS(n,f)},r.mux.addDashJS=function(f){i.addDashJS(n,f)},r.mux.removeHLSJS=function(){i.removeHLSJS(n)},r.mux.removeDashJS=function(){i.removeDashJS(n)},r.mux.setEmitTranslator=function(f){i.setEmitTranslator(n,f)},r.mux.setStateDataTranslator=function(f){i.setStateDataTranslator(n,f)},r.mux.setGetPlayheadTime=function(f){f||(f=t.getPlayheadTime),i.setGetPlayheadTime(n,f)},i.init(n,t),i.emit(n,"playerready"),r.paused||(i.emit(n,"play"),r.readyState>2&&i.emit(n,"playing")),r.mux.listeners={},rR.forEach(function(f){f==="error"&&!t.automaticErrorTracking||(r.mux.listeners[f]=function(){var m={};if(f==="error"){if(!r.error||r.error.code===1)return;m.player_error_code=r.error.code,m.player_error_message=nR[r.error.code]||r.error.message}i.emit(n,f,m)},r.addEventListener(f,r.mux.listeners[f],!1))}),r.mux.listeners.enterpictureinpicture=function(){i.emit(n,"playbackmodechange",{player_playback_mode:"pip",player_playback_mode_data:"{}"})},r.mux.listeners.leavepictureinpicture=function(){var f=tm()?"fullscreen":"standard";i.emit(n,"playbackmodechange",{player_playback_mode:f,player_playback_mode_data:"{}"})},r.addEventListener("enterpictureinpicture",r.mux.listeners.enterpictureinpicture,!1),r.addEventListener("leavepictureinpicture",r.mux.listeners.leavepictureinpicture,!1),r.mux.fullscreenChangeListener=function(){var f=tm(),m=document.fullscreenElement;if(f&&(m===r||m!=null&&m.contains(r)))i.emit(n,"playbackmodechange",{player_playback_mode:"fullscreen",player_playback_mode_data:"{}"});else if(!f){var p=document.pictureInPictureElement===r,g=p?"pip":"standard";i.emit(n,"playbackmodechange",{player_playback_mode:g,player_playback_mode_data:"{}"})}},document.addEventListener("fullscreenchange",r.mux.fullscreenChangeListener,!1)}function oR(i,e,t,s){var r=s;if(i&&typeof i[e]=="function")try{r=i[e].apply(i,t)}catch(n){Ve.info("safeCall error",n)}return r}var ko=mi(ji()),Wn;ko.default&&ko.default.WeakMap&&(Wn=new WeakMap);function lR(i,e){if(!i||!e||!ko.default||typeof ko.default.getComputedStyle!="function")return"";var t;return Wn&&Wn.has(i)&&(t=Wn.get(i)),t||(t=ko.default.getComputedStyle(i,null),Wn&&Wn.set(i,t)),t.getPropertyValue(e)}function dR(i){return Math.floor(i*1e3)}var Vr={TARGET_DURATION:"#EXT-X-TARGETDURATION",PART_INF:"#EXT-X-PART-INF",SERVER_CONTROL:"#EXT-X-SERVER-CONTROL",INF:"#EXTINF",PROGRAM_DATE_TIME:"#EXT-X-PROGRAM-DATE-TIME",VERSION:"#EXT-X-VERSION",SESSION_DATA:"#EXT-X-SESSION-DATA"},$d=function(i){return this.buffer="",this.manifest={segments:[],serverControl:{},sessionData:{}},this.currentUri={},this.process(i),this.manifest};$d.prototype.process=function(i){var e;for(this.buffer+=i,e=this.buffer.indexOf(`
15
15
  `);e>-1;e=this.buffer.indexOf(`
16
- `))this.processLine(this.buffer.substring(0,e)),this.buffer=this.buffer.substring(e+1)};$d.prototype.processLine=function(i){var e=i.indexOf(":"),t=fR(i,e),s=t[0],r=t.length===2?dm(t[1]):void 0;if(s[0]!=="#")this.currentUri.uri=s,this.manifest.segments.push(this.currentUri),this.manifest.targetDuration&&!("duration"in this.currentUri)&&(this.currentUri.duration=this.manifest.targetDuration),this.currentUri={};else switch(s){case Vr.TARGET_DURATION:{if(!isFinite(r)||r<0)return;this.manifest.targetDuration=r,this.setHoldBack();break}case Vr.PART_INF:{im(this.manifest,t),this.manifest.partInf.partTarget&&(this.manifest.partTargetDuration=this.manifest.partInf.partTarget),this.setHoldBack();break}case Vr.SERVER_CONTROL:{im(this.manifest,t),this.setHoldBack();break}case Vr.INF:{r===0?this.currentUri.duration=.01:r>0&&(this.currentUri.duration=r);break}case Vr.PROGRAM_DATE_TIME:{var n=r,a=new Date(n);this.manifest.dateTimeString||(this.manifest.dateTimeString=n,this.manifest.dateTimeObject=a),this.currentUri.dateTimeString=n,this.currentUri.dateTimeObject=a;break}case Vr.VERSION:{im(this.manifest,t);break}case Vr.SESSION_DATA:{var o=mR(t[1]),l=kE(o);Object.assign(this.manifest.sessionData,l)}}};$d.prototype.setHoldBack=function(){var i=this.manifest,e=i.serverControl,t=i.targetDuration,s=i.partTargetDuration;if(e){var r="holdBack",n="partHoldBack",a=t&&t*3,o=s&&s*2;t&&!e.hasOwnProperty(r)&&(e[r]=a),a&&e[r]<a&&(e[r]=a),s&&!e.hasOwnProperty(n)&&(e[n]=s*3),s&&e[n]<o&&(e[n]=o)}};var im=function(i,e){var t=FE(e[0].replace("#EXT-X-","")),s;hR(e[1])?(s={},s=Object.assign(cR(e[1]),s)):s=dm(e[1]),i[t]=s},FE=function(i){return i.toLowerCase().replace(/-(\w)/g,function(e){return e[1].toUpperCase()})},dm=function(i){if(i.toLowerCase()==="yes"||i.toLowerCase()==="no")return i.toLowerCase()==="yes";var e=i.indexOf(":")!==-1?i:parseFloat(i);return isNaN(e)?i:e},uR=function(i){var e={},t=i.split("=");if(t.length>1){var s=FE(t[0]);e[s]=dm(t[1])}return e},cR=function(i){for(var e=i.split(","),t={},s=0;e.length>s;s++){var r=e[s],n=uR(r);t=Object.assign(n,t)}return t},hR=function(i){return i.indexOf("=")>-1},fR=function(i,e){return e===-1?[i]:[i.substring(0,e),i.substring(e+1)]},mR=function(i){var e={};if(i){var t=i.search(","),s=i.slice(0,t),r=i.slice(t+1),n=[s,r];return n.forEach(function(a,o){for(var l=a.replace(/['"]+/g,"").split("="),d=0;d<l.length;d++)l[d]==="DATA-ID"&&(e["DATA-ID"]=l[1-d]),l[d]==="VALUE"&&(e.VALUE=l[1-d])}),{data:e}}},pR=$d,gR={safeCall:oR,safeIncrement:yt,getComputedStyle:lR,secondsToMs:dR,assign:Object.assign,headersStringToObject:lm,cdnHeadersToRequestId:Bd,extractHostnameAndDomain:Co,extractHostname:ki,manifestParser:pR,generateShortID:RE,generateUUID:Do,now:It.now,findMediaElement:Nd},vR=gR,ER={PLAYER_READY:"playerready",VIEW_INIT:"viewinit",VIDEO_CHANGE:"videochange",PLAY:"play",PAUSE:"pause",PLAYING:"playing",TIME_UPDATE:"timeupdate",SEEKING:"seeking",SEEKED:"seeked",REBUFFER_START:"rebufferstart",REBUFFER_END:"rebufferend",ERROR:"error",ENDED:"ended",RENDITION_CHANGE:"renditionchange",ORIENTATION_CHANGE:"orientationchange",PLAYBACK_MODE_CHANGE:"playbackmodechange",AD_REQUEST:"adrequest",AD_RESPONSE:"adresponse",AD_BREAK_START:"adbreakstart",AD_PLAY:"adplay",AD_PLAYING:"adplaying",AD_PAUSE:"adpause",AD_FIRST_QUARTILE:"adfirstquartile",AD_MID_POINT:"admidpoint",AD_THIRD_QUARTILE:"adthirdquartile",AD_ENDED:"adended",AD_BREAK_END:"adbreakend",AD_ERROR:"aderror",REQUEST_COMPLETED:"requestcompleted",REQUEST_FAILED:"requestfailed",REQUEST_CANCELLED:"requestcanceled",HEARTBEAT:"hb",DESTROY:"destroy"},yR=ER,TR="mux-embed",bR="5.16.1",_R="2.1",ht={},er=function(i){var e=arguments;typeof i=="string"?er.hasOwnProperty(i)?xo.default.setTimeout(function(){e=Array.prototype.splice.call(e,1),er[i].apply(null,e)},0):Ve.warn("`"+i+"` is an unknown task"):typeof i=="function"?xo.default.setTimeout(function(){i(er)},0):Ve.warn("`"+i+"` is invalid.")},AR={loaded:It.now(),NAME:TR,VERSION:bR,API_VERSION:_R,PLAYER_TRACKED:!1,monitor:function(i,e){return aR(er,i,e)},destroyMonitor:function(i){var e=Is(Nd(i),1),t=e[0];t&&t.mux&&typeof t.mux.destroy=="function"?t.mux.destroy():Ve.error("A video element monitor for `"+i+"` has not been initialized via `mux.monitor`.")},addHLSJS:function(i,e){var t=Ri(i);ht[t]?ht[t].addHLSJS(e):Ve.error("A monitor for `"+t+"` has not been initialized.")},addDashJS:function(i,e){var t=Ri(i);ht[t]?ht[t].addDashJS(e):Ve.error("A monitor for `"+t+"` has not been initialized.")},removeHLSJS:function(i){var e=Ri(i);ht[e]?ht[e].removeHLSJS():Ve.error("A monitor for `"+e+"` has not been initialized.")},removeDashJS:function(i){var e=Ri(i);ht[e]?ht[e].removeDashJS():Ve.error("A monitor for `"+e+"` has not been initialized.")},init:function(i,e){rm()&&e&&e.respectDoNotTrack&&Ve.info("The browser's Do Not Track flag is enabled - Mux beaconing is disabled.");var t=Ri(i);ht[t]=new sR(er,t,e)},emit:function(i,e,t){var s=Ri(i);ht[s]?(ht[s].emit(e,t),e==="destroy"&&delete ht[s]):Ve.error("A monitor for `"+s+"` has not been initialized.")},updateData:function(i,e){var t=Ri(i);ht[t]?ht[t].emit("hb",e):Ve.error("A monitor for `"+t+"` has not been initialized.")},setEmitTranslator:function(i,e){var t=Ri(i);ht[t]?ht[t].emitTranslator=e:Ve.error("A monitor for `"+t+"` has not been initialized.")},setStateDataTranslator:function(i,e){var t=Ri(i);ht[t]?ht[t].stateDataTranslator=e:Ve.error("A monitor for `"+t+"` has not been initialized.")},setGetPlayheadTime:function(i,e){var t=Ri(i);ht[t]?ht[t].getPlayheadTime=e:Ve.error("A monitor for `"+t+"` has not been initialized.")},checkDoNotTrack:rm,log:Ve,utils:vR,events:yR,WINDOW_HIDDEN:!1,WINDOW_UNLOADING:!1};Object.assign(er,AR);typeof xo.default!="undefined"&&typeof xo.default.addEventListener=="function"&&xo.default.addEventListener("pagehide",function(i){i.persisted||(er.WINDOW_UNLOADING=!0)},!1);var Hd=er;var Q=Number.isFinite||function(i){return typeof i=="number"&&isFinite(i)},SR=Number.isSafeInteger||function(i){return typeof i=="number"&&Math.abs(i)<=IR},IR=Number.MAX_SAFE_INTEGER||9007199254740991,se=function(i){return i.NETWORK_ERROR="networkError",i.MEDIA_ERROR="mediaError",i.KEY_SYSTEM_ERROR="keySystemError",i.MUX_ERROR="muxError",i.OTHER_ERROR="otherError",i}({}),M=function(i){return i.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",i.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",i.KEY_SYSTEM_NO_SESSION="keySystemNoSession",i.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",i.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",i.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",i.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",i.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",i.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",i.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",i.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",i.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",i.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",i.MANIFEST_LOAD_ERROR="manifestLoadError",i.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",i.MANIFEST_PARSING_ERROR="manifestParsingError",i.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",i.LEVEL_EMPTY_ERROR="levelEmptyError",i.LEVEL_LOAD_ERROR="levelLoadError",i.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",i.LEVEL_PARSING_ERROR="levelParsingError",i.LEVEL_SWITCH_ERROR="levelSwitchError",i.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",i.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",i.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",i.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",i.FRAG_LOAD_ERROR="fragLoadError",i.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",i.FRAG_DECRYPT_ERROR="fragDecryptError",i.FRAG_PARSING_ERROR="fragParsingError",i.FRAG_GAP="fragGap",i.REMUX_ALLOC_ERROR="remuxAllocError",i.KEY_LOAD_ERROR="keyLoadError",i.KEY_LOAD_TIMEOUT="keyLoadTimeOut",i.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",i.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",i.BUFFER_APPEND_ERROR="bufferAppendError",i.BUFFER_APPENDING_ERROR="bufferAppendingError",i.BUFFER_STALLED_ERROR="bufferStalledError",i.BUFFER_FULL_ERROR="bufferFullError",i.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",i.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",i.ASSET_LIST_LOAD_ERROR="assetListLoadError",i.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",i.ASSET_LIST_PARSING_ERROR="assetListParsingError",i.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",i.INTERNAL_EXCEPTION="internalException",i.INTERNAL_ABORTED="aborted",i.ATTACH_MEDIA_ERROR="attachMediaError",i.UNKNOWN="unknown",i}({}),E=function(i){return i.MEDIA_ATTACHING="hlsMediaAttaching",i.MEDIA_ATTACHED="hlsMediaAttached",i.MEDIA_DETACHING="hlsMediaDetaching",i.MEDIA_DETACHED="hlsMediaDetached",i.MEDIA_ENDED="hlsMediaEnded",i.STALL_RESOLVED="hlsStallResolved",i.BUFFER_RESET="hlsBufferReset",i.BUFFER_CODECS="hlsBufferCodecs",i.BUFFER_CREATED="hlsBufferCreated",i.BUFFER_APPENDING="hlsBufferAppending",i.BUFFER_APPENDED="hlsBufferAppended",i.BUFFER_EOS="hlsBufferEos",i.BUFFERED_TO_END="hlsBufferedToEnd",i.BUFFER_FLUSHING="hlsBufferFlushing",i.BUFFER_FLUSHED="hlsBufferFlushed",i.MANIFEST_LOADING="hlsManifestLoading",i.MANIFEST_LOADED="hlsManifestLoaded",i.MANIFEST_PARSED="hlsManifestParsed",i.LEVEL_SWITCHING="hlsLevelSwitching",i.LEVEL_SWITCHED="hlsLevelSwitched",i.LEVEL_LOADING="hlsLevelLoading",i.LEVEL_LOADED="hlsLevelLoaded",i.LEVEL_UPDATED="hlsLevelUpdated",i.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",i.LEVELS_UPDATED="hlsLevelsUpdated",i.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",i.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",i.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",i.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",i.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",i.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",i.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",i.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",i.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",i.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",i.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",i.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",i.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",i.CUES_PARSED="hlsCuesParsed",i.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",i.INIT_PTS_FOUND="hlsInitPtsFound",i.FRAG_LOADING="hlsFragLoading",i.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",i.FRAG_LOADED="hlsFragLoaded",i.FRAG_DECRYPTED="hlsFragDecrypted",i.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",i.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",i.FRAG_PARSING_METADATA="hlsFragParsingMetadata",i.FRAG_PARSED="hlsFragParsed",i.FRAG_BUFFERED="hlsFragBuffered",i.FRAG_CHANGED="hlsFragChanged",i.FPS_DROP="hlsFpsDrop",i.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",i.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",i.ERROR="hlsError",i.DESTROYING="hlsDestroying",i.KEY_LOADING="hlsKeyLoading",i.KEY_LOADED="hlsKeyLoaded",i.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",i.BACK_BUFFER_REACHED="hlsBackBufferReached",i.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",i.ASSET_LIST_LOADING="hlsAssetListLoading",i.ASSET_LIST_LOADED="hlsAssetListLoaded",i.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",i.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",i.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",i.INTERSTITIAL_STARTED="hlsInterstitialStarted",i.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",i.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",i.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",i.INTERSTITIAL_ENDED="hlsInterstitialEnded",i.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",i.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",i.EVENT_CUE_ENTER="hlsEventCueEnter",i}({}),Le={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},J={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"},sr=class{constructor(e,t=0,s=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_=s}sample(e,t){let s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*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_}},wm=class{constructor(e,t,s,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_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new sr(e),this.fast_=new sr(t),this.defaultTTFB_=r,this.ttfb_=new sr(e)}update(e,t){let{slow_:s,fast_:r,ttfb_:n}=this;s.halfLife!==e&&(this.slow_=new sr(e,s.getEstimate(),s.getTotalWeight())),r.halfLife!==t&&(this.fast_=new sr(t,r.getEstimate(),r.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new sr(e,n.getEstimate(),n.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);let s=8*t,r=e/1e3,n=s/r;this.fast_.sample(r,n),this.slow_.sample(r,n)}sampleTTFB(e){let t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}};function LR(i,e,t){return(e=xR(e))in i?Object.defineProperty(i,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):i[e]=t,i}function $e(){return $e=Object.assign?Object.assign.bind():function(i){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var s in t)({}).hasOwnProperty.call(t,s)&&(i[s]=t[s])}return i},$e.apply(null,arguments)}function BE(i,e){var t=Object.keys(i);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(i);e&&(s=s.filter(function(r){return Object.getOwnPropertyDescriptor(i,r).enumerable})),t.push.apply(t,s)}return t}function Fe(i){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?BE(Object(t),!0).forEach(function(s){LR(i,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(i,Object.getOwnPropertyDescriptors(t)):BE(Object(t)).forEach(function(s){Object.defineProperty(i,s,Object.getOwnPropertyDescriptor(t,s))})}return i}function RR(i,e){if(typeof i!="object"||!i)return i;var t=i[Symbol.toPrimitive];if(t!==void 0){var s=t.call(i,e);if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(i)}function xR(i){var e=RR(i,"string");return typeof e=="symbol"?e:e+""}var Qt=class{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;let s=`[${e}]:`;this.trace=rr,this.debug=t.debug.bind(null,s),this.log=t.log.bind(null,s),this.warn=t.warn.bind(null,s),this.info=t.info.bind(null,s),this.error=t.error.bind(null,s)}},rr=function(){},kR={trace:rr,debug:rr,log:rr,warn:rr,info:rr,error:rr};function Mm(){return $e({},kR)}function DR(i,e){let t=self.console[i];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${i}] >`):rr}function $E(i,e,t){return e[i]?e[i].bind(e):DR(i,t)}var Pm=Mm();function CR(i,e,t){let s=Mm();if(typeof console=="object"&&i===!0||typeof i=="object"){let r=["debug","log","info","warn","error"];r.forEach(n=>{s[n]=$E(n,i,t)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.6.15`)}catch{return Mm()}r.forEach(n=>{Pm[n]=$E(n,i)})}else $e(Pm,s);return s}var Be=Pm;function nr(i=!0){return typeof self=="undefined"?void 0:(i||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function wR(i){return typeof self!="undefined"&&i===self.ManagedMediaSource}function Xy(i,e){let t=Object.keys(i),s=Object.keys(e),r=t.length,n=s.length;return!r||!n||r===n&&!t.some(a=>s.indexOf(a)===-1)}function li(i,e=!1){if(typeof TextDecoder!="undefined"){let d=new TextDecoder("utf-8").decode(i);if(e){let u=d.indexOf("\0");return u!==-1?d.substring(0,u):d}return d.replace(/\0/g,"")}let t=i.length,s,r,n,a="",o=0;for(;o<t;){if(s=i[o++],s===0&&e)return a;if(s===0||s===3)continue;switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(s);break;case 12:case 13:r=i[o++],a+=String.fromCharCode((s&31)<<6|r&63);break;case 14:r=i[o++],n=i[o++],a+=String.fromCharCode((s&15)<<12|(r&63)<<6|(n&63)<<0);break}}return a}function Dt(i){let e="";for(let t=0;t<i.length;t++){let s=i[t].toString(16);s.length<2&&(s="0"+s),e+=s}return e}function Zy(i){return Uint8Array.from(i.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function MR(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var um={exports:{}},HE;function PR(){return HE||(HE=1,function(i,e){(function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,d,u){if(u=u||{},l=l.trim(),d=d.trim(),!d){if(!u.alwaysNormalize)return l;var c=o.parseURL(l);if(!c)throw new Error("Error trying to parse base URL.");return c.path=o.normalizePath(c.path),o.buildURLFromParts(c)}var h=o.parseURL(d);if(!h)throw new Error("Error trying to parse relative URL.");if(h.scheme)return u.alwaysNormalize?(h.path=o.normalizePath(h.path),o.buildURLFromParts(h)):d;var f=o.parseURL(l);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var m=r.exec(f.path);f.netLoc=m[1],f.path=m[2]}f.netLoc&&!f.path&&(f.path="/");var p={scheme:f.scheme,netLoc:h.netLoc,path:null,params:h.params,query:h.query,fragment:h.fragment};if(!h.netLoc&&(p.netLoc=f.netLoc,h.path[0]!=="/"))if(!h.path)p.path=f.path,h.params||(p.params=f.params,h.query||(p.query=f.query));else{var g=f.path,v=g.substring(0,g.lastIndexOf("/")+1)+h.path;p.path=o.normalizePath(v)}return p.path===null&&(p.path=u.alwaysNormalize?o.normalizePath(h.path):h.path),o.buildURLFromParts(p)},parseURL:function(l){var d=s.exec(l);return d?{scheme:d[1]||"",netLoc:d[2]||"",path:d[3]||"",params:d[4]||"",query:d[5]||"",fragment:d[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(n,"");l.length!==(l=l.replace(a,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};i.exports=o})()}(um)),um.exports}var Qp=PR(),Fo=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}}},We={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"},du=class{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,OR(this,"stats")}setByteRange(e,t){let s=e.split("@",2),r;s.length===1?r=(t==null?void 0:t.byteRangeEndOffset)||0:r=parseInt(s[1]),this._byteRange=[r,parseInt(s[0])+r]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[We.AUDIO]:null,[We.VIDEO]:null,[We.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new Fo),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Qp.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){let{elementaryStreams:e}=this;e[We.AUDIO]=null,e[We.VIDEO]=null,e[We.AUDIOVIDEO]=null}};function at(i){return i.sn!=="initSegment"}var Po=class extends du{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){let e=this.stats.total;if(e)return e}if(this.byteRange.length){let e=this.byteRange[0],t=this.byteRange[1];if(Q(e)&&Q(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;let{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){let s=Object.keys(t);if(s.length===1){let r=this._decryptdata=t[s[0]]||null;r&&(this._decryptdata=r.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;let e=Q(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;let s=Object.keys(this.levelkeys),r=s.length;if(r>1||r===1&&(t=this.levelkeys[s[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!Q(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return at(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){let t=this.levelkeys;if(t){var s;let r=t[e];r&&!((s=this._decryptdata)!=null&&s.keyId)&&(this._decryptdata=r.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,s,r,n,a=!1){let{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:t,endPTS:s,startDTS:r,endDTS:n,partial:a};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,s),l.startDTS=Math.min(l.startDTS,r),l.endDTS=Math.max(l.endDTS,n)}},Om=class extends du{constructor(e,t,s,r,n){super(s),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.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=r;let a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,n),n&&(this.fragOffset=n.fragOffset+n.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){let{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}};function Jy(i,e){let t=Object.getPrototypeOf(i);if(t){let s=Object.getOwnPropertyDescriptor(t,e);return s||Jy(t,e)}}function OR(i,e){let t=Jy(i,e);t&&(t.enumerable=!0,Object.defineProperty(i,e,t))}var GE=Math.pow(2,32)-1,NR=[].push,eT={video:1,audio:2,id3:3,text:4};function Tt(i){return String.fromCharCode.apply(null,i)}function tT(i,e){let t=i[e]<<8|i[e+1];return t<0?65536+t:t}function fe(i,e){let t=iT(i,e);return t<0?4294967296+t:t}function KE(i,e){let t=fe(i,e);return t*=Math.pow(2,32),t+=fe(i,e+4),t}function iT(i,e){return i[e]<<24|i[e+1]<<16|i[e+2]<<8|i[e+3]}function UR(i){let e=i.byteLength;for(let t=0;t<e;){let s=fe(i,t);if(s>8&&i[t+4]===109&&i[t+5]===111&&i[t+6]===111&&i[t+7]===102)return!0;t=s>1?t+s:e}return!1}function be(i,e){let t=[];if(!e.length)return t;let s=i.byteLength;for(let r=0;r<s;){let n=fe(i,r),a=Tt(i.subarray(r+4,r+8)),o=n>1?r+n:s;if(a===e[0])if(e.length===1)t.push(i.subarray(r+8,o));else{let l=be(i.subarray(r+8,o),e.slice(1));l.length&&NR.apply(t,l)}r=o}return t}function FR(i){let e=[],t=i[0],s=8,r=fe(i,s);s+=4;let n=0,a=0;t===0?(n=fe(i,s),a=fe(i,s+4),s+=8):(n=KE(i,s),a=KE(i,s+8),s+=16),s+=2;let o=i.length+a,l=tT(i,s);s+=2;for(let d=0;d<l;d++){let u=s,c=fe(i,u);u+=4;let h=c&2147483647;if((c&2147483648)>>>31===1)return Be.warn("SIDX has hierarchical references (not supported)"),null;let m=fe(i,u);u+=4,e.push({referenceSize:h,subsegmentDuration:m,info:{duration:m/r,start:o,end:o+h-1}}),o+=h,u+=4,s=u}return{earliestPresentationTime:n,timescale:r,version:t,referencesCount:l,references:e}}function sT(i){let e=[],t=be(i,["moov","trak"]);for(let r=0;r<t.length;r++){let n=t[r],a=be(n,["tkhd"])[0];if(a){let o=a[0],l=fe(a,o===0?12:20),d=be(n,["mdia","mdhd"])[0];if(d){o=d[0];let u=fe(d,o===0?12:20),c=be(n,["mdia","hdlr"])[0];if(c){let h=Tt(c.subarray(8,12)),f={soun:We.AUDIO,vide:We.VIDEO}[h],m=be(n,["mdia","minf","stbl","stsd"])[0],p=BR(m);f?(e[l]={timescale:u,type:f,stsd:p},e[f]=Fe({timescale:u,id:l},p)):e[l]={timescale:u,type:h,stsd:p}}}}}return be(i,["moov","mvex","trex"]).forEach(r=>{let n=fe(r,4),a=e[n];a&&(a.default={duration:fe(r,12),flags:fe(r,20)})}),e}function BR(i){let e=i.subarray(8),t=e.subarray(86),s=Tt(e.subarray(4,8)),r=s,n,a=s==="enca"||s==="encv";if(a){let d=be(e,[s])[0].subarray(s==="enca"?28:78);be(d,["sinf"]).forEach(c=>{let h=be(c,["schm"])[0];if(h){let f=Tt(h.subarray(4,8));if(f==="cbcs"||f==="cenc"){let m=be(c,["frma"])[0];m&&(r=Tt(m))}}})}let o=r;switch(r){case"avc1":case"avc2":case"avc3":case"avc4":{let l=be(t,["avcC"])[0];l&&l.length>3&&(r+="."+Kd(l[1])+Kd(l[2])+Kd(l[3]),n=Gd(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{let l=be(e,[s])[0],d=be(l.subarray(28),["esds"])[0];if(d&&d.length>7){let u=4;if(d[u++]!==3)break;u=cm(d,u),u+=2;let c=d[u++];if(c&128&&(u+=2),c&64&&(u+=d[u++]),d[u++]!==4)break;u=cm(d,u);let h=d[u++];if(h===64)r+="."+Kd(h);else break;if(u+=12,d[u++]!==5)break;u=cm(d,u);let f=d[u++],m=(f&248)>>3;m===31&&(m+=1+((f&7)<<3)+((d[u]&224)>>5)),r+="."+m}break}case"hvc1":case"hev1":{let l=be(t,["hvcC"])[0];if(l&&l.length>12){let d=l[1],u=["","A","B","C"][d>>6],c=d&31,h=fe(l,2),f=(d&32)>>5?"H":"L",m=l[12],p=l.subarray(6,12);r+="."+u+c,r+="."+$R(h).toString(16).toUpperCase(),r+="."+f+m;let g="";for(let v=p.length;v--;){let T=p[v];(T||g)&&(g="."+T.toString(16).toUpperCase()+g)}r+=g}n=Gd(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{r=Gd(r,t)||r;break}case"vp09":{let l=be(t,["vpcC"])[0];if(l&&l.length>6){let d=l[4],u=l[5],c=l[6]>>4&15;r+="."+Xi(d)+"."+Xi(u)+"."+Xi(c)}break}case"av01":{let l=be(t,["av1C"])[0];if(l&&l.length>2){let d=l[1]>>>5,u=l[1]&31,c=l[2]>>>7?"H":"M",h=(l[2]&64)>>6,f=(l[2]&32)>>5,m=d===2&&h?f?12:10:h?10:8,p=(l[2]&16)>>4,g=(l[2]&8)>>3,v=(l[2]&4)>>2,T=l[2]&3;r+="."+d+"."+Xi(u)+c+"."+Xi(m)+"."+p+"."+g+v+T+"."+Xi(1)+"."+Xi(1)+"."+Xi(1)+"."+0,n=Gd("dav1",t)}break}}return{codec:r,encrypted:a,supplemental:n}}function Gd(i,e){let t=be(e,["dvvC"]),s=t.length?t[0]:be(e,["dvcC"])[0];if(s){let r=s[2]>>1&127,n=s[2]<<5&32|s[3]>>3&31;return i+"."+Xi(r)+"."+Xi(n)}}function $R(i){let e=0;for(let t=0;t<32;t++)e|=(i>>t&1)<<31-t;return e>>>0}function cm(i,e){let t=e+5;for(;i[e++]&128&&e<t;);return e}function Kd(i){return("0"+i.toString(16).toUpperCase()).slice(-2)}function Xi(i){return(i<10?"0":"")+i}function HR(i,e){if(!i||!e)return;let t=e.keyId;t&&e.isCommonEncryption&&rT(i,(s,r)=>{let n=s.subarray(8,24);n.some(a=>a!==0)||(Be.log(`[eme] Patching keyId in 'enc${r?"a":"v"}>sinf>>tenc' box: ${Dt(n)} -> ${Dt(t)}`),s.set(t,8))})}function GR(i){let e=[];return rT(i,t=>e.push(t.subarray(8,24))),e}function rT(i,e){be(i,["moov","trak"]).forEach(s=>{let r=be(s,["mdia","minf","stbl","stsd"])[0];if(!r)return;let n=r.subarray(8),a=be(n,["enca"]),o=a.length>0;o||(a=be(n,["encv"])),a.forEach(l=>{let d=o?l.subarray(28):l.subarray(78);be(d,["sinf"]).forEach(c=>{let h=nT(c);h&&e(h,o)})})})}function nT(i){let e=be(i,["schm"])[0];if(e){let t=Tt(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){let s=be(i,["schi","tenc"])[0];if(s)return s}}}function KR(i,e,t){let s={},r=be(i,["moof","traf"]);for(let n=0;n<r.length;n++){let a=r[n],o=be(a,["tfhd"])[0],l=fe(o,4),d=e[l];if(!d)continue;s[l]||(s[l]={start:NaN,duration:0,sampleCount:0,timescale:d.timescale,type:d.type});let u=s[l],c=be(a,["tfdt"])[0];if(c){let y=c[0],b=fe(c,4);y===1&&(b===GE?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(b*=GE+1,b+=fe(c,8))),Q(b)&&(!Q(u.start)||b<u.start)&&(u.start=b)}let h=d.default,f=fe(o,0)|(h==null?void 0:h.flags),m=(h==null?void 0:h.duration)||0;f&8&&(f&2?m=fe(o,12):m=fe(o,8));let p=be(a,["trun"]),g=u.start||0,v=0,T=m;for(let y=0;y<p.length;y++){let b=p[y],A=fe(b,4),R=u.sampleCount;u.sampleCount+=A;let I=b[3]&1,x=b[3]&4,D=b[2]&1,S=b[2]&2,C=b[2]&4,P=b[2]&8,N=8,$=A;for(I&&(N+=4),x&&A&&(!(b[N+1]&1)&&u.keyFrameIndex===void 0&&(u.keyFrameIndex=R),N+=4,D?(T=fe(b,N),N+=4):T=m,S&&(N+=4),P&&(N+=4),g+=T,v+=T,$--);$--;)D?(T=fe(b,N),N+=4):T=m,S&&(N+=4),C&&(b[N+1]&1||u.keyFrameIndex===void 0&&(u.keyFrameIndex=u.sampleCount-($+1),u.keyFrameStart=g),N+=4),P&&(N+=4),g+=T,v+=T;!v&&m&&(v+=m*A)}u.duration+=v}if(!Object.keys(s).some(n=>s[n].duration)){let n=1/0,a=0,o=be(i,["sidx"]);for(let l=0;l<o.length;l++){let d=FR(o[l]);if(d!=null&&d.references){n=Math.min(n,d.earliestPresentationTime/d.timescale);let u=d.references.reduce((c,h)=>c+h.info.duration||0,0);a=Math.max(a,u+d.earliestPresentationTime/d.timescale)}}a&&Q(a)&&Object.keys(s).forEach(l=>{s[l].duration||(s[l].duration=a*s[l].timescale-s[l].start)})}return s}function VR(i){let e={valid:null,remainder:null},t=be(i,["moof"]);if(t.length<2)return e.remainder=i,e;let s=t[t.length-1];return e.valid=i.slice(0,s.byteOffset-8),e.remainder=i.slice(s.byteOffset-8),e}function pi(i,e){let t=new Uint8Array(i.length+e.length);return t.set(i),t.set(e,i.length),t}function VE(i,e){let t=[],s=e.samples,r=e.timescale,n=e.id,a=!1;return be(s,["moof"]).map(l=>{let d=l.byteOffset-8;be(l,["traf"]).map(c=>{let h=be(c,["tfdt"]).map(f=>{let m=f[0],p=fe(f,4);return m===1&&(p*=Math.pow(2,32),p+=fe(f,8)),p/r})[0];return h!==void 0&&(i=h),be(c,["tfhd"]).map(f=>{let m=fe(f,4),p=fe(f,0)&16777215,g=(p&1)!==0,v=(p&2)!==0,T=(p&8)!==0,y=0,b=(p&16)!==0,A=0,R=(p&32)!==0,I=8;m===n&&(g&&(I+=8),v&&(I+=4),T&&(y=fe(f,I),I+=4),b&&(A=fe(f,I),I+=4),R&&(I+=4),e.type==="video"&&(a=Ou(e.codec)),be(c,["trun"]).map(x=>{let D=x[0],S=fe(x,0)&16777215,C=(S&1)!==0,P=0,N=(S&4)!==0,$=(S&256)!==0,H=0,U=(S&512)!==0,j=0,q=(S&1024)!==0,Z=(S&2048)!==0,re=0,V=fe(x,4),G=8;C&&(P=fe(x,G),G+=4),N&&(G+=4);let ce=P+d;for(let Se=0;Se<V;Se++){if($?(H=fe(x,G),G+=4):H=y,U?(j=fe(x,G),G+=4):j=A,q&&(G+=4),Z&&(D===0?re=fe(x,G):re=iT(x,G),G+=4),e.type===We.VIDEO){let he=0;for(;he<j;){let Te=fe(s,ce);if(ce+=4,WR(a,s[ce])){let vt=s.subarray(ce,ce+Te);Xp(vt,a?2:1,i+re/r,t)}ce+=Te,he+=Te+4}}i+=H/r}}))})})}),t}function Ou(i){if(!i)return!1;let e=i.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function WR(i,e){if(i){let t=e>>1&63;return t===39||t===40}else return(e&31)===6}function Xp(i,e,t,s){let r=aT(i),n=0;n+=e;let a=0,o=0,l=0;for(;n<r.length;){a=0;do{if(n>=r.length)break;l=r[n++],a+=l}while(l===255);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(l===255);let d=r.length-n,u=n;if(o<d)n+=o;else if(o>d){Be.error(`Malformed SEI payload. ${o} is too small, only ${d} bytes left to parse.`);break}if(a===4){if(r[u++]===181){let h=tT(r,u);if(u+=2,h===49){let f=fe(r,u);if(u+=4,f===1195456820){let m=r[u++];if(m===3){let p=r[u++],g=31&p,v=64&p,T=v?2+g*3:0,y=new Uint8Array(T);if(v){y[0]=p;for(let b=1;b<T;b++)y[b]=r[u++]}s.push({type:m,payloadType:a,pts:t,bytes:y})}}}}}else if(a===5&&o>16){let c=[];for(let m=0;m<16;m++){let p=r[u++].toString(16);c.push(p.length==1?"0"+p:p),(m===3||m===5||m===7||m===9)&&c.push("-")}let h=o-16,f=new Uint8Array(h);for(let m=0;m<h;m++)f[m]=r[u++];s.push({payloadType:a,pts:t,uuid:c.join(""),userData:li(f),userDataBytes:f})}}}function aT(i){let e=i.byteLength,t=[],s=1;for(;s<e-2;)i[s]===0&&i[s+1]===0&&i[s+2]===3?(t.push(s+2),s+=2):s++;if(t.length===0)return i;let r=e-t.length,n=new Uint8Array(r),a=0;for(s=0;s<r;a++,s++)a===t[0]&&(a++,t.shift()),n[s]=i[a];return n}function qR(i){let e=i[0],t="",s="",r=0,n=0,a=0,o=0,l=0,d=0;if(e===0){for(;Tt(i.subarray(d,d+1))!=="\0";)t+=Tt(i.subarray(d,d+1)),d+=1;for(t+=Tt(i.subarray(d,d+1)),d+=1;Tt(i.subarray(d,d+1))!=="\0";)s+=Tt(i.subarray(d,d+1)),d+=1;s+=Tt(i.subarray(d,d+1)),d+=1,r=fe(i,12),n=fe(i,16),o=fe(i,20),l=fe(i,24),d=28}else if(e===1){d+=4,r=fe(i,d),d+=4;let c=fe(i,d);d+=4;let h=fe(i,d);for(d+=4,a=2**32*c+h,SR(a)||(a=Number.MAX_SAFE_INTEGER,Be.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=fe(i,d),d+=4,l=fe(i,d),d+=4;Tt(i.subarray(d,d+1))!=="\0";)t+=Tt(i.subarray(d,d+1)),d+=1;for(t+=Tt(i.subarray(d,d+1)),d+=1;Tt(i.subarray(d,d+1))!=="\0";)s+=Tt(i.subarray(d,d+1)),d+=1;s+=Tt(i.subarray(d,d+1)),d+=1}let u=i.subarray(d,i.byteLength);return{schemeIdUri:t,value:s,timeScale:r,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:u}}function YR(i,...e){let t=e.length,s=8,r=t;for(;r--;)s+=e[r].byteLength;let n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=s&255,n.set(i,4),r=0,s=8;r<t;r++)n.set(e[r],s),s+=e[r].byteLength;return n}function jR(i,e,t){if(i.byteLength!==16)throw new RangeError("Invalid system id");let s,r;s=0,r=new Uint8Array;let n;s>0?(n=new Uint8Array(4),e.length>0&&new DataView(n.buffer).setUint32(0,e.length,!1)):n=new Uint8Array;let a=new Uint8Array(4);return t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),YR([112,115,115,104],new Uint8Array([s,0,0,0]),i,n,r,a,t)}function zR(i){let e=[];if(i instanceof ArrayBuffer){let t=i.byteLength,s=0;for(;s+32<t;){let r=new DataView(i,s),n=QR(r);e.push(n),s+=n.size}}return e}function QR(i){let e=i.getUint32(0),t=i.byteOffset,s=i.byteLength;if(s<e)return{offset:t,size:s};if(i.getUint32(4)!==1886614376)return{offset:t,size:e};let n=i.getUint32(8)>>>24;if(n!==0&&n!==1)return{offset:t,size:e};let a=i.buffer,o=Dt(new Uint8Array(a,t+12,16)),l=null,d=null,u=0;if(n===0)u=28;else{let h=i.getUint32(28);if(!h||s<32+h*16)return{offset:t,size:e};l=[];for(let f=0;f<h;f++)l.push(new Uint8Array(a,t+32+f*16,16));u=32+h*16}if(!u)return{offset:t,size:e};let c=i.getUint32(u);return e-32<c?{offset:t,size:e}:(d=new Uint8Array(a,t+u+4,c),{version:n,systemId:o,kids:l,data:d,offset:t,size:e})}var oT=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),ra={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function Zp(i,e){let t=ra[e];return!!t&&!!t[i.slice(0,4)]}function Bo(i,e,t=!0){return!i.split(",").some(s=>!Jp(s,e,t))}function Jp(i,e,t=!0){var s;let r=nr(t);return(s=r==null?void 0:r.isTypeSupported($o(i,e)))!=null?s:!1}function $o(i,e){return`${e}/mp4;codecs=${i}`}function WE(i){if(i){let e=i.substring(0,4);return ra.video[e]}return 2}function uu(i){let e=oT();return i.split(",").reduce((t,s)=>{let n=e&&Ou(s)?9:ra.video[s];return n?(n*2+t)/(t?3:2):(ra.audio[s]+t)/(t?2:1)},0)}var hm={};function XR(i,e=!0){if(hm[i])return hm[i];let t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[i];for(let r=0;r<t.length;r++){var s;if(Jp(t[r],"audio",e))return hm[i]=t[r],t[r];if(t[r]==="mp3"&&(s=nr(e))!=null&&s.isTypeSupported("audio/mpeg"))return""}return i}var ZR=/flac|opus|mp4a\.40\.34/i;function cu(i,e=!0){return i.replace(ZR,t=>XR(t.toLowerCase(),e))}function JR(i,e){let t=[];if(i){let s=i.split(",");for(let r=0;r<s.length;r++)Zp(s[r],"video")||t.push(s[r])}return e&&t.push(e),t.join(",")}function iu(i,e){if(i&&(i.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(i)!==-1)&&(qE(i,"audio")||qE(i,"video")))return i;if(e){let t=e.split(",");if(t.length>1){if(i){for(let s=t.length;s--;)if(t[s].substring(0,4)===i.substring(0,4))return t[s]}return t[0]}}return e||i}function qE(i,e){return Zp(i,e)&&Jp(i,e)}function ex(i){let e=i.split(",");for(let t=0;t<e.length;t++){let s=e[t].split(".");s.length>2&&s[0]==="avc1"&&(e[t]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return e.join(",")}function tx(i){if(i.startsWith("av01.")){let e=i.split("."),t=["0","111","01","01","01","0"];for(let s=e.length;s>4&&s<10;s++)e[s]=t[s-4];return e.join(".")}return i}function YE(i){let e=nr(i)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Nm(i){return i.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var ix={supported:!0,powerEfficient:!0,smooth:!0},sx={supported:!1,smooth:!1,powerEfficient:!1},lT={supported:!0,configurations:[],decodingInfoResults:[ix]};function dT(i,e){return{supported:!1,configurations:e,decodingInfoResults:[sx],error:i}}function rx(i,e,t,s,r,n){let a=i.videoCodec,o=i.audioCodec?i.audioGroups:null,l=n==null?void 0:n.audioCodec,d=n==null?void 0:n.channels,u=d?parseInt(d):l?1/0:2,c=null;if(o!=null&&o.length)try{o.length===1&&o[0]?c=e.groups[o[0]].channels:c=o.reduce((h,f)=>{if(f){let m=e.groups[f];if(!m)throw new Error(`Audio track group ${f} not found`);Object.keys(m.channels).forEach(p=>{h[p]=(h[p]||0)+m.channels[p]})}return h},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(h=>Ou(h))||i.width>1920&&i.height>1088||i.height>1920&&i.width>1088||i.frameRate>Math.max(s,30)||i.videoRange!=="SDR"&&i.videoRange!==t||i.bitrate>Math.max(r,8e6))||!!c&&Q(u)&&Object.keys(c).some(h=>parseInt(h)>u)}function uT(i,e,t,s={}){let r=i.videoCodec;if(!r&&!i.audioCodec||!t)return Promise.resolve(lT);let n=[],a=nx(i),o=a.length,l=ax(i,e,o>0),d=l.length;for(let u=o||1*d||1;u--;){let c={type:"media-source"};if(o&&(c.video=a[u%o]),d){c.audio=l[u%d];let h=c.audio.bitrate;c.video&&h&&(c.video.bitrate-=h)}n.push(c)}if(r){let u=navigator.userAgent;if(r.split(",").some(c=>Ou(c))&&oT())return Promise.resolve(dT(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${u})`),n))}return Promise.all(n.map(u=>{let c=lx(u);return s[c]||(s[c]=t.decodingInfo(u))})).then(u=>({supported:!u.some(c=>!c.supported),configurations:n,decodingInfoResults:u})).catch(u=>({supported:!1,configurations:n,decodingInfoResults:[],error:u}))}function nx(i){var e;let t=(e=i.videoCodec)==null?void 0:e.split(","),s=cT(i),r=i.width||640,n=i.height||480,a=i.frameRate||30,o=i.videoRange.toLowerCase();return t?t.map(l=>{let d={contentType:$o(tx(l),"video"),width:r,height:n,bitrate:s,framerate:a};return o!=="sdr"&&(d.transferFunction=o),d}):[]}function ax(i,e,t){var s;let r=(s=i.audioCodec)==null?void 0:s.split(","),n=cT(i);return r&&i.audioGroups?i.audioGroups.reduce((a,o)=>{var l;let d=o?(l=e.groups[o])==null?void 0:l.tracks:null;return d?d.reduce((u,c)=>{if(c.groupId===o){let h=parseFloat(c.channels||"");r.forEach(f=>{let m={contentType:$o(f,"audio"),bitrate:t?ox(f,n):n};h&&(m.channels=""+h),u.push(m)})}return u},a):a},[]):[]}function ox(i,e){if(e<=1)return 1;let t=128e3;return i==="ec-3"?t=768e3:i==="ac-3"&&(t=64e4),Math.min(e/2,t)}function cT(i){return Math.ceil(Math.max(i.bitrate*.9,i.averageBitrate)/1e3)*1e3||1}function lx(i){let e="",{audio:t,video:s}=i;if(s){let r=Nm(s.contentType);e+=`${r}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(t){let r=Nm(t.contentType);e+=`${s?"_":""}${r}_c${t.channels}`}return e}var Um=["NONE","TYPE-0","TYPE-1",null];function dx(i){return Um.indexOf(i)>-1}var hu=["SDR","PQ","HLG"];function ux(i){return!!i&&hu.indexOf(i)>-1}var su={No:"",Yes:"YES",v2:"v2"};function jE(i){let{canSkipUntil:e,canSkipDateRanges:t,age:s}=i,r=s<e/2;return e&&r?t?su.v2:su.Yes:su.No}var fu=class{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){let t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}},tn=class{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(s=>!!s).map(s=>s.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;let s=(t=e.supplemental)==null?void 0:t.videoCodec;s&&s!==e.videoCodec&&(this.codecSet+=`,${s.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return zE(this._audioGroups,e)}hasSubtitleGroup(e){return zE(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let s=this._audioGroups;s||(s=this._audioGroups=[]),s.indexOf(t)===-1&&s.push(t)}else if(e==="text"){let s=this._subtitleGroups;s||(s=this._subtitleGroups=[]),s.indexOf(t)===-1&&s.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}};function zE(i,e){return!e||!i?!1:i.indexOf(e)!==-1}function cx(){if(typeof matchMedia=="function"){let i=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(i.media!==e.media)return i.matches===!0}return!1}function hx(i,e){let t=!1,s=[];if(i&&(t=i!=="SDR",s=[i]),e){s=e.allowedVideoRanges||hu.slice(0);let r=s.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:r&&cx(),t||(s=["SDR"])}return{preferHDR:t,allowedVideoRanges:s}}var fx=i=>{let e=new WeakSet;return(t,s)=>{if(i&&(s=i(t,s)),typeof s=="object"&&s!==null){if(e.has(s))return;e.add(s)}return s}},qe=(i,e)=>JSON.stringify(i,fx(e));function mx(i,e,t,s,r){let n=Object.keys(i),a=s==null?void 0:s.channels,o=s==null?void 0:s.audioCodec,l=r==null?void 0:r.videoCodec,d=a&&parseInt(a)===2,u=!1,c=!1,h=1/0,f=1/0,m=1/0,p=1/0,g=0,v=[],{preferHDR:T,allowedVideoRanges:y}=hx(e,r);for(let x=n.length;x--;){let D=i[n[x]];u||(u=D.channels[2]>0),h=Math.min(h,D.minHeight),f=Math.min(f,D.minFramerate),m=Math.min(m,D.minBitrate),y.filter(C=>D.videoRanges[C]>0).length>0&&(c=!0)}h=Q(h)?h:0,f=Q(f)?f:0;let b=Math.max(1080,h),A=Math.max(30,f);m=Q(m)?m:t,t=Math.max(m,t),c||(e=void 0);let R=n.length>1;return{codecSet:n.reduce((x,D)=>{let S=i[D];if(D===x)return x;if(v=c?y.filter(C=>S.videoRanges[C]>0):[],R){if(S.minBitrate>t)return zi(D,`min bitrate of ${S.minBitrate} > current estimate of ${t}`),x;if(!S.hasDefaultAudio)return zi(D,"no renditions with default or auto-select sound found"),x;if(o&&D.indexOf(o.substring(0,4))%5!==0)return zi(D,`audio codec preference "${o}" not found`),x;if(a&&!d){if(!S.channels[a])return zi(D,`no renditions with ${a} channel sound found (channels options: ${Object.keys(S.channels)})`),x}else if((!o||d)&&u&&S.channels[2]===0)return zi(D,"no renditions with stereo sound found"),x;if(S.minHeight>b)return zi(D,`min resolution of ${S.minHeight} > maximum of ${b}`),x;if(S.minFramerate>A)return zi(D,`min framerate of ${S.minFramerate} > maximum of ${A}`),x;if(!v.some(C=>S.videoRanges[C]>0))return zi(D,`no variants with VIDEO-RANGE of ${qe(v)} found`),x;if(l&&D.indexOf(l.substring(0,4))%5!==0)return zi(D,`video codec preference "${l}" not found`),x;if(S.maxScore<g)return zi(D,`max score of ${S.maxScore} < selected max of ${g}`),x}return x&&(uu(D)>=uu(x)||S.fragmentError>i[x].fragmentError)?x:(p=S.minIndex,g=S.maxScore,D)},void 0),videoRanges:v,preferHDR:T,minFramerate:f,minBitrate:m,minIndex:p}}function zi(i,e){Be.log(`[abr] start candidates with "${i}" ignored because ${e}`)}function hT(i){return i.reduce((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);let r=t.channels||"2";return s.channels[r]=(s.channels[r]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function px(i,e,t,s){return i.slice(t,s+1).reduce((r,n,a)=>{if(!n.codecSet)return r;let o=n.audioGroups,l=r[n.codecSet];l||(r[n.codecSet]=l={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:a,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),l.minBitrate=Math.min(l.minBitrate,n.bitrate);let d=Math.min(n.height,n.width);return l.minHeight=Math.min(l.minHeight,d),l.minFramerate=Math.min(l.minFramerate,n.frameRate),l.minIndex=Math.min(l.minIndex,a),l.maxScore=Math.max(l.maxScore,n.score),l.fragmentError+=n.fragmentError,l.videoRanges[n.videoRange]=(l.videoRanges[n.videoRange]||0)+1,o&&o.forEach(u=>{if(!u)return;let c=e.groups[u];c&&(l.hasDefaultAudio=l.hasDefaultAudio||e.hasDefaultAudio?c.hasDefault:c.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(c.channels).forEach(h=>{l.channels[h]=(l.channels[h]||0)+c.channels[h]}))}),r},{})}function QE(i){if(!i)return i;let{lang:e,assocLang:t,characteristics:s,channels:r,audioCodec:n}=i;return{lang:e,assocLang:t,characteristics:s,channels:r,audioCodec:n}}function Ji(i,e,t){if("attrs"in i){let s=e.indexOf(i);if(s!==-1)return s}for(let s=0;s<e.length;s++){let r=e[s];if(Jr(i,r,t))return s}return-1}function Jr(i,e,t){let{groupId:s,name:r,lang:n,assocLang:a,default:o}=i,l=i.forced;return(s===void 0||e.groupId===s)&&(r===void 0||e.name===r)&&(n===void 0||gx(n,e.lang))&&(n===void 0||e.assocLang===a)&&(o===void 0||e.default===o)&&(l===void 0||e.forced===l)&&(!("characteristics"in i)||vx(i.characteristics||"",e.characteristics))&&(t===void 0||t(i,e))}function gx(i,e="--"){return i.length===e.length?i===e:i.startsWith(e)||e.startsWith(i)}function vx(i,e=""){let t=i.split(","),s=e.split(",");return t.length===s.length&&!t.some(r=>s.indexOf(r)===-1)}function Xr(i,e){let{audioCodec:t,channels:s}=i;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(s===void 0||s===(e.channels||"2"))}function Ex(i,e,t,s,r){let n=e[s],o=e.reduce((h,f,m)=>{let p=f.uri;return(h[p]||(h[p]=[])).push(m),h},{})[n.uri];o.length>1&&(s=Math.max.apply(Math,o));let l=n.videoRange,d=n.frameRate,u=n.codecSet.substring(0,4),c=XE(e,s,h=>{if(h.videoRange!==l||h.frameRate!==d||h.codecSet.substring(0,4)!==u)return!1;let f=h.audioGroups,m=t.filter(p=>!f||f.indexOf(p.groupId)!==-1);return Ji(i,m,r)>-1});return c>-1?c:XE(e,s,h=>{let f=h.audioGroups,m=t.filter(p=>!f||f.indexOf(p.groupId)!==-1);return Ji(i,m,r)>-1})}function XE(i,e,t){for(let s=e;s>-1;s--)if(t(i[s]))return s;for(let s=e+1;s<i.length;s++)if(t(i[s]))return s;return-1}function mu(i,e){var t;return!!i&&i!==((t=e.loadLevelObj)==null?void 0:t.uri)}var Fm=class extends Qt{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var s;let{fragCurrent:r,partCurrent:n,hls:a}=this,{autoLevelEnabled:o,media:l}=a;if(!r||!l)return;let d=performance.now(),u=n?n.stats:r.stats,c=n?n.duration:r.duration,h=d-u.loading.start,f=a.minAutoLevel,m=r.level,p=this._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||m<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;let g=p>-1&&p!==m,v=!!t||g;if(!v&&(l.paused||!l.playbackRate||!l.readyState))return;let T=a.mainForwardBufferInfo;if(!v&&T===null)return;let y=this.bwEstimator.getEstimateTTFB(),b=Math.abs(l.playbackRate);if(h<=Math.max(y,1e3*(c/(b*2))))return;let A=T?T.len/b:0,R=u.loading.first?u.loading.first-u.loading.start:-1,I=u.loaded&&R>-1,x=this.getBwEstimate(),D=a.levels,S=D[m],C=Math.max(u.loaded,Math.round(c*(r.bitrate||S.averageBitrate)/8)),P=I?h-R:h;P<1&&I&&(P=Math.min(h,u.loaded*8/x));let N=I?u.loaded*1e3/P:0,$=y/1e3,H=N?(C-u.loaded)/N:C*8/x+$;if(H<=A)return;let U=N?N*8:x,j=((s=(t==null?void 0:t.details)||this.hls.latestLevelDetails)==null?void 0:s.live)===!0,q=this.hls.config.abrBandWidthUpFactor,Z=Number.POSITIVE_INFINITY,re;for(re=m-1;re>f;re--){let Se=D[re].maxBitrate,he=!D[re].details||j;if(Z=this.getTimeToLoadFrag($,U,c*Se,he),Z<Math.min(A,c+$))break}if(Z>=H||Z>c*10)return;I?this.bwEstimator.sample(h-Math.min(y,R),u.loaded):this.bwEstimator.sampleTTFB(h);let V=D[re].maxBitrate;this.getBwEstimate()*q>V&&this.resetEstimator(V);let G=this.findBestLevel(V,f,re,0,A,1,1);G>-1&&(re=G),this.warn(`Fragment ${r.sn}${n?" part "+n.index:""} of level ${m} is loading too slowly;
16
+ `))this.processLine(this.buffer.substring(0,e)),this.buffer=this.buffer.substring(e+1)};$d.prototype.processLine=function(i){var e=i.indexOf(":"),t=fR(i,e),s=t[0],r=t.length===2?dm(t[1]):void 0;if(s[0]!=="#")this.currentUri.uri=s,this.manifest.segments.push(this.currentUri),this.manifest.targetDuration&&!("duration"in this.currentUri)&&(this.currentUri.duration=this.manifest.targetDuration),this.currentUri={};else switch(s){case Vr.TARGET_DURATION:{if(!isFinite(r)||r<0)return;this.manifest.targetDuration=r,this.setHoldBack();break}case Vr.PART_INF:{im(this.manifest,t),this.manifest.partInf.partTarget&&(this.manifest.partTargetDuration=this.manifest.partInf.partTarget),this.setHoldBack();break}case Vr.SERVER_CONTROL:{im(this.manifest,t),this.setHoldBack();break}case Vr.INF:{r===0?this.currentUri.duration=.01:r>0&&(this.currentUri.duration=r);break}case Vr.PROGRAM_DATE_TIME:{var n=r,a=new Date(n);this.manifest.dateTimeString||(this.manifest.dateTimeString=n,this.manifest.dateTimeObject=a),this.currentUri.dateTimeString=n,this.currentUri.dateTimeObject=a;break}case Vr.VERSION:{im(this.manifest,t);break}case Vr.SESSION_DATA:{var o=mR(t[1]),l=kE(o);Object.assign(this.manifest.sessionData,l)}}};$d.prototype.setHoldBack=function(){var i=this.manifest,e=i.serverControl,t=i.targetDuration,s=i.partTargetDuration;if(e){var r="holdBack",n="partHoldBack",a=t&&t*3,o=s&&s*2;t&&!e.hasOwnProperty(r)&&(e[r]=a),a&&e[r]<a&&(e[r]=a),s&&!e.hasOwnProperty(n)&&(e[n]=s*3),s&&e[n]<o&&(e[n]=o)}};var im=function(i,e){var t=FE(e[0].replace("#EXT-X-","")),s;hR(e[1])?(s={},s=Object.assign(cR(e[1]),s)):s=dm(e[1]),i[t]=s},FE=function(i){return i.toLowerCase().replace(/-(\w)/g,function(e){return e[1].toUpperCase()})},dm=function(i){if(i.toLowerCase()==="yes"||i.toLowerCase()==="no")return i.toLowerCase()==="yes";var e=i.indexOf(":")!==-1?i:parseFloat(i);return isNaN(e)?i:e},uR=function(i){var e={},t=i.split("=");if(t.length>1){var s=FE(t[0]);e[s]=dm(t[1])}return e},cR=function(i){for(var e=i.split(","),t={},s=0;e.length>s;s++){var r=e[s],n=uR(r);t=Object.assign(n,t)}return t},hR=function(i){return i.indexOf("=")>-1},fR=function(i,e){return e===-1?[i]:[i.substring(0,e),i.substring(e+1)]},mR=function(i){var e={};if(i){var t=i.search(","),s=i.slice(0,t),r=i.slice(t+1),n=[s,r];return n.forEach(function(a,o){for(var l=a.replace(/['"]+/g,"").split("="),d=0;d<l.length;d++)l[d]==="DATA-ID"&&(e["DATA-ID"]=l[1-d]),l[d]==="VALUE"&&(e.VALUE=l[1-d])}),{data:e}}},pR=$d,gR={safeCall:oR,safeIncrement:yt,getComputedStyle:lR,secondsToMs:dR,assign:Object.assign,headersStringToObject:lm,cdnHeadersToRequestId:Bd,extractHostnameAndDomain:Co,extractHostname:ki,manifestParser:pR,generateShortID:RE,generateUUID:Do,now:It.now,findMediaElement:Nd},vR=gR,ER={PLAYER_READY:"playerready",VIEW_INIT:"viewinit",VIDEO_CHANGE:"videochange",PLAY:"play",PAUSE:"pause",PLAYING:"playing",TIME_UPDATE:"timeupdate",SEEKING:"seeking",SEEKED:"seeked",REBUFFER_START:"rebufferstart",REBUFFER_END:"rebufferend",ERROR:"error",ENDED:"ended",RENDITION_CHANGE:"renditionchange",ORIENTATION_CHANGE:"orientationchange",PLAYBACK_MODE_CHANGE:"playbackmodechange",AD_REQUEST:"adrequest",AD_RESPONSE:"adresponse",AD_BREAK_START:"adbreakstart",AD_PLAY:"adplay",AD_PLAYING:"adplaying",AD_PAUSE:"adpause",AD_FIRST_QUARTILE:"adfirstquartile",AD_MID_POINT:"admidpoint",AD_THIRD_QUARTILE:"adthirdquartile",AD_ENDED:"adended",AD_BREAK_END:"adbreakend",AD_ERROR:"aderror",REQUEST_COMPLETED:"requestcompleted",REQUEST_FAILED:"requestfailed",REQUEST_CANCELLED:"requestcanceled",HEARTBEAT:"hb",DESTROY:"destroy"},yR=ER,bR="mux-embed",TR="5.16.1",_R="2.1",ht={},er=function(i){var e=arguments;typeof i=="string"?er.hasOwnProperty(i)?xo.default.setTimeout(function(){e=Array.prototype.splice.call(e,1),er[i].apply(null,e)},0):Ve.warn("`"+i+"` is an unknown task"):typeof i=="function"?xo.default.setTimeout(function(){i(er)},0):Ve.warn("`"+i+"` is invalid.")},AR={loaded:It.now(),NAME:bR,VERSION:TR,API_VERSION:_R,PLAYER_TRACKED:!1,monitor:function(i,e){return aR(er,i,e)},destroyMonitor:function(i){var e=Is(Nd(i),1),t=e[0];t&&t.mux&&typeof t.mux.destroy=="function"?t.mux.destroy():Ve.error("A video element monitor for `"+i+"` has not been initialized via `mux.monitor`.")},addHLSJS:function(i,e){var t=Ri(i);ht[t]?ht[t].addHLSJS(e):Ve.error("A monitor for `"+t+"` has not been initialized.")},addDashJS:function(i,e){var t=Ri(i);ht[t]?ht[t].addDashJS(e):Ve.error("A monitor for `"+t+"` has not been initialized.")},removeHLSJS:function(i){var e=Ri(i);ht[e]?ht[e].removeHLSJS():Ve.error("A monitor for `"+e+"` has not been initialized.")},removeDashJS:function(i){var e=Ri(i);ht[e]?ht[e].removeDashJS():Ve.error("A monitor for `"+e+"` has not been initialized.")},init:function(i,e){rm()&&e&&e.respectDoNotTrack&&Ve.info("The browser's Do Not Track flag is enabled - Mux beaconing is disabled.");var t=Ri(i);ht[t]=new sR(er,t,e)},emit:function(i,e,t){var s=Ri(i);ht[s]?(ht[s].emit(e,t),e==="destroy"&&delete ht[s]):Ve.error("A monitor for `"+s+"` has not been initialized.")},updateData:function(i,e){var t=Ri(i);ht[t]?ht[t].emit("hb",e):Ve.error("A monitor for `"+t+"` has not been initialized.")},setEmitTranslator:function(i,e){var t=Ri(i);ht[t]?ht[t].emitTranslator=e:Ve.error("A monitor for `"+t+"` has not been initialized.")},setStateDataTranslator:function(i,e){var t=Ri(i);ht[t]?ht[t].stateDataTranslator=e:Ve.error("A monitor for `"+t+"` has not been initialized.")},setGetPlayheadTime:function(i,e){var t=Ri(i);ht[t]?ht[t].getPlayheadTime=e:Ve.error("A monitor for `"+t+"` has not been initialized.")},checkDoNotTrack:rm,log:Ve,utils:vR,events:yR,WINDOW_HIDDEN:!1,WINDOW_UNLOADING:!1};Object.assign(er,AR);typeof xo.default!="undefined"&&typeof xo.default.addEventListener=="function"&&xo.default.addEventListener("pagehide",function(i){i.persisted||(er.WINDOW_UNLOADING=!0)},!1);var Hd=er;var Q=Number.isFinite||function(i){return typeof i=="number"&&isFinite(i)},SR=Number.isSafeInteger||function(i){return typeof i=="number"&&Math.abs(i)<=IR},IR=Number.MAX_SAFE_INTEGER||9007199254740991,se=function(i){return i.NETWORK_ERROR="networkError",i.MEDIA_ERROR="mediaError",i.KEY_SYSTEM_ERROR="keySystemError",i.MUX_ERROR="muxError",i.OTHER_ERROR="otherError",i}({}),M=function(i){return i.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",i.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",i.KEY_SYSTEM_NO_SESSION="keySystemNoSession",i.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",i.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",i.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",i.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",i.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",i.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",i.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",i.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",i.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",i.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",i.MANIFEST_LOAD_ERROR="manifestLoadError",i.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",i.MANIFEST_PARSING_ERROR="manifestParsingError",i.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",i.LEVEL_EMPTY_ERROR="levelEmptyError",i.LEVEL_LOAD_ERROR="levelLoadError",i.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",i.LEVEL_PARSING_ERROR="levelParsingError",i.LEVEL_SWITCH_ERROR="levelSwitchError",i.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",i.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",i.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",i.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",i.FRAG_LOAD_ERROR="fragLoadError",i.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",i.FRAG_DECRYPT_ERROR="fragDecryptError",i.FRAG_PARSING_ERROR="fragParsingError",i.FRAG_GAP="fragGap",i.REMUX_ALLOC_ERROR="remuxAllocError",i.KEY_LOAD_ERROR="keyLoadError",i.KEY_LOAD_TIMEOUT="keyLoadTimeOut",i.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",i.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",i.BUFFER_APPEND_ERROR="bufferAppendError",i.BUFFER_APPENDING_ERROR="bufferAppendingError",i.BUFFER_STALLED_ERROR="bufferStalledError",i.BUFFER_FULL_ERROR="bufferFullError",i.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",i.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",i.ASSET_LIST_LOAD_ERROR="assetListLoadError",i.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",i.ASSET_LIST_PARSING_ERROR="assetListParsingError",i.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",i.INTERNAL_EXCEPTION="internalException",i.INTERNAL_ABORTED="aborted",i.ATTACH_MEDIA_ERROR="attachMediaError",i.UNKNOWN="unknown",i}({}),E=function(i){return i.MEDIA_ATTACHING="hlsMediaAttaching",i.MEDIA_ATTACHED="hlsMediaAttached",i.MEDIA_DETACHING="hlsMediaDetaching",i.MEDIA_DETACHED="hlsMediaDetached",i.MEDIA_ENDED="hlsMediaEnded",i.STALL_RESOLVED="hlsStallResolved",i.BUFFER_RESET="hlsBufferReset",i.BUFFER_CODECS="hlsBufferCodecs",i.BUFFER_CREATED="hlsBufferCreated",i.BUFFER_APPENDING="hlsBufferAppending",i.BUFFER_APPENDED="hlsBufferAppended",i.BUFFER_EOS="hlsBufferEos",i.BUFFERED_TO_END="hlsBufferedToEnd",i.BUFFER_FLUSHING="hlsBufferFlushing",i.BUFFER_FLUSHED="hlsBufferFlushed",i.MANIFEST_LOADING="hlsManifestLoading",i.MANIFEST_LOADED="hlsManifestLoaded",i.MANIFEST_PARSED="hlsManifestParsed",i.LEVEL_SWITCHING="hlsLevelSwitching",i.LEVEL_SWITCHED="hlsLevelSwitched",i.LEVEL_LOADING="hlsLevelLoading",i.LEVEL_LOADED="hlsLevelLoaded",i.LEVEL_UPDATED="hlsLevelUpdated",i.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",i.LEVELS_UPDATED="hlsLevelsUpdated",i.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",i.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",i.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",i.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",i.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",i.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",i.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",i.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",i.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",i.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",i.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",i.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",i.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",i.CUES_PARSED="hlsCuesParsed",i.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",i.INIT_PTS_FOUND="hlsInitPtsFound",i.FRAG_LOADING="hlsFragLoading",i.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",i.FRAG_LOADED="hlsFragLoaded",i.FRAG_DECRYPTED="hlsFragDecrypted",i.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",i.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",i.FRAG_PARSING_METADATA="hlsFragParsingMetadata",i.FRAG_PARSED="hlsFragParsed",i.FRAG_BUFFERED="hlsFragBuffered",i.FRAG_CHANGED="hlsFragChanged",i.FPS_DROP="hlsFpsDrop",i.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",i.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",i.ERROR="hlsError",i.DESTROYING="hlsDestroying",i.KEY_LOADING="hlsKeyLoading",i.KEY_LOADED="hlsKeyLoaded",i.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",i.BACK_BUFFER_REACHED="hlsBackBufferReached",i.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",i.ASSET_LIST_LOADING="hlsAssetListLoading",i.ASSET_LIST_LOADED="hlsAssetListLoaded",i.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",i.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",i.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",i.INTERSTITIAL_STARTED="hlsInterstitialStarted",i.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",i.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",i.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",i.INTERSTITIAL_ENDED="hlsInterstitialEnded",i.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",i.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",i.EVENT_CUE_ENTER="hlsEventCueEnter",i}({}),Le={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},J={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"},sr=class{constructor(e,t=0,s=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_=s}sample(e,t){let s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*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_}},wm=class{constructor(e,t,s,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_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new sr(e),this.fast_=new sr(t),this.defaultTTFB_=r,this.ttfb_=new sr(e)}update(e,t){let{slow_:s,fast_:r,ttfb_:n}=this;s.halfLife!==e&&(this.slow_=new sr(e,s.getEstimate(),s.getTotalWeight())),r.halfLife!==t&&(this.fast_=new sr(t,r.getEstimate(),r.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new sr(e,n.getEstimate(),n.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);let s=8*t,r=e/1e3,n=s/r;this.fast_.sample(r,n),this.slow_.sample(r,n)}sampleTTFB(e){let t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}};function LR(i,e,t){return(e=xR(e))in i?Object.defineProperty(i,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):i[e]=t,i}function $e(){return $e=Object.assign?Object.assign.bind():function(i){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var s in t)({}).hasOwnProperty.call(t,s)&&(i[s]=t[s])}return i},$e.apply(null,arguments)}function BE(i,e){var t=Object.keys(i);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(i);e&&(s=s.filter(function(r){return Object.getOwnPropertyDescriptor(i,r).enumerable})),t.push.apply(t,s)}return t}function Fe(i){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?BE(Object(t),!0).forEach(function(s){LR(i,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(i,Object.getOwnPropertyDescriptors(t)):BE(Object(t)).forEach(function(s){Object.defineProperty(i,s,Object.getOwnPropertyDescriptor(t,s))})}return i}function RR(i,e){if(typeof i!="object"||!i)return i;var t=i[Symbol.toPrimitive];if(t!==void 0){var s=t.call(i,e);if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(i)}function xR(i){var e=RR(i,"string");return typeof e=="symbol"?e:e+""}var Qt=class{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;let s=`[${e}]:`;this.trace=rr,this.debug=t.debug.bind(null,s),this.log=t.log.bind(null,s),this.warn=t.warn.bind(null,s),this.info=t.info.bind(null,s),this.error=t.error.bind(null,s)}},rr=function(){},kR={trace:rr,debug:rr,log:rr,warn:rr,info:rr,error:rr};function Mm(){return $e({},kR)}function DR(i,e){let t=self.console[i];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${i}] >`):rr}function $E(i,e,t){return e[i]?e[i].bind(e):DR(i,t)}var Pm=Mm();function CR(i,e,t){let s=Mm();if(typeof console=="object"&&i===!0||typeof i=="object"){let r=["debug","log","info","warn","error"];r.forEach(n=>{s[n]=$E(n,i,t)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.6.15`)}catch{return Mm()}r.forEach(n=>{Pm[n]=$E(n,i)})}else $e(Pm,s);return s}var Be=Pm;function nr(i=!0){return typeof self=="undefined"?void 0:(i||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function wR(i){return typeof self!="undefined"&&i===self.ManagedMediaSource}function Xy(i,e){let t=Object.keys(i),s=Object.keys(e),r=t.length,n=s.length;return!r||!n||r===n&&!t.some(a=>s.indexOf(a)===-1)}function li(i,e=!1){if(typeof TextDecoder!="undefined"){let d=new TextDecoder("utf-8").decode(i);if(e){let u=d.indexOf("\0");return u!==-1?d.substring(0,u):d}return d.replace(/\0/g,"")}let t=i.length,s,r,n,a="",o=0;for(;o<t;){if(s=i[o++],s===0&&e)return a;if(s===0||s===3)continue;switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(s);break;case 12:case 13:r=i[o++],a+=String.fromCharCode((s&31)<<6|r&63);break;case 14:r=i[o++],n=i[o++],a+=String.fromCharCode((s&15)<<12|(r&63)<<6|(n&63)<<0);break}}return a}function Dt(i){let e="";for(let t=0;t<i.length;t++){let s=i[t].toString(16);s.length<2&&(s="0"+s),e+=s}return e}function Zy(i){return Uint8Array.from(i.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function MR(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var um={exports:{}},HE;function PR(){return HE||(HE=1,function(i,e){(function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,d,u){if(u=u||{},l=l.trim(),d=d.trim(),!d){if(!u.alwaysNormalize)return l;var c=o.parseURL(l);if(!c)throw new Error("Error trying to parse base URL.");return c.path=o.normalizePath(c.path),o.buildURLFromParts(c)}var h=o.parseURL(d);if(!h)throw new Error("Error trying to parse relative URL.");if(h.scheme)return u.alwaysNormalize?(h.path=o.normalizePath(h.path),o.buildURLFromParts(h)):d;var f=o.parseURL(l);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var m=r.exec(f.path);f.netLoc=m[1],f.path=m[2]}f.netLoc&&!f.path&&(f.path="/");var p={scheme:f.scheme,netLoc:h.netLoc,path:null,params:h.params,query:h.query,fragment:h.fragment};if(!h.netLoc&&(p.netLoc=f.netLoc,h.path[0]!=="/"))if(!h.path)p.path=f.path,h.params||(p.params=f.params,h.query||(p.query=f.query));else{var g=f.path,v=g.substring(0,g.lastIndexOf("/")+1)+h.path;p.path=o.normalizePath(v)}return p.path===null&&(p.path=u.alwaysNormalize?o.normalizePath(h.path):h.path),o.buildURLFromParts(p)},parseURL:function(l){var d=s.exec(l);return d?{scheme:d[1]||"",netLoc:d[2]||"",path:d[3]||"",params:d[4]||"",query:d[5]||"",fragment:d[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(n,"");l.length!==(l=l.replace(a,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};i.exports=o})()}(um)),um.exports}var Qp=PR(),Fo=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}}},We={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"},du=class{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,OR(this,"stats")}setByteRange(e,t){let s=e.split("@",2),r;s.length===1?r=(t==null?void 0:t.byteRangeEndOffset)||0:r=parseInt(s[1]),this._byteRange=[r,parseInt(s[0])+r]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[We.AUDIO]:null,[We.VIDEO]:null,[We.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new Fo),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Qp.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){let{elementaryStreams:e}=this;e[We.AUDIO]=null,e[We.VIDEO]=null,e[We.AUDIOVIDEO]=null}};function at(i){return i.sn!=="initSegment"}var Po=class extends du{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){let e=this.stats.total;if(e)return e}if(this.byteRange.length){let e=this.byteRange[0],t=this.byteRange[1];if(Q(e)&&Q(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;let{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){let s=Object.keys(t);if(s.length===1){let r=this._decryptdata=t[s[0]]||null;r&&(this._decryptdata=r.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;let e=Q(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;let s=Object.keys(this.levelkeys),r=s.length;if(r>1||r===1&&(t=this.levelkeys[s[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!Q(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return at(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){let t=this.levelkeys;if(t){var s;let r=t[e];r&&!((s=this._decryptdata)!=null&&s.keyId)&&(this._decryptdata=r.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,s,r,n,a=!1){let{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:t,endPTS:s,startDTS:r,endDTS:n,partial:a};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,s),l.startDTS=Math.min(l.startDTS,r),l.endDTS=Math.max(l.endDTS,n)}},Om=class extends du{constructor(e,t,s,r,n){super(s),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.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=r;let a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,n),n&&(this.fragOffset=n.fragOffset+n.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){let{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}};function Jy(i,e){let t=Object.getPrototypeOf(i);if(t){let s=Object.getOwnPropertyDescriptor(t,e);return s||Jy(t,e)}}function OR(i,e){let t=Jy(i,e);t&&(t.enumerable=!0,Object.defineProperty(i,e,t))}var GE=Math.pow(2,32)-1,NR=[].push,eb={video:1,audio:2,id3:3,text:4};function bt(i){return String.fromCharCode.apply(null,i)}function tb(i,e){let t=i[e]<<8|i[e+1];return t<0?65536+t:t}function fe(i,e){let t=ib(i,e);return t<0?4294967296+t:t}function KE(i,e){let t=fe(i,e);return t*=Math.pow(2,32),t+=fe(i,e+4),t}function ib(i,e){return i[e]<<24|i[e+1]<<16|i[e+2]<<8|i[e+3]}function UR(i){let e=i.byteLength;for(let t=0;t<e;){let s=fe(i,t);if(s>8&&i[t+4]===109&&i[t+5]===111&&i[t+6]===111&&i[t+7]===102)return!0;t=s>1?t+s:e}return!1}function Te(i,e){let t=[];if(!e.length)return t;let s=i.byteLength;for(let r=0;r<s;){let n=fe(i,r),a=bt(i.subarray(r+4,r+8)),o=n>1?r+n:s;if(a===e[0])if(e.length===1)t.push(i.subarray(r+8,o));else{let l=Te(i.subarray(r+8,o),e.slice(1));l.length&&NR.apply(t,l)}r=o}return t}function FR(i){let e=[],t=i[0],s=8,r=fe(i,s);s+=4;let n=0,a=0;t===0?(n=fe(i,s),a=fe(i,s+4),s+=8):(n=KE(i,s),a=KE(i,s+8),s+=16),s+=2;let o=i.length+a,l=tb(i,s);s+=2;for(let d=0;d<l;d++){let u=s,c=fe(i,u);u+=4;let h=c&2147483647;if((c&2147483648)>>>31===1)return Be.warn("SIDX has hierarchical references (not supported)"),null;let m=fe(i,u);u+=4,e.push({referenceSize:h,subsegmentDuration:m,info:{duration:m/r,start:o,end:o+h-1}}),o+=h,u+=4,s=u}return{earliestPresentationTime:n,timescale:r,version:t,referencesCount:l,references:e}}function sb(i){let e=[],t=Te(i,["moov","trak"]);for(let r=0;r<t.length;r++){let n=t[r],a=Te(n,["tkhd"])[0];if(a){let o=a[0],l=fe(a,o===0?12:20),d=Te(n,["mdia","mdhd"])[0];if(d){o=d[0];let u=fe(d,o===0?12:20),c=Te(n,["mdia","hdlr"])[0];if(c){let h=bt(c.subarray(8,12)),f={soun:We.AUDIO,vide:We.VIDEO}[h],m=Te(n,["mdia","minf","stbl","stsd"])[0],p=BR(m);f?(e[l]={timescale:u,type:f,stsd:p},e[f]=Fe({timescale:u,id:l},p)):e[l]={timescale:u,type:h,stsd:p}}}}}return Te(i,["moov","mvex","trex"]).forEach(r=>{let n=fe(r,4),a=e[n];a&&(a.default={duration:fe(r,12),flags:fe(r,20)})}),e}function BR(i){let e=i.subarray(8),t=e.subarray(86),s=bt(e.subarray(4,8)),r=s,n,a=s==="enca"||s==="encv";if(a){let d=Te(e,[s])[0].subarray(s==="enca"?28:78);Te(d,["sinf"]).forEach(c=>{let h=Te(c,["schm"])[0];if(h){let f=bt(h.subarray(4,8));if(f==="cbcs"||f==="cenc"){let m=Te(c,["frma"])[0];m&&(r=bt(m))}}})}let o=r;switch(r){case"avc1":case"avc2":case"avc3":case"avc4":{let l=Te(t,["avcC"])[0];l&&l.length>3&&(r+="."+Kd(l[1])+Kd(l[2])+Kd(l[3]),n=Gd(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{let l=Te(e,[s])[0],d=Te(l.subarray(28),["esds"])[0];if(d&&d.length>7){let u=4;if(d[u++]!==3)break;u=cm(d,u),u+=2;let c=d[u++];if(c&128&&(u+=2),c&64&&(u+=d[u++]),d[u++]!==4)break;u=cm(d,u);let h=d[u++];if(h===64)r+="."+Kd(h);else break;if(u+=12,d[u++]!==5)break;u=cm(d,u);let f=d[u++],m=(f&248)>>3;m===31&&(m+=1+((f&7)<<3)+((d[u]&224)>>5)),r+="."+m}break}case"hvc1":case"hev1":{let l=Te(t,["hvcC"])[0];if(l&&l.length>12){let d=l[1],u=["","A","B","C"][d>>6],c=d&31,h=fe(l,2),f=(d&32)>>5?"H":"L",m=l[12],p=l.subarray(6,12);r+="."+u+c,r+="."+$R(h).toString(16).toUpperCase(),r+="."+f+m;let g="";for(let v=p.length;v--;){let b=p[v];(b||g)&&(g="."+b.toString(16).toUpperCase()+g)}r+=g}n=Gd(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{r=Gd(r,t)||r;break}case"vp09":{let l=Te(t,["vpcC"])[0];if(l&&l.length>6){let d=l[4],u=l[5],c=l[6]>>4&15;r+="."+Xi(d)+"."+Xi(u)+"."+Xi(c)}break}case"av01":{let l=Te(t,["av1C"])[0];if(l&&l.length>2){let d=l[1]>>>5,u=l[1]&31,c=l[2]>>>7?"H":"M",h=(l[2]&64)>>6,f=(l[2]&32)>>5,m=d===2&&h?f?12:10:h?10:8,p=(l[2]&16)>>4,g=(l[2]&8)>>3,v=(l[2]&4)>>2,b=l[2]&3;r+="."+d+"."+Xi(u)+c+"."+Xi(m)+"."+p+"."+g+v+b+"."+Xi(1)+"."+Xi(1)+"."+Xi(1)+"."+0,n=Gd("dav1",t)}break}}return{codec:r,encrypted:a,supplemental:n}}function Gd(i,e){let t=Te(e,["dvvC"]),s=t.length?t[0]:Te(e,["dvcC"])[0];if(s){let r=s[2]>>1&127,n=s[2]<<5&32|s[3]>>3&31;return i+"."+Xi(r)+"."+Xi(n)}}function $R(i){let e=0;for(let t=0;t<32;t++)e|=(i>>t&1)<<31-t;return e>>>0}function cm(i,e){let t=e+5;for(;i[e++]&128&&e<t;);return e}function Kd(i){return("0"+i.toString(16).toUpperCase()).slice(-2)}function Xi(i){return(i<10?"0":"")+i}function HR(i,e){if(!i||!e)return;let t=e.keyId;t&&e.isCommonEncryption&&rb(i,(s,r)=>{let n=s.subarray(8,24);n.some(a=>a!==0)||(Be.log(`[eme] Patching keyId in 'enc${r?"a":"v"}>sinf>>tenc' box: ${Dt(n)} -> ${Dt(t)}`),s.set(t,8))})}function GR(i){let e=[];return rb(i,t=>e.push(t.subarray(8,24))),e}function rb(i,e){Te(i,["moov","trak"]).forEach(s=>{let r=Te(s,["mdia","minf","stbl","stsd"])[0];if(!r)return;let n=r.subarray(8),a=Te(n,["enca"]),o=a.length>0;o||(a=Te(n,["encv"])),a.forEach(l=>{let d=o?l.subarray(28):l.subarray(78);Te(d,["sinf"]).forEach(c=>{let h=nb(c);h&&e(h,o)})})})}function nb(i){let e=Te(i,["schm"])[0];if(e){let t=bt(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){let s=Te(i,["schi","tenc"])[0];if(s)return s}}}function KR(i,e,t){let s={},r=Te(i,["moof","traf"]);for(let n=0;n<r.length;n++){let a=r[n],o=Te(a,["tfhd"])[0],l=fe(o,4),d=e[l];if(!d)continue;s[l]||(s[l]={start:NaN,duration:0,sampleCount:0,timescale:d.timescale,type:d.type});let u=s[l],c=Te(a,["tfdt"])[0];if(c){let y=c[0],T=fe(c,4);y===1&&(T===GE?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(T*=GE+1,T+=fe(c,8))),Q(T)&&(!Q(u.start)||T<u.start)&&(u.start=T)}let h=d.default,f=fe(o,0)|(h==null?void 0:h.flags),m=(h==null?void 0:h.duration)||0;f&8&&(f&2?m=fe(o,12):m=fe(o,8));let p=Te(a,["trun"]),g=u.start||0,v=0,b=m;for(let y=0;y<p.length;y++){let T=p[y],A=fe(T,4),R=u.sampleCount;u.sampleCount+=A;let I=T[3]&1,x=T[3]&4,D=T[2]&1,S=T[2]&2,C=T[2]&4,P=T[2]&8,N=8,$=A;for(I&&(N+=4),x&&A&&(!(T[N+1]&1)&&u.keyFrameIndex===void 0&&(u.keyFrameIndex=R),N+=4,D?(b=fe(T,N),N+=4):b=m,S&&(N+=4),P&&(N+=4),g+=b,v+=b,$--);$--;)D?(b=fe(T,N),N+=4):b=m,S&&(N+=4),C&&(T[N+1]&1||u.keyFrameIndex===void 0&&(u.keyFrameIndex=u.sampleCount-($+1),u.keyFrameStart=g),N+=4),P&&(N+=4),g+=b,v+=b;!v&&m&&(v+=m*A)}u.duration+=v}if(!Object.keys(s).some(n=>s[n].duration)){let n=1/0,a=0,o=Te(i,["sidx"]);for(let l=0;l<o.length;l++){let d=FR(o[l]);if(d!=null&&d.references){n=Math.min(n,d.earliestPresentationTime/d.timescale);let u=d.references.reduce((c,h)=>c+h.info.duration||0,0);a=Math.max(a,u+d.earliestPresentationTime/d.timescale)}}a&&Q(a)&&Object.keys(s).forEach(l=>{s[l].duration||(s[l].duration=a*s[l].timescale-s[l].start)})}return s}function VR(i){let e={valid:null,remainder:null},t=Te(i,["moof"]);if(t.length<2)return e.remainder=i,e;let s=t[t.length-1];return e.valid=i.slice(0,s.byteOffset-8),e.remainder=i.slice(s.byteOffset-8),e}function pi(i,e){let t=new Uint8Array(i.length+e.length);return t.set(i),t.set(e,i.length),t}function VE(i,e){let t=[],s=e.samples,r=e.timescale,n=e.id,a=!1;return Te(s,["moof"]).map(l=>{let d=l.byteOffset-8;Te(l,["traf"]).map(c=>{let h=Te(c,["tfdt"]).map(f=>{let m=f[0],p=fe(f,4);return m===1&&(p*=Math.pow(2,32),p+=fe(f,8)),p/r})[0];return h!==void 0&&(i=h),Te(c,["tfhd"]).map(f=>{let m=fe(f,4),p=fe(f,0)&16777215,g=(p&1)!==0,v=(p&2)!==0,b=(p&8)!==0,y=0,T=(p&16)!==0,A=0,R=(p&32)!==0,I=8;m===n&&(g&&(I+=8),v&&(I+=4),b&&(y=fe(f,I),I+=4),T&&(A=fe(f,I),I+=4),R&&(I+=4),e.type==="video"&&(a=Ou(e.codec)),Te(c,["trun"]).map(x=>{let D=x[0],S=fe(x,0)&16777215,C=(S&1)!==0,P=0,N=(S&4)!==0,$=(S&256)!==0,H=0,U=(S&512)!==0,j=0,q=(S&1024)!==0,Z=(S&2048)!==0,re=0,V=fe(x,4),G=8;C&&(P=fe(x,G),G+=4),N&&(G+=4);let ce=P+d;for(let Se=0;Se<V;Se++){if($?(H=fe(x,G),G+=4):H=y,U?(j=fe(x,G),G+=4):j=A,q&&(G+=4),Z&&(D===0?re=fe(x,G):re=ib(x,G),G+=4),e.type===We.VIDEO){let he=0;for(;he<j;){let be=fe(s,ce);if(ce+=4,WR(a,s[ce])){let vt=s.subarray(ce,ce+be);Xp(vt,a?2:1,i+re/r,t)}ce+=be,he+=be+4}}i+=H/r}}))})})}),t}function Ou(i){if(!i)return!1;let e=i.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function WR(i,e){if(i){let t=e>>1&63;return t===39||t===40}else return(e&31)===6}function Xp(i,e,t,s){let r=ab(i),n=0;n+=e;let a=0,o=0,l=0;for(;n<r.length;){a=0;do{if(n>=r.length)break;l=r[n++],a+=l}while(l===255);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(l===255);let d=r.length-n,u=n;if(o<d)n+=o;else if(o>d){Be.error(`Malformed SEI payload. ${o} is too small, only ${d} bytes left to parse.`);break}if(a===4){if(r[u++]===181){let h=tb(r,u);if(u+=2,h===49){let f=fe(r,u);if(u+=4,f===1195456820){let m=r[u++];if(m===3){let p=r[u++],g=31&p,v=64&p,b=v?2+g*3:0,y=new Uint8Array(b);if(v){y[0]=p;for(let T=1;T<b;T++)y[T]=r[u++]}s.push({type:m,payloadType:a,pts:t,bytes:y})}}}}}else if(a===5&&o>16){let c=[];for(let m=0;m<16;m++){let p=r[u++].toString(16);c.push(p.length==1?"0"+p:p),(m===3||m===5||m===7||m===9)&&c.push("-")}let h=o-16,f=new Uint8Array(h);for(let m=0;m<h;m++)f[m]=r[u++];s.push({payloadType:a,pts:t,uuid:c.join(""),userData:li(f),userDataBytes:f})}}}function ab(i){let e=i.byteLength,t=[],s=1;for(;s<e-2;)i[s]===0&&i[s+1]===0&&i[s+2]===3?(t.push(s+2),s+=2):s++;if(t.length===0)return i;let r=e-t.length,n=new Uint8Array(r),a=0;for(s=0;s<r;a++,s++)a===t[0]&&(a++,t.shift()),n[s]=i[a];return n}function qR(i){let e=i[0],t="",s="",r=0,n=0,a=0,o=0,l=0,d=0;if(e===0){for(;bt(i.subarray(d,d+1))!=="\0";)t+=bt(i.subarray(d,d+1)),d+=1;for(t+=bt(i.subarray(d,d+1)),d+=1;bt(i.subarray(d,d+1))!=="\0";)s+=bt(i.subarray(d,d+1)),d+=1;s+=bt(i.subarray(d,d+1)),d+=1,r=fe(i,12),n=fe(i,16),o=fe(i,20),l=fe(i,24),d=28}else if(e===1){d+=4,r=fe(i,d),d+=4;let c=fe(i,d);d+=4;let h=fe(i,d);for(d+=4,a=2**32*c+h,SR(a)||(a=Number.MAX_SAFE_INTEGER,Be.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=fe(i,d),d+=4,l=fe(i,d),d+=4;bt(i.subarray(d,d+1))!=="\0";)t+=bt(i.subarray(d,d+1)),d+=1;for(t+=bt(i.subarray(d,d+1)),d+=1;bt(i.subarray(d,d+1))!=="\0";)s+=bt(i.subarray(d,d+1)),d+=1;s+=bt(i.subarray(d,d+1)),d+=1}let u=i.subarray(d,i.byteLength);return{schemeIdUri:t,value:s,timeScale:r,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:u}}function YR(i,...e){let t=e.length,s=8,r=t;for(;r--;)s+=e[r].byteLength;let n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=s&255,n.set(i,4),r=0,s=8;r<t;r++)n.set(e[r],s),s+=e[r].byteLength;return n}function jR(i,e,t){if(i.byteLength!==16)throw new RangeError("Invalid system id");let s,r;s=0,r=new Uint8Array;let n;s>0?(n=new Uint8Array(4),e.length>0&&new DataView(n.buffer).setUint32(0,e.length,!1)):n=new Uint8Array;let a=new Uint8Array(4);return t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),YR([112,115,115,104],new Uint8Array([s,0,0,0]),i,n,r,a,t)}function zR(i){let e=[];if(i instanceof ArrayBuffer){let t=i.byteLength,s=0;for(;s+32<t;){let r=new DataView(i,s),n=QR(r);e.push(n),s+=n.size}}return e}function QR(i){let e=i.getUint32(0),t=i.byteOffset,s=i.byteLength;if(s<e)return{offset:t,size:s};if(i.getUint32(4)!==1886614376)return{offset:t,size:e};let n=i.getUint32(8)>>>24;if(n!==0&&n!==1)return{offset:t,size:e};let a=i.buffer,o=Dt(new Uint8Array(a,t+12,16)),l=null,d=null,u=0;if(n===0)u=28;else{let h=i.getUint32(28);if(!h||s<32+h*16)return{offset:t,size:e};l=[];for(let f=0;f<h;f++)l.push(new Uint8Array(a,t+32+f*16,16));u=32+h*16}if(!u)return{offset:t,size:e};let c=i.getUint32(u);return e-32<c?{offset:t,size:e}:(d=new Uint8Array(a,t+u+4,c),{version:n,systemId:o,kids:l,data:d,offset:t,size:e})}var ob=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),ra={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function Zp(i,e){let t=ra[e];return!!t&&!!t[i.slice(0,4)]}function Bo(i,e,t=!0){return!i.split(",").some(s=>!Jp(s,e,t))}function Jp(i,e,t=!0){var s;let r=nr(t);return(s=r==null?void 0:r.isTypeSupported($o(i,e)))!=null?s:!1}function $o(i,e){return`${e}/mp4;codecs=${i}`}function WE(i){if(i){let e=i.substring(0,4);return ra.video[e]}return 2}function uu(i){let e=ob();return i.split(",").reduce((t,s)=>{let n=e&&Ou(s)?9:ra.video[s];return n?(n*2+t)/(t?3:2):(ra.audio[s]+t)/(t?2:1)},0)}var hm={};function XR(i,e=!0){if(hm[i])return hm[i];let t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[i];for(let r=0;r<t.length;r++){var s;if(Jp(t[r],"audio",e))return hm[i]=t[r],t[r];if(t[r]==="mp3"&&(s=nr(e))!=null&&s.isTypeSupported("audio/mpeg"))return""}return i}var ZR=/flac|opus|mp4a\.40\.34/i;function cu(i,e=!0){return i.replace(ZR,t=>XR(t.toLowerCase(),e))}function JR(i,e){let t=[];if(i){let s=i.split(",");for(let r=0;r<s.length;r++)Zp(s[r],"video")||t.push(s[r])}return e&&t.push(e),t.join(",")}function iu(i,e){if(i&&(i.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(i)!==-1)&&(qE(i,"audio")||qE(i,"video")))return i;if(e){let t=e.split(",");if(t.length>1){if(i){for(let s=t.length;s--;)if(t[s].substring(0,4)===i.substring(0,4))return t[s]}return t[0]}}return e||i}function qE(i,e){return Zp(i,e)&&Jp(i,e)}function ex(i){let e=i.split(",");for(let t=0;t<e.length;t++){let s=e[t].split(".");s.length>2&&s[0]==="avc1"&&(e[t]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return e.join(",")}function tx(i){if(i.startsWith("av01.")){let e=i.split("."),t=["0","111","01","01","01","0"];for(let s=e.length;s>4&&s<10;s++)e[s]=t[s-4];return e.join(".")}return i}function YE(i){let e=nr(i)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Nm(i){return i.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var ix={supported:!0,powerEfficient:!0,smooth:!0},sx={supported:!1,smooth:!1,powerEfficient:!1},lb={supported:!0,configurations:[],decodingInfoResults:[ix]};function db(i,e){return{supported:!1,configurations:e,decodingInfoResults:[sx],error:i}}function rx(i,e,t,s,r,n){let a=i.videoCodec,o=i.audioCodec?i.audioGroups:null,l=n==null?void 0:n.audioCodec,d=n==null?void 0:n.channels,u=d?parseInt(d):l?1/0:2,c=null;if(o!=null&&o.length)try{o.length===1&&o[0]?c=e.groups[o[0]].channels:c=o.reduce((h,f)=>{if(f){let m=e.groups[f];if(!m)throw new Error(`Audio track group ${f} not found`);Object.keys(m.channels).forEach(p=>{h[p]=(h[p]||0)+m.channels[p]})}return h},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(h=>Ou(h))||i.width>1920&&i.height>1088||i.height>1920&&i.width>1088||i.frameRate>Math.max(s,30)||i.videoRange!=="SDR"&&i.videoRange!==t||i.bitrate>Math.max(r,8e6))||!!c&&Q(u)&&Object.keys(c).some(h=>parseInt(h)>u)}function ub(i,e,t,s={}){let r=i.videoCodec;if(!r&&!i.audioCodec||!t)return Promise.resolve(lb);let n=[],a=nx(i),o=a.length,l=ax(i,e,o>0),d=l.length;for(let u=o||1*d||1;u--;){let c={type:"media-source"};if(o&&(c.video=a[u%o]),d){c.audio=l[u%d];let h=c.audio.bitrate;c.video&&h&&(c.video.bitrate-=h)}n.push(c)}if(r){let u=navigator.userAgent;if(r.split(",").some(c=>Ou(c))&&ob())return Promise.resolve(db(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${u})`),n))}return Promise.all(n.map(u=>{let c=lx(u);return s[c]||(s[c]=t.decodingInfo(u))})).then(u=>({supported:!u.some(c=>!c.supported),configurations:n,decodingInfoResults:u})).catch(u=>({supported:!1,configurations:n,decodingInfoResults:[],error:u}))}function nx(i){var e;let t=(e=i.videoCodec)==null?void 0:e.split(","),s=cb(i),r=i.width||640,n=i.height||480,a=i.frameRate||30,o=i.videoRange.toLowerCase();return t?t.map(l=>{let d={contentType:$o(tx(l),"video"),width:r,height:n,bitrate:s,framerate:a};return o!=="sdr"&&(d.transferFunction=o),d}):[]}function ax(i,e,t){var s;let r=(s=i.audioCodec)==null?void 0:s.split(","),n=cb(i);return r&&i.audioGroups?i.audioGroups.reduce((a,o)=>{var l;let d=o?(l=e.groups[o])==null?void 0:l.tracks:null;return d?d.reduce((u,c)=>{if(c.groupId===o){let h=parseFloat(c.channels||"");r.forEach(f=>{let m={contentType:$o(f,"audio"),bitrate:t?ox(f,n):n};h&&(m.channels=""+h),u.push(m)})}return u},a):a},[]):[]}function ox(i,e){if(e<=1)return 1;let t=128e3;return i==="ec-3"?t=768e3:i==="ac-3"&&(t=64e4),Math.min(e/2,t)}function cb(i){return Math.ceil(Math.max(i.bitrate*.9,i.averageBitrate)/1e3)*1e3||1}function lx(i){let e="",{audio:t,video:s}=i;if(s){let r=Nm(s.contentType);e+=`${r}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(t){let r=Nm(t.contentType);e+=`${s?"_":""}${r}_c${t.channels}`}return e}var Um=["NONE","TYPE-0","TYPE-1",null];function dx(i){return Um.indexOf(i)>-1}var hu=["SDR","PQ","HLG"];function ux(i){return!!i&&hu.indexOf(i)>-1}var su={No:"",Yes:"YES",v2:"v2"};function jE(i){let{canSkipUntil:e,canSkipDateRanges:t,age:s}=i,r=s<e/2;return e&&r?t?su.v2:su.Yes:su.No}var fu=class{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){let t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}},tn=class{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(s=>!!s).map(s=>s.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;let s=(t=e.supplemental)==null?void 0:t.videoCodec;s&&s!==e.videoCodec&&(this.codecSet+=`,${s.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return zE(this._audioGroups,e)}hasSubtitleGroup(e){return zE(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let s=this._audioGroups;s||(s=this._audioGroups=[]),s.indexOf(t)===-1&&s.push(t)}else if(e==="text"){let s=this._subtitleGroups;s||(s=this._subtitleGroups=[]),s.indexOf(t)===-1&&s.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}};function zE(i,e){return!e||!i?!1:i.indexOf(e)!==-1}function cx(){if(typeof matchMedia=="function"){let i=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(i.media!==e.media)return i.matches===!0}return!1}function hx(i,e){let t=!1,s=[];if(i&&(t=i!=="SDR",s=[i]),e){s=e.allowedVideoRanges||hu.slice(0);let r=s.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:r&&cx(),t||(s=["SDR"])}return{preferHDR:t,allowedVideoRanges:s}}var fx=i=>{let e=new WeakSet;return(t,s)=>{if(i&&(s=i(t,s)),typeof s=="object"&&s!==null){if(e.has(s))return;e.add(s)}return s}},qe=(i,e)=>JSON.stringify(i,fx(e));function mx(i,e,t,s,r){let n=Object.keys(i),a=s==null?void 0:s.channels,o=s==null?void 0:s.audioCodec,l=r==null?void 0:r.videoCodec,d=a&&parseInt(a)===2,u=!1,c=!1,h=1/0,f=1/0,m=1/0,p=1/0,g=0,v=[],{preferHDR:b,allowedVideoRanges:y}=hx(e,r);for(let x=n.length;x--;){let D=i[n[x]];u||(u=D.channels[2]>0),h=Math.min(h,D.minHeight),f=Math.min(f,D.minFramerate),m=Math.min(m,D.minBitrate),y.filter(C=>D.videoRanges[C]>0).length>0&&(c=!0)}h=Q(h)?h:0,f=Q(f)?f:0;let T=Math.max(1080,h),A=Math.max(30,f);m=Q(m)?m:t,t=Math.max(m,t),c||(e=void 0);let R=n.length>1;return{codecSet:n.reduce((x,D)=>{let S=i[D];if(D===x)return x;if(v=c?y.filter(C=>S.videoRanges[C]>0):[],R){if(S.minBitrate>t)return zi(D,`min bitrate of ${S.minBitrate} > current estimate of ${t}`),x;if(!S.hasDefaultAudio)return zi(D,"no renditions with default or auto-select sound found"),x;if(o&&D.indexOf(o.substring(0,4))%5!==0)return zi(D,`audio codec preference "${o}" not found`),x;if(a&&!d){if(!S.channels[a])return zi(D,`no renditions with ${a} channel sound found (channels options: ${Object.keys(S.channels)})`),x}else if((!o||d)&&u&&S.channels[2]===0)return zi(D,"no renditions with stereo sound found"),x;if(S.minHeight>T)return zi(D,`min resolution of ${S.minHeight} > maximum of ${T}`),x;if(S.minFramerate>A)return zi(D,`min framerate of ${S.minFramerate} > maximum of ${A}`),x;if(!v.some(C=>S.videoRanges[C]>0))return zi(D,`no variants with VIDEO-RANGE of ${qe(v)} found`),x;if(l&&D.indexOf(l.substring(0,4))%5!==0)return zi(D,`video codec preference "${l}" not found`),x;if(S.maxScore<g)return zi(D,`max score of ${S.maxScore} < selected max of ${g}`),x}return x&&(uu(D)>=uu(x)||S.fragmentError>i[x].fragmentError)?x:(p=S.minIndex,g=S.maxScore,D)},void 0),videoRanges:v,preferHDR:b,minFramerate:f,minBitrate:m,minIndex:p}}function zi(i,e){Be.log(`[abr] start candidates with "${i}" ignored because ${e}`)}function hb(i){return i.reduce((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);let r=t.channels||"2";return s.channels[r]=(s.channels[r]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function px(i,e,t,s){return i.slice(t,s+1).reduce((r,n,a)=>{if(!n.codecSet)return r;let o=n.audioGroups,l=r[n.codecSet];l||(r[n.codecSet]=l={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:a,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),l.minBitrate=Math.min(l.minBitrate,n.bitrate);let d=Math.min(n.height,n.width);return l.minHeight=Math.min(l.minHeight,d),l.minFramerate=Math.min(l.minFramerate,n.frameRate),l.minIndex=Math.min(l.minIndex,a),l.maxScore=Math.max(l.maxScore,n.score),l.fragmentError+=n.fragmentError,l.videoRanges[n.videoRange]=(l.videoRanges[n.videoRange]||0)+1,o&&o.forEach(u=>{if(!u)return;let c=e.groups[u];c&&(l.hasDefaultAudio=l.hasDefaultAudio||e.hasDefaultAudio?c.hasDefault:c.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(c.channels).forEach(h=>{l.channels[h]=(l.channels[h]||0)+c.channels[h]}))}),r},{})}function QE(i){if(!i)return i;let{lang:e,assocLang:t,characteristics:s,channels:r,audioCodec:n}=i;return{lang:e,assocLang:t,characteristics:s,channels:r,audioCodec:n}}function Ji(i,e,t){if("attrs"in i){let s=e.indexOf(i);if(s!==-1)return s}for(let s=0;s<e.length;s++){let r=e[s];if(Jr(i,r,t))return s}return-1}function Jr(i,e,t){let{groupId:s,name:r,lang:n,assocLang:a,default:o}=i,l=i.forced;return(s===void 0||e.groupId===s)&&(r===void 0||e.name===r)&&(n===void 0||gx(n,e.lang))&&(n===void 0||e.assocLang===a)&&(o===void 0||e.default===o)&&(l===void 0||e.forced===l)&&(!("characteristics"in i)||vx(i.characteristics||"",e.characteristics))&&(t===void 0||t(i,e))}function gx(i,e="--"){return i.length===e.length?i===e:i.startsWith(e)||e.startsWith(i)}function vx(i,e=""){let t=i.split(","),s=e.split(",");return t.length===s.length&&!t.some(r=>s.indexOf(r)===-1)}function Xr(i,e){let{audioCodec:t,channels:s}=i;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(s===void 0||s===(e.channels||"2"))}function Ex(i,e,t,s,r){let n=e[s],o=e.reduce((h,f,m)=>{let p=f.uri;return(h[p]||(h[p]=[])).push(m),h},{})[n.uri];o.length>1&&(s=Math.max.apply(Math,o));let l=n.videoRange,d=n.frameRate,u=n.codecSet.substring(0,4),c=XE(e,s,h=>{if(h.videoRange!==l||h.frameRate!==d||h.codecSet.substring(0,4)!==u)return!1;let f=h.audioGroups,m=t.filter(p=>!f||f.indexOf(p.groupId)!==-1);return Ji(i,m,r)>-1});return c>-1?c:XE(e,s,h=>{let f=h.audioGroups,m=t.filter(p=>!f||f.indexOf(p.groupId)!==-1);return Ji(i,m,r)>-1})}function XE(i,e,t){for(let s=e;s>-1;s--)if(t(i[s]))return s;for(let s=e+1;s<i.length;s++)if(t(i[s]))return s;return-1}function mu(i,e){var t;return!!i&&i!==((t=e.loadLevelObj)==null?void 0:t.uri)}var Fm=class extends Qt{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var s;let{fragCurrent:r,partCurrent:n,hls:a}=this,{autoLevelEnabled:o,media:l}=a;if(!r||!l)return;let d=performance.now(),u=n?n.stats:r.stats,c=n?n.duration:r.duration,h=d-u.loading.start,f=a.minAutoLevel,m=r.level,p=this._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||m<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;let g=p>-1&&p!==m,v=!!t||g;if(!v&&(l.paused||!l.playbackRate||!l.readyState))return;let b=a.mainForwardBufferInfo;if(!v&&b===null)return;let y=this.bwEstimator.getEstimateTTFB(),T=Math.abs(l.playbackRate);if(h<=Math.max(y,1e3*(c/(T*2))))return;let A=b?b.len/T:0,R=u.loading.first?u.loading.first-u.loading.start:-1,I=u.loaded&&R>-1,x=this.getBwEstimate(),D=a.levels,S=D[m],C=Math.max(u.loaded,Math.round(c*(r.bitrate||S.averageBitrate)/8)),P=I?h-R:h;P<1&&I&&(P=Math.min(h,u.loaded*8/x));let N=I?u.loaded*1e3/P:0,$=y/1e3,H=N?(C-u.loaded)/N:C*8/x+$;if(H<=A)return;let U=N?N*8:x,j=((s=(t==null?void 0:t.details)||this.hls.latestLevelDetails)==null?void 0:s.live)===!0,q=this.hls.config.abrBandWidthUpFactor,Z=Number.POSITIVE_INFINITY,re;for(re=m-1;re>f;re--){let Se=D[re].maxBitrate,he=!D[re].details||j;if(Z=this.getTimeToLoadFrag($,U,c*Se,he),Z<Math.min(A,c+$))break}if(Z>=H||Z>c*10)return;I?this.bwEstimator.sample(h-Math.min(y,R),u.loaded):this.bwEstimator.sampleTTFB(h);let V=D[re].maxBitrate;this.getBwEstimate()*q>V&&this.resetEstimator(V);let G=this.findBestLevel(V,f,re,0,A,1,1);G>-1&&(re=G),this.warn(`Fragment ${r.sn}${n?" part "+n.index:""} of level ${m} is loading too slowly;
17
17
  Fragment duration: ${r.duration.toFixed(3)}
18
18
  Time to underbuffer: ${A.toFixed(3)} s
19
19
  Estimated load time for current fragment: ${H.toFixed(3)} s
@@ -23,39 +23,39 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
23
23
  New BW estimate: ${this.getBwEstimate()|0} bps
24
24
  Switching to level ${re} @ ${V|0} bps`),a.nextLoadLevel=a.nextAutoLevel=re,this.clearTimer();let ce=()=>{if(this.clearTimer(),this.fragCurrent===r&&this.hls.loadLevel===re&&re>0){let Se=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${re>0?"and switching down":""}
25
25
  Fragment duration: ${r.duration.toFixed(3)} s
26
- Time to underbuffer: ${Se.toFixed(3)} s`),r.abortRequests(),this.fragCurrent=this.partCurrent=null,re>f){let he=this.findBestLevel(this.hls.levels[f].bitrate,f,re,0,Se,1,1);he===-1&&(he=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=he,this.resetEstimator(this.hls.levels[he].bitrate)}}};g||H>Z*2?ce():this.timer=self.setInterval(ce,Z*1e3),a.trigger(E.FRAG_LOAD_EMERGENCY_ABORTED,{frag:r,part:n,stats:u})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){let e=this.hls.config;return new wm(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){let{hls:e}=this;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e&&(e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(E.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){let s=t.frag;if(!this.ignoreFragment(s)){if(!s.bitrateTest){var r;this.fragCurrent=s,this.partCurrent=(r=t.part)!=null?r:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case M.BUFFER_ADD_CODEC_ERROR:case M.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case M.FRAG_LOAD_TIMEOUT:{let s=t.frag,{fragCurrent:r,partCurrent:n}=this;if(s&&r&&s.sn===r.sn&&s.level===r.level){let a=performance.now(),o=n?n.stats:s.stats,l=a-o.loading.start,d=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&d>-1){let c=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(c,d),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,t,s,r){let n=e+s/t,a=r?e+this.lastLevelLoadSec:0;return n+a}onLevelLoaded(e,t){let s=this.hls.config,{loading:r}=t.stats,n=r.end-r.first;Q(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:s}){let r=s?s.stats:t.stats;if(t.type===J.MAIN&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){let n=s?s.duration:t.duration,a=this.hls.levels[t.level],o=(a.loaded?a.loaded.bytes:0)+r.loaded,l=(a.loaded?a.loaded.duration:0)+n;a.loaded={bytes:o,duration:l},a.realBitrate=Math.round(8*o/l)}if(t.bitrateTest){let n={stats:r,frag:t,part:s,id:t.type};this.onFragBuffered(E.FRAG_BUFFERED,n),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){let{frag:s,part:r}=t,n=r!=null&&r.stats.loaded?r.stats:s.stats;if(n.aborted||this.ignoreFragment(s))return;let a=n.parsing.end-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,n.loaded),n.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==J.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){let{maxAutoLevel:e,minAutoLevel:t}=this.hls,s=this.getBwEstimate(),r=this.hls.config.maxStarvationDelay,n=this.findBestLevel(s,t,e,0,r,1,1);if(n>-1)return n;let a=this.hls.firstLevel,o=Math.min(Math.max(a,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${a} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){let e=this.forcedAutoLevel,s=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(e!==-1&&(!s||!r||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;let n=s&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){let a=this.hls.levels;if(a.length>Math.max(e,n)&&a[e].loadError<=a[n].loadError)return e}return this._nextAutoLevel=n,this.nextAutoLevelKey=this.getAutoLevelKey(),n}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){let{fragCurrent:e,partCurrent:t,hls:s}=this;if(s.levels.length<=1)return s.loadLevel;let{maxAutoLevel:r,config:n,minAutoLevel:a}=s,o=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),d=this.getStarvationDelay(),u=n.abrBandWidthFactor,c=n.abrBandWidthUpFactor;if(d){let g=this.findBestLevel(l,a,r,d,0,u,c);if(g>=0)return this.rebufferNotice=-1,g}let h=o?Math.min(o,n.maxStarvationDelay):n.maxStarvationDelay;if(!d){let g=this.bitrateTestDelay;g&&(h=(o?Math.min(o,n.maxLoadingDelay):n.maxLoadingDelay)-g,this.info(`bitrate test took ${Math.round(1e3*g)}ms, set first fragment max fetchDuration to ${Math.round(1e3*h)} ms`),u=c=1)}let f=this.findBestLevel(l,a,r,d,h,u,c);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${d?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;let m=s.levels[a],p=s.loadLevelObj;return p&&(m==null?void 0:m.bitrate)<p.bitrate?a:s.loadLevel}getStarvationDelay(){let e=this.hls,t=e.media;if(!t)return 1/0;let s=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,r=e.mainForwardBufferInfo;return(r?r.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,s,r,n,a,o){var l;let d=r+n,u=this.lastLoadedFragLevel,c=u===-1?this.hls.firstLevel:u,{fragCurrent:h,partCurrent:f}=this,{levels:m,allAudioTracks:p,loadLevel:g,config:v}=this.hls;if(m.length===1)return 0;let T=m[c],y=!!((l=this.hls.latestLevelDetails)!=null&&l.live),b=g===-1||u===-1,A,R="SDR",I=(T==null?void 0:T.frameRate)||0,{audioPreference:x,videoPreference:D}=v,S=this.audioTracksByGroup||(this.audioTracksByGroup=hT(p)),C=-1;if(b){if(this.firstSelection!==-1)return this.firstSelection;let U=this.codecTiers||(this.codecTiers=px(m,S,t,s)),j=mx(U,R,e,x,D),{codecSet:q,videoRanges:Z,minFramerate:re,minBitrate:V,minIndex:G,preferHDR:ce}=j;C=G,A=q,R=ce?Z[Z.length-1]:Z[0],I=re,e=Math.max(e,V),this.log(`picked start tier ${qe(j)}`)}else A=T==null?void 0:T.codecSet,R=T==null?void 0:T.videoRange;let P=f?f.duration:h?h.duration:0,N=this.bwEstimator.getEstimateTTFB()/1e3,$=[];for(let U=s;U>=t;U--){var H;let j=m[U],q=U>c;if(!j)continue;if(v.useMediaCapabilities&&!j.supportedResult&&!j.supportedPromise){let he=navigator.mediaCapabilities;typeof(he==null?void 0:he.decodingInfo)=="function"&&rx(j,S,R,I,e,x)?(j.supportedPromise=uT(j,S,he,this.supportedCache),j.supportedPromise.then(Te=>{if(!this.hls)return;j.supportedResult=Te;let vt=this.hls.levels,ut=vt.indexOf(j);Te.error?this.warn(`MediaCapabilities decodingInfo error: "${Te.error}" for level ${ut} ${qe(Te)}`):Te.supported?Te.decodingInfoResults.some(Ft=>Ft.smooth===!1||Ft.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${ut} not smooth or powerEfficient: ${qe(Te)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${ut} ${qe(Te)}`),ut>-1&&vt.length>1&&(this.log(`Removing unsupported level ${ut}`),this.hls.removeLevel(ut),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(Te=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${Te}`)})):j.supportedResult=lT}if((A&&j.codecSet!==A||R&&j.videoRange!==R||q&&I>j.frameRate||!q&&I>0&&I<j.frameRate||(H=j.supportedResult)!=null&&(H=H.decodingInfoResults)!=null&&H.some(he=>he.smooth===!1))&&(!b||U!==C)){$.push(U);continue}let Z=j.details,re=(f?Z==null?void 0:Z.partTarget:Z==null?void 0:Z.averagetargetduration)||P,V;q?V=o*e:V=a*e;let G=P&&r>=P*2&&n===0?j.averageBitrate:j.maxBitrate,ce=this.getTimeToLoadFrag(N,V,G*re,Z===void 0);if(V>=G&&(U===u||j.loadError===0&&j.fragmentError===0)&&(ce<=N||!Q(ce)||y&&!this.bitrateTestDelay||ce<d)){let he=this.forcedAutoLevel;return U!==g&&(he===-1||he!==g)&&($.length&&this.trace(`Skipped level(s) ${$.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${m[$[0]].codecs}" ${m[$[0]].videoRange}; not compatible with "${A}" ${R}`),this.info(`switch candidate:${c}->${U} adjustedbw(${Math.round(V)})-bitrate=${Math.round(V-G)} ttfb:${N.toFixed(1)} avgDuration:${re.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${ce.toFixed(1)} firstSelection:${b} codecSet:${j.codecSet} videoRange:${j.videoRange} hls.loadLevel:${g}`)),b&&(this.firstSelection=U),U}}return-1}set nextAutoLevel(e){let t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){let{maxAutoLevel:t,minAutoLevel:s}=this.hls;return Math.min(Math.max(e,s),t)}},fT={search:function(i,e){let t=0,s=i.length-1,r=null,n=null;for(;t<=s;){r=(t+s)/2|0,n=i[r];let a=e(n);if(a>0)t=r+1;else if(a<0)s=r-1;else return n}return null}};function yx(i,e,t){if(e===null||!Array.isArray(i)||!i.length||!Q(e))return null;let s=i[0].programDateTime;if(e<(s||0))return null;let r=i[i.length-1].endProgramDateTime;if(e>=(r||0))return null;for(let n=0;n<i.length;++n){let a=i[n];if(bx(e,t,a))return a}return null}function sn(i,e,t=0,s=0,r=.005){let n=null;if(i){n=e[1+i.sn-e[0].sn]||null;let o=i.endDTS-t;o>0&&o<15e-7&&(t+=15e-7),n&&i.level!==n.level&&n.end<=i.end&&(n=e[2+i.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(n=e[0]);if(n&&((!i||i.level===n.level)&&ZE(t,s,n)===0||Tx(n,i,Math.min(r,s))))return n;let a=fT.search(e,ZE.bind(null,t,s));return a&&(a!==i||!n)?a:n}function Tx(i,e,t){if(e&&e.start===0&&e.level<i.level&&(e.endPTS||0)>0){let s=e.tagList.reduce((r,n)=>(n[0]==="INF"&&(r+=parseFloat(n[1])),r),t);return i.start<=s}return!1}function ZE(i=0,e=0,t){if(t.start<=i&&t.start+t.duration>i)return 0;let s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-s<=i?1:t.start-s>i&&t.start?-1:0}function bx(i,e,t){let s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-s>i}function mT(i,e,t){if(i&&i.startCC<=e&&i.endCC>=e){let s=i.fragments,{fragmentHint:r}=i;r&&(s=s.concat(r));let n;return fT.search(s,a=>a.cc<e?1:a.cc>e?-1:(n=a,a.end<=t?1:a.start>t?-1:0)),n||null}return null}function pu(i){switch(i.details){case M.FRAG_LOAD_TIMEOUT:case M.KEY_LOAD_TIMEOUT:case M.LEVEL_LOAD_TIMEOUT:case M.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function pT(i){return i.details.startsWith("key")}function gT(i){return pT(i)&&!!i.frag&&!i.frag.decryptdata}function JE(i,e){let t=pu(e);return i.default[`${t?"timeout":"error"}Retry`]}function eg(i,e){let t=i.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*i.retryDelayMs,i.maxRetryDelayMs)}function ey(i){return Fe(Fe({},i),{errorRetry:null,timeoutRetry:null})}function gu(i,e,t,s){if(!i)return!1;let r=s==null?void 0:s.code,n=e<i.maxNumRetry&&(_x(r)||!!t);return i.shouldRetry?i.shouldRetry(i,e,t,s,n):n}function _x(i){return Bm(i)||!!i&&(i<400||i>499)}function Bm(i){return i===0&&navigator.onLine===!1}var Rt={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},ni={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8},$m=class extends Qt{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){let e=this.hls;e.on(E.ERROR,this.onError,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){let e=this.hls;e&&(e.off(E.ERROR,this.onError,this),e.off(E.ERROR,this.onErrorOut,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===J.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;let t=this.hls,s=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||s===-1?t.loadLevel:s}variantHasKey(e,t){if(e){var s;if((s=e.details)!=null&&s.hasKey(t))return!0;let r=e.audioGroups;if(r)return this.hls.allAudioTracks.filter(a=>r.indexOf(a.groupId)>=0).some(a=>{var o;return(o=a.details)==null?void 0:o.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var s;if(t.fatal)return;let r=this.hls,n=t.context;switch(t.details){case M.FRAG_LOAD_ERROR:case M.FRAG_LOAD_TIMEOUT:case M.KEY_LOAD_ERROR:case M.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case M.FRAG_PARSING_ERROR:if((s=t.frag)!=null&&s.gap){t.errorAction=ea();return}case M.FRAG_GAP:case M.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Rt.SendAlternateToPenaltyBox;return}case M.LEVEL_EMPTY_ERROR:case M.LEVEL_PARSING_ERROR:{var a;let l=t.parent===J.MAIN?t.level:r.loadLevel;t.details===M.LEVEL_EMPTY_ERROR&&((a=t.context)!=null&&(a=a.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,l):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,l))}return;case M.LEVEL_LOAD_ERROR:case M.LEVEL_LOAD_TIMEOUT:typeof(n==null?void 0:n.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level));return;case M.AUDIO_TRACK_LOAD_ERROR:case M.AUDIO_TRACK_LOAD_TIMEOUT:case M.SUBTITLE_LOAD_ERROR:case M.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){let l=r.loadLevelObj;if(l&&(n.type===Le.AUDIO_TRACK&&l.hasAudioGroup(n.groupId)||n.type===Le.SUBTITLE_TRACK&&l.hasSubtitleGroup(n.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=Rt.SendAlternateToPenaltyBox,t.errorAction.flags=ni.MoveAllAlternatesMatchingHost;return}}return;case M.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:Rt.SendAlternateToPenaltyBox,flags:ni.MoveAllAlternatesMatchingHDCP};return;case M.KEY_SYSTEM_SESSION_UPDATE_FAILED:case M.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case M.KEY_SYSTEM_NO_SESSION:t.errorAction={action:Rt.SendAlternateToPenaltyBox,flags:ni.MoveAllAlternatesMatchingKey};return;case M.BUFFER_ADD_CODEC_ERROR:case M.REMUX_ALLOC_ERROR:case M.BUFFER_APPEND_ERROR:if(!t.errorAction){var o;t.errorAction=this.getLevelSwitchAction(t,(o=t.level)!=null?o:r.loadLevel)}return;case M.INTERNAL_EXCEPTION:case M.BUFFER_APPENDING_ERROR:case M.BUFFER_FULL_ERROR:case M.LEVEL_SWITCH_ERROR:case M.BUFFER_STALLED_ERROR:case M.BUFFER_SEEK_OVER_HOLE:case M.BUFFER_NUDGE_ON_STALL:t.errorAction=ea();return}t.type===se.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=ea())}getPlaylistRetryOrSwitchAction(e,t){let s=this.hls,r=JE(s.config.playlistLoadPolicy,e),n=this.playlistError++;if(gu(r,n,pu(e),e.response))return{action:Rt.RetryRequest,flags:ni.None,retryConfig:r,retryCount:n};let o=this.getLevelSwitchAction(e,t);return r&&(o.retryConfig=r,o.retryCount=n),o}getFragRetryOrSwitchAction(e){let t=this.hls,s=this.getVariantLevelIndex(e.frag),r=t.levels[s],{fragLoadPolicy:n,keyLoadPolicy:a}=t.config,o=JE(pT(e)?a:n,e),l=t.levels.reduce((u,c)=>u+c.fragmentError,0);if(r&&(e.details!==M.FRAG_GAP&&r.fragmentError++,!gT(e)&&gu(o,l,pu(e),e.response)))return{action:Rt.RetryRequest,flags:ni.None,retryConfig:o,retryCount:l};let d=this.getLevelSwitchAction(e,s);return o&&(d.retryConfig=o,d.retryCount=l),d}getLevelSwitchAction(e,t){let s=this.hls;t==null&&(t=s.loadLevel);let r=this.hls.levels[t];if(r){var n,a;let d=e.details;r.loadError++,d===M.BUFFER_APPEND_ERROR&&r.fragmentError++;let u=-1,{levels:c,loadLevel:h,minAutoLevel:f,maxAutoLevel:m}=s;!s.autoLevelEnabled&&!s.config.preserveManualLevelOnError&&(s.loadLevel=-1);let p=(n=e.frag)==null?void 0:n.type,v=(p===J.AUDIO&&d===M.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(d===M.BUFFER_ADD_CODEC_ERROR||d===M.BUFFER_APPEND_ERROR))&&c.some(({audioCodec:R})=>r.audioCodec!==R),y=e.sourceBufferName==="video"&&(d===M.BUFFER_ADD_CODEC_ERROR||d===M.BUFFER_APPEND_ERROR)&&c.some(({codecSet:R,audioCodec:I})=>r.codecSet!==R&&r.audioCodec===I),{type:b,groupId:A}=(a=e.context)!=null?a:{};for(let R=c.length;R--;){let I=(R+h)%c.length;if(I!==h&&I>=f&&I<=m&&c[I].loadError===0){var o,l;let x=c[I];if(d===M.FRAG_GAP&&p===J.MAIN&&e.frag){let D=c[I].details;if(D){let S=sn(e.frag,D.fragments,e.frag.start);if(S!=null&&S.gap)continue}}else{if(b===Le.AUDIO_TRACK&&x.hasAudioGroup(A)||b===Le.SUBTITLE_TRACK&&x.hasSubtitleGroup(A))continue;if(p===J.AUDIO&&(o=r.audioGroups)!=null&&o.some(D=>x.hasAudioGroup(D))||p===J.SUBTITLE&&(l=r.subtitleGroups)!=null&&l.some(D=>x.hasSubtitleGroup(D))||v&&r.audioCodec===x.audioCodec||y&&r.codecSet===x.codecSet||!v&&r.codecSet!==x.codecSet)continue}u=I;break}}if(u>-1&&s.loadLevel!==u)return e.levelRetry=!0,this.playlistError=0,{action:Rt.SendAlternateToPenaltyBox,flags:ni.None,nextAutoLevel:u}}return{action:Rt.SendAlternateToPenaltyBox,flags:ni.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s;switch((s=t.errorAction)==null?void 0:s.action){case Rt.DoNothing:break;case Rt.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==M.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break;case Rt.RetryRequest:break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){let t=this.hls,s=e.errorAction;if(!s)return;let{flags:r}=s,n=s.nextAutoLevel;switch(r){case ni.None:this.switchLevel(e,n);break;case ni.MoveAllAlternatesMatchingHDCP:{let l=this.getVariantLevelIndex(e.frag),d=t.levels[l],u=d==null?void 0:d.attrs["HDCP-LEVEL"];if(s.hdcpLevel=u,u==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(u){t.maxHdcpLevel=Um[Um.indexOf(u)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case ni.MoveAllAlternatesMatchingKey:{let l=e.decryptdata;if(l){let d=this.hls.levels,u=d.length;for(let h=u;h--;)if(this.variantHasKey(d[h],l)){var a,o;this.log(`Banned key found in level ${h} (${d[h].bitrate}bps) or audio group "${(a=d[h].audioGroups)==null?void 0:a.join(",")}" (${(o=e.frag)==null?void 0:o.type} fragment) ${Dt(l.keyId||[])}`),d[h].fragmentError++,d[h].loadError++,this.log(`Removing level ${h} with key error (${e.error})`),this.hls.removeLevel(h)}let c=e.frag;if(this.hls.levels.length<u)s.resolved=!0;else if(c&&c.type!==J.MAIN){let h=c.decryptdata;h&&!l.matches(h)&&(s.resolved=!0)}}break}}s.resolved||this.switchLevel(e,n)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===M.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){let s=Nm(e.mimeType),r=this.hls.levels;for(let n=r.length;n--;)r[n][`${e.sourceBufferName}Codec`]===s&&(this.log(`Removing level ${n} for ${e.details} ("${s}" not supported)`),this.hls.removeLevel(n))}}};function ea(i){let e={action:Rt.DoNothing,flags:ni.None};return i&&(e.resolved=!0),e}var bt={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"},Hm=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&&(e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.BUFFER_APPENDED,this.onBufferAppended,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.BUFFER_APPENDED,this.onBufferAppended,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){let s=this.activePartLists[t];if(s)for(let r=s.length;r--;){let n=s[r];if(!n)break;if(n.start<=e&&e<=n.end&&n.loaded)return n}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,s){let{fragments:r}=this,n=Object.keys(r);for(let a=n.length;a--;){let o=r[n[a]];if((o==null?void 0:o.body.type)===t&&(!s||o.buffered)){let l=o.body;if(l.start<=e&&e<=l.end)return l}}return null}detectEvictedFragments(e,t,s,r,n){this.timeRanges&&(this.timeRanges[e]=t);let a=(r==null?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach(o=>{let l=this.fragments[o];if(!l||a>=l.body.sn)return;if(!l.buffered&&(!l.loaded||n)){l.body.type===s&&this.removeFragment(l.body);return}let d=l.range[e];if(d){if(d.time.length===0){this.removeFragment(l.body);return}d.time.some(u=>{let c=!this.isTimeBuffered(u.startPTS,u.endPTS,t);return c&&this.removeFragment(l.body),c})}})}detectPartialFragments(e){let t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;let s=e.frag,r=Yn(s),n=this.fragments[r];if(!n||n.buffered&&s.gap)return;let a=!s.relurl;Object.keys(t).forEach(o=>{let l=s.elementaryStreams[o];if(!l)return;let d=t[o],u=a||l.partial===!0;n.range[o]=this.getBufferedTimes(s,e.part,u,d)}),n.loaded=null,Object.keys(n.range).length?(this.bufferedEnd(n,s),Vd(n)||this.removeParts(s.sn-1,s.type)):this.removeFragment(n.body)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){let s=this.activePartLists[t];s&&(this.activePartLists[t]=ty(s,r=>r.fragment.sn>=e))}fragBuffered(e,t){let s=Yn(e),r=this.fragments[s];!r&&t&&(r=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,this.bufferedEnd(r,e))}getBufferedTimes(e,t,s,r){let n={time:[],partial:s},a=e.start,o=e.end,l=e.minEndPTS||o,d=e.maxStartPTS||a;for(let u=0;u<r.length;u++){let c=r.start(u)-this.bufferPadding,h=r.end(u)+this.bufferPadding;if(d>=c&&l<=h){n.time.push({startPTS:Math.max(a,r.start(u)),endPTS:Math.min(o,r.end(u))});break}else if(a<h&&o>c){let f=Math.max(a,r.start(u)),m=Math.min(o,r.end(u));m>f&&(n.partial=!0,n.time.push({startPTS:f,endPTS:m}))}else if(o<=c)break}return n}getPartialFragment(e){let t=null,s,r,n,a=0,{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(d=>{let u=l[d];u&&Vd(u)&&(r=u.body.start-o,n=u.body.end+o,e>=r&&e<=n&&(s=Math.min(e-r,n-e),a<=s&&(t=u.body,a=s)))}),t}isEndListAppended(e){let t=this.endListFragments[e];return t!==void 0&&(t.buffered||Vd(t))}getState(e){let t=Yn(e),s=this.fragments[t];return s?s.buffered?Vd(s)?bt.PARTIAL:bt.OK:bt.APPENDING:bt.NOT_LOADED}isTimeBuffered(e,t,s){let r,n;for(let a=0;a<s.length;a++){if(r=s.start(a)-this.bufferPadding,n=s.end(a)+this.bufferPadding,e>=r&&t<=n)return!0;if(t<=r)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;let s=t.frag,r=t.part?null:t,n=Yn(s);this.fragments[n]={body:s,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){let{frag:s,part:r,timeRanges:n,type:a}=t;if(s.sn==="initSegment")return;let o=s.type;if(r){let d=this.activePartLists[o];d||(this.activePartLists[o]=d=[]),d.push(r)}this.timeRanges=n;let l=n[a];this.detectEvictedFragments(a,l,o,r)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){let t=Yn(e);return!!this.fragments[t]}hasFragments(e){let{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let r=s.length;r--;){let n=t[s[r]];if((n==null?void 0:n.body.type)===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,s,r,n){r&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{let o=this.fragments[a];if(!o)return;let l=o.body;l.type!==s||r&&!l.gap||l.start<t&&l.end>e&&(o.buffered||n)&&this.removeFragment(l)})}removeFragment(e){let t=Yn(e);e.clearElementaryStreamInfo();let s=this.activePartLists[e.type];if(s){let r=e.sn;this.activePartLists[e.type]=ty(s,n=>n.fragment.sn!==r)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;let t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(s=>s.clearElementaryStreamInfo())}};function Vd(i){var e,t,s;return i.buffered&&!!(i.body.gap||(e=i.range.video)!=null&&e.partial||(t=i.range.audio)!=null&&t.partial||(s=i.range.audiovideo)!=null&&s.partial)}function Yn(i){return`${i.type}_${i.level}_${i.sn}`}function ty(i,e){return i.filter(t=>{let s=e(t);return s||t.clearElementaryStreamInfo(),s})}var ar={cbc:0,ctr:1},Gm=class{constructor(e,t,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=s}decrypt(e,t){switch(this.aesMode){case ar.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case ar.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}};function Ax(i){let e=i.byteLength,t=e&&new DataView(i.buffer).getUint8(e-1);return t?i.slice(0,e-t):i}var Km=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),s=new Uint32Array(4);for(let r=0;r<4;r++)s[r]=t.getUint32(r*4);return s}initTable(){let e=this.sBox,t=this.invSBox,s=this.subMix,r=s[0],n=s[1],a=s[2],o=s[3],l=this.invSubMix,d=l[0],u=l[1],c=l[2],h=l[3],f=new Uint32Array(256),m=0,p=0,g=0;for(g=0;g<256;g++)g<128?f[g]=g<<1:f[g]=g<<1^283;for(g=0;g<256;g++){let v=p^p<<1^p<<2^p<<3^p<<4;v=v>>>8^v&255^99,e[m]=v,t[v]=m;let T=f[m],y=f[T],b=f[y],A=f[v]*257^v*16843008;r[m]=A<<24|A>>>8,n[m]=A<<16|A>>>16,a[m]=A<<8|A>>>24,o[m]=A,A=b*16843009^y*65537^T*257^m*16843008,d[v]=A<<24|A>>>8,u[v]=A<<16|A>>>16,c[v]=A<<8|A>>>24,h[v]=A,m?(m=T^f[f[f[b^T]]],p^=f[f[p]]):m=p=1}}expandKey(e){let t=this.uint8ArrayToUint32Array_(e),s=!0,r=0;for(;r<t.length&&s;)s=t[r]===this.key[r],r++;if(s)return;this.key=t;let n=this.keySize=t.length;if(n!==4&&n!==6&&n!==8)throw new Error("Invalid aes key size="+n);let a=this.ksRows=(n+6+1)*4,o,l,d=this.keySchedule=new Uint32Array(a),u=this.invKeySchedule=new Uint32Array(a),c=this.sBox,h=this.rcon,f=this.invSubMix,m=f[0],p=f[1],g=f[2],v=f[3],T,y;for(o=0;o<a;o++){if(o<n){T=d[o]=t[o];continue}y=T,o%n===0?(y=y<<8|y>>>24,y=c[y>>>24]<<24|c[y>>>16&255]<<16|c[y>>>8&255]<<8|c[y&255],y^=h[o/n|0]<<24):n>6&&o%n===4&&(y=c[y>>>24]<<24|c[y>>>16&255]<<16|c[y>>>8&255]<<8|c[y&255]),d[o]=T=(d[o-n]^y)>>>0}for(l=0;l<a;l++)o=a-l,l&3?y=d[o]:y=d[o-4],l<4||o<=4?u[l]=y:u[l]=m[c[y>>>24]]^p[c[y>>>16&255]]^g[c[y>>>8&255]]^v[c[y&255]],u[l]=u[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,s){let r=this.keySize+6,n=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,l=o[0],d=o[1],u=o[2],c=o[3],h=this.uint8ArrayToUint32Array_(s),f=h[0],m=h[1],p=h[2],g=h[3],v=new Int32Array(e),T=new Int32Array(v.length),y,b,A,R,I,x,D,S,C,P,N,$,H,U,j=this.networkToHostOrderSwap;for(;t<v.length;){for(C=j(v[t]),P=j(v[t+1]),N=j(v[t+2]),$=j(v[t+3]),I=C^n[0],x=$^n[1],D=N^n[2],S=P^n[3],H=4,U=1;U<r;U++)y=l[I>>>24]^d[x>>16&255]^u[D>>8&255]^c[S&255]^n[H],b=l[x>>>24]^d[D>>16&255]^u[S>>8&255]^c[I&255]^n[H+1],A=l[D>>>24]^d[S>>16&255]^u[I>>8&255]^c[x&255]^n[H+2],R=l[S>>>24]^d[I>>16&255]^u[x>>8&255]^c[D&255]^n[H+3],I=y,x=b,D=A,S=R,H=H+4;y=a[I>>>24]<<24^a[x>>16&255]<<16^a[D>>8&255]<<8^a[S&255]^n[H],b=a[x>>>24]<<24^a[D>>16&255]<<16^a[S>>8&255]<<8^a[I&255]^n[H+1],A=a[D>>>24]<<24^a[S>>16&255]<<16^a[I>>8&255]<<8^a[x&255]^n[H+2],R=a[S>>>24]<<24^a[I>>16&255]<<16^a[x>>8&255]<<8^a[D&255]^n[H+3],T[t]=j(y^f),T[t+1]=j(R^m),T[t+2]=j(A^p),T[t+3]=j(b^g),f=C,m=P,p=N,g=$,t=t+4}return T.buffer}},Vm=class{constructor(e,t,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=s}expandKey(){let e=Sx(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}};function Sx(i){switch(i){case ar.cbc:return"AES-CBC";case ar.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${i}`)}}var Ix=16,Ho=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.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{let s=self.crypto;s&&(this.subtle=s.subtle||s.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 s=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?Ax(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,r){return this.useSoftware?new Promise((n,a)=>{let o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,t,s,r);let l=this.flush();l?n(l.buffer):a(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s,r)}softwareDecrypt(e,t,s,r){let{currentIV:n,currentResult:a,remainderData:o}=this;if(r!==ar.cbc||t.byteLength!==16)return Be.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=pi(o,e),this.remainderData=null);let l=this.getValidChunk(e);if(!l.length)return null;n&&(s=n);let d=this.softwareDecrypter;d||(d=this.softwareDecrypter=new Km),d.expandKey(t);let u=a;return this.currentResult=d.decrypt(l.buffer,0,s),this.currentIV=l.slice(-16).buffer,u||null}webCryptoDecrypt(e,t,s,r){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,r));this.key=t,this.fastAesKey=new Vm(this.subtle,t,r)}return this.fastAesKey.expandKey().then(n=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Gm(this.subtle,new Uint8Array(s),r).decrypt(e.buffer,n)):Promise.reject(new Error("web crypto not initialized"))).catch(n=>(Be.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(e,t,s,r)))}onWebCryptoError(e,t,s,r){let n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,r);let a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(n?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e,s=e.length-e.length%Ix;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&(Be.log(`[decrypter]: ${e}`),this.logEnabled=!1)}},iy=Math.pow(2,17),Wm=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 s=e.url;if(!s)return Promise.reject(new Mi({type:se.NETWORK_ERROR,details:M.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${s?"part list":"url"}`),networkDetails:null}));this.abort();let r=this.config,n=r.fLoader,a=r.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(m=>m[0]==="GAP")){l(ry(e));return}else e.gap=!1;let d=this.loader=n?new n(r):new a(r),u=sy(e);e.loader=d;let c=ey(r.fragLoadPolicy.default),h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:iy};e.stats=d.stats;let f={onSuccess:(m,p,g,v)=>{this.resetLoader(e,d);let T=m.data;g.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(T.slice(0,16)),T=T.slice(16)),o({frag:e,part:null,payload:T,networkDetails:v})},onError:(m,p,g,v)=>{this.resetLoader(e,d),l(new Mi({type:se.NETWORK_ERROR,details:M.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Fe({url:s,data:void 0},m),error:new Error(`HTTP Error ${m.code} ${m.text}`),networkDetails:g,stats:v}))},onAbort:(m,p,g)=>{this.resetLoader(e,d),l(new Mi({type:se.NETWORK_ERROR,details:M.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:g,stats:m}))},onTimeout:(m,p,g)=>{this.resetLoader(e,d),l(new Mi({type:se.NETWORK_ERROR,details:M.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:g,stats:m}))}};t&&(f.onProgress=(m,p,g,v)=>t({frag:e,part:null,payload:g,networkDetails:v})),d.load(u,h,f)})}loadPart(e,t,s){this.abort();let r=this.config,n=r.fLoader,a=r.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(ry(e,t));return}let d=this.loader=n?new n(r):new a(r),u=sy(e,t);e.loader=d;let c=ey(r.fragLoadPolicy.default),h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:iy};t.stats=d.stats,d.load(u,h,{onSuccess:(f,m,p,g)=>{this.resetLoader(e,d),this.updateStatsFromPart(e,t);let v={frag:e,part:t,payload:f.data,networkDetails:g};s(v),o(v)},onError:(f,m,p,g)=>{this.resetLoader(e,d),l(new Mi({type:se.NETWORK_ERROR,details:M.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Fe({url:u.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:g}))},onAbort:(f,m,p)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,d),l(new Mi({type:se.NETWORK_ERROR,details:M.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:p,stats:f}))},onTimeout:(f,m,p)=>{this.resetLoader(e,d),l(new Mi({type:se.NETWORK_ERROR,details:M.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:p,stats:f}))}})})}updateStatsFromPart(e,t){let s=e.stats,r=t.stats,n=r.total;if(s.loaded+=r.loaded,n){let l=Math.round(e.duration/t.duration),d=Math.min(Math.round(s.loaded/n),l),c=(l-d)*Math.round(s.loaded/d);s.total=s.loaded+c}else s.total=Math.max(s.loaded,s.total);let a=s.loading,o=r.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}};function sy(i,e=null){let t=e||i,s={frag:i,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},r=t.byteRangeStartOffset,n=t.byteRangeEndOffset;if(Q(r)&&Q(n)){var a;let o=r,l=n;if(i.sn==="initSegment"&&Lx((a=i.decryptdata)==null?void 0:a.method)){let d=n-r;d%16&&(l=n+(16-d%16)),r!==0&&(s.resetIV=!0,o=r-16)}s.rangeStart=o,s.rangeEnd=l}return s}function ry(i,e){let t=new Error(`GAP ${i.gap?"tag":"attribute"} found`),s={type:se.MEDIA_ERROR,details:M.FRAG_GAP,fatal:!1,frag:i,error:t,networkDetails:null};return e&&(s.part=e),(e||i).stats.aborted=!0,new Mi(s)}function Lx(i){return i==="AES-128"||i==="AES-256"}var Mi=class extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}},vu=class extends Qt{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}},Go=class{constructor(e,t,s,r=0,n=-1,a=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=Wd(),this.buffering={audio:Wd(),video:Wd(),audiovideo:Wd()},this.level=e,this.sn=t,this.id=s,this.size=r,this.part=n,this.partial=a}};function Wd(){return{start:0,executeStart:0,executeEnd:0,end:0}}var ny={length:0,start:()=>0,end:()=>0},Ee=class i{static isBuffered(e,t){if(e){let s=i.getBuffered(e);for(let r=s.length;r--;)if(t>=s.start(r)&&t<=s.end(r))return!0}return!1}static bufferedRanges(e){if(e){let t=i.getBuffered(e);return i.timeRangesToArray(t)}return[]}static timeRangesToArray(e){let t=[];for(let s=0;s<e.length;s++)t.push({start:e.start(s),end:e.end(s)});return t}static bufferInfo(e,t,s){if(e){let r=i.bufferedRanges(e);if(r.length)return i.bufferedInfo(r,t,s)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.length>1&&e.sort((u,c)=>u.start-c.start||c.end-u.end);let r=-1,n=[];if(s)for(let u=0;u<e.length;u++){t>=e[u].start&&t<=e[u].end&&(r=u);let c=n.length;if(c){let h=n[c-1].end;e[u].start-h<s?e[u].end>h&&(n[c-1].end=e[u].end):n.push(e[u])}else n.push(e[u])}else n=e;let a=0,o,l=t,d=t;for(let u=0;u<n.length;u++){let c=n[u].start,h=n[u].end;if(r===-1&&t>=c&&t<=h&&(r=u),t+s>=c&&t<h)l=c,d=h,a=d-t;else if(t+s<c){o=c;break}}return{len:a,start:l||0,end:d||0,nextStart:o,buffered:e,bufferedIndex:r}}static getBuffered(e){try{return e.buffered||ny}catch(t){return Be.log("failed to get media.buffered",t),ny}}},vT=/\{\$([a-zA-Z0-9-_]+)\}/g;function ay(i){return vT.test(i)}function qm(i,e){if(i.variableList!==null||i.hasVariableRefs){let t=i.variableList;return e.replace(vT,s=>{let r=s.substring(2,s.length-1),n=t==null?void 0:t[r];return n===void 0?(i.playlistParsingError||(i.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),s):n})}return e}function oy(i,e,t){let s=i.variableList;s||(i.variableList=s={});let r,n;if("QUERYPARAM"in e){r=e.QUERYPARAM;try{let a=new self.URL(t).searchParams;if(a.has(r))n=a.get(r);else throw new Error(`"${r}" does not match any query parameter in URI: "${t}"`)}catch(a){i.playlistParsingError||(i.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else r=e.NAME,n=e.VALUE;r in s?i.playlistParsingError||(i.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):s[r]=n||""}function Rx(i,e,t){let s=e.IMPORT;if(t&&s in t){let r=i.variableList;r||(i.variableList=r={}),r[s]=t[s]}else i.playlistParsingError||(i.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}var xx=/^(\d+)x(\d+)$/,ly=/(.+?)=(".*?"|.*?)(?:,|$)/g,tt=class i{constructor(e,t){typeof e=="string"&&(e=i.parseAttrList(e,t)),$e(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){let t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;let s=new Uint8Array(t.length/2);for(let r=0;r<t.length/2;r++)s[r]=parseInt(t.slice(r*2,r*2+2),16);return s}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 s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){let s=this[e];return(s?s.split(/[ ,]+/):[]).reduce((r,n)=>(r[n.toLowerCase()]=!0,r),t)}bool(e){return this[e]==="YES"}decimalResolution(e){let t=xx.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let s,r={},n='"';for(ly.lastIndex=0;(s=ly.exec(e))!==null;){let a=s[1].trim(),o=s[2],l=o.indexOf(n)===0&&o.lastIndexOf(n)===o.length-1,d=!1;if(l)o=o.slice(1,-1);else switch(a){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":d=!0}if(t&&(l||d))o=qm(t,o);else if(!d&&!l)switch(a){case"CLOSED-CAPTIONS":if(o==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":Be.warn(`${e}: attribute ${a} is missing quotes`)}r[a]=o}return r}},kx="com.apple.hls.interstitial";function Dx(i){return i!=="ID"&&i!=="CLASS"&&i!=="CUE"&&i!=="START-DATE"&&i!=="DURATION"&&i!=="END-DATE"&&i!=="END-ON-NEXT"}function Cx(i){return i==="SCTE35-OUT"||i==="SCTE35-IN"||i==="SCTE35-CMD"}var Eu=class{constructor(e,t,s=0){var r;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(t==null?void 0:t.tagAnchor)||null,this.tagOrder=(r=t==null?void 0:t.tagOrder)!=null?r:s,t){let n=t.attr;for(let a in n)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==n[a]){Be.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=$e(new tt({}),n,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){let n=(t==null?void 0:t.endDate)||new Date(this.attr["END-DATE"]);Q(n.getTime())&&(this._endDate=n)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){let e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){let{tagAnchor:e}=this;return e===null||e.programDateTime===null?(Be.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){let e=this._endDate||this._dateAtEnd;if(e)return e;let t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){let e=this.attr.decimalFloatingPoint("DURATION");if(Q(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===kx}get isValid(){return!!this.id&&!this._badValueForSameId&&Q(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}},wx=10,Ym=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.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!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.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}let t=this.lastPartSn-e.lastPartSn,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&s>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let s=t.decryptdata;return s||(t.setKeyFormat(e.keyFormat),s=t.decryptdata),!!s&&e.matches(s)})}get hasProgramDateTime(){return this.fragments.length?Q(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||wx}get drift(){let e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){let e=this.partList;if(e){let t=this.lastPartIndex;if(t!==-1){for(let s=e.length;s--;)if(e[s].index>t)return e[s].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){let e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}};function yu(i,e){return i.length===e.length?!i.some((t,s)=>t!==e[s]):!1}function dy(i,e){return!i&&!e?!0:!i||!e?!1:yu(i,e)}function ta(i){return i==="AES-128"||i==="AES-256"||i==="AES-256-CTR"}function tg(i){switch(i){case"AES-128":case"AES-256":return ar.cbc;case"AES-256-CTR":return ar.ctr;default:throw new Error(`invalid full segment method ${i}`)}}function ig(i){return Uint8Array.from(atob(i),e=>e.charCodeAt(0))}function jm(i){return Uint8Array.from(unescape(encodeURIComponent(i)),e=>e.charCodeAt(0))}function Mx(i){let e=jm(i).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function ET(i){let e=function(s,r,n){let a=s[r];s[r]=s[n],s[n]=a};e(i,0,3),e(i,1,2),e(i,4,5),e(i,6,7)}function yT(i){let e=i.split(":"),t=null;if(e[0]==="data"&&e.length===2){let s=e[1].split(";"),r=s[s.length-1].split(",");if(r.length===2){let n=r[0]==="base64",a=r[1];n?(s.splice(-1,1),t=ig(a)):t=Mx(a)}}return t}var Tu=typeof self!="undefined"?self:void 0,it={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Ct={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function ru(i){switch(i){case Ct.FAIRPLAY:return it.FAIRPLAY;case Ct.PLAYREADY:return it.PLAYREADY;case Ct.WIDEVINE:return it.WIDEVINE;case Ct.CLEARKEY:return it.CLEARKEY}}function fm(i){switch(i){case it.FAIRPLAY:return Ct.FAIRPLAY;case it.PLAYREADY:return Ct.PLAYREADY;case it.WIDEVINE:return Ct.WIDEVINE;case it.CLEARKEY:return Ct.CLEARKEY}}function Mo(i){let{drmSystems:e,widevineLicenseUrl:t}=i,s=e?[it.FAIRPLAY,it.WIDEVINE,it.PLAYREADY,it.CLEARKEY].filter(r=>!!e[r]):[];return!s[it.WIDEVINE]&&t&&s.push(it.WIDEVINE),s}var TT=function(i){return Tu!=null&&(i=Tu.navigator)!=null&&i.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function Px(i,e,t,s){let r;switch(i){case it.FAIRPLAY:r=["cenc","sinf"];break;case it.WIDEVINE:case it.PLAYREADY:r=["cenc"];break;case it.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${i}`)}return Ox(r,e,t,s)}function Ox(i,e,t,s){return[{initDataTypes:i,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:e.map(n=>({contentType:`audio/mp4; codecs=${n}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:t.map(n=>({contentType:`video/mp4; codecs=${n}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}function Nx(i){var e;return!!i&&(i.sessionType==="persistent-license"||!!((e=i.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function bT(i){let e=new Uint16Array(i.buffer,i.byteOffset,i.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),s=t.substring(t.indexOf("<"),t.length),a=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(a){let o=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute("VALUE");if(o){let l=ig(o).subarray(0,16);return ET(l),l}}return null}var jn={},na=class i{static clearKeyUriToKeyIdMap(){jn={}}static setKeyIdForUri(e,t){jn[e]=t}static addKeyIdForUri(e){let t=Object.keys(jn).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,t),jn[e]=s,s}constructor(e,t,s,r=[1],n=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=s,this.keyFormatVersions=r,this.iv=n,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!ta(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(Zy(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&yu(e.keyFormatVersions,this.keyFormatVersions)&&dy(e.iv,this.iv)&&dy(e.keyId,this.keyId)}isSupported(){if(this.method){if(ta(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Ct.FAIRPLAY:case Ct.WIDEVINE:case Ct.PLAYREADY:case Ct.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(ta(this.method)){let n=this.iv;return n||(typeof e!="number"&&(Be.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),n=Fx(e)),new i(this.method,this.uri,"identity",this.keyFormatVersions,n)}if(this.keyId){let n=jn[this.uri];if(n&&!yu(this.keyId,n)&&i.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}let s=yT(this.uri);if(s)switch(this.keyFormat){case Ct.WIDEVINE:if(this.pssh=s,!this.keyId){let n=zR(s.buffer);if(n.length){var r;let a=n[0];this.keyId=(r=a.kids)!=null&&r.length?a.kids[0]:null}}this.keyId||(this.keyId=uy(t));break;case Ct.PLAYREADY:{let n=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=jR(n,null,s),this.keyId=bT(s);break}default:{let n=s.subarray(0,16);if(n.length!==16){let a=new Uint8Array(16);a.set(n,16-n.length),n=a}this.keyId=n;break}}if(!this.keyId||this.keyId.byteLength!==16){let n;n=Ux(t),n||(n=uy(t),n||(n=jn[this.uri])),n&&(this.keyId=n,i.setKeyIdForUri(this.uri,n))}return this}};function Ux(i){let e=i==null?void 0:i[Ct.WIDEVINE];return e?e.keyId:null}function uy(i){let e=i==null?void 0:i[Ct.PLAYREADY];if(e){let t=yT(e.uri);if(t)return bT(t)}return null}function Fx(i){let e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=i>>8*(15-t)&255;return e}var cy=/#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,hy=/#EXT-X-MEDIA:(.*)/g,Bx=/^#EXT(?:INF|-X-TARGETDURATION):/m,mm=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),$x=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),Zr=class i{static findGroup(e,t){for(let s=0;s<e.length;s++){let r=e[s];if(r.id===t)return r}}static resolve(e,t){return Qp.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Bx.test(e)}static parseMasterPlaylist(e,t){let s=ay(e),r={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:s},n=[];if(cy.lastIndex=0,!e.startsWith("#EXTM3U"))return r.playlistParsingError=new Error("no EXTM3U delimiter"),r;let a;for(;(a=cy.exec(e))!=null;)if(a[1]){var o;let d=new tt(a[1],r),u=qm(r,a[2]),c={attrs:d,bitrate:d.decimalInteger("BANDWIDTH")||d.decimalInteger("AVERAGE-BANDWIDTH"),name:d.NAME,url:i.resolve(u,t)},h=d.decimalResolution("RESOLUTION");h&&(c.width=h.width,c.height=h.height),py(d.CODECS,c);let f=d["SUPPLEMENTAL-CODECS"];f&&(c.supplemental={},py(f,c.supplemental)),(o=c.unknownCodecs)!=null&&o.length||n.push(c),r.levels.push(c)}else if(a[3]){let d=a[3],u=a[4];switch(d){case"SESSION-DATA":{let c=new tt(u,r),h=c["DATA-ID"];h&&(r.sessionData===null&&(r.sessionData={}),r.sessionData[h]=c);break}case"SESSION-KEY":{let c=fy(u,t,r);c.encrypted&&c.isSupported()?(r.sessionKeys===null&&(r.sessionKeys=[]),r.sessionKeys.push(c)):Be.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${u}"`);break}case"DEFINE":{{let c=new tt(u,r);oy(r,c,t)}break}case"CONTENT-STEERING":{let c=new tt(u,r);r.contentSteering={uri:i.resolve(c["SERVER-URI"],t),pathwayId:c["PATHWAY-ID"]||"."};break}case"START":{r.startTimeOffset=my(u);break}}}let l=n.length>0&&n.length<r.levels.length;return r.levels=l?n:r.levels,r.levels.length===0&&(r.playlistParsingError=new Error("no levels found in manifest")),r}static parseMasterPlaylistMedia(e,t,s){let r,n={},a=s.levels,o={AUDIO:a.map(d=>({id:d.attrs.AUDIO,audioCodec:d.audioCodec})),SUBTITLES:a.map(d=>({id:d.attrs.SUBTITLES,textCodec:d.textCodec})),"CLOSED-CAPTIONS":[]},l=0;for(hy.lastIndex=0;(r=hy.exec(e))!==null;){let d=new tt(r[1],s),u=d.TYPE;if(u){let c=o[u],h=n[u]||[];n[u]=h;let f=d.LANGUAGE,m=d["ASSOC-LANGUAGE"],p=d.CHANNELS,g=d.CHARACTERISTICS,v=d["INSTREAM-ID"],T={attrs:d,bitrate:0,id:l++,groupId:d["GROUP-ID"]||"",name:d.NAME||f||"",type:u,default:d.bool("DEFAULT"),autoselect:d.bool("AUTOSELECT"),forced:d.bool("FORCED"),lang:f,url:d.URI?i.resolve(d.URI,t):""};if(m&&(T.assocLang=m),p&&(T.channels=p),g&&(T.characteristics=g),v&&(T.instreamId=v),c!=null&&c.length){let y=i.findGroup(c,T.groupId)||c[0];gy(T,y,"audioCodec"),gy(T,y,"textCodec")}h.push(T)}}return n}static parseLevelPlaylist(e,t,s,r,n,a){var o;let l={url:t},d=new Ym(t),u=d.fragments,c=[],h=null,f=0,m=0,p=0,g=0,v=0,T=null,y=new Po(r,l),b,A,R,I=-1,x=!1,D=null,S;if(mm.lastIndex=0,d.m3u8=e,d.hasVariableRefs=ay(e),((o=mm.exec(e))==null?void 0:o[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;(b=mm.exec(e))!==null;){x&&(x=!1,y=new Po(r,l),y.playlistOffset=p,y.setStart(p),y.sn=f,y.cc=g,v&&(y.bitrate=v),y.level=s,h&&(y.initSegment=h,h.rawProgramDateTime&&(y.rawProgramDateTime=h.rawProgramDateTime,h.rawProgramDateTime=null),D&&(y.setByteRange(D),D=null)));let $=b[1];if($){y.duration=parseFloat($);let H=(" "+b[2]).slice(1);y.title=H||null,y.tagList.push(H?["INF",$,H]:["INF",$])}else if(b[3]){if(Q(y.duration)){y.playlistOffset=p,y.setStart(p),R&&Ey(y,R,d),y.sn=f,y.level=s,y.cc=g,u.push(y);let H=(" "+b[3]).slice(1);y.relurl=qm(d,H),zm(y,T,c),T=y,p+=y.duration,f++,m=0,x=!0}}else{if(b=b[0].match($x),!b){Be.warn("No matches on slow regex match for level playlist!");continue}for(A=1;A<b.length&&b[A]===void 0;A++);let H=(" "+b[A]).slice(1),U=(" "+b[A+1]).slice(1),j=b[A+2]?(" "+b[A+2]).slice(1):null;switch(H){case"BYTERANGE":T?y.setByteRange(U,T):y.setByteRange(U);break;case"PROGRAM-DATE-TIME":y.rawProgramDateTime=U,y.tagList.push(["PROGRAM-DATE-TIME",U]),I===-1&&(I=u.length);break;case"PLAYLIST-TYPE":d.type&&Rs(d,H,b),d.type=U.toUpperCase();break;case"MEDIA-SEQUENCE":d.startSN!==0?Rs(d,H,b):u.length>0&&yy(d,H,b),f=d.startSN=parseInt(U);break;case"SKIP":{d.skippedSegments&&Rs(d,H,b);let q=new tt(U,d),Z=q.decimalInteger("SKIPPED-SEGMENTS");if(Q(Z)){d.skippedSegments+=Z;for(let V=Z;V--;)u.push(null);f+=Z}let re=q.enumeratedString("RECENTLY-REMOVED-DATERANGES");re&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(re.split(" ")));break}case"TARGETDURATION":d.targetduration!==0&&Rs(d,H,b),d.targetduration=Math.max(parseInt(U),1);break;case"VERSION":d.version!==null&&Rs(d,H,b),d.version=parseInt(U);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":d.live||Rs(d,H,b),d.live=!1;break;case"#":(U||j)&&y.tagList.push(j?[U,j]:[U]);break;case"DISCONTINUITY":g++,y.tagList.push(["DIS"]);break;case"GAP":y.gap=!0,y.tagList.push([H]);break;case"BITRATE":y.tagList.push([H,U]),v=parseInt(U)*1e3,Q(v)?y.bitrate=v:v=0;break;case"DATERANGE":{let q=new tt(U,d),Z=new Eu(q,d.dateRanges[q.ID],d.dateRangeTagCount);d.dateRangeTagCount++,Z.isValid||d.skippedSegments?d.dateRanges[Z.id]=Z:Be.warn(`Ignoring invalid DATERANGE tag: "${U}"`),y.tagList.push(["EXT-X-DATERANGE",U]);break}case"DEFINE":{{let q=new tt(U,d);"IMPORT"in q?Rx(d,q,a):oy(d,q,t)}break}case"DISCONTINUITY-SEQUENCE":d.startCC!==0?Rs(d,H,b):u.length>0&&yy(d,H,b),d.startCC=g=parseInt(U);break;case"KEY":{let q=fy(U,t,d);if(q.isSupported()){if(q.method==="NONE"){R=void 0;break}R||(R={});let Z=R[q.keyFormat];Z!=null&&Z.matches(q)||(Z&&(R=$e({},R)),R[q.keyFormat]=q)}else Be.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${U}"`);break}case"START":d.startTimeOffset=my(U);break;case"MAP":{let q=new tt(U,d);if(y.duration){let Z=new Po(r,l);vy(Z,q,s,R),h=Z,y.initSegment=h,h.rawProgramDateTime&&!y.rawProgramDateTime&&(y.rawProgramDateTime=h.rawProgramDateTime)}else{let Z=y.byteRangeEndOffset;if(Z){let re=y.byteRangeStartOffset;D=`${Z-re}@${re}`}else D=null;vy(y,q,s,R),h=y,x=!0}h.cc=g;break}case"SERVER-CONTROL":{S&&Rs(d,H,b),S=new tt(U),d.canBlockReload=S.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=S.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&S.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=S.optionalFloat("PART-HOLD-BACK",0),d.holdBack=S.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{d.partTarget&&Rs(d,H,b);let q=new tt(U);d.partTarget=q.decimalFloatingPoint("PART-TARGET");break}case"PART":{let q=d.partList;q||(q=d.partList=[]);let Z=m>0?q[q.length-1]:void 0,re=m++,V=new tt(U,d),G=new Om(V,y,l,re,Z);q.push(G),y.duration+=G.duration;break}case"PRELOAD-HINT":{let q=new tt(U,d);d.preloadHint=q;break}case"RENDITION-REPORT":{let q=new tt(U,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(q);break}default:Be.warn(`line parsed but not handled: ${b}`);break}}}T&&!T.relurl?(u.pop(),p-=T.duration,d.partList&&(d.fragmentHint=T)):d.partList&&(zm(y,T,c),y.cc=g,d.fragmentHint=y,R&&Ey(y,R,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));let C=u.length,P=u[0],N=u[C-1];if(p+=d.skippedSegments*d.targetduration,p>0&&C&&N){d.averagetargetduration=p/C;let $=N.sn;d.endSN=$!=="initSegment"?$:0,d.live||(N.endList=!0),I>0&&(Gx(u,I),P&&c.unshift(P))}return d.fragmentHint&&(p+=d.fragmentHint.duration),d.totalduration=p,c.length&&d.dateRangeTagCount&&P&&_T(c,d),d.endCC=g,d}};function _T(i,e){let t=i.length;if(!t)if(e.hasProgramDateTime){let o=e.fragments[e.fragments.length-1];i.push(o),t++}else return;let s=i[t-1],r=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let o=n.length;o--;){let l=e.dateRanges[n[o]],d=l.startDate.getTime();l.tagAnchor=s.ref;for(let u=t;u--;){var a;if(((a=i[u])==null?void 0:a.sn)<e.startSN)break;let c=Hx(e,d,i,u,r);if(c!==-1){l.tagAnchor=e.fragments[c].ref;break}}}}function Hx(i,e,t,s,r){let n=t[s];if(n){let o=n.programDateTime;if(e>=o||s===0){var a;let l=(((a=t[s+1])==null?void 0:a.start)||r)-n.start;if(e<=o+l*1e3){let d=t[s].sn-i.startSN;if(d<0)return-1;let u=i.fragments;if(u.length>t.length){let h=(t[s+1]||u[u.length-1]).sn-i.startSN;for(let f=h;f>d;f--){let m=u[f].programDateTime;if(e>=m&&e<m+u[f].duration*1e3)return f}}return d}}}return-1}function fy(i,e,t){var s,r;let n=new tt(i,t),a=(s=n.METHOD)!=null?s:"",o=n.URI,l=n.hexadecimalInteger("IV"),d=n.KEYFORMATVERSIONS,u=(r=n.KEYFORMAT)!=null?r:"identity";o&&n.IV&&!l&&Be.error(`Invalid IV: ${n.IV}`);let c=o?Zr.resolve(o,e):"",h=(d||"1").split("/").map(Number).filter(Number.isFinite);return new na(a,c,u,h,l,n.KEYID)}function my(i){let t=new tt(i).decimalFloatingPoint("TIME-OFFSET");return Q(t)?t:null}function py(i,e){let t=(i||"").split(/[ ,]+/).filter(s=>s);["video","audio","text"].forEach(s=>{let r=t.filter(n=>Zp(n,s));r.length&&(e[`${s}Codec`]=r.map(n=>n.split("/")[0]).join(","),t=t.filter(n=>r.indexOf(n)===-1))}),e.unknownCodecs=t}function gy(i,e,t){let s=e[t];s&&(i[t]=s)}function Gx(i,e){let t=i[e];for(let s=e;s--;){let r=i[s];if(!r)return;r.programDateTime=t.programDateTime-r.duration*1e3,t=r}}function zm(i,e,t){i.rawProgramDateTime?t.push(i):e!=null&&e.programDateTime&&(i.programDateTime=e.endProgramDateTime)}function vy(i,e,t,s){i.relurl=e.URI,e.BYTERANGE&&i.setByteRange(e.BYTERANGE),i.level=t,i.sn="initSegment",s&&(i.levelkeys=s),i.initSegment=null}function Ey(i,e,t){i.levelkeys=e;let{encryptedFragments:s}=t;(!s.length||s[s.length-1].levelkeys!==e)&&Object.keys(e).some(r=>e[r].isCommonEncryption)&&s.push(i)}function Rs(i,e,t){i.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function yy(i,e,t){i.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function pm(i,e){let t=e.startPTS;if(Q(t)){let s=0,r;e.sn>i.sn?(s=t-i.start,r=i):(s=i.start-t,r=e),r.duration!==s&&r.setDuration(s)}else e.sn>i.sn?i.cc===e.cc&&i.minEndPTS?e.setStart(i.start+(i.minEndPTS-i.start)):e.setStart(i.start+i.duration):e.setStart(Math.max(i.start-e.duration,0))}function AT(i,e,t,s,r,n,a){s-t<=0&&(a.warn("Fragment should have a positive duration",e),s=t+e.duration,n=r+e.duration);let l=t,d=s,u=e.startPTS,c=e.endPTS;if(Q(u)){let v=Math.abs(u-t);i&&v>i.totalduration?a.warn(`media timestamps and playlist times differ by ${v}s for level ${e.level} ${i.url}`):Q(e.deltaPTS)?e.deltaPTS=Math.max(v,e.deltaPTS):e.deltaPTS=v,l=Math.max(t,u),t=Math.min(t,u),r=e.startDTS!==void 0?Math.min(r,e.startDTS):r,d=Math.min(s,c),s=Math.max(s,c),n=e.endDTS!==void 0?Math.max(n,e.endDTS):n}let h=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(s-e.start),e.startPTS=t,e.maxStartPTS=l,e.startDTS=r,e.endPTS=s,e.minEndPTS=d,e.endDTS=n;let f=e.sn;if(!i||f<i.startSN||f>i.endSN)return 0;let m,p=f-i.startSN,g=i.fragments;for(g[p]=e,m=p;m>0;m--)pm(g[m],g[m-1]);for(m=p;m<g.length-1;m++)pm(g[m],g[m+1]);return i.fragmentHint&&pm(g[g.length-1],i.fragmentHint),i.PTSKnown=i.alignedSliding=!0,h}function Kx(i,e,t){if(i===e)return;let s=null,r=i.fragments;for(let u=r.length-1;u>=0;u--){let c=r[u].initSegment;if(c){s=c;break}}i.fragmentHint&&delete i.fragmentHint.endPTS;let n;qx(i,e,(u,c,h,f)=>{if((!e.startCC||e.skippedSegments)&&c.cc!==u.cc){let m=u.cc-c.cc;for(let p=h;p<f.length;p++)f[p].cc+=m;e.endCC=f[f.length-1].cc}Q(u.startPTS)&&Q(u.endPTS)&&(c.setStart(c.startPTS=u.startPTS),c.startDTS=u.startDTS,c.maxStartPTS=u.maxStartPTS,c.endPTS=u.endPTS,c.endDTS=u.endDTS,c.minEndPTS=u.minEndPTS,c.setDuration(u.endPTS-u.startPTS),c.duration&&(n=c),e.PTSKnown=e.alignedSliding=!0),u.hasStreams&&(c.elementaryStreams=u.elementaryStreams),c.loader=u.loader,u.hasStats&&(c.stats=u.stats),u.initSegment&&(c.initSegment=u.initSegment,s=u.initSegment)});let a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(s&&o.forEach(u=>{var c;u&&(!u.initSegment||u.initSegment.relurl===((c=s)==null?void 0:c.relurl))&&(u.initSegment=s)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(u=>!u),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let u=e.skippedSegments;u--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=Vx(i.dateRanges,e,t));let u=i.fragments.filter(c=>c.rawProgramDateTime);if(i.hasProgramDateTime&&!e.hasProgramDateTime)for(let c=1;c<o.length;c++)o[c].programDateTime===null&&zm(o[c],o[c-1],u);_T(u,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var l;let u=LT(i,e.startSN-1);e.startCC=(l=u==null?void 0:u.cc)!=null?l:a[0].cc}Wx(i.partList,e.partList,(u,c)=>{c.elementaryStreams=u.elementaryStreams,c.stats=u.stats}),n?AT(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,t):ST(i,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=i.driftStartTime,e.driftStart=i.driftStart;let d=e.advancedDateTime;if(e.advanced&&d){let u=e.edge;e.driftStart||(e.driftStartTime=d,e.driftStart=u),e.driftEndTime=d,e.driftEnd=u}else e.driftEndTime=i.driftEndTime,e.driftEnd=i.driftEnd,e.advancedDateTime=i.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=i.requestScheduled)}function Vx(i,e,t){let{dateRanges:s,recentlyRemovedDateranges:r}=e,n=$e({},i);r&&r.forEach(l=>{delete n[l]});let o=Object.keys(n).length;return o?(Object.keys(s).forEach(l=>{let d=n[l],u=new Eu(s[l].attr,d);u.isValid?(n[l]=u,d||(u.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${qe(s[l].attr)}"`)}),n):s}function Wx(i,e,t){if(i&&e){let s=0;for(let r=0,n=i.length;r<=n;r++){let a=i[r],o=e[r+s];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):s--}}}function qx(i,e,t){let s=e.skippedSegments,r=Math.max(i.startSN,e.startSN)-e.startSN,n=(i.fragmentHint?1:0)+(s?e.endSN:Math.min(i.endSN,e.endSN))-e.startSN,a=e.startSN-i.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=i.fragmentHint?i.fragments.concat(i.fragmentHint):i.fragments;for(let d=r;d<=n;d++){let u=l[a+d],c=o[d];if(s&&!c&&u&&(c=e.fragments[d]=u),u&&c){t(u,c,d,o);let h=u.relurl,f=c.relurl;if(h&&Yx(h,f)){e.playlistParsingError=Ty(`media sequence mismatch ${c.sn}:`,i,e,u,c);return}else if(u.cc!==c.cc){e.playlistParsingError=Ty(`discontinuity sequence mismatch (${u.cc}!=${c.cc})`,i,e,u,c);return}}}}function Ty(i,e,t,s,r){return new Error(`${i} ${r.url}
26
+ Time to underbuffer: ${Se.toFixed(3)} s`),r.abortRequests(),this.fragCurrent=this.partCurrent=null,re>f){let he=this.findBestLevel(this.hls.levels[f].bitrate,f,re,0,Se,1,1);he===-1&&(he=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=he,this.resetEstimator(this.hls.levels[he].bitrate)}}};g||H>Z*2?ce():this.timer=self.setInterval(ce,Z*1e3),a.trigger(E.FRAG_LOAD_EMERGENCY_ABORTED,{frag:r,part:n,stats:u})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){let e=this.hls.config;return new wm(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){let{hls:e}=this;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e&&(e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(E.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){let s=t.frag;if(!this.ignoreFragment(s)){if(!s.bitrateTest){var r;this.fragCurrent=s,this.partCurrent=(r=t.part)!=null?r:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case M.BUFFER_ADD_CODEC_ERROR:case M.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case M.FRAG_LOAD_TIMEOUT:{let s=t.frag,{fragCurrent:r,partCurrent:n}=this;if(s&&r&&s.sn===r.sn&&s.level===r.level){let a=performance.now(),o=n?n.stats:s.stats,l=a-o.loading.start,d=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&d>-1){let c=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(c,d),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,t,s,r){let n=e+s/t,a=r?e+this.lastLevelLoadSec:0;return n+a}onLevelLoaded(e,t){let s=this.hls.config,{loading:r}=t.stats,n=r.end-r.first;Q(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:s}){let r=s?s.stats:t.stats;if(t.type===J.MAIN&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){let n=s?s.duration:t.duration,a=this.hls.levels[t.level],o=(a.loaded?a.loaded.bytes:0)+r.loaded,l=(a.loaded?a.loaded.duration:0)+n;a.loaded={bytes:o,duration:l},a.realBitrate=Math.round(8*o/l)}if(t.bitrateTest){let n={stats:r,frag:t,part:s,id:t.type};this.onFragBuffered(E.FRAG_BUFFERED,n),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){let{frag:s,part:r}=t,n=r!=null&&r.stats.loaded?r.stats:s.stats;if(n.aborted||this.ignoreFragment(s))return;let a=n.parsing.end-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,n.loaded),n.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==J.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){let{maxAutoLevel:e,minAutoLevel:t}=this.hls,s=this.getBwEstimate(),r=this.hls.config.maxStarvationDelay,n=this.findBestLevel(s,t,e,0,r,1,1);if(n>-1)return n;let a=this.hls.firstLevel,o=Math.min(Math.max(a,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${a} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){let e=this.forcedAutoLevel,s=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(e!==-1&&(!s||!r||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;let n=s&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){let a=this.hls.levels;if(a.length>Math.max(e,n)&&a[e].loadError<=a[n].loadError)return e}return this._nextAutoLevel=n,this.nextAutoLevelKey=this.getAutoLevelKey(),n}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){let{fragCurrent:e,partCurrent:t,hls:s}=this;if(s.levels.length<=1)return s.loadLevel;let{maxAutoLevel:r,config:n,minAutoLevel:a}=s,o=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),d=this.getStarvationDelay(),u=n.abrBandWidthFactor,c=n.abrBandWidthUpFactor;if(d){let g=this.findBestLevel(l,a,r,d,0,u,c);if(g>=0)return this.rebufferNotice=-1,g}let h=o?Math.min(o,n.maxStarvationDelay):n.maxStarvationDelay;if(!d){let g=this.bitrateTestDelay;g&&(h=(o?Math.min(o,n.maxLoadingDelay):n.maxLoadingDelay)-g,this.info(`bitrate test took ${Math.round(1e3*g)}ms, set first fragment max fetchDuration to ${Math.round(1e3*h)} ms`),u=c=1)}let f=this.findBestLevel(l,a,r,d,h,u,c);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${d?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;let m=s.levels[a],p=s.loadLevelObj;return p&&(m==null?void 0:m.bitrate)<p.bitrate?a:s.loadLevel}getStarvationDelay(){let e=this.hls,t=e.media;if(!t)return 1/0;let s=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,r=e.mainForwardBufferInfo;return(r?r.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,s,r,n,a,o){var l;let d=r+n,u=this.lastLoadedFragLevel,c=u===-1?this.hls.firstLevel:u,{fragCurrent:h,partCurrent:f}=this,{levels:m,allAudioTracks:p,loadLevel:g,config:v}=this.hls;if(m.length===1)return 0;let b=m[c],y=!!((l=this.hls.latestLevelDetails)!=null&&l.live),T=g===-1||u===-1,A,R="SDR",I=(b==null?void 0:b.frameRate)||0,{audioPreference:x,videoPreference:D}=v,S=this.audioTracksByGroup||(this.audioTracksByGroup=hb(p)),C=-1;if(T){if(this.firstSelection!==-1)return this.firstSelection;let U=this.codecTiers||(this.codecTiers=px(m,S,t,s)),j=mx(U,R,e,x,D),{codecSet:q,videoRanges:Z,minFramerate:re,minBitrate:V,minIndex:G,preferHDR:ce}=j;C=G,A=q,R=ce?Z[Z.length-1]:Z[0],I=re,e=Math.max(e,V),this.log(`picked start tier ${qe(j)}`)}else A=b==null?void 0:b.codecSet,R=b==null?void 0:b.videoRange;let P=f?f.duration:h?h.duration:0,N=this.bwEstimator.getEstimateTTFB()/1e3,$=[];for(let U=s;U>=t;U--){var H;let j=m[U],q=U>c;if(!j)continue;if(v.useMediaCapabilities&&!j.supportedResult&&!j.supportedPromise){let he=navigator.mediaCapabilities;typeof(he==null?void 0:he.decodingInfo)=="function"&&rx(j,S,R,I,e,x)?(j.supportedPromise=ub(j,S,he,this.supportedCache),j.supportedPromise.then(be=>{if(!this.hls)return;j.supportedResult=be;let vt=this.hls.levels,ut=vt.indexOf(j);be.error?this.warn(`MediaCapabilities decodingInfo error: "${be.error}" for level ${ut} ${qe(be)}`):be.supported?be.decodingInfoResults.some(Ft=>Ft.smooth===!1||Ft.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${ut} not smooth or powerEfficient: ${qe(be)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${ut} ${qe(be)}`),ut>-1&&vt.length>1&&(this.log(`Removing unsupported level ${ut}`),this.hls.removeLevel(ut),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(be=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${be}`)})):j.supportedResult=lb}if((A&&j.codecSet!==A||R&&j.videoRange!==R||q&&I>j.frameRate||!q&&I>0&&I<j.frameRate||(H=j.supportedResult)!=null&&(H=H.decodingInfoResults)!=null&&H.some(he=>he.smooth===!1))&&(!T||U!==C)){$.push(U);continue}let Z=j.details,re=(f?Z==null?void 0:Z.partTarget:Z==null?void 0:Z.averagetargetduration)||P,V;q?V=o*e:V=a*e;let G=P&&r>=P*2&&n===0?j.averageBitrate:j.maxBitrate,ce=this.getTimeToLoadFrag(N,V,G*re,Z===void 0);if(V>=G&&(U===u||j.loadError===0&&j.fragmentError===0)&&(ce<=N||!Q(ce)||y&&!this.bitrateTestDelay||ce<d)){let he=this.forcedAutoLevel;return U!==g&&(he===-1||he!==g)&&($.length&&this.trace(`Skipped level(s) ${$.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${m[$[0]].codecs}" ${m[$[0]].videoRange}; not compatible with "${A}" ${R}`),this.info(`switch candidate:${c}->${U} adjustedbw(${Math.round(V)})-bitrate=${Math.round(V-G)} ttfb:${N.toFixed(1)} avgDuration:${re.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${ce.toFixed(1)} firstSelection:${T} codecSet:${j.codecSet} videoRange:${j.videoRange} hls.loadLevel:${g}`)),T&&(this.firstSelection=U),U}}return-1}set nextAutoLevel(e){let t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){let{maxAutoLevel:t,minAutoLevel:s}=this.hls;return Math.min(Math.max(e,s),t)}},fb={search:function(i,e){let t=0,s=i.length-1,r=null,n=null;for(;t<=s;){r=(t+s)/2|0,n=i[r];let a=e(n);if(a>0)t=r+1;else if(a<0)s=r-1;else return n}return null}};function yx(i,e,t){if(e===null||!Array.isArray(i)||!i.length||!Q(e))return null;let s=i[0].programDateTime;if(e<(s||0))return null;let r=i[i.length-1].endProgramDateTime;if(e>=(r||0))return null;for(let n=0;n<i.length;++n){let a=i[n];if(Tx(e,t,a))return a}return null}function sn(i,e,t=0,s=0,r=.005){let n=null;if(i){n=e[1+i.sn-e[0].sn]||null;let o=i.endDTS-t;o>0&&o<15e-7&&(t+=15e-7),n&&i.level!==n.level&&n.end<=i.end&&(n=e[2+i.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(n=e[0]);if(n&&((!i||i.level===n.level)&&ZE(t,s,n)===0||bx(n,i,Math.min(r,s))))return n;let a=fb.search(e,ZE.bind(null,t,s));return a&&(a!==i||!n)?a:n}function bx(i,e,t){if(e&&e.start===0&&e.level<i.level&&(e.endPTS||0)>0){let s=e.tagList.reduce((r,n)=>(n[0]==="INF"&&(r+=parseFloat(n[1])),r),t);return i.start<=s}return!1}function ZE(i=0,e=0,t){if(t.start<=i&&t.start+t.duration>i)return 0;let s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-s<=i?1:t.start-s>i&&t.start?-1:0}function Tx(i,e,t){let s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-s>i}function mb(i,e,t){if(i&&i.startCC<=e&&i.endCC>=e){let s=i.fragments,{fragmentHint:r}=i;r&&(s=s.concat(r));let n;return fb.search(s,a=>a.cc<e?1:a.cc>e?-1:(n=a,a.end<=t?1:a.start>t?-1:0)),n||null}return null}function pu(i){switch(i.details){case M.FRAG_LOAD_TIMEOUT:case M.KEY_LOAD_TIMEOUT:case M.LEVEL_LOAD_TIMEOUT:case M.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function pb(i){return i.details.startsWith("key")}function gb(i){return pb(i)&&!!i.frag&&!i.frag.decryptdata}function JE(i,e){let t=pu(e);return i.default[`${t?"timeout":"error"}Retry`]}function eg(i,e){let t=i.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*i.retryDelayMs,i.maxRetryDelayMs)}function ey(i){return Fe(Fe({},i),{errorRetry:null,timeoutRetry:null})}function gu(i,e,t,s){if(!i)return!1;let r=s==null?void 0:s.code,n=e<i.maxNumRetry&&(_x(r)||!!t);return i.shouldRetry?i.shouldRetry(i,e,t,s,n):n}function _x(i){return Bm(i)||!!i&&(i<400||i>499)}function Bm(i){return i===0&&navigator.onLine===!1}var Rt={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},ni={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8},$m=class extends Qt{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){let e=this.hls;e.on(E.ERROR,this.onError,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){let e=this.hls;e&&(e.off(E.ERROR,this.onError,this),e.off(E.ERROR,this.onErrorOut,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===J.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;let t=this.hls,s=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||s===-1?t.loadLevel:s}variantHasKey(e,t){if(e){var s;if((s=e.details)!=null&&s.hasKey(t))return!0;let r=e.audioGroups;if(r)return this.hls.allAudioTracks.filter(a=>r.indexOf(a.groupId)>=0).some(a=>{var o;return(o=a.details)==null?void 0:o.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var s;if(t.fatal)return;let r=this.hls,n=t.context;switch(t.details){case M.FRAG_LOAD_ERROR:case M.FRAG_LOAD_TIMEOUT:case M.KEY_LOAD_ERROR:case M.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case M.FRAG_PARSING_ERROR:if((s=t.frag)!=null&&s.gap){t.errorAction=ea();return}case M.FRAG_GAP:case M.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Rt.SendAlternateToPenaltyBox;return}case M.LEVEL_EMPTY_ERROR:case M.LEVEL_PARSING_ERROR:{var a;let l=t.parent===J.MAIN?t.level:r.loadLevel;t.details===M.LEVEL_EMPTY_ERROR&&((a=t.context)!=null&&(a=a.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,l):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,l))}return;case M.LEVEL_LOAD_ERROR:case M.LEVEL_LOAD_TIMEOUT:typeof(n==null?void 0:n.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level));return;case M.AUDIO_TRACK_LOAD_ERROR:case M.AUDIO_TRACK_LOAD_TIMEOUT:case M.SUBTITLE_LOAD_ERROR:case M.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){let l=r.loadLevelObj;if(l&&(n.type===Le.AUDIO_TRACK&&l.hasAudioGroup(n.groupId)||n.type===Le.SUBTITLE_TRACK&&l.hasSubtitleGroup(n.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=Rt.SendAlternateToPenaltyBox,t.errorAction.flags=ni.MoveAllAlternatesMatchingHost;return}}return;case M.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:Rt.SendAlternateToPenaltyBox,flags:ni.MoveAllAlternatesMatchingHDCP};return;case M.KEY_SYSTEM_SESSION_UPDATE_FAILED:case M.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case M.KEY_SYSTEM_NO_SESSION:t.errorAction={action:Rt.SendAlternateToPenaltyBox,flags:ni.MoveAllAlternatesMatchingKey};return;case M.BUFFER_ADD_CODEC_ERROR:case M.REMUX_ALLOC_ERROR:case M.BUFFER_APPEND_ERROR:if(!t.errorAction){var o;t.errorAction=this.getLevelSwitchAction(t,(o=t.level)!=null?o:r.loadLevel)}return;case M.INTERNAL_EXCEPTION:case M.BUFFER_APPENDING_ERROR:case M.BUFFER_FULL_ERROR:case M.LEVEL_SWITCH_ERROR:case M.BUFFER_STALLED_ERROR:case M.BUFFER_SEEK_OVER_HOLE:case M.BUFFER_NUDGE_ON_STALL:t.errorAction=ea();return}t.type===se.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=ea())}getPlaylistRetryOrSwitchAction(e,t){let s=this.hls,r=JE(s.config.playlistLoadPolicy,e),n=this.playlistError++;if(gu(r,n,pu(e),e.response))return{action:Rt.RetryRequest,flags:ni.None,retryConfig:r,retryCount:n};let o=this.getLevelSwitchAction(e,t);return r&&(o.retryConfig=r,o.retryCount=n),o}getFragRetryOrSwitchAction(e){let t=this.hls,s=this.getVariantLevelIndex(e.frag),r=t.levels[s],{fragLoadPolicy:n,keyLoadPolicy:a}=t.config,o=JE(pb(e)?a:n,e),l=t.levels.reduce((u,c)=>u+c.fragmentError,0);if(r&&(e.details!==M.FRAG_GAP&&r.fragmentError++,!gb(e)&&gu(o,l,pu(e),e.response)))return{action:Rt.RetryRequest,flags:ni.None,retryConfig:o,retryCount:l};let d=this.getLevelSwitchAction(e,s);return o&&(d.retryConfig=o,d.retryCount=l),d}getLevelSwitchAction(e,t){let s=this.hls;t==null&&(t=s.loadLevel);let r=this.hls.levels[t];if(r){var n,a;let d=e.details;r.loadError++,d===M.BUFFER_APPEND_ERROR&&r.fragmentError++;let u=-1,{levels:c,loadLevel:h,minAutoLevel:f,maxAutoLevel:m}=s;!s.autoLevelEnabled&&!s.config.preserveManualLevelOnError&&(s.loadLevel=-1);let p=(n=e.frag)==null?void 0:n.type,v=(p===J.AUDIO&&d===M.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(d===M.BUFFER_ADD_CODEC_ERROR||d===M.BUFFER_APPEND_ERROR))&&c.some(({audioCodec:R})=>r.audioCodec!==R),y=e.sourceBufferName==="video"&&(d===M.BUFFER_ADD_CODEC_ERROR||d===M.BUFFER_APPEND_ERROR)&&c.some(({codecSet:R,audioCodec:I})=>r.codecSet!==R&&r.audioCodec===I),{type:T,groupId:A}=(a=e.context)!=null?a:{};for(let R=c.length;R--;){let I=(R+h)%c.length;if(I!==h&&I>=f&&I<=m&&c[I].loadError===0){var o,l;let x=c[I];if(d===M.FRAG_GAP&&p===J.MAIN&&e.frag){let D=c[I].details;if(D){let S=sn(e.frag,D.fragments,e.frag.start);if(S!=null&&S.gap)continue}}else{if(T===Le.AUDIO_TRACK&&x.hasAudioGroup(A)||T===Le.SUBTITLE_TRACK&&x.hasSubtitleGroup(A))continue;if(p===J.AUDIO&&(o=r.audioGroups)!=null&&o.some(D=>x.hasAudioGroup(D))||p===J.SUBTITLE&&(l=r.subtitleGroups)!=null&&l.some(D=>x.hasSubtitleGroup(D))||v&&r.audioCodec===x.audioCodec||y&&r.codecSet===x.codecSet||!v&&r.codecSet!==x.codecSet)continue}u=I;break}}if(u>-1&&s.loadLevel!==u)return e.levelRetry=!0,this.playlistError=0,{action:Rt.SendAlternateToPenaltyBox,flags:ni.None,nextAutoLevel:u}}return{action:Rt.SendAlternateToPenaltyBox,flags:ni.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s;switch((s=t.errorAction)==null?void 0:s.action){case Rt.DoNothing:break;case Rt.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==M.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break;case Rt.RetryRequest:break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){let t=this.hls,s=e.errorAction;if(!s)return;let{flags:r}=s,n=s.nextAutoLevel;switch(r){case ni.None:this.switchLevel(e,n);break;case ni.MoveAllAlternatesMatchingHDCP:{let l=this.getVariantLevelIndex(e.frag),d=t.levels[l],u=d==null?void 0:d.attrs["HDCP-LEVEL"];if(s.hdcpLevel=u,u==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(u){t.maxHdcpLevel=Um[Um.indexOf(u)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case ni.MoveAllAlternatesMatchingKey:{let l=e.decryptdata;if(l){let d=this.hls.levels,u=d.length;for(let h=u;h--;)if(this.variantHasKey(d[h],l)){var a,o;this.log(`Banned key found in level ${h} (${d[h].bitrate}bps) or audio group "${(a=d[h].audioGroups)==null?void 0:a.join(",")}" (${(o=e.frag)==null?void 0:o.type} fragment) ${Dt(l.keyId||[])}`),d[h].fragmentError++,d[h].loadError++,this.log(`Removing level ${h} with key error (${e.error})`),this.hls.removeLevel(h)}let c=e.frag;if(this.hls.levels.length<u)s.resolved=!0;else if(c&&c.type!==J.MAIN){let h=c.decryptdata;h&&!l.matches(h)&&(s.resolved=!0)}}break}}s.resolved||this.switchLevel(e,n)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===M.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){let s=Nm(e.mimeType),r=this.hls.levels;for(let n=r.length;n--;)r[n][`${e.sourceBufferName}Codec`]===s&&(this.log(`Removing level ${n} for ${e.details} ("${s}" not supported)`),this.hls.removeLevel(n))}}};function ea(i){let e={action:Rt.DoNothing,flags:ni.None};return i&&(e.resolved=!0),e}var Tt={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"},Hm=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&&(e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.BUFFER_APPENDED,this.onBufferAppended,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.BUFFER_APPENDED,this.onBufferAppended,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){let s=this.activePartLists[t];if(s)for(let r=s.length;r--;){let n=s[r];if(!n)break;if(n.start<=e&&e<=n.end&&n.loaded)return n}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,s){let{fragments:r}=this,n=Object.keys(r);for(let a=n.length;a--;){let o=r[n[a]];if((o==null?void 0:o.body.type)===t&&(!s||o.buffered)){let l=o.body;if(l.start<=e&&e<=l.end)return l}}return null}detectEvictedFragments(e,t,s,r,n){this.timeRanges&&(this.timeRanges[e]=t);let a=(r==null?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach(o=>{let l=this.fragments[o];if(!l||a>=l.body.sn)return;if(!l.buffered&&(!l.loaded||n)){l.body.type===s&&this.removeFragment(l.body);return}let d=l.range[e];if(d){if(d.time.length===0){this.removeFragment(l.body);return}d.time.some(u=>{let c=!this.isTimeBuffered(u.startPTS,u.endPTS,t);return c&&this.removeFragment(l.body),c})}})}detectPartialFragments(e){let t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;let s=e.frag,r=Yn(s),n=this.fragments[r];if(!n||n.buffered&&s.gap)return;let a=!s.relurl;Object.keys(t).forEach(o=>{let l=s.elementaryStreams[o];if(!l)return;let d=t[o],u=a||l.partial===!0;n.range[o]=this.getBufferedTimes(s,e.part,u,d)}),n.loaded=null,Object.keys(n.range).length?(this.bufferedEnd(n,s),Vd(n)||this.removeParts(s.sn-1,s.type)):this.removeFragment(n.body)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){let s=this.activePartLists[t];s&&(this.activePartLists[t]=ty(s,r=>r.fragment.sn>=e))}fragBuffered(e,t){let s=Yn(e),r=this.fragments[s];!r&&t&&(r=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,this.bufferedEnd(r,e))}getBufferedTimes(e,t,s,r){let n={time:[],partial:s},a=e.start,o=e.end,l=e.minEndPTS||o,d=e.maxStartPTS||a;for(let u=0;u<r.length;u++){let c=r.start(u)-this.bufferPadding,h=r.end(u)+this.bufferPadding;if(d>=c&&l<=h){n.time.push({startPTS:Math.max(a,r.start(u)),endPTS:Math.min(o,r.end(u))});break}else if(a<h&&o>c){let f=Math.max(a,r.start(u)),m=Math.min(o,r.end(u));m>f&&(n.partial=!0,n.time.push({startPTS:f,endPTS:m}))}else if(o<=c)break}return n}getPartialFragment(e){let t=null,s,r,n,a=0,{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(d=>{let u=l[d];u&&Vd(u)&&(r=u.body.start-o,n=u.body.end+o,e>=r&&e<=n&&(s=Math.min(e-r,n-e),a<=s&&(t=u.body,a=s)))}),t}isEndListAppended(e){let t=this.endListFragments[e];return t!==void 0&&(t.buffered||Vd(t))}getState(e){let t=Yn(e),s=this.fragments[t];return s?s.buffered?Vd(s)?Tt.PARTIAL:Tt.OK:Tt.APPENDING:Tt.NOT_LOADED}isTimeBuffered(e,t,s){let r,n;for(let a=0;a<s.length;a++){if(r=s.start(a)-this.bufferPadding,n=s.end(a)+this.bufferPadding,e>=r&&t<=n)return!0;if(t<=r)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;let s=t.frag,r=t.part?null:t,n=Yn(s);this.fragments[n]={body:s,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){let{frag:s,part:r,timeRanges:n,type:a}=t;if(s.sn==="initSegment")return;let o=s.type;if(r){let d=this.activePartLists[o];d||(this.activePartLists[o]=d=[]),d.push(r)}this.timeRanges=n;let l=n[a];this.detectEvictedFragments(a,l,o,r)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){let t=Yn(e);return!!this.fragments[t]}hasFragments(e){let{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let r=s.length;r--;){let n=t[s[r]];if((n==null?void 0:n.body.type)===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,s,r,n){r&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{let o=this.fragments[a];if(!o)return;let l=o.body;l.type!==s||r&&!l.gap||l.start<t&&l.end>e&&(o.buffered||n)&&this.removeFragment(l)})}removeFragment(e){let t=Yn(e);e.clearElementaryStreamInfo();let s=this.activePartLists[e.type];if(s){let r=e.sn;this.activePartLists[e.type]=ty(s,n=>n.fragment.sn!==r)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;let t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(s=>s.clearElementaryStreamInfo())}};function Vd(i){var e,t,s;return i.buffered&&!!(i.body.gap||(e=i.range.video)!=null&&e.partial||(t=i.range.audio)!=null&&t.partial||(s=i.range.audiovideo)!=null&&s.partial)}function Yn(i){return`${i.type}_${i.level}_${i.sn}`}function ty(i,e){return i.filter(t=>{let s=e(t);return s||t.clearElementaryStreamInfo(),s})}var ar={cbc:0,ctr:1},Gm=class{constructor(e,t,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=s}decrypt(e,t){switch(this.aesMode){case ar.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case ar.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}};function Ax(i){let e=i.byteLength,t=e&&new DataView(i.buffer).getUint8(e-1);return t?i.slice(0,e-t):i}var Km=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),s=new Uint32Array(4);for(let r=0;r<4;r++)s[r]=t.getUint32(r*4);return s}initTable(){let e=this.sBox,t=this.invSBox,s=this.subMix,r=s[0],n=s[1],a=s[2],o=s[3],l=this.invSubMix,d=l[0],u=l[1],c=l[2],h=l[3],f=new Uint32Array(256),m=0,p=0,g=0;for(g=0;g<256;g++)g<128?f[g]=g<<1:f[g]=g<<1^283;for(g=0;g<256;g++){let v=p^p<<1^p<<2^p<<3^p<<4;v=v>>>8^v&255^99,e[m]=v,t[v]=m;let b=f[m],y=f[b],T=f[y],A=f[v]*257^v*16843008;r[m]=A<<24|A>>>8,n[m]=A<<16|A>>>16,a[m]=A<<8|A>>>24,o[m]=A,A=T*16843009^y*65537^b*257^m*16843008,d[v]=A<<24|A>>>8,u[v]=A<<16|A>>>16,c[v]=A<<8|A>>>24,h[v]=A,m?(m=b^f[f[f[T^b]]],p^=f[f[p]]):m=p=1}}expandKey(e){let t=this.uint8ArrayToUint32Array_(e),s=!0,r=0;for(;r<t.length&&s;)s=t[r]===this.key[r],r++;if(s)return;this.key=t;let n=this.keySize=t.length;if(n!==4&&n!==6&&n!==8)throw new Error("Invalid aes key size="+n);let a=this.ksRows=(n+6+1)*4,o,l,d=this.keySchedule=new Uint32Array(a),u=this.invKeySchedule=new Uint32Array(a),c=this.sBox,h=this.rcon,f=this.invSubMix,m=f[0],p=f[1],g=f[2],v=f[3],b,y;for(o=0;o<a;o++){if(o<n){b=d[o]=t[o];continue}y=b,o%n===0?(y=y<<8|y>>>24,y=c[y>>>24]<<24|c[y>>>16&255]<<16|c[y>>>8&255]<<8|c[y&255],y^=h[o/n|0]<<24):n>6&&o%n===4&&(y=c[y>>>24]<<24|c[y>>>16&255]<<16|c[y>>>8&255]<<8|c[y&255]),d[o]=b=(d[o-n]^y)>>>0}for(l=0;l<a;l++)o=a-l,l&3?y=d[o]:y=d[o-4],l<4||o<=4?u[l]=y:u[l]=m[c[y>>>24]]^p[c[y>>>16&255]]^g[c[y>>>8&255]]^v[c[y&255]],u[l]=u[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,s){let r=this.keySize+6,n=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,l=o[0],d=o[1],u=o[2],c=o[3],h=this.uint8ArrayToUint32Array_(s),f=h[0],m=h[1],p=h[2],g=h[3],v=new Int32Array(e),b=new Int32Array(v.length),y,T,A,R,I,x,D,S,C,P,N,$,H,U,j=this.networkToHostOrderSwap;for(;t<v.length;){for(C=j(v[t]),P=j(v[t+1]),N=j(v[t+2]),$=j(v[t+3]),I=C^n[0],x=$^n[1],D=N^n[2],S=P^n[3],H=4,U=1;U<r;U++)y=l[I>>>24]^d[x>>16&255]^u[D>>8&255]^c[S&255]^n[H],T=l[x>>>24]^d[D>>16&255]^u[S>>8&255]^c[I&255]^n[H+1],A=l[D>>>24]^d[S>>16&255]^u[I>>8&255]^c[x&255]^n[H+2],R=l[S>>>24]^d[I>>16&255]^u[x>>8&255]^c[D&255]^n[H+3],I=y,x=T,D=A,S=R,H=H+4;y=a[I>>>24]<<24^a[x>>16&255]<<16^a[D>>8&255]<<8^a[S&255]^n[H],T=a[x>>>24]<<24^a[D>>16&255]<<16^a[S>>8&255]<<8^a[I&255]^n[H+1],A=a[D>>>24]<<24^a[S>>16&255]<<16^a[I>>8&255]<<8^a[x&255]^n[H+2],R=a[S>>>24]<<24^a[I>>16&255]<<16^a[x>>8&255]<<8^a[D&255]^n[H+3],b[t]=j(y^f),b[t+1]=j(R^m),b[t+2]=j(A^p),b[t+3]=j(T^g),f=C,m=P,p=N,g=$,t=t+4}return b.buffer}},Vm=class{constructor(e,t,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=s}expandKey(){let e=Sx(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}};function Sx(i){switch(i){case ar.cbc:return"AES-CBC";case ar.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${i}`)}}var Ix=16,Ho=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.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{let s=self.crypto;s&&(this.subtle=s.subtle||s.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 s=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?Ax(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,r){return this.useSoftware?new Promise((n,a)=>{let o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,t,s,r);let l=this.flush();l?n(l.buffer):a(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s,r)}softwareDecrypt(e,t,s,r){let{currentIV:n,currentResult:a,remainderData:o}=this;if(r!==ar.cbc||t.byteLength!==16)return Be.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=pi(o,e),this.remainderData=null);let l=this.getValidChunk(e);if(!l.length)return null;n&&(s=n);let d=this.softwareDecrypter;d||(d=this.softwareDecrypter=new Km),d.expandKey(t);let u=a;return this.currentResult=d.decrypt(l.buffer,0,s),this.currentIV=l.slice(-16).buffer,u||null}webCryptoDecrypt(e,t,s,r){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,r));this.key=t,this.fastAesKey=new Vm(this.subtle,t,r)}return this.fastAesKey.expandKey().then(n=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Gm(this.subtle,new Uint8Array(s),r).decrypt(e.buffer,n)):Promise.reject(new Error("web crypto not initialized"))).catch(n=>(Be.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(e,t,s,r)))}onWebCryptoError(e,t,s,r){let n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,r);let a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(n?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e,s=e.length-e.length%Ix;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&(Be.log(`[decrypter]: ${e}`),this.logEnabled=!1)}},iy=Math.pow(2,17),Wm=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 s=e.url;if(!s)return Promise.reject(new Mi({type:se.NETWORK_ERROR,details:M.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${s?"part list":"url"}`),networkDetails:null}));this.abort();let r=this.config,n=r.fLoader,a=r.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(m=>m[0]==="GAP")){l(ry(e));return}else e.gap=!1;let d=this.loader=n?new n(r):new a(r),u=sy(e);e.loader=d;let c=ey(r.fragLoadPolicy.default),h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:iy};e.stats=d.stats;let f={onSuccess:(m,p,g,v)=>{this.resetLoader(e,d);let b=m.data;g.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(b.slice(0,16)),b=b.slice(16)),o({frag:e,part:null,payload:b,networkDetails:v})},onError:(m,p,g,v)=>{this.resetLoader(e,d),l(new Mi({type:se.NETWORK_ERROR,details:M.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Fe({url:s,data:void 0},m),error:new Error(`HTTP Error ${m.code} ${m.text}`),networkDetails:g,stats:v}))},onAbort:(m,p,g)=>{this.resetLoader(e,d),l(new Mi({type:se.NETWORK_ERROR,details:M.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:g,stats:m}))},onTimeout:(m,p,g)=>{this.resetLoader(e,d),l(new Mi({type:se.NETWORK_ERROR,details:M.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:g,stats:m}))}};t&&(f.onProgress=(m,p,g,v)=>t({frag:e,part:null,payload:g,networkDetails:v})),d.load(u,h,f)})}loadPart(e,t,s){this.abort();let r=this.config,n=r.fLoader,a=r.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(ry(e,t));return}let d=this.loader=n?new n(r):new a(r),u=sy(e,t);e.loader=d;let c=ey(r.fragLoadPolicy.default),h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:iy};t.stats=d.stats,d.load(u,h,{onSuccess:(f,m,p,g)=>{this.resetLoader(e,d),this.updateStatsFromPart(e,t);let v={frag:e,part:t,payload:f.data,networkDetails:g};s(v),o(v)},onError:(f,m,p,g)=>{this.resetLoader(e,d),l(new Mi({type:se.NETWORK_ERROR,details:M.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Fe({url:u.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:g}))},onAbort:(f,m,p)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,d),l(new Mi({type:se.NETWORK_ERROR,details:M.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:p,stats:f}))},onTimeout:(f,m,p)=>{this.resetLoader(e,d),l(new Mi({type:se.NETWORK_ERROR,details:M.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${h.timeout}ms`),networkDetails:p,stats:f}))}})})}updateStatsFromPart(e,t){let s=e.stats,r=t.stats,n=r.total;if(s.loaded+=r.loaded,n){let l=Math.round(e.duration/t.duration),d=Math.min(Math.round(s.loaded/n),l),c=(l-d)*Math.round(s.loaded/d);s.total=s.loaded+c}else s.total=Math.max(s.loaded,s.total);let a=s.loading,o=r.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}};function sy(i,e=null){let t=e||i,s={frag:i,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},r=t.byteRangeStartOffset,n=t.byteRangeEndOffset;if(Q(r)&&Q(n)){var a;let o=r,l=n;if(i.sn==="initSegment"&&Lx((a=i.decryptdata)==null?void 0:a.method)){let d=n-r;d%16&&(l=n+(16-d%16)),r!==0&&(s.resetIV=!0,o=r-16)}s.rangeStart=o,s.rangeEnd=l}return s}function ry(i,e){let t=new Error(`GAP ${i.gap?"tag":"attribute"} found`),s={type:se.MEDIA_ERROR,details:M.FRAG_GAP,fatal:!1,frag:i,error:t,networkDetails:null};return e&&(s.part=e),(e||i).stats.aborted=!0,new Mi(s)}function Lx(i){return i==="AES-128"||i==="AES-256"}var Mi=class extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}},vu=class extends Qt{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}},Go=class{constructor(e,t,s,r=0,n=-1,a=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=Wd(),this.buffering={audio:Wd(),video:Wd(),audiovideo:Wd()},this.level=e,this.sn=t,this.id=s,this.size=r,this.part=n,this.partial=a}};function Wd(){return{start:0,executeStart:0,executeEnd:0,end:0}}var ny={length:0,start:()=>0,end:()=>0},Ee=class i{static isBuffered(e,t){if(e){let s=i.getBuffered(e);for(let r=s.length;r--;)if(t>=s.start(r)&&t<=s.end(r))return!0}return!1}static bufferedRanges(e){if(e){let t=i.getBuffered(e);return i.timeRangesToArray(t)}return[]}static timeRangesToArray(e){let t=[];for(let s=0;s<e.length;s++)t.push({start:e.start(s),end:e.end(s)});return t}static bufferInfo(e,t,s){if(e){let r=i.bufferedRanges(e);if(r.length)return i.bufferedInfo(r,t,s)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.length>1&&e.sort((u,c)=>u.start-c.start||c.end-u.end);let r=-1,n=[];if(s)for(let u=0;u<e.length;u++){t>=e[u].start&&t<=e[u].end&&(r=u);let c=n.length;if(c){let h=n[c-1].end;e[u].start-h<s?e[u].end>h&&(n[c-1].end=e[u].end):n.push(e[u])}else n.push(e[u])}else n=e;let a=0,o,l=t,d=t;for(let u=0;u<n.length;u++){let c=n[u].start,h=n[u].end;if(r===-1&&t>=c&&t<=h&&(r=u),t+s>=c&&t<h)l=c,d=h,a=d-t;else if(t+s<c){o=c;break}}return{len:a,start:l||0,end:d||0,nextStart:o,buffered:e,bufferedIndex:r}}static getBuffered(e){try{return e.buffered||ny}catch(t){return Be.log("failed to get media.buffered",t),ny}}},vb=/\{\$([a-zA-Z0-9-_]+)\}/g;function ay(i){return vb.test(i)}function qm(i,e){if(i.variableList!==null||i.hasVariableRefs){let t=i.variableList;return e.replace(vb,s=>{let r=s.substring(2,s.length-1),n=t==null?void 0:t[r];return n===void 0?(i.playlistParsingError||(i.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),s):n})}return e}function oy(i,e,t){let s=i.variableList;s||(i.variableList=s={});let r,n;if("QUERYPARAM"in e){r=e.QUERYPARAM;try{let a=new self.URL(t).searchParams;if(a.has(r))n=a.get(r);else throw new Error(`"${r}" does not match any query parameter in URI: "${t}"`)}catch(a){i.playlistParsingError||(i.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else r=e.NAME,n=e.VALUE;r in s?i.playlistParsingError||(i.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):s[r]=n||""}function Rx(i,e,t){let s=e.IMPORT;if(t&&s in t){let r=i.variableList;r||(i.variableList=r={}),r[s]=t[s]}else i.playlistParsingError||(i.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}var xx=/^(\d+)x(\d+)$/,ly=/(.+?)=(".*?"|.*?)(?:,|$)/g,tt=class i{constructor(e,t){typeof e=="string"&&(e=i.parseAttrList(e,t)),$e(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){let t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;let s=new Uint8Array(t.length/2);for(let r=0;r<t.length/2;r++)s[r]=parseInt(t.slice(r*2,r*2+2),16);return s}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 s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){let s=this[e];return(s?s.split(/[ ,]+/):[]).reduce((r,n)=>(r[n.toLowerCase()]=!0,r),t)}bool(e){return this[e]==="YES"}decimalResolution(e){let t=xx.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let s,r={},n='"';for(ly.lastIndex=0;(s=ly.exec(e))!==null;){let a=s[1].trim(),o=s[2],l=o.indexOf(n)===0&&o.lastIndexOf(n)===o.length-1,d=!1;if(l)o=o.slice(1,-1);else switch(a){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":d=!0}if(t&&(l||d))o=qm(t,o);else if(!d&&!l)switch(a){case"CLOSED-CAPTIONS":if(o==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":Be.warn(`${e}: attribute ${a} is missing quotes`)}r[a]=o}return r}},kx="com.apple.hls.interstitial";function Dx(i){return i!=="ID"&&i!=="CLASS"&&i!=="CUE"&&i!=="START-DATE"&&i!=="DURATION"&&i!=="END-DATE"&&i!=="END-ON-NEXT"}function Cx(i){return i==="SCTE35-OUT"||i==="SCTE35-IN"||i==="SCTE35-CMD"}var Eu=class{constructor(e,t,s=0){var r;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(t==null?void 0:t.tagAnchor)||null,this.tagOrder=(r=t==null?void 0:t.tagOrder)!=null?r:s,t){let n=t.attr;for(let a in n)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==n[a]){Be.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=$e(new tt({}),n,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){let n=(t==null?void 0:t.endDate)||new Date(this.attr["END-DATE"]);Q(n.getTime())&&(this._endDate=n)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){let e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){let{tagAnchor:e}=this;return e===null||e.programDateTime===null?(Be.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){let e=this._endDate||this._dateAtEnd;if(e)return e;let t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){let e=this.attr.decimalFloatingPoint("DURATION");if(Q(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===kx}get isValid(){return!!this.id&&!this._badValueForSameId&&Q(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}},wx=10,Ym=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.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!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.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}let t=this.lastPartSn-e.lastPartSn,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&s>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let s=t.decryptdata;return s||(t.setKeyFormat(e.keyFormat),s=t.decryptdata),!!s&&e.matches(s)})}get hasProgramDateTime(){return this.fragments.length?Q(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||wx}get drift(){let e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){let e=this.partList;if(e){let t=this.lastPartIndex;if(t!==-1){for(let s=e.length;s--;)if(e[s].index>t)return e[s].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){let e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}};function yu(i,e){return i.length===e.length?!i.some((t,s)=>t!==e[s]):!1}function dy(i,e){return!i&&!e?!0:!i||!e?!1:yu(i,e)}function ta(i){return i==="AES-128"||i==="AES-256"||i==="AES-256-CTR"}function tg(i){switch(i){case"AES-128":case"AES-256":return ar.cbc;case"AES-256-CTR":return ar.ctr;default:throw new Error(`invalid full segment method ${i}`)}}function ig(i){return Uint8Array.from(atob(i),e=>e.charCodeAt(0))}function jm(i){return Uint8Array.from(unescape(encodeURIComponent(i)),e=>e.charCodeAt(0))}function Mx(i){let e=jm(i).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function Eb(i){let e=function(s,r,n){let a=s[r];s[r]=s[n],s[n]=a};e(i,0,3),e(i,1,2),e(i,4,5),e(i,6,7)}function yb(i){let e=i.split(":"),t=null;if(e[0]==="data"&&e.length===2){let s=e[1].split(";"),r=s[s.length-1].split(",");if(r.length===2){let n=r[0]==="base64",a=r[1];n?(s.splice(-1,1),t=ig(a)):t=Mx(a)}}return t}var bu=typeof self!="undefined"?self:void 0,it={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Ct={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function ru(i){switch(i){case Ct.FAIRPLAY:return it.FAIRPLAY;case Ct.PLAYREADY:return it.PLAYREADY;case Ct.WIDEVINE:return it.WIDEVINE;case Ct.CLEARKEY:return it.CLEARKEY}}function fm(i){switch(i){case it.FAIRPLAY:return Ct.FAIRPLAY;case it.PLAYREADY:return Ct.PLAYREADY;case it.WIDEVINE:return Ct.WIDEVINE;case it.CLEARKEY:return Ct.CLEARKEY}}function Mo(i){let{drmSystems:e,widevineLicenseUrl:t}=i,s=e?[it.FAIRPLAY,it.WIDEVINE,it.PLAYREADY,it.CLEARKEY].filter(r=>!!e[r]):[];return!s[it.WIDEVINE]&&t&&s.push(it.WIDEVINE),s}var bb=function(i){return bu!=null&&(i=bu.navigator)!=null&&i.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function Px(i,e,t,s){let r;switch(i){case it.FAIRPLAY:r=["cenc","sinf"];break;case it.WIDEVINE:case it.PLAYREADY:r=["cenc"];break;case it.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${i}`)}return Ox(r,e,t,s)}function Ox(i,e,t,s){return[{initDataTypes:i,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:e.map(n=>({contentType:`audio/mp4; codecs=${n}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:t.map(n=>({contentType:`video/mp4; codecs=${n}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}function Nx(i){var e;return!!i&&(i.sessionType==="persistent-license"||!!((e=i.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function Tb(i){let e=new Uint16Array(i.buffer,i.byteOffset,i.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),s=t.substring(t.indexOf("<"),t.length),a=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(a){let o=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute("VALUE");if(o){let l=ig(o).subarray(0,16);return Eb(l),l}}return null}var jn={},na=class i{static clearKeyUriToKeyIdMap(){jn={}}static setKeyIdForUri(e,t){jn[e]=t}static addKeyIdForUri(e){let t=Object.keys(jn).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,t),jn[e]=s,s}constructor(e,t,s,r=[1],n=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=s,this.keyFormatVersions=r,this.iv=n,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!ta(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(Zy(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&yu(e.keyFormatVersions,this.keyFormatVersions)&&dy(e.iv,this.iv)&&dy(e.keyId,this.keyId)}isSupported(){if(this.method){if(ta(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Ct.FAIRPLAY:case Ct.WIDEVINE:case Ct.PLAYREADY:case Ct.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(ta(this.method)){let n=this.iv;return n||(typeof e!="number"&&(Be.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),n=Fx(e)),new i(this.method,this.uri,"identity",this.keyFormatVersions,n)}if(this.keyId){let n=jn[this.uri];if(n&&!yu(this.keyId,n)&&i.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}let s=yb(this.uri);if(s)switch(this.keyFormat){case Ct.WIDEVINE:if(this.pssh=s,!this.keyId){let n=zR(s.buffer);if(n.length){var r;let a=n[0];this.keyId=(r=a.kids)!=null&&r.length?a.kids[0]:null}}this.keyId||(this.keyId=uy(t));break;case Ct.PLAYREADY:{let n=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=jR(n,null,s),this.keyId=Tb(s);break}default:{let n=s.subarray(0,16);if(n.length!==16){let a=new Uint8Array(16);a.set(n,16-n.length),n=a}this.keyId=n;break}}if(!this.keyId||this.keyId.byteLength!==16){let n;n=Ux(t),n||(n=uy(t),n||(n=jn[this.uri])),n&&(this.keyId=n,i.setKeyIdForUri(this.uri,n))}return this}};function Ux(i){let e=i==null?void 0:i[Ct.WIDEVINE];return e?e.keyId:null}function uy(i){let e=i==null?void 0:i[Ct.PLAYREADY];if(e){let t=yb(e.uri);if(t)return Tb(t)}return null}function Fx(i){let e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=i>>8*(15-t)&255;return e}var cy=/#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,hy=/#EXT-X-MEDIA:(.*)/g,Bx=/^#EXT(?:INF|-X-TARGETDURATION):/m,mm=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),$x=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),Zr=class i{static findGroup(e,t){for(let s=0;s<e.length;s++){let r=e[s];if(r.id===t)return r}}static resolve(e,t){return Qp.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Bx.test(e)}static parseMasterPlaylist(e,t){let s=ay(e),r={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:s},n=[];if(cy.lastIndex=0,!e.startsWith("#EXTM3U"))return r.playlistParsingError=new Error("no EXTM3U delimiter"),r;let a;for(;(a=cy.exec(e))!=null;)if(a[1]){var o;let d=new tt(a[1],r),u=qm(r,a[2]),c={attrs:d,bitrate:d.decimalInteger("BANDWIDTH")||d.decimalInteger("AVERAGE-BANDWIDTH"),name:d.NAME,url:i.resolve(u,t)},h=d.decimalResolution("RESOLUTION");h&&(c.width=h.width,c.height=h.height),py(d.CODECS,c);let f=d["SUPPLEMENTAL-CODECS"];f&&(c.supplemental={},py(f,c.supplemental)),(o=c.unknownCodecs)!=null&&o.length||n.push(c),r.levels.push(c)}else if(a[3]){let d=a[3],u=a[4];switch(d){case"SESSION-DATA":{let c=new tt(u,r),h=c["DATA-ID"];h&&(r.sessionData===null&&(r.sessionData={}),r.sessionData[h]=c);break}case"SESSION-KEY":{let c=fy(u,t,r);c.encrypted&&c.isSupported()?(r.sessionKeys===null&&(r.sessionKeys=[]),r.sessionKeys.push(c)):Be.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${u}"`);break}case"DEFINE":{{let c=new tt(u,r);oy(r,c,t)}break}case"CONTENT-STEERING":{let c=new tt(u,r);r.contentSteering={uri:i.resolve(c["SERVER-URI"],t),pathwayId:c["PATHWAY-ID"]||"."};break}case"START":{r.startTimeOffset=my(u);break}}}let l=n.length>0&&n.length<r.levels.length;return r.levels=l?n:r.levels,r.levels.length===0&&(r.playlistParsingError=new Error("no levels found in manifest")),r}static parseMasterPlaylistMedia(e,t,s){let r,n={},a=s.levels,o={AUDIO:a.map(d=>({id:d.attrs.AUDIO,audioCodec:d.audioCodec})),SUBTITLES:a.map(d=>({id:d.attrs.SUBTITLES,textCodec:d.textCodec})),"CLOSED-CAPTIONS":[]},l=0;for(hy.lastIndex=0;(r=hy.exec(e))!==null;){let d=new tt(r[1],s),u=d.TYPE;if(u){let c=o[u],h=n[u]||[];n[u]=h;let f=d.LANGUAGE,m=d["ASSOC-LANGUAGE"],p=d.CHANNELS,g=d.CHARACTERISTICS,v=d["INSTREAM-ID"],b={attrs:d,bitrate:0,id:l++,groupId:d["GROUP-ID"]||"",name:d.NAME||f||"",type:u,default:d.bool("DEFAULT"),autoselect:d.bool("AUTOSELECT"),forced:d.bool("FORCED"),lang:f,url:d.URI?i.resolve(d.URI,t):""};if(m&&(b.assocLang=m),p&&(b.channels=p),g&&(b.characteristics=g),v&&(b.instreamId=v),c!=null&&c.length){let y=i.findGroup(c,b.groupId)||c[0];gy(b,y,"audioCodec"),gy(b,y,"textCodec")}h.push(b)}}return n}static parseLevelPlaylist(e,t,s,r,n,a){var o;let l={url:t},d=new Ym(t),u=d.fragments,c=[],h=null,f=0,m=0,p=0,g=0,v=0,b=null,y=new Po(r,l),T,A,R,I=-1,x=!1,D=null,S;if(mm.lastIndex=0,d.m3u8=e,d.hasVariableRefs=ay(e),((o=mm.exec(e))==null?void 0:o[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;(T=mm.exec(e))!==null;){x&&(x=!1,y=new Po(r,l),y.playlistOffset=p,y.setStart(p),y.sn=f,y.cc=g,v&&(y.bitrate=v),y.level=s,h&&(y.initSegment=h,h.rawProgramDateTime&&(y.rawProgramDateTime=h.rawProgramDateTime,h.rawProgramDateTime=null),D&&(y.setByteRange(D),D=null)));let $=T[1];if($){y.duration=parseFloat($);let H=(" "+T[2]).slice(1);y.title=H||null,y.tagList.push(H?["INF",$,H]:["INF",$])}else if(T[3]){if(Q(y.duration)){y.playlistOffset=p,y.setStart(p),R&&Ey(y,R,d),y.sn=f,y.level=s,y.cc=g,u.push(y);let H=(" "+T[3]).slice(1);y.relurl=qm(d,H),zm(y,b,c),b=y,p+=y.duration,f++,m=0,x=!0}}else{if(T=T[0].match($x),!T){Be.warn("No matches on slow regex match for level playlist!");continue}for(A=1;A<T.length&&T[A]===void 0;A++);let H=(" "+T[A]).slice(1),U=(" "+T[A+1]).slice(1),j=T[A+2]?(" "+T[A+2]).slice(1):null;switch(H){case"BYTERANGE":b?y.setByteRange(U,b):y.setByteRange(U);break;case"PROGRAM-DATE-TIME":y.rawProgramDateTime=U,y.tagList.push(["PROGRAM-DATE-TIME",U]),I===-1&&(I=u.length);break;case"PLAYLIST-TYPE":d.type&&Rs(d,H,T),d.type=U.toUpperCase();break;case"MEDIA-SEQUENCE":d.startSN!==0?Rs(d,H,T):u.length>0&&yy(d,H,T),f=d.startSN=parseInt(U);break;case"SKIP":{d.skippedSegments&&Rs(d,H,T);let q=new tt(U,d),Z=q.decimalInteger("SKIPPED-SEGMENTS");if(Q(Z)){d.skippedSegments+=Z;for(let V=Z;V--;)u.push(null);f+=Z}let re=q.enumeratedString("RECENTLY-REMOVED-DATERANGES");re&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(re.split(" ")));break}case"TARGETDURATION":d.targetduration!==0&&Rs(d,H,T),d.targetduration=Math.max(parseInt(U),1);break;case"VERSION":d.version!==null&&Rs(d,H,T),d.version=parseInt(U);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":d.live||Rs(d,H,T),d.live=!1;break;case"#":(U||j)&&y.tagList.push(j?[U,j]:[U]);break;case"DISCONTINUITY":g++,y.tagList.push(["DIS"]);break;case"GAP":y.gap=!0,y.tagList.push([H]);break;case"BITRATE":y.tagList.push([H,U]),v=parseInt(U)*1e3,Q(v)?y.bitrate=v:v=0;break;case"DATERANGE":{let q=new tt(U,d),Z=new Eu(q,d.dateRanges[q.ID],d.dateRangeTagCount);d.dateRangeTagCount++,Z.isValid||d.skippedSegments?d.dateRanges[Z.id]=Z:Be.warn(`Ignoring invalid DATERANGE tag: "${U}"`),y.tagList.push(["EXT-X-DATERANGE",U]);break}case"DEFINE":{{let q=new tt(U,d);"IMPORT"in q?Rx(d,q,a):oy(d,q,t)}break}case"DISCONTINUITY-SEQUENCE":d.startCC!==0?Rs(d,H,T):u.length>0&&yy(d,H,T),d.startCC=g=parseInt(U);break;case"KEY":{let q=fy(U,t,d);if(q.isSupported()){if(q.method==="NONE"){R=void 0;break}R||(R={});let Z=R[q.keyFormat];Z!=null&&Z.matches(q)||(Z&&(R=$e({},R)),R[q.keyFormat]=q)}else Be.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${U}"`);break}case"START":d.startTimeOffset=my(U);break;case"MAP":{let q=new tt(U,d);if(y.duration){let Z=new Po(r,l);vy(Z,q,s,R),h=Z,y.initSegment=h,h.rawProgramDateTime&&!y.rawProgramDateTime&&(y.rawProgramDateTime=h.rawProgramDateTime)}else{let Z=y.byteRangeEndOffset;if(Z){let re=y.byteRangeStartOffset;D=`${Z-re}@${re}`}else D=null;vy(y,q,s,R),h=y,x=!0}h.cc=g;break}case"SERVER-CONTROL":{S&&Rs(d,H,T),S=new tt(U),d.canBlockReload=S.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=S.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&S.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=S.optionalFloat("PART-HOLD-BACK",0),d.holdBack=S.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{d.partTarget&&Rs(d,H,T);let q=new tt(U);d.partTarget=q.decimalFloatingPoint("PART-TARGET");break}case"PART":{let q=d.partList;q||(q=d.partList=[]);let Z=m>0?q[q.length-1]:void 0,re=m++,V=new tt(U,d),G=new Om(V,y,l,re,Z);q.push(G),y.duration+=G.duration;break}case"PRELOAD-HINT":{let q=new tt(U,d);d.preloadHint=q;break}case"RENDITION-REPORT":{let q=new tt(U,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(q);break}default:Be.warn(`line parsed but not handled: ${T}`);break}}}b&&!b.relurl?(u.pop(),p-=b.duration,d.partList&&(d.fragmentHint=b)):d.partList&&(zm(y,b,c),y.cc=g,d.fragmentHint=y,R&&Ey(y,R,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));let C=u.length,P=u[0],N=u[C-1];if(p+=d.skippedSegments*d.targetduration,p>0&&C&&N){d.averagetargetduration=p/C;let $=N.sn;d.endSN=$!=="initSegment"?$:0,d.live||(N.endList=!0),I>0&&(Gx(u,I),P&&c.unshift(P))}return d.fragmentHint&&(p+=d.fragmentHint.duration),d.totalduration=p,c.length&&d.dateRangeTagCount&&P&&_b(c,d),d.endCC=g,d}};function _b(i,e){let t=i.length;if(!t)if(e.hasProgramDateTime){let o=e.fragments[e.fragments.length-1];i.push(o),t++}else return;let s=i[t-1],r=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let o=n.length;o--;){let l=e.dateRanges[n[o]],d=l.startDate.getTime();l.tagAnchor=s.ref;for(let u=t;u--;){var a;if(((a=i[u])==null?void 0:a.sn)<e.startSN)break;let c=Hx(e,d,i,u,r);if(c!==-1){l.tagAnchor=e.fragments[c].ref;break}}}}function Hx(i,e,t,s,r){let n=t[s];if(n){let o=n.programDateTime;if(e>=o||s===0){var a;let l=(((a=t[s+1])==null?void 0:a.start)||r)-n.start;if(e<=o+l*1e3){let d=t[s].sn-i.startSN;if(d<0)return-1;let u=i.fragments;if(u.length>t.length){let h=(t[s+1]||u[u.length-1]).sn-i.startSN;for(let f=h;f>d;f--){let m=u[f].programDateTime;if(e>=m&&e<m+u[f].duration*1e3)return f}}return d}}}return-1}function fy(i,e,t){var s,r;let n=new tt(i,t),a=(s=n.METHOD)!=null?s:"",o=n.URI,l=n.hexadecimalInteger("IV"),d=n.KEYFORMATVERSIONS,u=(r=n.KEYFORMAT)!=null?r:"identity";o&&n.IV&&!l&&Be.error(`Invalid IV: ${n.IV}`);let c=o?Zr.resolve(o,e):"",h=(d||"1").split("/").map(Number).filter(Number.isFinite);return new na(a,c,u,h,l,n.KEYID)}function my(i){let t=new tt(i).decimalFloatingPoint("TIME-OFFSET");return Q(t)?t:null}function py(i,e){let t=(i||"").split(/[ ,]+/).filter(s=>s);["video","audio","text"].forEach(s=>{let r=t.filter(n=>Zp(n,s));r.length&&(e[`${s}Codec`]=r.map(n=>n.split("/")[0]).join(","),t=t.filter(n=>r.indexOf(n)===-1))}),e.unknownCodecs=t}function gy(i,e,t){let s=e[t];s&&(i[t]=s)}function Gx(i,e){let t=i[e];for(let s=e;s--;){let r=i[s];if(!r)return;r.programDateTime=t.programDateTime-r.duration*1e3,t=r}}function zm(i,e,t){i.rawProgramDateTime?t.push(i):e!=null&&e.programDateTime&&(i.programDateTime=e.endProgramDateTime)}function vy(i,e,t,s){i.relurl=e.URI,e.BYTERANGE&&i.setByteRange(e.BYTERANGE),i.level=t,i.sn="initSegment",s&&(i.levelkeys=s),i.initSegment=null}function Ey(i,e,t){i.levelkeys=e;let{encryptedFragments:s}=t;(!s.length||s[s.length-1].levelkeys!==e)&&Object.keys(e).some(r=>e[r].isCommonEncryption)&&s.push(i)}function Rs(i,e,t){i.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function yy(i,e,t){i.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function pm(i,e){let t=e.startPTS;if(Q(t)){let s=0,r;e.sn>i.sn?(s=t-i.start,r=i):(s=i.start-t,r=e),r.duration!==s&&r.setDuration(s)}else e.sn>i.sn?i.cc===e.cc&&i.minEndPTS?e.setStart(i.start+(i.minEndPTS-i.start)):e.setStart(i.start+i.duration):e.setStart(Math.max(i.start-e.duration,0))}function Ab(i,e,t,s,r,n,a){s-t<=0&&(a.warn("Fragment should have a positive duration",e),s=t+e.duration,n=r+e.duration);let l=t,d=s,u=e.startPTS,c=e.endPTS;if(Q(u)){let v=Math.abs(u-t);i&&v>i.totalduration?a.warn(`media timestamps and playlist times differ by ${v}s for level ${e.level} ${i.url}`):Q(e.deltaPTS)?e.deltaPTS=Math.max(v,e.deltaPTS):e.deltaPTS=v,l=Math.max(t,u),t=Math.min(t,u),r=e.startDTS!==void 0?Math.min(r,e.startDTS):r,d=Math.min(s,c),s=Math.max(s,c),n=e.endDTS!==void 0?Math.max(n,e.endDTS):n}let h=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(s-e.start),e.startPTS=t,e.maxStartPTS=l,e.startDTS=r,e.endPTS=s,e.minEndPTS=d,e.endDTS=n;let f=e.sn;if(!i||f<i.startSN||f>i.endSN)return 0;let m,p=f-i.startSN,g=i.fragments;for(g[p]=e,m=p;m>0;m--)pm(g[m],g[m-1]);for(m=p;m<g.length-1;m++)pm(g[m],g[m+1]);return i.fragmentHint&&pm(g[g.length-1],i.fragmentHint),i.PTSKnown=i.alignedSliding=!0,h}function Kx(i,e,t){if(i===e)return;let s=null,r=i.fragments;for(let u=r.length-1;u>=0;u--){let c=r[u].initSegment;if(c){s=c;break}}i.fragmentHint&&delete i.fragmentHint.endPTS;let n;qx(i,e,(u,c,h,f)=>{if((!e.startCC||e.skippedSegments)&&c.cc!==u.cc){let m=u.cc-c.cc;for(let p=h;p<f.length;p++)f[p].cc+=m;e.endCC=f[f.length-1].cc}Q(u.startPTS)&&Q(u.endPTS)&&(c.setStart(c.startPTS=u.startPTS),c.startDTS=u.startDTS,c.maxStartPTS=u.maxStartPTS,c.endPTS=u.endPTS,c.endDTS=u.endDTS,c.minEndPTS=u.minEndPTS,c.setDuration(u.endPTS-u.startPTS),c.duration&&(n=c),e.PTSKnown=e.alignedSliding=!0),u.hasStreams&&(c.elementaryStreams=u.elementaryStreams),c.loader=u.loader,u.hasStats&&(c.stats=u.stats),u.initSegment&&(c.initSegment=u.initSegment,s=u.initSegment)});let a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(s&&o.forEach(u=>{var c;u&&(!u.initSegment||u.initSegment.relurl===((c=s)==null?void 0:c.relurl))&&(u.initSegment=s)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(u=>!u),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let u=e.skippedSegments;u--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=Vx(i.dateRanges,e,t));let u=i.fragments.filter(c=>c.rawProgramDateTime);if(i.hasProgramDateTime&&!e.hasProgramDateTime)for(let c=1;c<o.length;c++)o[c].programDateTime===null&&zm(o[c],o[c-1],u);_b(u,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var l;let u=Lb(i,e.startSN-1);e.startCC=(l=u==null?void 0:u.cc)!=null?l:a[0].cc}Wx(i.partList,e.partList,(u,c)=>{c.elementaryStreams=u.elementaryStreams,c.stats=u.stats}),n?Ab(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,t):Sb(i,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=i.driftStartTime,e.driftStart=i.driftStart;let d=e.advancedDateTime;if(e.advanced&&d){let u=e.edge;e.driftStart||(e.driftStartTime=d,e.driftStart=u),e.driftEndTime=d,e.driftEnd=u}else e.driftEndTime=i.driftEndTime,e.driftEnd=i.driftEnd,e.advancedDateTime=i.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=i.requestScheduled)}function Vx(i,e,t){let{dateRanges:s,recentlyRemovedDateranges:r}=e,n=$e({},i);r&&r.forEach(l=>{delete n[l]});let o=Object.keys(n).length;return o?(Object.keys(s).forEach(l=>{let d=n[l],u=new Eu(s[l].attr,d);u.isValid?(n[l]=u,d||(u.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${qe(s[l].attr)}"`)}),n):s}function Wx(i,e,t){if(i&&e){let s=0;for(let r=0,n=i.length;r<=n;r++){let a=i[r],o=e[r+s];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):s--}}}function qx(i,e,t){let s=e.skippedSegments,r=Math.max(i.startSN,e.startSN)-e.startSN,n=(i.fragmentHint?1:0)+(s?e.endSN:Math.min(i.endSN,e.endSN))-e.startSN,a=e.startSN-i.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=i.fragmentHint?i.fragments.concat(i.fragmentHint):i.fragments;for(let d=r;d<=n;d++){let u=l[a+d],c=o[d];if(s&&!c&&u&&(c=e.fragments[d]=u),u&&c){t(u,c,d,o);let h=u.relurl,f=c.relurl;if(h&&Yx(h,f)){e.playlistParsingError=by(`media sequence mismatch ${c.sn}:`,i,e,u,c);return}else if(u.cc!==c.cc){e.playlistParsingError=by(`discontinuity sequence mismatch (${u.cc}!=${c.cc})`,i,e,u,c);return}}}}function by(i,e,t,s,r){return new Error(`${i} ${r.url}
27
27
  Playlist starting @${e.startSN}
28
28
  ${e.m3u8}
29
29
 
30
30
  Playlist starting @${t.startSN}
31
- ${t.m3u8}`)}function ST(i,e,t=!0){let s=e.startSN+e.skippedSegments-i.startSN,r=i.fragments,n=s>=0,a=0;if(n&&s<r.length)a=r[s].start;else if(n&&e.startSN===i.endSN+1)a=i.fragmentEnd;else if(n&&t)a=i.fragmentStart+s*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)a=i.fragmentStart;else return;Qm(e,a)}function Qm(i,e){if(e){let t=i.fragments;for(let s=i.skippedSegments;s<t.length;s++)t[s].addStart(e);i.fragmentHint&&i.fragmentHint.addStart(e)}}function IT(i,e=1/0){let t=1e3*i.targetduration;if(i.updated){let s=i.fragments;if(s.length&&t*4>e){let n=s[s.length-1].duration*1e3;n<t&&(t=n)}}else t/=2;return Math.round(t)}function LT(i,e,t){if(!i)return null;let s=i.fragments[e-i.startSN];return s||(s=i.fragmentHint,s&&s.sn===e)?s:e<i.startSN&&t&&t.sn===e?t:null}function by(i,e,t){return i?RT(i.partList,e,t):null}function RT(i,e,t){if(i)for(let s=i.length;s--;){let r=i[s];if(r.index===t&&r.fragment.sn===e)return r}return null}function xT(i){i.forEach((e,t)=>{var s;(s=e.details)==null||s.fragments.forEach(r=>{r.level=t,r.initSegment&&(r.initSegment.level=t)})})}function Yx(i,e){return i!==e&&e?_y(i)!==_y(e):!1}function _y(i){return i.replace(/\?[^?]*$/,"")}function Oo(i,e){for(let s=0,r=i.length;s<r;s++){var t;if(((t=i[s])==null?void 0:t.cc)===e)return i[s]}return null}function jx(i,e){return!!(i&&e.startCC<i.endCC&&e.endCC>i.startCC)}function Ay(i,e){let t=i.start+e;i.startPTS=t,i.setStart(t),i.endPTS=t+i.duration}function kT(i,e){let t=e.fragments;for(let s=0,r=t.length;s<r;s++)Ay(t[s],i);e.fragmentHint&&Ay(e.fragmentHint,i),e.alignedSliding=!0}function zx(i,e){i&&(DT(e,i),e.alignedSliding||bu(e,i),!e.alignedSliding&&!e.skippedSegments&&ST(i,e,!1))}function DT(i,e){if(!jx(e,i))return;let t=Math.min(e.endCC,i.endCC),s=Oo(e.fragments,t),r=Oo(i.fragments,t);if(!s||!r)return;Be.log(`Aligning playlist at start of dicontinuity sequence ${t}`);let n=s.start-r.start;kT(n,i)}function bu(i,e){if(!i.hasProgramDateTime||!e.hasProgramDateTime)return;let t=i.fragments,s=e.fragments;if(!t.length||!s.length)return;let r,n,a=Math.min(e.endCC,i.endCC);e.startCC<a&&i.startCC<a&&(r=Oo(s,a),n=Oo(t,a)),(!r||!n)&&(r=s[Math.floor(s.length/2)],n=Oo(t,r.cc)||t[Math.floor(t.length/2)]);let o=r.programDateTime,l=n.programDateTime;if(!o||!l)return;let d=(l-o)/1e3-(n.start-r.start);kT(d,i)}function Ht(i,e,t){zt(i,e,t),i.addEventListener(e,t)}function zt(i,e,t){i.removeEventListener(e,t)}var Qx={toString:function(i){let e="",t=i.length;for(let s=0;s<t;s++)e+=`[${i.start(s).toFixed(3)}-${i.end(s).toFixed(3)}]`;return e}},O={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"},Ko=class extends vu{constructor(e,t,s,r,n){super(r,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=O.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.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.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{let{config:a,fragCurrent:o,media:l,mediaBuffer:d,state:u}=this,c=l?l.currentTime:0,h=Ee.bufferInfo(d||l,c,a.maxBufferHole),f=!h.len;if(this.log(`Media seeking to ${Q(c)?c.toFixed(3):c}, state: ${u}, ${f?"out of":"in"} buffer`),this.state===O.ENDED)this.resetLoadingState();else if(o){let m=a.maxFragLookUpTolerance,p=o.start-m,g=o.start+o.duration+m;if(f||g<h.start||p>h.end){let v=c>g;(c<p||v)&&(v&&o.loader&&(this.log(`Cancelling fragment load for seek (sn: ${o.sn})`),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(l){this.fragmentTracker.removeFragmentsInRange(c,1/0,this.playlistType,!0);let m=this.lastCurrentTime;if(c>m&&(this.lastCurrentTime=c),!this.loadingParts){let p=Math.max(h.end,c),g=this.shouldLoadParts(this.getLevelDetails(),p);g&&(this.log(`LL-Part loading ON after seeking to ${c.toFixed(2)} with buffer @${p.toFixed(2)}`),this.loadingParts=g)}}this.hls.hasEnoughToStart||(this.log(`Setting ${f?"startPosition":"nextLoadPosition"} to ${c} for seek without enough to start`),this.nextLoadPosition=c,f&&(this.startPosition=c)),f&&this.state===O.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=n,this.hls=e,this.fragmentLoader=new Wm(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Ho(e.config)}registerListeners(){let{hls:e}=this;e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===O.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);let e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=O.STOPPED}get startPositionValue(){let{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;let s=e.end||0,r=this.config.timelineOffset||0;if(s<=r)return!1;let n=e.buffered;this.config.maxBufferHole&&n&&n.length>1&&(e=Ee.bufferedInfo(n,e.start,0));let a=e.nextStart;if(a&&a>r&&a<t.edge||this.media.currentTime<e.start)return!1;let l=t.partList;if(l!=null&&l.length){let u=l[l.length-1];return Ee.isBuffered(this.media,u.start+u.duration/2)}let d=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(d)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){let e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){let s=this.media=this.mediaBuffer=t.media;Ht(s,"seeking",this.onMediaSeeking),Ht(s,"ended",this.onMediaEnded);let r=this.config;this.levels&&r.autoStartLoad&&this.state===O.STOPPED&&this.startLoad(r.startPosition)}onMediaDetaching(e,t){let s=!!t.transferMedia,r=this.media;if(r!==null){if(r.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),zt(r,"seeking",this.onMediaSeeking),zt(r,"ended",this.onMediaEnded),this.keyLoader&&!s&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,s){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=O.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,s){this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){let r=n=>{let a=n.frag;if(this.fragContextChanged(a)){this.warn(`${a.type} sn: ${a.sn}${n.part?" part: "+n.part.index:""} of ${this.fragInfo(a,!1,n.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(a);return}a.stats.chunkCount++,this._handleFragmentLoadProgress(n)};this._doFragLoad(e,t,s,r).then(n=>{if(!n)return;let a=this.state,o=n.frag;if(this.fragContextChanged(o)){(a===O.FRAG_LOADING||!this.fragCurrent&&a===O.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=O.IDLE);return}"payload"in n&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(E.FRAG_LOADED,n)),this._handleFragmentLoadComplete(n)}).catch(n=>{this.state===O.STOPPED||this.state===O.ERROR||(this.warn(`Frag error: ${(n==null?void 0:n.message)||n}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;let{fragmentTracker:s}=this;if(s.getState(e)===bt.APPENDING){let n=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,n),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength),l=this.backtrackFragment;((l?e.sn-l.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&s.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===bt.PARTIAL&&s.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)}waitForLive(e){let t=e.details;return(t==null?void 0:t.live)&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,s=null){if(!(e-t))return;let r={startOffset:e,endOffset:t,type:s};this.hls.trigger(E.BUFFER_FLUSHING,r)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(s=>{let r=s==null?void 0:s.frag;if(!r||this.fragContextChanged(r)||!this.levels)throw new Error("init load aborted");return s}).then(s=>{let{hls:r}=this,{frag:n,payload:a}=s,o=n.decryptdata;if(a&&a.byteLength>0&&o!=null&&o.key&&o.iv&&ta(o.method)){let l=self.performance.now();return this.decrypter.decrypt(new Uint8Array(a),o.key.buffer,o.iv.buffer,tg(o.method)).catch(d=>{throw r.trigger(E.ERROR,{type:se.MEDIA_ERROR,details:M.FRAG_DECRYPT_ERROR,fatal:!1,error:d,reason:d.message,frag:n}),d}).then(d=>{let u=self.performance.now();return r.trigger(E.FRAG_DECRYPTED,{frag:n,payload:d,stats:{tstart:l,tdecrypt:u}}),s.payload=d,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)}).catch(s=>{this.state===O.STOPPED||this.state===O.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){let{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");let s=e.frag.stats;this.state!==O.STOPPED&&(this.state=O.IDLE),e.frag.data=new Uint8Array(e.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var s,r;let n=e.tracks;if(n&&!t.encrypted&&((s=n.audio)!=null&&s.encrypted||(r=n.video)!=null&&r.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){let a=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${a?"attached mediaKeys: "+a.mediaKeys:"detached"})`);return this.warn(o.message),!a||a.mediaKeys?!1:(this.hls.trigger(E.ERROR,{type:se.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){let{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){let s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${s?Qx.toString(Ee.getBuffered(s)):"(detached)"})`),at(e)){var r;if(e.type!==J.SUBTITLE){let a=e.elementaryStreams;if(!Object.keys(a).some(o=>!!a[o])){this.state=O.IDLE;return}}let n=(r=this.levels)==null?void 0:r[e.level];n!=null&&n.fragmentError&&(this.log(`Resetting level fragment error count of ${n.fragmentError} on frag buffered`),n.fragmentError=0)}this.state=O.IDLE}_handleFragmentLoadComplete(e){let{transmuxer:t}=this;if(!t)return;let{frag:s,part:r,partsLoaded:n}=e,a=!n||n.length===0||n.some(l=>!l),o=new Go(s.level,s.sn,s.stats.chunkCount+1,0,r?r.index:-1,!a);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,s=null,r){var n;this.fragCurrent=e;let a=t.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;if(e.encrypted&&!((n=e.decryptdata)!=null&&n.key)){if(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=O.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(h=>{if(!this.fragContextChanged(h.frag))return this.hls.trigger(E.KEY_LOADED,h),this.state===O.KEY_LOADING&&(this.state=O.IDLE),h}),this.hls.trigger(E.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(o=this.keyLoader.loadClear(e,a.encryptedFragments,this.startFragRequested),o&&this.log("[eme] blocking frag load until media-keys acquired"));let l=this.fragPrevious;if(at(e)&&(!l||e.sn!==l.sn)){let h=this.shouldLoadParts(t.details,e.end);h!==this.loadingParts&&(this.log(`LL-Part loading ${h?"ON":"OFF"} loading sn ${l==null?void 0:l.sn}->${e.sn}`),this.loadingParts=h)}if(s=Math.max(e.start,s||0),this.loadingParts&&at(e)){let h=a.partList;if(h&&r){s>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);let f=this.getNextPart(h,e,s);if(f>-1){let m=h[f];e=this.fragCurrent=m.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${m.index} (${f}/${h.length-1}) of ${this.fragInfo(e,!1,m)}) cc: ${e.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=m.start+m.duration,this.state=O.FRAG_LOADING;let p;return o?p=o.then(g=>!g||this.fragContextChanged(g.frag)?null:this.doFragPartsLoad(e,m,t,r)).catch(g=>this.handleFragLoadError(g)):p=this.doFragPartsLoad(e,m,t,r).catch(g=>this.handleFragLoadError(g)),this.hls.trigger(E.FRAG_LOADING,{frag:e,part:m,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):p}else if(!e.url||this.loadedEndOfParts(h,s))return Promise.resolve(null)}}if(at(e)&&this.loadingParts){var d;this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(d=a.partList)==null?void 0:d.filter(h=>h.loaded).map(h=>`[${h.start}-${h.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+a.startSN+"-"+a.endSN+"]"}, target: ${parseFloat(s.toFixed(3))}`),Q(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=O.FRAG_LOADING;let u=this.config.progressive&&e.type!==J.SUBTITLE,c;return u&&o?c=o.then(h=>!h||this.fragContextChanged(h.frag)?null:this.fragmentLoader.load(e,r)).catch(h=>this.handleFragLoadError(h)):c=Promise.all([this.fragmentLoader.load(e,u?r:void 0),o]).then(([h])=>(!u&&r&&r(h),h)).catch(h=>this.handleFragLoadError(h)),this.hls.trigger(E.FRAG_LOADING,{frag:e,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):c}doFragPartsLoad(e,t,s,r){return new Promise((n,a)=>{var o;let l=[],d=(o=s.details)==null?void 0:o.partList,u=c=>{this.fragmentLoader.loadPart(e,c,r).then(h=>{l[c.index]=h;let f=h.part;this.hls.trigger(E.FRAG_LOADED,h);let m=by(s.details,e.sn,c.index+1)||RT(d,e.sn,c.index+1);if(m)u(m);else return n({frag:e,part:f,partsLoaded:l})}).catch(a)};u(t)})}handleFragLoadError(e){if("data"in e){let t=e.data;t.frag&&t.details===M.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===se.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(E.ERROR,t)}else this.hls.trigger(E.ERROR,{type:se.OTHER_ERROR,details:M.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){let t=this.getCurrentContext(e);if(!t||this.state!==O.PARSING){!this.fragCurrent&&this.state!==O.STOPPED&&this.state!==O.ERROR&&(this.state=O.IDLE);return}let{frag:s,part:r,level:n}=t,a=self.performance.now();s.stats.parsing.end=a,r&&(r.stats.parsing.end=a);let o=this.getLevelDetails(),d=o&&s.sn>o.endSN||this.shouldLoadParts(o,s.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} after parsing segment ending @${s.end.toFixed(2)}`),this.loadingParts=d),this.updateLevelTiming(s,r,n,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var s;let n=e.partList[0];if(n.fragment.type===J.SUBTITLE)return!1;let a=n.end+(((s=e.fragmentHint)==null?void 0:s.duration)||0);if(t>=a){var r;if((this.hls.hasEnoughToStart?((r=this.media)==null?void 0:r.currentTime)||this.lastCurrentTime:this.getLoadPosition())>n.start-n.fragment.duration)return!0}}}return!1}getCurrentContext(e){let{levels:t,fragCurrent:s}=this,{level:r,sn:n,part:a}=e;if(!(t!=null&&t[r]))return this.warn(`Levels object was unset while buffering fragment ${n} of ${this.playlistLabel()} ${r}. The current chunk will not be buffered.`),null;let o=t[r],l=o.details,d=a>-1?by(l,n,a):null,u=d?d.fragment:LT(l,n,s);return u?(s&&s!==u&&(u.stats=s.stats),{frag:u,part:d,level:o}):null}bufferFragmentData(e,t,s,r,n){if(this.state!==O.PARSING)return;let{data1:a,data2:o}=e,l=a;if(o&&(l=pi(a,o)),!l.length)return;let d=this.initPTS[t.cc],u=d?-d.baseTime/d.timescale:void 0,c={type:e.type,frag:t,part:s,chunkMeta:r,offset:u,parent:t.type,data:l};if(this.hls.trigger(E.BUFFER_APPENDING,c),e.dropped&&e.independent&&!s){if(n)return;this.flushBufferGap(t)}}flushBufferGap(e){let t=this.media;if(!t)return;if(!Ee.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}let s=t.currentTime,r=Ee.bufferInfo(t,s,0),n=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,n*.25),o=Math.max(Math.min(e.start-a,r.end-a),s+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var s;let r=this.getLoadPosition();if(!Q(r))return null;let a=this.lastCurrentTime>r||(s=this.media)!=null&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,r,t,a)}getFwdBufferInfoAtPos(e,t,s,r){let n=Ee.bufferInfo(e,t,r);if(n.len===0&&n.nextStart!==void 0){let a=this.fragmentTracker.getBufferedFrag(t,s);if(a&&(n.nextStart<=a.end||a.gap)){let o=Math.max(Math.min(n.nextStart,a.end)-t,r);return Ee.bufferInfo(e,t,o)}}return n}getMaxBufferLength(e){let{config:t}=this,s;return e?s=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):s=t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){let s=this.config,r=Math.max(Math.min(e-t,s.maxBufferLength),t),n=Math.max(e-t*3,s.maxMaxBufferLength/2,r);return n>=r?(s.maxMaxBufferLength=n,this.warn(`Reduce max buffer length to ${n}s`),!0):!1}getAppendedFrag(e,t=J.MAIN){let s=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return s&&"fragment"in s?s.fragment:s}getNextFragment(e,t){let s=t.fragments,r=s.length;if(!r)return null;let{config:n}=this,a=s[0].start,o=n.lowLatencyMode&&!!t.partList,l=null;if(t.live){let c=n.initialLiveManifestSize;if(r<c)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${c})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a){var d;o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),l=this.getInitialLiveFragment(t);let h=this.hls.startPosition,f=this.hls.liveSyncPosition,m=l?(h!==-1&&h>=a?h:f)||l.start:e;this.log(`Setting startPosition to ${m} to match start frag at live edge. mainStart: ${h} liveSyncPosition: ${f} frag.start: ${(d=l)==null?void 0:d.start}`),this.startPosition=this.nextLoadPosition=m}}else e<=a&&(l=s[0]);if(!l){let c=this.loadingParts?t.partEnd:t.fragmentEnd;l=this.getFragmentAtPosition(e,c,t)}let u=this.filterReplacedPrimary(l,t);if(!u&&l){let c=l.sn-t.startSN;u=this.filterReplacedPrimary(s[c+1]||null,t)}return this.mapToInitFragWhenRequired(u)}isLoopLoading(e,t){let s=this.fragmentTracker.getState(e);return(s===bt.OK||s===bt.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,s,r,n){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.gap&&s.nextStart)){let o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,r,0);if(o!==null&&s.len+o.len>=n){let l=a.sn;return this.loopSn!==l&&(this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${l}`),this.loopSn=l),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(Sy(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(Sy(this.config)&&e.type!==J.SUBTITLE){let s=this.hls.interstitialsManager,r=s==null?void 0:s.bufferingItem;if(r){let a=r.event;if(a){if(a.appendInPlace||Math.abs(e.start-r.start)>1||r.start===0)return null}else if(e.end<=r.start&&(t==null?void 0:t.live)===!1||e.start>r.end&&r.nextEvent&&(r.nextEvent.appendInPlace||e.start-r.end>1))return null}let n=s==null?void 0:s.playerQueue;if(n)for(let a=n.length;a--;){let o=n[a].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,s){let r=-1,n=!1,a=!0;for(let o=0,l=e.length;o<l;o++){let d=e[o];if(a=a&&!d.independent,r>-1&&s<d.start)break;let u=d.loaded;u?r=-1:(n||(d.independent||a)&&d.fragment===t)&&(d.fragment!==t&&this.warn(`Need buffer at ${s} but next unloaded part starts at ${d.start}`),r=o),n=u}return r}loadedEndOfParts(e,t){let s;for(let r=e.length;r--;){if(s=e[r],!s.loaded)return!1;if(t>s.start)return!0}return!1}getInitialLiveFragment(e){let t=e.fragments,s=this.fragPrevious,r=null;if(s){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),r=yx(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){let n=s.sn+1;if(n>=e.startSN&&n<=e.endSN){let a=t[n-e.startSN];s.cc===a.cc&&(r=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=mT(e,s.cc,s.end),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{let n=this.hls.liveSyncPosition;n!==null&&(r=this.getFragmentAtPosition(n,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r}getFragmentAtPosition(e,t,s){let{config:r}=this,{fragPrevious:n}=this,{fragments:a,endSN:o}=s,{fragmentHint:l}=s,{maxFragLookUpTolerance:d}=r,u=s.partList,c=!!(this.loadingParts&&u!=null&&u.length&&l);c&&!this.bitrateTest&&u[u.length-1].fragment.sn===l.sn&&(a=a.concat(l),o=l.sn);let h;if(e<t){var f;let p=e<this.lastCurrentTime||e>t-d||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:d;h=sn(n,a,e,p)}else h=a[a.length-1];if(h){let m=h.sn-s.startSN,p=this.fragmentTracker.getState(h);if((p===bt.OK||p===bt.PARTIAL&&h.gap)&&(n=h),n&&h.sn===n.sn&&(!c||u[0].fragment.sn>h.sn||!s.live)&&h.level===n.level){let v=a[m+1];h.sn<o&&this.fragmentTracker.getState(v)!==bt.OK?h=v:h=null}}return h}alignPlaylists(e,t,s){let r=e.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;let n=e.fragmentStart,a=!t,o=e.alignedSliding&&Q(n);if(a||!o&&!n){zx(s,e);let l=e.fragmentStart;return this.log(`Live playlist sliding: ${l.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${r}`),l}return n}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let s=this.startPosition;s<t&&(s=-1);let r=this.timelineOffset;if(s===-1){let n=this.startTimeOffset!==null,a=n?this.startTimeOffset:e.startTimeOffset;a!==null&&Q(a)?(s=t+a,a<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${a} found in ${n?"multivariant":"media"} playlist`),this.startPosition=s):e.live?(s=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${s}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+r}this.nextLoadPosition=s+r}getLoadPosition(){var e;let{media:t}=this,s=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?s=t.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&at(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==O.FRAG_LOADING_WAITING_RETRY)&&(this.state=O.IDLE)}onFragmentOrKeyLoadError(e,t){var s;if(t.chunkMeta&&!t.frag){let v=this.getCurrentContext(t.chunkMeta);v&&(t.frag=v.frag)}let r=t.frag;if(!r||r.type!==e||!this.levels)return;if(this.fragContextChanged(r)){var n;this.warn(`Frag load error must match current frag to retry ${r.url} > ${(n=this.fragCurrent)==null?void 0:n.url}`);return}let a=t.details===M.FRAG_GAP;a&&this.fragmentTracker.fragBuffered(r,!0);let o=t.errorAction;if(!o){this.state=O.ERROR;return}let{action:l,flags:d,retryCount:u=0,retryConfig:c}=o,h=!!c,f=h&&l===Rt.RetryRequest,m=h&&!o.resolved&&d===ni.MoveAllAlternatesMatchingHost,p=(s=this.hls.latestLevelDetails)==null?void 0:s.live;if(!f&&m&&at(r)&&!r.endList&&p&&!gT(t))this.resetFragmentErrors(e),this.treatAsGap(r),o.resolved=!0;else if((f||m)&&u<c.maxNumRetry){var g;let v=Bm((g=t.response)==null?void 0:g.code),T=eg(c,u);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+T,this.state=O.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,v){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${r.sn} of ${e} ${r.level} errored with ${t.details}, retrying loading ${u+1}/${c.maxNumRetry} in ${T}ms`)}else if(c)if(this.resetFragmentErrors(e),u<c.maxNumRetry)!a&&l!==Rt.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${u})`);return}else l===Rt.SendAlternateToPenaltyBox?this.state=O.WAITING_LEVEL:this.state=O.ERROR;this.tickImmediate()}checkRetryDate(){let e=self.performance.now(),t=this.retryDate,s=t===1/0;(!t||e>=t||s&&!Bm(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=O.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===O.PARSING||this.state===O.PARSED){let t=e.frag,s=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,s),n=r&&r.len>.5;n&&this.reduceMaxBufferLength(r.len,(t==null?void 0:t.duration)||10);let a=!n;return a&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${s} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===J.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==O.STOPPED&&(this.state=O.IDLE)}afterBufferFlushed(e,t,s){if(!e)return;let r=Ee.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,s),this.state===O.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==O.STOPPED&&(this.state=O.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;let e=this.levelLastLoaded,t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,s,r){let n=s.details;if(!n){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((l,d)=>{let u=e.elementaryStreams[d];if(u){let c=u.endPTS-u.startPTS;if(c<=0)return this.warn(`Could not parse fragment ${e.sn} ${d} duration reliably (${c})`),l||!1;let h=r?0:AT(n,e,u.startPTS,u.endPTS,u.startDTS,u.endDTS,this);return this.hls.trigger(E.LEVEL_PTS_UPDATED,{details:n,level:s,drift:h,type:d,frag:e,start:u.startPTS,end:u.endPTS}),!0}return l},!1)){var o;let l=((o=this.transmuxer)==null?void 0:o.error)===null;if((s.fragmentError===0||l&&(s.fragmentError<2||e.endList))&&this.treatAsGap(e,s),l){let d=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(d.message),this.hls.trigger(E.ERROR,{type:se.MEDIA_ERROR,details:M.FRAG_PARSING_ERROR,fatal:!1,error:d,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=O.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(E.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===J.MAIN?"level":"track"}fragInfo(e,t=!0,s){var r,n;return`${this.playlistLabel()} ${e.level} (${s?"part":"frag"}:[${((r=t&&!s?e.startPTS:(s||e).start)!=null?r:NaN).toFixed(3)}-${((n=t&&!s?e.endPTS:(s||e).end)!=null?n:NaN).toFixed(3)}]${s&&e.type==="main"?"INDEPENDENT="+(s.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){let t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}};function Sy(i){return!!i.interstitialsController&&i.enableInterstitialPlayback!==!1}var _u=class{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){let{chunks:e,dataLength:t}=this,s;if(e.length)e.length===1?s=e[0]:s=Xx(e,t);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}};function Xx(i,e){let t=new Uint8Array(e),s=0;for(let r=0;r<i.length;r++){let n=i[r];t.set(n,s),s+=n.length}return t}var gm={exports:{}},Iy;function Zx(){return Iy||(Iy=1,function(i){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function r(l,d,u){this.fn=l,this.context=d,this.once=u||!1}function n(l,d,u,c,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var f=new r(u,c||l,h),m=t?t+d:d;return l._events[m]?l._events[m].fn?l._events[m]=[l._events[m],f]:l._events[m].push(f):(l._events[m]=f,l._eventsCount++),l}function a(l,d){--l._eventsCount===0?l._events=new s:delete l._events[d]}function o(){this._events=new s,this._eventsCount=0}o.prototype.eventNames=function(){var d=[],u,c;if(this._eventsCount===0)return d;for(c in u=this._events)e.call(u,c)&&d.push(t?c.slice(1):c);return Object.getOwnPropertySymbols?d.concat(Object.getOwnPropertySymbols(u)):d},o.prototype.listeners=function(d){var u=t?t+d:d,c=this._events[u];if(!c)return[];if(c.fn)return[c.fn];for(var h=0,f=c.length,m=new Array(f);h<f;h++)m[h]=c[h].fn;return m},o.prototype.listenerCount=function(d){var u=t?t+d:d,c=this._events[u];return c?c.fn?1:c.length:0},o.prototype.emit=function(d,u,c,h,f,m){var p=t?t+d:d;if(!this._events[p])return!1;var g=this._events[p],v=arguments.length,T,y;if(g.fn){switch(g.once&&this.removeListener(d,g.fn,void 0,!0),v){case 1:return g.fn.call(g.context),!0;case 2:return g.fn.call(g.context,u),!0;case 3:return g.fn.call(g.context,u,c),!0;case 4:return g.fn.call(g.context,u,c,h),!0;case 5:return g.fn.call(g.context,u,c,h,f),!0;case 6:return g.fn.call(g.context,u,c,h,f,m),!0}for(y=1,T=new Array(v-1);y<v;y++)T[y-1]=arguments[y];g.fn.apply(g.context,T)}else{var b=g.length,A;for(y=0;y<b;y++)switch(g[y].once&&this.removeListener(d,g[y].fn,void 0,!0),v){case 1:g[y].fn.call(g[y].context);break;case 2:g[y].fn.call(g[y].context,u);break;case 3:g[y].fn.call(g[y].context,u,c);break;case 4:g[y].fn.call(g[y].context,u,c,h);break;default:if(!T)for(A=1,T=new Array(v-1);A<v;A++)T[A-1]=arguments[A];g[y].fn.apply(g[y].context,T)}}return!0},o.prototype.on=function(d,u,c){return n(this,d,u,c,!1)},o.prototype.once=function(d,u,c){return n(this,d,u,c,!0)},o.prototype.removeListener=function(d,u,c,h){var f=t?t+d:d;if(!this._events[f])return this;if(!u)return a(this,f),this;var m=this._events[f];if(m.fn)m.fn===u&&(!h||m.once)&&(!c||m.context===c)&&a(this,f);else{for(var p=0,g=[],v=m.length;p<v;p++)(m[p].fn!==u||h&&!m[p].once||c&&m[p].context!==c)&&g.push(m[p]);g.length?this._events[f]=g.length===1?g[0]:g:a(this,f)}return this},o.prototype.removeAllListeners=function(d){var u;return d?(u=t?t+d:d,this._events[u]&&a(this,u)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,i.exports=o}(gm)),gm.exports}var Jx=Zx(),sg=MR(Jx),Vo="1.6.15",aa={};function ek(){return typeof __HLS_WORKER_BUNDLE__=="function"}function tk(){let i=aa[Vo];if(i)return i.clientCount++,i;let e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e),r={worker:new self.Worker(t),objectURL:t,clientCount:1};return aa[Vo]=r,r}function ik(i){let e=aa[i];if(e)return e.clientCount++,e;let t=new self.URL(i,self.location.href).href,r={worker:new self.Worker(t),scriptURL:t,clientCount:1};return aa[i]=r,r}function sk(i){let e=aa[i||Vo];if(e&&e.clientCount--===1){let{worker:s,objectURL:r}=e;delete aa[i||Vo],r&&self.URL.revokeObjectURL(r),s.terminate()}}function CT(i,e){return e+10<=i.length&&i[e]===51&&i[e+1]===68&&i[e+2]===73&&i[e+3]<255&&i[e+4]<255&&i[e+6]<128&&i[e+7]<128&&i[e+8]<128&&i[e+9]<128}function rg(i,e){return e+10<=i.length&&i[e]===73&&i[e+1]===68&&i[e+2]===51&&i[e+3]<255&&i[e+4]<255&&i[e+6]<128&&i[e+7]<128&&i[e+8]<128&&i[e+9]<128}function Nu(i,e){let t=0;return t=(i[e]&127)<<21,t|=(i[e+1]&127)<<14,t|=(i[e+2]&127)<<7,t|=i[e+3]&127,t}function Wo(i,e){let t=e,s=0;for(;rg(i,e);){s+=10;let r=Nu(i,e+6);s+=r,CT(i,e+10)&&(s+=10),e+=s}if(s>0)return i.subarray(t,t+s)}function rk(i,e,t,s){let r=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],n=e[t+2],a=n>>2&15;if(a>12){let f=new Error(`invalid ADTS sampling index:${a}`);i.emit(E.ERROR,E.ERROR,{type:se.MEDIA_ERROR,details:M.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.message});return}let o=(n>>6&3)+1,l=e[t+3]>>6&3|(n&1)<<2,d="mp4a.40."+o,u=r[a],c=a;(o===5||o===29)&&(c-=3);let h=[o<<3|(c&14)>>1,(c&1)<<7|l<<3];return Be.log(`manifest codec:${s}, parsed codec:${d}, channels:${l}, rate:${u} (ADTS object type:${o} sampling index:${a})`),{config:h,samplerate:u,channelCount:l,codec:d,parsedCodec:d,manifestCodec:s}}function wT(i,e){return i[e]===255&&(i[e+1]&246)===240}function MT(i,e){return i[e+1]&1?7:9}function ng(i,e){return(i[e+3]&3)<<11|i[e+4]<<3|(i[e+5]&224)>>>5}function nk(i,e){return e+5<i.length}function Au(i,e){return e+1<i.length&&wT(i,e)}function ak(i,e){return nk(i,e)&&wT(i,e)&&ng(i,e)<=i.length-e}function ok(i,e){if(Au(i,e)){let t=MT(i,e);if(e+t>=i.length)return!1;let s=ng(i,e);if(s<=t)return!1;let r=e+s;return r===i.length||Au(i,r)}return!1}function PT(i,e,t,s,r){if(!i.samplerate){let n=rk(e,t,s,r);if(!n)return;$e(i,n)}}function OT(i){return 1024*9e4/i}function lk(i,e){let t=MT(i,e);if(e+t<=i.length){let s=ng(i,e)-t;if(s>0)return{headerLength:t,frameLength:s}}}function NT(i,e,t,s,r){let n=OT(i.samplerate),a=s+r*n,o=lk(e,t),l;if(o){let{frameLength:c,headerLength:h}=o,f=h+c,m=Math.max(0,t+f-e.length);m?(l=new Uint8Array(f-h),l.set(e.subarray(t+h,e.length),0)):l=e.subarray(t+h,t+f);let p={unit:l,pts:a};return m||i.samples.push(p),{sample:p,length:f,missing:m}}let d=e.length-t;return l=new Uint8Array(d),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:a},length:d,missing:-1}}function dk(i,e){return rg(i,e)&&Nu(i,e+6)+10<=i.length-e}function uk(i){return i instanceof ArrayBuffer?i:i.byteOffset==0&&i.byteLength==i.buffer.byteLength?i.buffer:new Uint8Array(i).buffer}function vm(i,e=0,t=1/0){return ck(i,e,t,Uint8Array)}function ck(i,e,t,s){let r=hk(i),n=1;"BYTES_PER_ELEMENT"in s&&(n=s.BYTES_PER_ELEMENT);let a=fk(i)?i.byteOffset:0,o=(a+i.byteLength)/n,l=(a+e)/n,d=Math.floor(Math.max(0,Math.min(l,o))),u=Math.floor(Math.min(d+Math.max(t,0),o));return new s(r,d,u-d)}function hk(i){return i instanceof ArrayBuffer?i:i.buffer}function fk(i){return i&&i.buffer instanceof ArrayBuffer&&i.byteLength!==void 0&&i.byteOffset!==void 0}function mk(i){let e={key:i.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(i.size<2)return;if(i.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}let s=i.data.subarray(1).indexOf(0);if(s===-1)return;let r=li(vm(i.data,1,s)),n=i.data[2+s],a=i.data.subarray(3+s).indexOf(0);if(a===-1)return;let o=li(vm(i.data,3+s,a)),l;return r==="-->"?l=li(vm(i.data,4+s+a)):l=uk(i.data.subarray(4+s+a)),e.mimeType=r,e.pictureType=n,e.description=o,e.data=l,e}function pk(i){if(i.size<2)return;let e=li(i.data,!0),t=new Uint8Array(i.data.subarray(e.length+1));return{key:i.type,info:e,data:t.buffer}}function gk(i){if(i.size<2)return;if(i.type==="TXXX"){let t=1,s=li(i.data.subarray(t),!0);t+=s.length+1;let r=li(i.data.subarray(t));return{key:i.type,info:s,data:r}}let e=li(i.data.subarray(1));return{key:i.type,info:"",data:e}}function vk(i){if(i.type==="WXXX"){if(i.size<2)return;let t=1,s=li(i.data.subarray(t),!0);t+=s.length+1;let r=li(i.data.subarray(t));return{key:i.type,info:s,data:r}}let e=li(i.data);return{key:i.type,info:"",data:e}}function Ek(i){return i.type==="PRIV"?pk(i):i.type[0]==="W"?vk(i):i.type==="APIC"?mk(i):gk(i)}function yk(i){let e=String.fromCharCode(i[0],i[1],i[2],i[3]),t=Nu(i,4),s=10;return{type:e,size:t,data:i.subarray(s,s+t)}}var qd=10,Tk=10;function UT(i){let e=0,t=[];for(;rg(i,e);){let s=Nu(i,e+6);i[e+5]>>6&1&&(e+=qd),e+=qd;let r=e+s;for(;e+Tk<r;){let n=yk(i.subarray(e)),a=Ek(n);a&&t.push(a),e+=n.size+qd}CT(i,e)&&(e+=qd)}return t}function FT(i){return i&&i.key==="PRIV"&&i.info==="com.apple.streaming.transportStreamTimestamp"}function bk(i){if(i.data.byteLength===8){let e=new Uint8Array(i.data),t=e[3]&1,s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,t&&(s+=4772185884e-2),Math.round(s)}}function ag(i){let e=UT(i);for(let t=0;t<e.length;t++){let s=e[t];if(FT(s))return bk(s)}}var oi=function(i){return i.audioId3="org.id3",i.dateRange="com.apple.quicktime.HLS",i.emsg="https://aomedia.org/emsg/ID3",i.misbklv="urn:misb:KLV:bin:1910.1",i}({});function Zi(i="",e=9e4){return{type:i,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}var qo=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,s,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,s){}demux(e,t){this.cachedData&&(e=pi(this.cachedData,e),this.cachedData=null);let s=Wo(e,0),r=s?s.length:0,n,a=this._audioTrack,o=this._id3Track,l=s?ag(s):void 0,d=e.length;for((this.basePTS===null||this.frameIndex===0&&Q(l))&&(this.basePTS=_k(l,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),s&&s.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:oi.audioId3,duration:Number.POSITIVE_INFINITY});r<d;){if(this.canParse(e,r)){let u=this.appendFrame(a,e,r);u?(this.frameIndex++,this.lastPTS=u.sample.pts,r+=u.length,n=r):r=d}else dk(e,r)?(s=Wo(e,r),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:oi.audioId3,duration:Number.POSITIVE_INFINITY}),r+=s.length,n=r):r++;if(r===d&&n!==d){let u=e.slice(n);this.cachedData?this.cachedData=pi(this.cachedData,u):this.cachedData=u}}return{audioTrack:a,videoTrack:Zi(),id3Track:o,textTrack:Zi()}}demuxSampleAes(e,t,s){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:Zi(),id3Track:this._id3Track,textTrack:Zi()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}},_k=(i,e,t)=>{if(Q(i))return i*90;let s=t?t.baseTime*9e4/t.timescale:0;return e*9e4+s},Yd=null,Ak=[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],Sk=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Ik=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Lk=[0,1,1,4];function BT(i,e,t,s,r){if(t+24>e.length)return;let n=$T(e,t);if(n&&t+n.frameLength<=e.length){let a=n.samplesPerFrame*9e4/n.sampleRate,o=s+r*a,l={unit:e.subarray(t,t+n.frameLength),pts:o,dts:o};return i.config=[],i.channelCount=n.channelCount,i.samplerate=n.sampleRate,i.samples.push(l),{sample:l,length:n.frameLength,missing:0}}}function $T(i,e){let t=i[e+1]>>3&3,s=i[e+1]>>1&3,r=i[e+2]>>4&15,n=i[e+2]>>2&3;if(t!==1&&r!==0&&r!==15&&n!==3){let a=i[e+2]>>1&1,o=i[e+3]>>6,l=t===3?3-s:s===3?3:4,d=Ak[l*14+r-1]*1e3,c=Sk[(t===3?0:t===2?1:2)*3+n],h=o===3?1:2,f=Ik[t][s],m=Lk[s],p=f*8*m,g=Math.floor(f*d/c+a)*m;if(Yd===null){let y=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Yd=y?parseInt(y[1]):0}return!!Yd&&Yd<=87&&s===2&&d>=224e3&&o===0&&(i[e+3]=i[e+3]|128),{sampleRate:c,channelCount:h,frameLength:g,samplesPerFrame:p}}}function og(i,e){return i[e]===255&&(i[e+1]&224)===224&&(i[e+1]&6)!==0}function HT(i,e){return e+1<i.length&&og(i,e)}function Rk(i,e){return og(i,e)&&4<=i.length-e}function GT(i,e){if(e+1<i.length&&og(i,e)){let s=$T(i,e),r=4;s!=null&&s.frameLength&&(r=s.frameLength);let n=e+r;return n===i.length||HT(i,n)}return!1}var Xm=class extends qo{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,s,r){super.resetInitSegment(e,t,s,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;let s=Wo(e,0),r=(s==null?void 0:s.length)||0;if(GT(e,r))return!1;for(let n=e.length;r<n;r++)if(ok(e,r))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return ak(e,t)}appendFrame(e,t,s){PT(e,this.observer,t,s,e.manifestCodec);let r=NT(e,t,s,this.basePTS,this.frameIndex);if(r&&r.missing===0)return r}},KT=(i,e)=>{let t=0,s=5;e+=s;let r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;s>0;){a[0]=i[e];let o=Math.min(s,8),l=8-o;n[0]=4278190080>>>24+l<<l,r[0]=(a[0]&n[0])>>l,t=t?t<<o|r[0]:r[0],e+=1,s-=o}return t},Zm=class extends qo{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,r){super.resetInitSegment(e,t,s,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,s){let r=VT(e,t,s,this.basePTS,this.frameIndex);if(r!==-1)return{sample:e.samples[e.samples.length-1],length:r,missing:0}}static probe(e){if(!e)return!1;let t=Wo(e,0);if(!t)return!1;let s=t.length;return e[s]===11&&e[s+1]===119&&ag(t)!==void 0&&KT(e,s)<16}};function VT(i,e,t,s,r){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;let n=e[t+4]>>6;if(n>=3)return-1;let o=[48e3,44100,32e3][n],l=e[t+4]&63,u=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][l*3+n]*2;if(t+u>e.length)return-1;let c=e[t+6]>>5,h=0;c===2?h+=2:(c&1&&c!==1&&(h+=2),c&4&&(h+=2));let f=(e[t+6]<<8|e[t+7])>>12-h&1,p=[2,1,2,3,3,4,4,5][c]+f,g=e[t+5]>>3,v=e[t+5]&7,T=new Uint8Array([n<<6|g<<1|v>>2,(v&3)<<6|c<<3|f<<2|l>>4,l<<4&224]),y=1536/o*9e4,b=s+r*y,A=e.subarray(t,t+u);return i.config=T,i.channelCount=p,i.samplerate=o,i.samples.push({unit:A,pts:b}),u}var Jm=class extends qo{resetInitSegment(e,t,s,r){super.resetInitSegment(e,t,s,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=Wo(e,0),s=(t==null?void 0:t.length)||0;if(t&&e[s]===11&&e[s+1]===119&&ag(t)!==void 0&&KT(e,s)<=16)return!1;for(let r=e.length;s<r;s++)if(GT(e,s))return Be.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return Rk(e,t)}appendFrame(e,t,s){if(this.basePTS!==null)return BT(e,t,s,this.basePTS,this.frameIndex)}},xk=/\/emsg[-/]ID3/i,ep=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,s,r){let n=this.videoTrack=Zi("video",1),a=this.audioTrack=Zi("audio",1),o=this.txtTrack=Zi("text",1);if(this.id3Track=Zi("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;let l=sT(e);if(l.video){let{id:d,timescale:u,codec:c,supplemental:h}=l.video;n.id=d,n.timescale=o.timescale=u,n.codec=c,n.supplemental=h}if(l.audio){let{id:d,timescale:u,codec:c}=l.audio;a.id=d,a.timescale=u,a.codec=c}o.id=eT.text,n.sampleDuration=0,n.duration=a.duration=r}resetContiguity(){this.remainderData=null}static probe(e){return UR(e)}demux(e,t){this.timeOffset=t;let s=e,r=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=pi(this.remainderData,e));let o=VR(s);this.remainderData=o.remainder,r.samples=o.valid||new Uint8Array}else r.samples=s;let a=this.extractID3Track(r,t);return n.samples=VE(t,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){let e=this.timeOffset,t=this.videoTrack,s=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;let r=this.extractID3Track(t,this.timeOffset);return s.samples=VE(e,t),{videoTrack:t,audioTrack:Zi(),id3Track:r,textTrack:Zi()}}extractID3Track(e,t){let s=this.id3Track;if(e.samples.length){let r=be(e.samples,["emsg"]);r&&r.forEach(n=>{let a=qR(n);if(xk.test(a.schemeIdUri)){let o=Ly(a,t),l=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);let d=a.payload;s.samples.push({data:d,len:d.byteLength,dts:o,pts:o,type:oi.emsg,duration:l})}else if(this.config.enableEmsgKLVMetadata&&a.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){let o=Ly(a,t);s.samples.push({data:a.payload,len:a.payload.byteLength,dts:o,pts:o,type:oi.misbklv,duration:Number.POSITIVE_INFINITY})}})}return s}demuxSampleAes(e,t,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}};function Ly(i,e){return Q(i.presentationTime)?i.presentationTime/i.timeScale:e+i.presentationTimeDelta/i.timeScale}var tp=class{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Ho(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,ar.cbc)}decryptAacSample(e,t,s){let r=e[t].unit;if(r.length<=16)return;let n=r.subarray(16,r.length-r.length%16),a=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(a).then(o=>{let l=new Uint8Array(o);r.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)}).catch(s)}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length){s();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){let t=Math.floor((e.length-48)/160)*16+16,s=new Int8Array(t),r=0;for(let n=32;n<e.length-16;n+=160,r+=16)s.set(e.subarray(n,n+16),r);return s}getAvcDecryptedUnit(e,t){let s=new Uint8Array(t),r=0;for(let n=32;n<e.length-16;n+=160,r+=16)e.set(s.subarray(r,r+16),n);return e}decryptAvcSample(e,t,s,r,n){let a=aT(n.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(l=>{n.data=this.getAvcDecryptedUnit(a,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,r)}).catch(r)}decryptAvcSamples(e,t,s,r){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length){r();return}let n=e[t].units;for(;!(s>=n.length);s++){let a=n[s];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,s,r,a),!this.decrypter.isSync()))return}}}},Su=class{constructor(){this.VideoSample=null}createVideoSample(e,t,s){return{key:e,frame:!1,pts:t,dts:s,units:[],length:0}}getLastNalUnit(e){var t;let s=this.VideoSample,r;if((!s||s.units.length===0)&&(s=e[e.length-1]),(t=s)!=null&&t.units){let n=s.units;r=n[n.length-1]}return r}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){let s=t.samples,r=s.length;if(r){let n=s[r-1];e.pts=n.pts,e.dts=n.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,s){let r=t.byteLength,n=e.naluState||0,a=n,o=[],l=0,d,u,c,h=-1,f=0;for(n===-1&&(h=0,f=this.getNALuType(t,0),n=0,l=1);l<r;){if(d=t[l++],!n){n=d?0:1;continue}if(n===1){n=d?0:2;continue}if(!d)n=3;else if(d===1){if(u=l-n-1,h>=0){let m={data:t.subarray(h,u),type:f};o.push(m)}else{let m=this.getLastNalUnit(e.samples);m&&(a&&l<=4-a&&m.state&&(m.data=m.data.subarray(0,m.data.byteLength-a)),u>0&&(m.data=pi(m.data,t.subarray(0,u)),m.state=0))}l<r?(c=this.getNALuType(t,l),h=l,f=c,n=0):n=-1}else n=0}if(h>=0&&n>=0){let m={data:t.subarray(h,r),type:f,state:n};o.push(m)}if(o.length===0){let m=this.getLastNalUnit(e.samples);m&&(m.data=pi(m.data,t))}return e.naluState=n,o}},en=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,s=e.byteLength-t,r=new Uint8Array(4),n=Math.min(4,t);if(n===0)throw new Error("no bytes available");r.set(e.subarray(s,s+n)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=n*8,this.bytesAvailable-=n}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e),s=this.word>>>32-t;if(e>32&&Be.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?s<<t|this.readBits(t):s}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if((this.word&2147483648>>>e)!==0)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){let e=this.skipLZ();return this.readBits(e+1)-1}readEG(){let e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}},ip=class extends Su{parsePES(e,t,s,r){let n=this.parseNALu(e,s.data,r),a=this.VideoSample,o,l=!1;s.data=null,a&&n.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),n.forEach(d=>{var u,c;switch(d.type){case 1:{let p=!1;o=!0;let g=d.data;if(l&&g.length>4){let v=this.readSliceType(g);(v===2||v===4||v===7||v===9)&&(p=!0)}if(p){var h;(h=a)!=null&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.frame=!0,a.key=p;break}case 5:o=!0,(u=a)!=null&&u.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 6:{o=!0,Xp(d.data,1,s.pts,t.samples);break}case 7:{var f,m;o=!0,l=!0;let p=d.data,g=this.readSPS(p);if(!e.sps||e.width!==g.width||e.height!==g.height||((f=e.pixelRatio)==null?void 0:f[0])!==g.pixelRatio[0]||((m=e.pixelRatio)==null?void 0:m[1])!==g.pixelRatio[1]){e.width=g.width,e.height=g.height,e.pixelRatio=g.pixelRatio,e.sps=[p];let v=p.subarray(1,4),T="avc1.";for(let y=0;y<3;y++){let b=v[y].toString(16);b.length<2&&(b="0"+b),T+=b}e.codec=T}break}case 8:o=!0,e.pps=[d.data];break;case 9:o=!0,e.audFound=!0,(c=a)!=null&&c.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:o=!0;break;default:o=!1;break}a&&o&&a.units.push(d)}),r&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){let t=new en(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s=8,r=8,n;for(let a=0;a<e;a++)r!==0&&(n=t.readEG(),r=(s+n+256)%256),s=r===0?s:r}readSPS(e){let t=new en(e),s=0,r=0,n=0,a=0,o,l,d,u=t.readUByte.bind(t),c=t.readBits.bind(t),h=t.readUEG.bind(t),f=t.readBoolean.bind(t),m=t.skipBits.bind(t),p=t.skipEG.bind(t),g=t.skipUEG.bind(t),v=this.skipScalingList.bind(this);u();let T=u();if(c(5),m(3),u(),g(),T===100||T===110||T===122||T===244||T===44||T===83||T===86||T===118||T===128){let x=h();if(x===3&&m(1),g(),g(),m(1),f())for(l=x!==3?8:12,d=0;d<l;d++)f()&&(d<6?v(16,t):v(64,t))}g();let y=h();if(y===0)h();else if(y===1)for(m(1),p(),p(),o=h(),d=0;d<o;d++)p();g(),m(1);let b=h(),A=h(),R=c(1);R===0&&m(1),m(1),f()&&(s=h(),r=h(),n=h(),a=h());let I=[1,1];if(f()&&f())switch(u()){case 1:I=[1,1];break;case 2:I=[12,11];break;case 3:I=[10,11];break;case 4:I=[16,11];break;case 5:I=[40,33];break;case 6:I=[24,11];break;case 7:I=[20,11];break;case 8:I=[32,11];break;case 9:I=[80,33];break;case 10:I=[18,11];break;case 11:I=[15,11];break;case 12:I=[64,33];break;case 13:I=[160,99];break;case 14:I=[4,3];break;case 15:I=[3,2];break;case 16:I=[2,1];break;case 255:{I=[u()<<8|u(),u()<<8|u()];break}}return{width:Math.ceil((b+1)*16-s*2-r*2),height:(2-R)*(A+1)*16-(R?2:4)*(n+a),pixelRatio:I}}},sp=class extends Su{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,s,r){let n=this.parseNALu(e,s.data,r),a=this.VideoSample,o,l=!1;s.data=null,a&&n.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),n.forEach(d=>{var u,c;switch(d.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),a.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:if(o=!0,l){var h;(h=a)!=null&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:o=!0,(u=a)!=null&&u.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 39:o=!0,Xp(d.data,2,s.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=$e(e.params,this.readVPS(d.data)),this.initVPS=d.data),e.vps=[d.data];break;case 33:if(o=!0,l=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],d.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){let f=this.readSPS(d.data);e.width=f.width,e.height=f.height,e.pixelRatio=f.pixelRatio,e.codec=f.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(let m in f.params)e.params[m]=f.params[m]}this.pushParameterSet(e.sps,d.data,e.vps),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0;break;case 34:if(o=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];let f=this.readPPS(d.data);for(let m in f)e.params[m]=f[m]}this.pushParameterSet(e.pps,d.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(c=a)!=null&&c.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;default:o=!1;break}a&&o&&a.units.push(d)}),r&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,s){(s&&s[0]===this.initVPS||!s&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){let t=new Uint8Array(e.byteLength),s=0;for(let r=0;r<e.byteLength;r++)r>=2&&e[r]===3&&e[r-1]===0&&e[r-2]===0||(t[s]=e[r],s++);return new Uint8Array(t.buffer,0,s)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){let t=new en(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);let s=t.readBits(3),r=t.readBoolean();return{numTemporalLayers:s+1,temporalIdNested:r}}readSPS(e){let t=new en(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);let s=t.readBits(3);t.readBoolean();let r=t.readBits(2),n=t.readBoolean(),a=t.readBits(5),o=t.readUByte(),l=t.readUByte(),d=t.readUByte(),u=t.readUByte(),c=t.readUByte(),h=t.readUByte(),f=t.readUByte(),m=t.readUByte(),p=t.readUByte(),g=t.readUByte(),v=t.readUByte(),T=[],y=[];for(let ke=0;ke<s;ke++)T.push(t.readBoolean()),y.push(t.readBoolean());if(s>0)for(let ke=s;ke<8;ke++)t.readBits(2);for(let ke=0;ke<s;ke++)T[ke]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),y[ke]&&t.readUByte();t.readUEG();let b=t.readUEG();b==3&&t.skipBits(1);let A=t.readUEG(),R=t.readUEG(),I=t.readBoolean(),x=0,D=0,S=0,C=0;I&&(x+=t.readUEG(),D+=t.readUEG(),S+=t.readUEG(),C+=t.readUEG());let P=t.readUEG(),N=t.readUEG(),$=t.readUEG(),H=t.readBoolean();for(let ke=H?0:s;ke<=s;ke++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let Et=0;Et<4;Et++)for(let Bt=0;Bt<(Et===3?2:6);Bt++)if(!t.readBoolean())t.readUEG();else{let fi=Math.min(64,1<<4+(Et<<1));Et>1&&t.readEG();for(let De=0;De<fi;De++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());let q=t.readUEG(),Z=0;for(let ke=0;ke<q;ke++){let Et=!1;if(ke!==0&&(Et=t.readBoolean()),Et){ke===q&&t.readUEG(),t.readBoolean(),t.readUEG();let Bt=0;for(let Yi=0;Yi<=Z;Yi++){let fi=t.readBoolean(),De=!1;fi||(De=t.readBoolean()),(fi||De)&&Bt++}Z=Bt}else{let Bt=t.readUEG(),Yi=t.readUEG();Z=Bt+Yi;for(let fi=0;fi<Bt;fi++)t.readUEG(),t.readBoolean();for(let fi=0;fi<Yi;fi++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){let ke=t.readUEG();for(let Et=0;Et<ke;Et++){for(let Bt=0;Bt<$+4;Bt++)t.readBits(1);t.readBits(1)}}let V=0,G=1,ce=1,Se=!0,he=1,Te=0;t.readBoolean(),t.readBoolean();let vt=!1;if(t.readBoolean()){if(t.readBoolean()){let ri=t.readUByte(),Rd=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],Kn=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];ri>0&&ri<16?(G=Rd[ri-1],ce=Kn[ri-1]):ri===255&&(G=t.readBits(16),ce=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),vt=t.readBoolean(),vt&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(he=t.readBits(32),Te=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){let Kn=t.readBoolean(),xd=t.readBoolean(),Kr=!1;(Kn||xd)&&(Kr=t.readBoolean(),Kr&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),Kr&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let kd=0;kd<=s;kd++){Se=t.readBoolean();let Yf=Se||t.readBoolean(),Dd=!1;Yf?t.readEG():Dd=t.readBoolean();let Nt=Dd?1:t.readUEG()+1;if(Kn)for(let Je=0;Je<Nt;Je++)t.readUEG(),t.readUEG(),Kr&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(xd)for(let Je=0;Je<Nt;Je++)t.readUEG(),t.readUEG(),Kr&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),V=t.readUEG())}let Ft=A,si=R;if(I){let ke=1,Et=1;b===1?ke=Et=2:b==2&&(ke=2),Ft=A-ke*D-ke*x,si=R-Et*C-Et*S}let Ii=r?["A","B","C"][r]:"",Js=o<<24|l<<16|d<<8|u,Hn=0;for(let ke=0;ke<32;ke++)Hn=(Hn|(Js>>ke&1)<<31-ke)>>>0;let Gn=Hn.toString(16);return a===1&&Gn==="2"&&(Gn="6"),{codecString:`hvc1.${Ii}${a}.${Gn}.${n?"H":"L"}${v}.B0`,params:{general_tier_flag:n,general_profile_idc:a,general_profile_space:r,general_profile_compatibility_flags:[o,l,d,u],general_constraint_indicator_flags:[c,h,f,m,p,g],general_level_idc:v,bit_depth:P+8,bit_depth_luma_minus8:P,bit_depth_chroma_minus8:N,min_spatial_segmentation_idc:V,chroma_format_idc:b,frame_rate:{fixed:Se,fps:Te/he}},width:Ft,height:si,pixelRatio:[G,ce]}}readPPS(e){let t=new en(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);let r=t.readBoolean(),n=t.readBoolean(),a=1;return n&&r?a=0:n?a=3:r&&(a=2),{parallelismType:a}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}},Lt=188,rp=class i{constructor(e,t,s,r){this.logger=void 0,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._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=s,this.logger=r,this.videoParser=null}static probe(e,t){let s=i.syncOffset(e);return s>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),s!==-1}static syncOffset(e){let t=e.length,s=Math.min(Lt*5,t-Lt)+1,r=0;for(;r<s;){let n=!1,a=-1,o=0;for(let l=r;l<t;l+=Lt)if(e[l]===71&&(t-l===Lt||e[l+Lt]===71)){if(o++,a===-1&&(a=l,a!==0&&(s=Math.min(a+Lt*99,e.length-Lt)+1)),n||(n=np(e,l)===0),n&&o>1&&(a===0&&o>2||l+Lt>s))return a}else{if(o)return-1;break}r++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:eT[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,s,r){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=i.createTrack("video"),this._videoTrack.duration=r,this._audioTrack=i.createTrack("audio",r),this._id3Track=i.createTrack("id3"),this._txtTrack=i.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s}resetTimeStamp(){}resetContiguity(){let{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s=!1,r=!1){s||(this.sampleAes=null);let n,a=this._videoTrack,o=this._audioTrack,l=this._id3Track,d=this._txtTrack,u=a.pid,c=a.pesData,h=o.pid,f=l.pid,m=o.pesData,p=l.pesData,g=null,v=this.pmtParsed,T=this._pmtId,y=e.length;if(this.remainderData&&(e=pi(this.remainderData,e),y=e.length,this.remainderData=null),y<Lt&&!r)return this.remainderData=e,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:d};let b=Math.max(0,i.syncOffset(e));y-=(y-b)%Lt,y<e.byteLength&&!r&&(this.remainderData=new Uint8Array(e.buffer,y,e.buffer.byteLength-y));let A=0;for(let I=b;I<y;I+=Lt)if(e[I]===71){let x=!!(e[I+1]&64),D=np(e,I),S=(e[I+3]&48)>>4,C;if(S>1){if(C=I+5+e[I+4],C===I+Lt)continue}else C=I+4;switch(D){case u:x&&(c&&(n=zn(c,this.logger))&&(this.readyVideoParser(a.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(a,d,n,!1)),c={data:[],size:0}),c&&(c.data.push(e.subarray(C,I+Lt)),c.size+=I+Lt-C);break;case h:if(x){if(m&&(n=zn(m,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,n);break;case"mp3":this.parseMPEGPES(o,n);break;case"ac3":this.parseAC3PES(o,n);break}m={data:[],size:0}}m&&(m.data.push(e.subarray(C,I+Lt)),m.size+=I+Lt-C);break;case f:x&&(p&&(n=zn(p,this.logger))&&this.parseID3PES(l,n),p={data:[],size:0}),p&&(p.data.push(e.subarray(C,I+Lt)),p.size+=I+Lt-C);break;case 0:x&&(C+=e[C]+1),T=this._pmtId=kk(e,C);break;case T:{x&&(C+=e[C]+1);let P=Dk(e,C,this.typeSupported,s,this.observer,this.logger);u=P.videoPid,u>0&&(a.pid=u,a.segmentCodec=P.segmentVideoCodec),h=P.audioPid,h>0&&(o.pid=h,o.segmentCodec=P.segmentAudioCodec),f=P.id3Pid,f>0&&(l.pid=f),g!==null&&!v&&(this.logger.warn(`MPEG-TS PMT found at ${I} after unknown PID '${g}'. Backtracking to sync byte @${b} to parse all TS packets.`),g=null,I=b-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:g=D;break}}else A++;A>0&&ap(this.observer,new Error(`Found ${A} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=c,o.pesData=m,l.pesData=p;let R={audioTrack:o,videoTrack:a,id3Track:l,textTrack:d};return r&&this.extractRemainingSamples(R),R}flush(){let{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){let{audioTrack:t,videoTrack:s,id3Track:r,textTrack:n}=e,a=s.pesData,o=t.pesData,l=r.pesData,d;if(a&&(d=zn(a,this.logger))?(this.readyVideoParser(s.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(s,n,d,!0),s.pesData=null)):s.pesData=a,o&&(d=zn(o,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,d);break;case"mp3":this.parseMPEGPES(t,d);break;case"ac3":this.parseAC3PES(t,d);break}t.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;l&&(d=zn(l,this.logger))?(this.parseID3PES(r,d),r.pesData=null):r.pesData=l}demuxSampleAes(e,t,s){let r=this.demux(e,s,!0,!this.config.progressive),n=this.sampleAes=new tp(this.observer,this.config,t);return this.decrypt(r,n)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new ip:e==="hevc"&&(this.videoParser=new sp))}decrypt(e,t){return new Promise(s=>{let{audioTrack:r,videoTrack:n}=e;r.samples&&r.segmentCodec==="aac"?t.decryptAacSamples(r.samples,0,()=>{n.samples?t.decryptAvcSamples(n.samples,0,0,()=>{s(e)}):s(e)}):n.samples&&t.decryptAvcSamples(n.samples,0,0,()=>{s(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let s=0,r=this.aacOverFlow,n=t.data;if(r){this.aacOverFlow=null;let c=r.missing,h=r.sample.unit.byteLength;if(c===-1)n=pi(r.sample.unit,n);else{let f=h-c;r.sample.unit.set(n.subarray(0,c),f),e.samples.push(r.sample),s=r.missing}}let a,o;for(a=s,o=n.length;a<o-1&&!Au(n,a);a++);if(a!==s){let c,h=a<o-1;if(h?c=`AAC PES did not start with ADTS header,offset:${a}`:c="No ADTS header found in AAC PES",ap(this.observer,new Error(c),h,this.logger),!h)return}PT(e,this.observer,n,a,this.audioCodec);let l;if(t.pts!==void 0)l=t.pts;else if(r){let c=OT(e.samplerate);l=r.sample.pts+c}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let d=0,u;for(;a<o;)if(u=NT(e,n,a,l,d),a+=u.length,u.missing){this.aacOverFlow=u;break}else for(d++;a<o-1&&!Au(n,a);a++);}parseMPEGPES(e,t){let s=t.data,r=s.length,n=0,a=0,o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<r;)if(HT(s,a)){let l=BT(e,s,a,o,n);if(l)a+=l.length,n++;else break}else a++}parseAC3PES(e,t){{let s=t.data,r=t.pts;if(r===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}let n=s.length,a=0,o=0,l;for(;o<n&&(l=VT(e,s,o,r,a++))>0;)o+=l}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}let s=$e({},t,{type:this._videoTrack?oi.emsg:oi.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}};function np(i,e){return((i[e+1]&31)<<8)+i[e+2]}function kk(i,e){return(i[e+10]&31)<<8|i[e+11]}function Dk(i,e,t,s,r,n){let a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(i[e+1]&15)<<8|i[e+2],l=e+3+o-4,d=(i[e+10]&15)<<8|i[e+11];for(e+=12+d;e<l;){let u=np(i,e),c=(i[e+3]&15)<<8|i[e+4];switch(i[e]){case 207:if(!s){Em("ADTS AAC",n);break}case 15:a.audioPid===-1&&(a.audioPid=u);break;case 21:a.id3Pid===-1&&(a.id3Pid=u);break;case 219:if(!s){Em("H.264",n);break}case 27:a.videoPid===-1&&(a.videoPid=u);break;case 3:case 4:!t.mpeg&&!t.mp3?n.log("MPEG audio found, not supported in this browser"):a.audioPid===-1&&(a.audioPid=u,a.segmentAudioCodec="mp3");break;case 193:if(!s){Em("AC-3",n);break}case 129:t.ac3?a.audioPid===-1&&(a.audioPid=u,a.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(a.audioPid===-1&&c>0){let h=e+5,f=c;for(;f>2;){switch(i[h]){case 106:t.ac3!==!0?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=u,a.segmentAudioCodec="ac3");break}let p=i[h+1]+2;h+=p,f-=p}}break;case 194:case 135:return ap(r,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:a.videoPid===-1&&(a.videoPid=u,a.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"));break}e+=c+5}return a}function ap(i,e,t,s){s.warn(`parsing error: ${e.message}`),i.emit(E.ERROR,E.ERROR,{type:se.MEDIA_ERROR,details:M.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function Em(i,e){e.log(`${i} with AES-128-CBC encryption found in unencrypted stream`)}function zn(i,e){let t=0,s,r,n,a,o,l=i.data;if(!i||i.size===0)return null;for(;l[0].length<19&&l.length>1;)l[0]=pi(l[0],l[1]),l.splice(1,1);if(s=l[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(r=(s[4]<<8)+s[5],r&&r>i.size-6)return null;let u=s[7];u&192&&(a=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,u&64?(o=(s[14]&14)*536870912+(s[15]&255)*4194304+(s[16]&254)*16384+(s[17]&255)*128+(s[18]&254)/2,a-o>60*9e4&&(e.warn(`${Math.round((a-o)/9e4)}s delta between PTS and DTS, align them`),a=o)):o=a),n=s[8];let c=n+9;if(i.size<=c)return null;i.size-=c;let h=new Uint8Array(i.size);for(let f=0,m=l.length;f<m;f++){s=l[f];let p=s.byteLength;if(c)if(c>p){c-=p;continue}else s=s.subarray(c),p-=c,c=0;h.set(s,t),t+=p}return r&&(r-=n+3),{data:h,pts:a,dts:o,len:r}}return null}var op=class{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}},tr=Math.pow(2,32)-1,_t=class i{static init(){i.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in i.types)i.types.hasOwnProperty(e)&&(i.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);let t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),s=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]);i.HDLR_TYPES={video:t,audio:s};let r=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),n=new Uint8Array([0,0,0,0,0,0,0,0]);i.STTS=i.STSC=i.STCO=n,i.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),i.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),i.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),i.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]);i.FTYP=i.box(i.types.ftyp,a,l,a,o),i.DINF=i.box(i.types.dinf,i.box(i.types.dref,r))}static box(e,...t){let s=8,r=t.length,n=r;for(;r--;)s+=t[r].byteLength;let a=new Uint8Array(s);for(a[0]=s>>24&255,a[1]=s>>16&255,a[2]=s>>8&255,a[3]=s&255,a.set(e,4),r=0,s=8;r<n;r++)a.set(t[r],s),s+=t[r].byteLength;return a}static hdlr(e){return i.box(i.types.hdlr,i.HDLR_TYPES[e])}static mdat(e){return i.box(i.types.mdat,e)}static mdhd(e,t){t*=e;let s=Math.floor(t/(tr+1)),r=Math.floor(t%(tr+1));return i.box(i.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,s>>24,s>>16&255,s>>8&255,s&255,r>>24,r>>16&255,r>>8&255,r&255,85,196,0,0]))}static mdia(e){return i.box(i.types.mdia,i.mdhd(e.timescale||0,e.duration||0),i.hdlr(e.type),i.minf(e))}static mfhd(e){return i.box(i.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?i.box(i.types.minf,i.box(i.types.smhd,i.SMHD),i.DINF,i.stbl(e)):i.box(i.types.minf,i.box(i.types.vmhd,i.VMHD),i.DINF,i.stbl(e))}static moof(e,t,s){return i.box(i.types.moof,i.mfhd(e),i.traf(s,t))}static moov(e){let t=e.length,s=[];for(;t--;)s[t]=i.trak(e[t]);return i.box.apply(null,[i.types.moov,i.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(i.mvex(e)))}static mvex(e){let t=e.length,s=[];for(;t--;)s[t]=i.trex(e[t]);return i.box.apply(null,[i.types.mvex,...s])}static mvhd(e,t){t*=e;let s=Math.floor(t/(tr+1)),r=Math.floor(t%(tr+1)),n=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,s>>24,s>>16&255,s>>8&255,s&255,r>>24,r>>16&255,r>>8&255,r&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return i.box(i.types.mvhd,n)}static sdtp(e){let t=e.samples||[],s=new Uint8Array(4+t.length),r,n;for(r=0;r<t.length;r++)n=t[r].flags,s[r+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return i.box(i.types.sdtp,s)}static stbl(e){return i.box(i.types.stbl,i.stsd(e),i.box(i.types.stts,i.STTS),i.box(i.types.stsc,i.STSC),i.box(i.types.stsz,i.STSZ),i.box(i.types.stco,i.STCO))}static avc1(e){let t=[],s=[],r,n,a;for(r=0;r<e.sps.length;r++)n=e.sps[r],a=n.byteLength,t.push(a>>>8&255),t.push(a&255),t=t.concat(Array.prototype.slice.call(n));for(r=0;r<e.pps.length;r++)n=e.pps[r],a=n.byteLength,s.push(a>>>8&255),s.push(a&255),s=s.concat(Array.prototype.slice.call(n));let o=i.box(i.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(s))),l=e.width,d=e.height,u=e.pixelRatio[0],c=e.pixelRatio[1];return i.box(i.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&255,d>>8&255,d&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,i.box(i.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),i.box(i.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,c>>24,c>>16&255,c>>8&255,c&255])))}static esds(e){let t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){let t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return i.box(i.types.mp4a,i.audioStsd(e),i.box(i.types.esds,i.esds(e)))}static mp3(e){return i.box(i.types[".mp3"],i.audioStsd(e))}static ac3(e){return i.box(i.types["ac-3"],i.audioStsd(e),i.box(i.types.dac3,e.config))}static stsd(e){let{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return i.box(i.types.stsd,i.STSD,i.mp4a(e));if(t==="ac3"&&e.config)return i.box(i.types.stsd,i.STSD,i.ac3(e));if(t==="mp3"&&e.codec==="mp3")return i.box(i.types.stsd,i.STSD,i.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return i.box(i.types.stsd,i.STSD,i.avc1(e));if(t==="hevc"&&e.vps)return i.box(i.types.stsd,i.STSD,i.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){let t=e.id,s=(e.duration||0)*(e.timescale||0),r=e.width||0,n=e.height||0,a=Math.floor(s/(tr+1)),o=Math.floor(s%(tr+1));return i.box(i.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,r>>8&255,r&255,0,0,n>>8&255,n&255,0,0]))}static traf(e,t){let s=i.sdtp(e),r=e.id,n=Math.floor(t/(tr+1)),a=Math.floor(t%(tr+1));return i.box(i.types.traf,i.box(i.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,r&255])),i.box(i.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,a>>24,a>>16&255,a>>8&255,a&255])),i.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,i.box(i.types.trak,i.tkhd(e),i.mdia(e))}static trex(e){let t=e.id;return i.box(i.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){let s=e.samples||[],r=s.length,n=12+16*r,a=new Uint8Array(n),o,l,d,u,c,h;for(t+=8+n,a.set([e.type==="video"?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,r&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<r;o++)l=s[o],d=l.duration,u=l.size,c=l.flags,h=l.cts,a.set([d>>>24&255,d>>>16&255,d>>>8&255,d&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,c.isLeading<<2|c.dependsOn,c.isDependedOn<<6|c.hasRedundancy<<4|c.paddingValue<<1|c.isNonSync,c.degradPrio&61440,c.degradPrio&15,h>>>24&255,h>>>16&255,h>>>8&255,h&255],12+16*o);return i.box(i.types.trun,a)}static initSegment(e){i.types||i.init();let t=i.moov(e);return pi(i.FTYP,t)}static hvc1(e){let t=e.params,s=[e.vps,e.sps,e.pps],r=4,n=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),r-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),s.length]),a=n.length;for(let m=0;m<s.length;m+=1){a+=3;for(let p=0;p<s[m].length;p+=1)a+=2+s[m][p].length}let o=new Uint8Array(a);o.set(n,0),a=n.length;let l=s.length-1;for(let m=0;m<s.length;m+=1){o.set(new Uint8Array([32+m|(m===l?128:0),0,s[m].length]),a),a+=3;for(let p=0;p<s[m].length;p+=1)o.set(new Uint8Array([s[m][p].length>>8,s[m][p].length&255]),a),a+=2,o.set(s[m][p],a),a+=s[m][p].length}let d=i.box(i.types.hvcC,o),u=e.width,c=e.height,h=e.pixelRatio[0],f=e.pixelRatio[1];return i.box(i.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,u>>8&255,u&255,c>>8&255,c&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),d,i.box(i.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),i.box(i.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,f>>24,f>>16&255,f>>8&255,f&255])))}};_t.types=void 0;_t.HDLR_TYPES=void 0;_t.STTS=void 0;_t.STSC=void 0;_t.STCO=void 0;_t.STSZ=void 0;_t.VMHD=void 0;_t.SMHD=void 0;_t.STSD=void 0;_t.FTYP=void 0;_t.DINF=void 0;var WT=9e4;function lg(i,e,t=1,s=!1){let r=i*e*t;return s?Math.round(r):r}function Ck(i,e,t=1,s=!1){return lg(i,e,1/t,s)}function wo(i,e=!1){return lg(i,1e3,1/WT,e)}function wk(i,e=1){return lg(i,WT,1/e)}function Ry(i){let{baseTime:e,timescale:t,trackId:s}=i;return`${e/t} (${e}/${t}) trackId: ${s}`}var Mk=10*1e3,Pk=1024,Ok=1152,Nk=1536,Qn=null,ym=null;function xy(i,e,t,s){return{duration:e,size:t,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:i?2:1,isNonSync:i?0:1}}}var ia=class extends Qt{constructor(e,t,s,r){if(super("mp4-remuxer",r),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.ISGenerated=!1,Qn===null){let a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Qn=a?parseInt(a[1]):0}if(ym===null){let n=navigator.userAgent.match(/Safari\/(\d+)/i);ym=n?parseInt(n[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){let t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&Ry(t)} > ${e&&Ry(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1,s=e[0].pts,r=e.reduce((n,a)=>{let o=a.pts,l=o-n;return l<-4294967296&&(t=!0,o=ai(o,s),l=o-n),l>0?n:o},s);return t&&this.debug("PTS rollover detected"),r}remux(e,t,s,r,n,a,o,l){let d,u,c,h,f,m,p=n,g=n,v=e.pid>-1,T=t.pid>-1,y=t.samples.length,b=e.samples.length>0,A=o&&y>0||y>1;if((!v||b)&&(!T||A)||this.ISGenerated||o){if(this.ISGenerated){var I,x,D,S;let $=this.videoTrackConfig;($&&(t.width!==$.width||t.height!==$.height||((I=t.pixelRatio)==null?void 0:I[0])!==((x=$.pixelRatio)==null?void 0:x[0])||((D=t.pixelRatio)==null?void 0:D[1])!==((S=$.pixelRatio)==null?void 0:S[1]))||!$&&A||this.nextAudioTs===null&&b)&&this.resetInitSegment()}this.ISGenerated||(c=this.generateIS(e,t,n,a));let C=this.isVideoContiguous,P=-1,N;if(A&&(P=Uk(t.samples),!C&&this.config.forceKeyFrameOnDiscontinuity))if(m=!0,P>0){this.warn(`Dropped ${P} out of ${y} video samples due to a missing keyframe`);let $=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(P),t.dropped+=P,g+=(t.samples[0].pts-$)/t.inputTimeScale,N=g}else P===-1&&(this.warn(`No keyframe found out of ${y} video samples`),m=!1);if(this.ISGenerated){if(b&&A){let $=this.getVideoStartPts(t.samples),U=(ai(e.samples[0].pts,$)-$)/t.inputTimeScale;p+=Math.max(0,U),g+=Math.max(0,-U)}if(b){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),c=this.generateIS(e,t,n,a)),u=this.remuxAudio(e,p,this.isAudioContiguous,a,T||A||l===J.AUDIO?g:void 0),A){let $=u?u.endPTS-u.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),c=this.generateIS(e,t,n,a)),d=this.remuxVideo(t,g,C,$)}}else A&&(d=this.remuxVideo(t,g,C,0));d&&(d.firstKeyFrame=P,d.independent=P!==-1,d.firstKeyFramePTS=N)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(f=qT(s,n,this._initPTS,this._initDTS)),r.samples.length&&(h=YT(r,n,this._initPTS))),{audio:u,video:d,initSegment:c,independent:m,text:h,id3:f}}computeInitPts(e,t,s,r){let n=Math.round(s*t),a=ai(e,n);if(a<n+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(n-a)/t} ${r}`);a<n+t;)a+=8589934592;return a-n}generateIS(e,t,s,r){let n=e.samples,a=t.samples,o=this.typeSupported,l={},d=this._initPTS,u=!d||r,c="audio/mp4",h,f,m,p=-1;if(u&&(h=f=1/0),e.config&&n.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(c="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}l.audio={id:"audio",container:c,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):_t.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(p=e.id,m=e.inputTimeScale,!d||m!==d.timescale?h=f=this.computeInitPts(n[0].pts,m,s,"audio"):u=!1)}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:_t.initSegment([t]),metadata:{width:t.width,height:t.height}},u)if(p=t.id,m=t.inputTimeScale,!d||m!==d.timescale){let g=this.getVideoStartPts(a),v=ai(a[0].dts,g),T=this.computeInitPts(v,m,s,"video"),y=this.computeInitPts(g,m,s,"video");f=Math.min(f,T),h=Math.min(h,y)}else u=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,u?(d&&this.warn(`Timestamps at playlist time: ${r?"":"~"}${s} ${h/m} != initPTS: ${d.baseTime/d.timescale} (${d.baseTime}/${d.timescale}) trackId: ${d.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${h/m} (${h}/${m}) trackId: ${p}`),this._initPTS={baseTime:h,timescale:m,trackId:p},this._initDTS={baseTime:f,timescale:m,trackId:p}):h=m=void 0,{tracks:l,initPTS:h,timescale:m,trackId:p}}remuxVideo(e,t,s,r){let n=e.inputTimeScale,a=e.samples,o=[],l=a.length,d=this._initPTS,u=d.baseTime*n/d.timescale,c=this.nextVideoTs,h=8,f=this.videoSampleDuration,m,p,g=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY,T=!1;if(!s||c===null){let V=u+t*n,G=a[0].pts-ai(a[0].dts,a[0].pts);Qn&&c!==null&&Math.abs(V-G-(c+u))<15e3?s=!0:c=V-G-u}let y=c+u;for(let V=0;V<l;V++){let G=a[V];G.pts=ai(G.pts,y),G.dts=ai(G.dts,y),G.dts<a[V>0?V-1:V].dts&&(T=!0)}T&&a.sort(function(V,G){let ce=V.dts-G.dts,Se=V.pts-G.pts;return ce||Se}),m=a[0].dts,p=a[a.length-1].dts;let b=p-m,A=b?Math.round(b/(l-1)):f||e.inputTimeScale/30;if(s){let V=m-y,G=V>A,ce=V<-1;if((G||ce)&&(G?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${wo(V,!0)} ms (${V}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${wo(-V,!0)} ms (${V}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!ce||y>=a[0].pts||Qn)){m=y;let Se=a[0].pts-V;if(G)a[0].dts=m,a[0].pts=Se;else{let he=!0;for(let Te=0;Te<a.length&&!(a[Te].dts>Se&&he);Te++){let vt=a[Te].pts;if(a[Te].dts-=V,a[Te].pts-=V,Te<a.length-1){let ut=a[Te+1].pts,Ft=a[Te].pts,si=ut<=Ft,Ii=ut<=vt;he=si==Ii}}}this.log(`Video: Initial PTS/DTS adjusted: ${wo(Se,!0)}/${wo(m,!0)}, delta: ${wo(V,!0)} ms`)}}m=Math.max(0,m);let R=0,I=0,x=m;for(let V=0;V<l;V++){let G=a[V],ce=G.units,Se=ce.length,he=0;for(let Te=0;Te<Se;Te++)he+=ce[Te].data.length;I+=he,R+=Se,G.length=he,G.dts<x?(G.dts=x,x+=A/4|0||1):x=G.dts,g=Math.min(G.pts,g),v=Math.max(G.pts,v)}p=a[l-1].dts;let D=I+4*R+8,S;try{S=new Uint8Array(D)}catch(V){this.observer.emit(E.ERROR,E.ERROR,{type:se.MUX_ERROR,details:M.REMUX_ALLOC_ERROR,fatal:!1,error:V,bytes:D,reason:`fail allocating video mdat ${D}`});return}let C=new DataView(S.buffer);C.setUint32(0,D),S.set(_t.types.mdat,4);let P=!1,N=Number.POSITIVE_INFINITY,$=Number.POSITIVE_INFINITY,H=Number.NEGATIVE_INFINITY,U=Number.NEGATIVE_INFINITY;for(let V=0;V<l;V++){let G=a[V],ce=G.units,Se=0;for(let vt=0,ut=ce.length;vt<ut;vt++){let Ft=ce[vt],si=Ft.data,Ii=Ft.data.byteLength;C.setUint32(h,Ii),h+=4,S.set(si,h),h+=Ii,Se+=4+Ii}let he;if(V<l-1)f=a[V+1].dts-G.dts,he=a[V+1].pts-G.pts;else{let vt=this.config,ut=V>0?G.dts-a[V-1].dts:A;if(he=V>0?G.pts-a[V-1].pts:A,vt.stretchShortVideoTrack&&this.nextAudioTs!==null){let Ft=Math.floor(vt.maxBufferHole*n),si=(r?g+r*n:this.nextAudioTs+u)-G.pts;si>Ft?(f=si-ut,f<0?f=ut:P=!0,this.log(`It is approximately ${si/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=ut}else f=ut}let Te=Math.round(G.pts-G.dts);N=Math.min(N,f),H=Math.max(H,f),$=Math.min($,he),U=Math.max(U,he),o.push(xy(G.key,f,Se,Te))}if(o.length){if(Qn){if(Qn<70){let V=o[0].flags;V.dependsOn=2,V.isNonSync=0}}else if(ym&&U-$<H-N&&A/H<.025&&o[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let V=m;for(let G=0,ce=o.length;G<ce;G++){let Se=V+o[G].duration,he=V+o[G].cts;if(G<ce-1){let Te=Se+o[G+1].cts;o[G].duration=Te-he}else o[G].duration=G?o[G-1].duration:A;o[G].cts=0,V=Se}}}f=P||!f?A:f;let j=p+f;this.nextVideoTs=c=j-u,this.videoSampleDuration=f,this.isVideoContiguous=!0;let re={data1:_t.moof(e.sequenceNumber++,m,$e(e,{samples:o})),data2:S,startPTS:(g-u)/n,endPTS:(v+f-u)/n,startDTS:(m-u)/n,endDTS:c/n,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,re}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return Ok;case"ac3":return Nk;default:return Pk}}remuxAudio(e,t,s,r,n){let a=e.inputTimeScale,o=e.samplerate?e.samplerate:a,l=a/o,d=this.getSamplesPerFrame(e),u=d*l,c=this._initPTS,h=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],m=n!==void 0,p=e.samples,g=h?0:8,v=this.nextAudioTs||-1,T=c.baseTime*a/c.timescale,y=T+t*a;if(this.isAudioContiguous=s=s||p.length&&v>0&&(r&&Math.abs(y-(v+T))<9e3||Math.abs(ai(p[0].pts,y)-(v+T))<20*u),p.forEach(function(U){U.pts=ai(U.pts,y)}),!s||v<0){let U=p.length;if(p=p.filter(j=>j.pts>=0),U!==p.length&&this.warn(`Removed ${p.length-U} of ${U} samples (initPTS ${T} / ${a})`),!p.length)return;n===0?v=0:r&&!m?v=Math.max(0,y-T):v=p[0].pts-T}if(e.segmentCodec==="aac"){let U=this.config.maxAudioFramesDrift;for(let j=0,q=v+T;j<p.length;j++){let Z=p[j],re=Z.pts,V=re-q,G=Math.abs(1e3*V/a);if(V<=-U*u&&m)j===0&&(this.warn(`Audio frame @ ${(re/a).toFixed(3)}s overlaps marker by ${Math.round(1e3*V/a)} ms.`),this.nextAudioTs=v=re-T,q=re);else if(V>=U*u&&G<Mk&&m){let ce=Math.round(V/u);for(q=re-ce*u;q<0&&ce&&u;)ce--,q+=u;j===0&&(this.nextAudioTs=v=q-T),this.warn(`Injecting ${ce} audio frames @ ${((q-T)/a).toFixed(3)}s due to ${Math.round(1e3*V/a)} ms gap.`);for(let Se=0;Se<ce;Se++){let he=op.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);he||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),he=Z.unit.subarray()),p.splice(j,0,{unit:he,pts:q}),q+=u,j++}}Z.pts=q,q+=u}}let b=null,A=null,R,I=0,x=p.length;for(;x--;)I+=p[x].unit.byteLength;for(let U=0,j=p.length;U<j;U++){let q=p[U],Z=q.unit,re=q.pts;if(A!==null){let G=f[U-1];G.duration=Math.round((re-A)/l)}else if(s&&e.segmentCodec==="aac"&&(re=v+T),b=re,I>0){I+=g;try{R=new Uint8Array(I)}catch(G){this.observer.emit(E.ERROR,E.ERROR,{type:se.MUX_ERROR,details:M.REMUX_ALLOC_ERROR,fatal:!1,error:G,bytes:I,reason:`fail allocating audio mdat ${I}`});return}h||(new DataView(R.buffer).setUint32(0,I),R.set(_t.types.mdat,4))}else return;R.set(Z,g);let V=Z.byteLength;g+=V,f.push(xy(!0,d,V,0)),A=re}let D=f.length;if(!D)return;let S=f[f.length-1];v=A-T,this.nextAudioTs=v+l*S.duration;let C=h?new Uint8Array(0):_t.moof(e.sequenceNumber++,b/l,$e({},e,{samples:f}));e.samples=[];let P=(b-T)/a,N=this.nextAudioTs/a,H={data1:C,data2:R,startPTS:P,endPTS:N,startDTS:P,endDTS:N,type:"audio",hasAudio:!0,hasVideo:!1,nb:D};return this.isAudioContiguous=!0,H}};function ai(i,e){let t;if(e===null)return i;for(e<i?t=-8589934592:t=8589934592;Math.abs(i-e)>4294967296;)i+=t;return i}function Uk(i){for(let e=0;e<i.length;e++)if(i[e].key)return e;return-1}function qT(i,e,t,s){let r=i.samples.length;if(!r)return;let n=i.inputTimeScale;for(let o=0;o<r;o++){let l=i.samples[o];l.pts=ai(l.pts-t.baseTime*n/t.timescale,e*n)/n,l.dts=ai(l.dts-s.baseTime*n/s.timescale,e*n)/n}let a=i.samples;return i.samples=[],{samples:a}}function YT(i,e,t){let s=i.samples.length;if(!s)return;let r=i.inputTimeScale;for(let a=0;a<s;a++){let o=i.samples[a];o.pts=ai(o.pts-t.baseTime*r/t.timescale,e*r)/r}i.samples.sort((a,o)=>a.pts-o.pts);let n=i.samples;return i.samples=[],{samples:n}}var lp=class extends Qt{constructor(e,t,s,r){super("passthrough-remuxer",r),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,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;let t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,s,r){this.audioCodec=t,this.videoCodec=s,this.generateInitSegment(e,r),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:s,videoCodec:r}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}let{audio:n,video:a}=this.initData=sT(e);if(t)HR(e,t);else{let l=n||a;l!=null&&l.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${l.codec}")!`)}n&&(s=ky(n,We.AUDIO,this)),a&&(r=ky(a,We.VIDEO,this));let o={};n&&a?o.audiovideo={container:"video/mp4",codec:s+","+r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:n?o.audio={container:"audio/mp4",codec:s,encrypted:n.encrypted,initSegment:e,id:"audio"}:a?o.video={container:"video/mp4",codec:r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(e,t,s,r,n,a){var o,l;let{initPTS:d,lastEndTime:u}=this,c={audio:void 0,video:void 0,text:r,id3:s,initSegment:void 0};Q(u)||(u=this.lastEndTime=n||0);let h=t.samples;if(!h.length)return c;let f={initPTS:void 0,timescale:void 0,trackId:void 0},m=this.initData;if((o=m)!=null&&o.length||(this.generateInitSegment(h),m=this.initData),!((l=m)!=null&&l.length))return this.warn("Failed to generate initSegment."),c;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);let p=KR(h,m,this),g=m.audio?p[m.audio.id]:null,v=m.video?p[m.video.id]:null,T=jd(v,1/0),y=jd(g,1/0),b=jd(v,0,!0),A=jd(g,0,!0),R=n,I=0,x=g&&(!v||!d&&y<T||d&&d.trackId===m.audio.id),D=x?g:v;if(D){let q=D.timescale,Z=D.start-n*q,re=x?m.audio.id:m.video.id;R=D.start/q,I=x?A-y:b-T,(a||!d)&&(Fk(d,R,n,I)||q!==d.timescale)&&(d&&this.warn(`Timestamps at playlist time: ${a?"":"~"}${n} ${Z/q} != initPTS: ${d.baseTime/d.timescale} (${d.baseTime}/${d.timescale}) trackId: ${d.trackId}`),this.log(`Found initPTS at playlist time: ${n} offset: ${R-n} (${Z}/${q}) trackId: ${re}`),d=null,f.initPTS=Z,f.timescale=q,f.trackId=re)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${n}`);d?(f.initPTS=d.baseTime,f.timescale=d.timescale,f.trackId=d.trackId):((!f.timescale||f.trackId===void 0||f.initPTS===void 0)&&(this.warn("Could not set initPTS"),f.initPTS=R,f.timescale=1,f.trackId=-1),this.initPTS=d={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});let S=R-d.baseTime/d.timescale,C=S+I;I>0?this.lastEndTime=C:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());let P=!!m.audio,N=!!m.video,$="";P&&($+="audio"),N&&($+="video");let H=(m.audio?m.audio.encrypted:!1)||(m.video?m.video.encrypted:!1),U={data1:h,startPTS:S,startDTS:S,endPTS:C,endDTS:C,type:$,hasAudio:P,hasVideo:N,nb:1,dropped:0,encrypted:H};c.audio=P&&!N?U:void 0,c.video=N?U:void 0;let j=v==null?void 0:v.sampleCount;if(j){let q=v.keyFrameIndex,Z=q!==-1;U.nb=j,U.dropped=q===0||this.isVideoContiguous?0:Z?q:j,U.independent=Z,U.firstKeyFrame=q,Z&&v.keyFrameStart&&(U.firstKeyFramePTS=(v.keyFrameStart-d.baseTime)/d.timescale),this.isVideoContiguous||(c.independent=Z),this.isVideoContiguous||(this.isVideoContiguous=Z),U.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${q}/${j} dropped: ${U.dropped} start: ${U.firstKeyFramePTS||"NA"}`)}return c.initSegment=f,c.id3=qT(s,n,d,d),r.samples.length&&(c.text=YT(r,n,d)),c}};function jd(i,e,t=!1){return(i==null?void 0:i.start)!==void 0?(i.start+(t?i.duration:0))/i.timescale:e}function Fk(i,e,t,s){if(i===null)return!0;let r=Math.max(s,1),n=e-i.baseTime/i.timescale;return Math.abs(n-t)>r}function ky(i,e,t){let s=i.codec;return s&&s.length>4?s:e===We.AUDIO?s==="ec-3"||s==="ac-3"||s==="alac"?s:s==="fLaC"||s==="Opus"?cu(s,!1):(t.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"):(t.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1")}var ks;try{ks=self.performance.now.bind(self.performance)}catch{ks=Date.now}var nu=[{demux:ep,remux:lp},{demux:rp,remux:ia},{demux:Xm,remux:ia},{demux:Jm,remux:ia}];nu.splice(2,0,{demux:Zm,remux:ia});var Iu=class{constructor(e,t,s,r,n,a){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=s,this.id=n,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,r){let n=s.transmuxing;n.executeStart=ks();let a=new Uint8Array(e),{currentTransmuxState:o,transmuxConfig:l}=this;r&&(this.currentTransmuxState=r);let{contiguous:d,discontinuity:u,trackSwitch:c,accurateTimeOffset:h,timeOffset:f,initSegmentChange:m}=r||o,{audioCodec:p,videoCodec:g,defaultInitPts:v,duration:T,initSegmentData:y}=l,b=Bk(a,t);if(b&&ta(b.method)){let x=this.getDecrypter(),D=tg(b.method);if(x.isSync()){let S=x.softwareDecrypt(a,b.key.buffer,b.iv.buffer,D);if(s.part>-1){let P=x.flush();S=P&&P.buffer}if(!S)return n.executeEnd=ks(),Tm(s);a=new Uint8Array(S)}else return this.asyncResult=!0,this.decryptionPromise=x.webCryptoDecrypt(a,b.key.buffer,b.iv.buffer,D).then(S=>{let C=this.push(S,null,s);return this.decryptionPromise=null,C}),this.decryptionPromise}let A=this.needsProbing(u,c);if(A){let x=this.configureTransmuxer(a);if(x)return this.logger.warn(`[transmuxer] ${x.message}`),this.observer.emit(E.ERROR,E.ERROR,{type:se.MEDIA_ERROR,details:M.FRAG_PARSING_ERROR,fatal:!1,error:x,reason:x.message}),n.executeEnd=ks(),Tm(s)}(u||c||m||A)&&this.resetInitSegment(y,p,g,T,t),(u||m||A)&&this.resetInitialTimestamp(v),d||this.resetContiguity();let R=this.transmux(a,b,f,h,s);this.asyncResult=Yo(R);let I=this.currentTransmuxState;return I.contiguous=!0,I.discontinuity=!1,I.trackSwitch=!1,n.executeEnd=ks(),R}flush(e){let t=e.transmuxing;t.executeStart=ks();let{decrypter:s,currentTransmuxState:r,decryptionPromise:n}=this;if(n)return this.asyncResult=!0,n.then(()=>this.flush(e));let a=[],{timeOffset:o}=r;if(s){let c=s.flush();c&&a.push(this.push(c.buffer,null,e))}let{demuxer:l,remuxer:d}=this;if(!l||!d){t.executeEnd=ks();let c=[Tm(e)];return this.asyncResult?Promise.resolve(c):c}let u=l.flush(o);return Yo(u)?(this.asyncResult=!0,u.then(c=>(this.flushRemux(a,c,e),a))):(this.flushRemux(a,u,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,s){let{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=t,{accurateTimeOffset:l,timeOffset:d}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===J.MAIN?"level":"track"} ${s.level}`);let u=this.remuxer.remux(r,n,a,o,d,l,!0,this.id);e.push({remuxResult:u,chunkMeta:s}),s.transmuxing.executeEnd=ks()}resetInitialTimestamp(e){let{demuxer:t,remuxer:s}=this;!t||!s||(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){let{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,r,n){let{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(e,t,s,r),o.resetInitSegment(e,t,s,n))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,s,r,n){let a;return t&&t.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,s,r,n):a=this.transmuxUnencrypted(e,s,r,n),a}transmuxUnencrypted(e,t,s,r){let{audioTrack:n,videoTrack:a,id3Track:o,textTrack:l}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(n,a,o,l,t,s,!1,this.id),chunkMeta:r}}transmuxSampleAes(e,t,s,r,n){return this.demuxer.demuxSampleAes(e,t,s).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,s,r,!1,this.id),chunkMeta:n}))}configureTransmuxer(e){let{config:t,observer:s,typeSupported:r}=this,n;for(let c=0,h=nu.length;c<h;c++){var a;if((a=nu[c].demux)!=null&&a.probe(e,this.logger)){n=nu[c];break}}if(!n)return new Error("Failed to find demuxer by probing fragment data");let o=this.demuxer,l=this.remuxer,d=n.remux,u=n.demux;(!l||!(l instanceof d))&&(this.remuxer=new d(s,t,r,this.logger)),(!o||!(o instanceof u))&&(this.demuxer=new u(s,t,r,this.logger),this.probe=u.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Ho(this.config)),e}};function Bk(i,e){let t=null;return i.byteLength>0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(t=e),t}var Tm=i=>({remuxResult:{},chunkMeta:i});function Yo(i){return"then"in i&&i.then instanceof Function}var dp=class{constructor(e,t,s,r,n){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=s,this.duration=r,this.defaultInitPts=n||null}},up=class{constructor(e,t,s,r,n,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=s,this.trackSwitch=r,this.timeOffset=n,this.initSegmentChange=a}},Dy=0,Lu=class{constructor(e,t,s,r){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Dy++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=l=>{let d=l.data,u=this.hls;if(!(!u||!(d!=null&&d.event)||d.instanceNo!==this.instanceNo))switch(d.event){case"init":{var c;let h=(c=this.workerContext)==null?void 0:c.objectURL;h&&self.URL.revokeObjectURL(h);break}case"transmuxComplete":{this.handleTransmuxComplete(d.data);break}case"flush":{this.onFlush(d.data);break}case"workerLog":{u.logger[d.data.logType]&&u.logger[d.data.logType](d.data.message);break}default:{d.data=d.data||{},d.data.frag=this.frag,d.data.part=this.part,d.data.id=this.id,u.trigger(d.event,d.data);break}}},this.onWorkerError=l=>{if(!this.hls)return;let d=new Error(`${l.message} (${l.filename}:${l.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(E.ERROR,{type:se.OTHER_ERROR,details:M.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:d})};let n=e.config;this.hls=e,this.id=t,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=s,this.onFlush=r;let a=(l,d)=>{d=d||{},d.frag=this.frag||void 0,l===E.ERROR&&(d=d,d.parent=this.id,d.part=this.part,this.error=d.error),this.hls.trigger(l,d)};this.observer=new sg,this.observer.on(E.FRAG_DECRYPTED,a),this.observer.on(E.ERROR,a);let o=YE(n.preferManagedMediaSource);if(this.useWorker&&typeof Worker!="undefined"){let l=this.hls.logger;if(n.workerPath||ek()){try{n.workerPath?(l.log(`loading Web Worker ${n.workerPath} for "${t}"`),this.workerContext=ik(n.workerPath)):(l.log(`injecting Web Worker for "${t}"`),this.workerContext=tk());let{worker:u}=this.workerContext;u.addEventListener("message",this.onWorkerMessage),u.addEventListener("error",this.onWorkerError),u.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:qe(n)})}catch(u){l.warn(`Error setting up "${t}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new Iu(this.observer,o,n,"",t,e.logger)}return}}this.transmuxer=new Iu(this.observer,o,n,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){let e=this.instanceNo;this.instanceNo=Dy++;let t=this.hls.config,s=YE(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:qe(t)})}}terminateWorker(){if(this.workerContext){let{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),sk(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{let t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}let e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,s,r,n,a,o,l,d,u){var c,h;d.transmuxing.start=self.performance.now();let{instanceNo:f,transmuxer:m}=this,p=a?a.start:n.start,g=n.decryptdata,v=this.frag,T=!(v&&n.cc===v.cc),y=!(v&&d.level===v.level),b=v?d.sn-v.sn:-1,A=this.part?d.part-this.part.index:-1,R=b===0&&d.id>1&&d.id===(v==null?void 0:v.stats.chunkCount),I=!y&&(b===1||b===0&&(A===1||R&&A<=0)),x=self.performance.now();(y||b||n.stats.parsing.start===0)&&(n.stats.parsing.start=x),a&&(A||!I)&&(a.stats.parsing.start=x);let D=!(v&&((c=n.initSegment)==null?void 0:c.url)===((h=v.initSegment)==null?void 0:h.url)),S=new up(T,I,l,y,p,D);if(!I||T||D){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${n.type} sn: ${d.sn}${d.part>-1?" part: "+d.part:""} ${this.id===J.MAIN?"level":"track"}: ${d.level} id: ${d.id}
32
- discontinuity: ${T}
31
+ ${t.m3u8}`)}function Sb(i,e,t=!0){let s=e.startSN+e.skippedSegments-i.startSN,r=i.fragments,n=s>=0,a=0;if(n&&s<r.length)a=r[s].start;else if(n&&e.startSN===i.endSN+1)a=i.fragmentEnd;else if(n&&t)a=i.fragmentStart+s*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)a=i.fragmentStart;else return;Qm(e,a)}function Qm(i,e){if(e){let t=i.fragments;for(let s=i.skippedSegments;s<t.length;s++)t[s].addStart(e);i.fragmentHint&&i.fragmentHint.addStart(e)}}function Ib(i,e=1/0){let t=1e3*i.targetduration;if(i.updated){let s=i.fragments;if(s.length&&t*4>e){let n=s[s.length-1].duration*1e3;n<t&&(t=n)}}else t/=2;return Math.round(t)}function Lb(i,e,t){if(!i)return null;let s=i.fragments[e-i.startSN];return s||(s=i.fragmentHint,s&&s.sn===e)?s:e<i.startSN&&t&&t.sn===e?t:null}function Ty(i,e,t){return i?Rb(i.partList,e,t):null}function Rb(i,e,t){if(i)for(let s=i.length;s--;){let r=i[s];if(r.index===t&&r.fragment.sn===e)return r}return null}function xb(i){i.forEach((e,t)=>{var s;(s=e.details)==null||s.fragments.forEach(r=>{r.level=t,r.initSegment&&(r.initSegment.level=t)})})}function Yx(i,e){return i!==e&&e?_y(i)!==_y(e):!1}function _y(i){return i.replace(/\?[^?]*$/,"")}function Oo(i,e){for(let s=0,r=i.length;s<r;s++){var t;if(((t=i[s])==null?void 0:t.cc)===e)return i[s]}return null}function jx(i,e){return!!(i&&e.startCC<i.endCC&&e.endCC>i.startCC)}function Ay(i,e){let t=i.start+e;i.startPTS=t,i.setStart(t),i.endPTS=t+i.duration}function kb(i,e){let t=e.fragments;for(let s=0,r=t.length;s<r;s++)Ay(t[s],i);e.fragmentHint&&Ay(e.fragmentHint,i),e.alignedSliding=!0}function zx(i,e){i&&(Db(e,i),e.alignedSliding||Tu(e,i),!e.alignedSliding&&!e.skippedSegments&&Sb(i,e,!1))}function Db(i,e){if(!jx(e,i))return;let t=Math.min(e.endCC,i.endCC),s=Oo(e.fragments,t),r=Oo(i.fragments,t);if(!s||!r)return;Be.log(`Aligning playlist at start of dicontinuity sequence ${t}`);let n=s.start-r.start;kb(n,i)}function Tu(i,e){if(!i.hasProgramDateTime||!e.hasProgramDateTime)return;let t=i.fragments,s=e.fragments;if(!t.length||!s.length)return;let r,n,a=Math.min(e.endCC,i.endCC);e.startCC<a&&i.startCC<a&&(r=Oo(s,a),n=Oo(t,a)),(!r||!n)&&(r=s[Math.floor(s.length/2)],n=Oo(t,r.cc)||t[Math.floor(t.length/2)]);let o=r.programDateTime,l=n.programDateTime;if(!o||!l)return;let d=(l-o)/1e3-(n.start-r.start);kb(d,i)}function Ht(i,e,t){zt(i,e,t),i.addEventListener(e,t)}function zt(i,e,t){i.removeEventListener(e,t)}var Qx={toString:function(i){let e="",t=i.length;for(let s=0;s<t;s++)e+=`[${i.start(s).toFixed(3)}-${i.end(s).toFixed(3)}]`;return e}},O={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"},Ko=class extends vu{constructor(e,t,s,r,n){super(r,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=O.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.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.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{let{config:a,fragCurrent:o,media:l,mediaBuffer:d,state:u}=this,c=l?l.currentTime:0,h=Ee.bufferInfo(d||l,c,a.maxBufferHole),f=!h.len;if(this.log(`Media seeking to ${Q(c)?c.toFixed(3):c}, state: ${u}, ${f?"out of":"in"} buffer`),this.state===O.ENDED)this.resetLoadingState();else if(o){let m=a.maxFragLookUpTolerance,p=o.start-m,g=o.start+o.duration+m;if(f||g<h.start||p>h.end){let v=c>g;(c<p||v)&&(v&&o.loader&&(this.log(`Cancelling fragment load for seek (sn: ${o.sn})`),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(l){this.fragmentTracker.removeFragmentsInRange(c,1/0,this.playlistType,!0);let m=this.lastCurrentTime;if(c>m&&(this.lastCurrentTime=c),!this.loadingParts){let p=Math.max(h.end,c),g=this.shouldLoadParts(this.getLevelDetails(),p);g&&(this.log(`LL-Part loading ON after seeking to ${c.toFixed(2)} with buffer @${p.toFixed(2)}`),this.loadingParts=g)}}this.hls.hasEnoughToStart||(this.log(`Setting ${f?"startPosition":"nextLoadPosition"} to ${c} for seek without enough to start`),this.nextLoadPosition=c,f&&(this.startPosition=c)),f&&this.state===O.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=n,this.hls=e,this.fragmentLoader=new Wm(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Ho(e.config)}registerListeners(){let{hls:e}=this;e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===O.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);let e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=O.STOPPED}get startPositionValue(){let{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;let s=e.end||0,r=this.config.timelineOffset||0;if(s<=r)return!1;let n=e.buffered;this.config.maxBufferHole&&n&&n.length>1&&(e=Ee.bufferedInfo(n,e.start,0));let a=e.nextStart;if(a&&a>r&&a<t.edge||this.media.currentTime<e.start)return!1;let l=t.partList;if(l!=null&&l.length){let u=l[l.length-1];return Ee.isBuffered(this.media,u.start+u.duration/2)}let d=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(d)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){let e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){let s=this.media=this.mediaBuffer=t.media;Ht(s,"seeking",this.onMediaSeeking),Ht(s,"ended",this.onMediaEnded);let r=this.config;this.levels&&r.autoStartLoad&&this.state===O.STOPPED&&this.startLoad(r.startPosition)}onMediaDetaching(e,t){let s=!!t.transferMedia,r=this.media;if(r!==null){if(r.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),zt(r,"seeking",this.onMediaSeeking),zt(r,"ended",this.onMediaEnded),this.keyLoader&&!s&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,s){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=O.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,s){this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){let r=n=>{let a=n.frag;if(this.fragContextChanged(a)){this.warn(`${a.type} sn: ${a.sn}${n.part?" part: "+n.part.index:""} of ${this.fragInfo(a,!1,n.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(a);return}a.stats.chunkCount++,this._handleFragmentLoadProgress(n)};this._doFragLoad(e,t,s,r).then(n=>{if(!n)return;let a=this.state,o=n.frag;if(this.fragContextChanged(o)){(a===O.FRAG_LOADING||!this.fragCurrent&&a===O.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=O.IDLE);return}"payload"in n&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(E.FRAG_LOADED,n)),this._handleFragmentLoadComplete(n)}).catch(n=>{this.state===O.STOPPED||this.state===O.ERROR||(this.warn(`Frag error: ${(n==null?void 0:n.message)||n}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;let{fragmentTracker:s}=this;if(s.getState(e)===Tt.APPENDING){let n=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,n),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength),l=this.backtrackFragment;((l?e.sn-l.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&s.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===Tt.PARTIAL&&s.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)}waitForLive(e){let t=e.details;return(t==null?void 0:t.live)&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,s=null){if(!(e-t))return;let r={startOffset:e,endOffset:t,type:s};this.hls.trigger(E.BUFFER_FLUSHING,r)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(s=>{let r=s==null?void 0:s.frag;if(!r||this.fragContextChanged(r)||!this.levels)throw new Error("init load aborted");return s}).then(s=>{let{hls:r}=this,{frag:n,payload:a}=s,o=n.decryptdata;if(a&&a.byteLength>0&&o!=null&&o.key&&o.iv&&ta(o.method)){let l=self.performance.now();return this.decrypter.decrypt(new Uint8Array(a),o.key.buffer,o.iv.buffer,tg(o.method)).catch(d=>{throw r.trigger(E.ERROR,{type:se.MEDIA_ERROR,details:M.FRAG_DECRYPT_ERROR,fatal:!1,error:d,reason:d.message,frag:n}),d}).then(d=>{let u=self.performance.now();return r.trigger(E.FRAG_DECRYPTED,{frag:n,payload:d,stats:{tstart:l,tdecrypt:u}}),s.payload=d,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)}).catch(s=>{this.state===O.STOPPED||this.state===O.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){let{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");let s=e.frag.stats;this.state!==O.STOPPED&&(this.state=O.IDLE),e.frag.data=new Uint8Array(e.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var s,r;let n=e.tracks;if(n&&!t.encrypted&&((s=n.audio)!=null&&s.encrypted||(r=n.video)!=null&&r.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){let a=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${a?"attached mediaKeys: "+a.mediaKeys:"detached"})`);return this.warn(o.message),!a||a.mediaKeys?!1:(this.hls.trigger(E.ERROR,{type:se.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){let{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){let s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${s?Qx.toString(Ee.getBuffered(s)):"(detached)"})`),at(e)){var r;if(e.type!==J.SUBTITLE){let a=e.elementaryStreams;if(!Object.keys(a).some(o=>!!a[o])){this.state=O.IDLE;return}}let n=(r=this.levels)==null?void 0:r[e.level];n!=null&&n.fragmentError&&(this.log(`Resetting level fragment error count of ${n.fragmentError} on frag buffered`),n.fragmentError=0)}this.state=O.IDLE}_handleFragmentLoadComplete(e){let{transmuxer:t}=this;if(!t)return;let{frag:s,part:r,partsLoaded:n}=e,a=!n||n.length===0||n.some(l=>!l),o=new Go(s.level,s.sn,s.stats.chunkCount+1,0,r?r.index:-1,!a);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,s=null,r){var n;this.fragCurrent=e;let a=t.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;if(e.encrypted&&!((n=e.decryptdata)!=null&&n.key)){if(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=O.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(h=>{if(!this.fragContextChanged(h.frag))return this.hls.trigger(E.KEY_LOADED,h),this.state===O.KEY_LOADING&&(this.state=O.IDLE),h}),this.hls.trigger(E.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(o=this.keyLoader.loadClear(e,a.encryptedFragments,this.startFragRequested),o&&this.log("[eme] blocking frag load until media-keys acquired"));let l=this.fragPrevious;if(at(e)&&(!l||e.sn!==l.sn)){let h=this.shouldLoadParts(t.details,e.end);h!==this.loadingParts&&(this.log(`LL-Part loading ${h?"ON":"OFF"} loading sn ${l==null?void 0:l.sn}->${e.sn}`),this.loadingParts=h)}if(s=Math.max(e.start,s||0),this.loadingParts&&at(e)){let h=a.partList;if(h&&r){s>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);let f=this.getNextPart(h,e,s);if(f>-1){let m=h[f];e=this.fragCurrent=m.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${m.index} (${f}/${h.length-1}) of ${this.fragInfo(e,!1,m)}) cc: ${e.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=m.start+m.duration,this.state=O.FRAG_LOADING;let p;return o?p=o.then(g=>!g||this.fragContextChanged(g.frag)?null:this.doFragPartsLoad(e,m,t,r)).catch(g=>this.handleFragLoadError(g)):p=this.doFragPartsLoad(e,m,t,r).catch(g=>this.handleFragLoadError(g)),this.hls.trigger(E.FRAG_LOADING,{frag:e,part:m,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):p}else if(!e.url||this.loadedEndOfParts(h,s))return Promise.resolve(null)}}if(at(e)&&this.loadingParts){var d;this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(d=a.partList)==null?void 0:d.filter(h=>h.loaded).map(h=>`[${h.start}-${h.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+a.startSN+"-"+a.endSN+"]"}, target: ${parseFloat(s.toFixed(3))}`),Q(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=O.FRAG_LOADING;let u=this.config.progressive&&e.type!==J.SUBTITLE,c;return u&&o?c=o.then(h=>!h||this.fragContextChanged(h.frag)?null:this.fragmentLoader.load(e,r)).catch(h=>this.handleFragLoadError(h)):c=Promise.all([this.fragmentLoader.load(e,u?r:void 0),o]).then(([h])=>(!u&&r&&r(h),h)).catch(h=>this.handleFragLoadError(h)),this.hls.trigger(E.FRAG_LOADING,{frag:e,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):c}doFragPartsLoad(e,t,s,r){return new Promise((n,a)=>{var o;let l=[],d=(o=s.details)==null?void 0:o.partList,u=c=>{this.fragmentLoader.loadPart(e,c,r).then(h=>{l[c.index]=h;let f=h.part;this.hls.trigger(E.FRAG_LOADED,h);let m=Ty(s.details,e.sn,c.index+1)||Rb(d,e.sn,c.index+1);if(m)u(m);else return n({frag:e,part:f,partsLoaded:l})}).catch(a)};u(t)})}handleFragLoadError(e){if("data"in e){let t=e.data;t.frag&&t.details===M.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===se.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(E.ERROR,t)}else this.hls.trigger(E.ERROR,{type:se.OTHER_ERROR,details:M.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){let t=this.getCurrentContext(e);if(!t||this.state!==O.PARSING){!this.fragCurrent&&this.state!==O.STOPPED&&this.state!==O.ERROR&&(this.state=O.IDLE);return}let{frag:s,part:r,level:n}=t,a=self.performance.now();s.stats.parsing.end=a,r&&(r.stats.parsing.end=a);let o=this.getLevelDetails(),d=o&&s.sn>o.endSN||this.shouldLoadParts(o,s.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} after parsing segment ending @${s.end.toFixed(2)}`),this.loadingParts=d),this.updateLevelTiming(s,r,n,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var s;let n=e.partList[0];if(n.fragment.type===J.SUBTITLE)return!1;let a=n.end+(((s=e.fragmentHint)==null?void 0:s.duration)||0);if(t>=a){var r;if((this.hls.hasEnoughToStart?((r=this.media)==null?void 0:r.currentTime)||this.lastCurrentTime:this.getLoadPosition())>n.start-n.fragment.duration)return!0}}}return!1}getCurrentContext(e){let{levels:t,fragCurrent:s}=this,{level:r,sn:n,part:a}=e;if(!(t!=null&&t[r]))return this.warn(`Levels object was unset while buffering fragment ${n} of ${this.playlistLabel()} ${r}. The current chunk will not be buffered.`),null;let o=t[r],l=o.details,d=a>-1?Ty(l,n,a):null,u=d?d.fragment:Lb(l,n,s);return u?(s&&s!==u&&(u.stats=s.stats),{frag:u,part:d,level:o}):null}bufferFragmentData(e,t,s,r,n){if(this.state!==O.PARSING)return;let{data1:a,data2:o}=e,l=a;if(o&&(l=pi(a,o)),!l.length)return;let d=this.initPTS[t.cc],u=d?-d.baseTime/d.timescale:void 0,c={type:e.type,frag:t,part:s,chunkMeta:r,offset:u,parent:t.type,data:l};if(this.hls.trigger(E.BUFFER_APPENDING,c),e.dropped&&e.independent&&!s){if(n)return;this.flushBufferGap(t)}}flushBufferGap(e){let t=this.media;if(!t)return;if(!Ee.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}let s=t.currentTime,r=Ee.bufferInfo(t,s,0),n=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,n*.25),o=Math.max(Math.min(e.start-a,r.end-a),s+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var s;let r=this.getLoadPosition();if(!Q(r))return null;let a=this.lastCurrentTime>r||(s=this.media)!=null&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,r,t,a)}getFwdBufferInfoAtPos(e,t,s,r){let n=Ee.bufferInfo(e,t,r);if(n.len===0&&n.nextStart!==void 0){let a=this.fragmentTracker.getBufferedFrag(t,s);if(a&&(n.nextStart<=a.end||a.gap)){let o=Math.max(Math.min(n.nextStart,a.end)-t,r);return Ee.bufferInfo(e,t,o)}}return n}getMaxBufferLength(e){let{config:t}=this,s;return e?s=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):s=t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){let s=this.config,r=Math.max(Math.min(e-t,s.maxBufferLength),t),n=Math.max(e-t*3,s.maxMaxBufferLength/2,r);return n>=r?(s.maxMaxBufferLength=n,this.warn(`Reduce max buffer length to ${n}s`),!0):!1}getAppendedFrag(e,t=J.MAIN){let s=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return s&&"fragment"in s?s.fragment:s}getNextFragment(e,t){let s=t.fragments,r=s.length;if(!r)return null;let{config:n}=this,a=s[0].start,o=n.lowLatencyMode&&!!t.partList,l=null;if(t.live){let c=n.initialLiveManifestSize;if(r<c)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${c})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a){var d;o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),l=this.getInitialLiveFragment(t);let h=this.hls.startPosition,f=this.hls.liveSyncPosition,m=l?(h!==-1&&h>=a?h:f)||l.start:e;this.log(`Setting startPosition to ${m} to match start frag at live edge. mainStart: ${h} liveSyncPosition: ${f} frag.start: ${(d=l)==null?void 0:d.start}`),this.startPosition=this.nextLoadPosition=m}}else e<=a&&(l=s[0]);if(!l){let c=this.loadingParts?t.partEnd:t.fragmentEnd;l=this.getFragmentAtPosition(e,c,t)}let u=this.filterReplacedPrimary(l,t);if(!u&&l){let c=l.sn-t.startSN;u=this.filterReplacedPrimary(s[c+1]||null,t)}return this.mapToInitFragWhenRequired(u)}isLoopLoading(e,t){let s=this.fragmentTracker.getState(e);return(s===Tt.OK||s===Tt.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,s,r,n){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.gap&&s.nextStart)){let o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,r,0);if(o!==null&&s.len+o.len>=n){let l=a.sn;return this.loopSn!==l&&(this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${l}`),this.loopSn=l),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(Sy(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(Sy(this.config)&&e.type!==J.SUBTITLE){let s=this.hls.interstitialsManager,r=s==null?void 0:s.bufferingItem;if(r){let a=r.event;if(a){if(a.appendInPlace||Math.abs(e.start-r.start)>1||r.start===0)return null}else if(e.end<=r.start&&(t==null?void 0:t.live)===!1||e.start>r.end&&r.nextEvent&&(r.nextEvent.appendInPlace||e.start-r.end>1))return null}let n=s==null?void 0:s.playerQueue;if(n)for(let a=n.length;a--;){let o=n[a].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,s){let r=-1,n=!1,a=!0;for(let o=0,l=e.length;o<l;o++){let d=e[o];if(a=a&&!d.independent,r>-1&&s<d.start)break;let u=d.loaded;u?r=-1:(n||(d.independent||a)&&d.fragment===t)&&(d.fragment!==t&&this.warn(`Need buffer at ${s} but next unloaded part starts at ${d.start}`),r=o),n=u}return r}loadedEndOfParts(e,t){let s;for(let r=e.length;r--;){if(s=e[r],!s.loaded)return!1;if(t>s.start)return!0}return!1}getInitialLiveFragment(e){let t=e.fragments,s=this.fragPrevious,r=null;if(s){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),r=yx(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){let n=s.sn+1;if(n>=e.startSN&&n<=e.endSN){let a=t[n-e.startSN];s.cc===a.cc&&(r=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=mb(e,s.cc,s.end),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{let n=this.hls.liveSyncPosition;n!==null&&(r=this.getFragmentAtPosition(n,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r}getFragmentAtPosition(e,t,s){let{config:r}=this,{fragPrevious:n}=this,{fragments:a,endSN:o}=s,{fragmentHint:l}=s,{maxFragLookUpTolerance:d}=r,u=s.partList,c=!!(this.loadingParts&&u!=null&&u.length&&l);c&&!this.bitrateTest&&u[u.length-1].fragment.sn===l.sn&&(a=a.concat(l),o=l.sn);let h;if(e<t){var f;let p=e<this.lastCurrentTime||e>t-d||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:d;h=sn(n,a,e,p)}else h=a[a.length-1];if(h){let m=h.sn-s.startSN,p=this.fragmentTracker.getState(h);if((p===Tt.OK||p===Tt.PARTIAL&&h.gap)&&(n=h),n&&h.sn===n.sn&&(!c||u[0].fragment.sn>h.sn||!s.live)&&h.level===n.level){let v=a[m+1];h.sn<o&&this.fragmentTracker.getState(v)!==Tt.OK?h=v:h=null}}return h}alignPlaylists(e,t,s){let r=e.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;let n=e.fragmentStart,a=!t,o=e.alignedSliding&&Q(n);if(a||!o&&!n){zx(s,e);let l=e.fragmentStart;return this.log(`Live playlist sliding: ${l.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${r}`),l}return n}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let s=this.startPosition;s<t&&(s=-1);let r=this.timelineOffset;if(s===-1){let n=this.startTimeOffset!==null,a=n?this.startTimeOffset:e.startTimeOffset;a!==null&&Q(a)?(s=t+a,a<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${a} found in ${n?"multivariant":"media"} playlist`),this.startPosition=s):e.live?(s=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${s}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+r}this.nextLoadPosition=s+r}getLoadPosition(){var e;let{media:t}=this,s=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?s=t.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&at(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==O.FRAG_LOADING_WAITING_RETRY)&&(this.state=O.IDLE)}onFragmentOrKeyLoadError(e,t){var s;if(t.chunkMeta&&!t.frag){let v=this.getCurrentContext(t.chunkMeta);v&&(t.frag=v.frag)}let r=t.frag;if(!r||r.type!==e||!this.levels)return;if(this.fragContextChanged(r)){var n;this.warn(`Frag load error must match current frag to retry ${r.url} > ${(n=this.fragCurrent)==null?void 0:n.url}`);return}let a=t.details===M.FRAG_GAP;a&&this.fragmentTracker.fragBuffered(r,!0);let o=t.errorAction;if(!o){this.state=O.ERROR;return}let{action:l,flags:d,retryCount:u=0,retryConfig:c}=o,h=!!c,f=h&&l===Rt.RetryRequest,m=h&&!o.resolved&&d===ni.MoveAllAlternatesMatchingHost,p=(s=this.hls.latestLevelDetails)==null?void 0:s.live;if(!f&&m&&at(r)&&!r.endList&&p&&!gb(t))this.resetFragmentErrors(e),this.treatAsGap(r),o.resolved=!0;else if((f||m)&&u<c.maxNumRetry){var g;let v=Bm((g=t.response)==null?void 0:g.code),b=eg(c,u);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+b,this.state=O.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,v){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${r.sn} of ${e} ${r.level} errored with ${t.details}, retrying loading ${u+1}/${c.maxNumRetry} in ${b}ms`)}else if(c)if(this.resetFragmentErrors(e),u<c.maxNumRetry)!a&&l!==Rt.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${u})`);return}else l===Rt.SendAlternateToPenaltyBox?this.state=O.WAITING_LEVEL:this.state=O.ERROR;this.tickImmediate()}checkRetryDate(){let e=self.performance.now(),t=this.retryDate,s=t===1/0;(!t||e>=t||s&&!Bm(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=O.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===O.PARSING||this.state===O.PARSED){let t=e.frag,s=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,s),n=r&&r.len>.5;n&&this.reduceMaxBufferLength(r.len,(t==null?void 0:t.duration)||10);let a=!n;return a&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${s} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===J.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==O.STOPPED&&(this.state=O.IDLE)}afterBufferFlushed(e,t,s){if(!e)return;let r=Ee.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,s),this.state===O.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==O.STOPPED&&(this.state=O.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;let e=this.levelLastLoaded,t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,s,r){let n=s.details;if(!n){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((l,d)=>{let u=e.elementaryStreams[d];if(u){let c=u.endPTS-u.startPTS;if(c<=0)return this.warn(`Could not parse fragment ${e.sn} ${d} duration reliably (${c})`),l||!1;let h=r?0:Ab(n,e,u.startPTS,u.endPTS,u.startDTS,u.endDTS,this);return this.hls.trigger(E.LEVEL_PTS_UPDATED,{details:n,level:s,drift:h,type:d,frag:e,start:u.startPTS,end:u.endPTS}),!0}return l},!1)){var o;let l=((o=this.transmuxer)==null?void 0:o.error)===null;if((s.fragmentError===0||l&&(s.fragmentError<2||e.endList))&&this.treatAsGap(e,s),l){let d=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(d.message),this.hls.trigger(E.ERROR,{type:se.MEDIA_ERROR,details:M.FRAG_PARSING_ERROR,fatal:!1,error:d,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=O.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(E.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===J.MAIN?"level":"track"}fragInfo(e,t=!0,s){var r,n;return`${this.playlistLabel()} ${e.level} (${s?"part":"frag"}:[${((r=t&&!s?e.startPTS:(s||e).start)!=null?r:NaN).toFixed(3)}-${((n=t&&!s?e.endPTS:(s||e).end)!=null?n:NaN).toFixed(3)}]${s&&e.type==="main"?"INDEPENDENT="+(s.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){let t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}};function Sy(i){return!!i.interstitialsController&&i.enableInterstitialPlayback!==!1}var _u=class{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){let{chunks:e,dataLength:t}=this,s;if(e.length)e.length===1?s=e[0]:s=Xx(e,t);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}};function Xx(i,e){let t=new Uint8Array(e),s=0;for(let r=0;r<i.length;r++){let n=i[r];t.set(n,s),s+=n.length}return t}var gm={exports:{}},Iy;function Zx(){return Iy||(Iy=1,function(i){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function r(l,d,u){this.fn=l,this.context=d,this.once=u||!1}function n(l,d,u,c,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var f=new r(u,c||l,h),m=t?t+d:d;return l._events[m]?l._events[m].fn?l._events[m]=[l._events[m],f]:l._events[m].push(f):(l._events[m]=f,l._eventsCount++),l}function a(l,d){--l._eventsCount===0?l._events=new s:delete l._events[d]}function o(){this._events=new s,this._eventsCount=0}o.prototype.eventNames=function(){var d=[],u,c;if(this._eventsCount===0)return d;for(c in u=this._events)e.call(u,c)&&d.push(t?c.slice(1):c);return Object.getOwnPropertySymbols?d.concat(Object.getOwnPropertySymbols(u)):d},o.prototype.listeners=function(d){var u=t?t+d:d,c=this._events[u];if(!c)return[];if(c.fn)return[c.fn];for(var h=0,f=c.length,m=new Array(f);h<f;h++)m[h]=c[h].fn;return m},o.prototype.listenerCount=function(d){var u=t?t+d:d,c=this._events[u];return c?c.fn?1:c.length:0},o.prototype.emit=function(d,u,c,h,f,m){var p=t?t+d:d;if(!this._events[p])return!1;var g=this._events[p],v=arguments.length,b,y;if(g.fn){switch(g.once&&this.removeListener(d,g.fn,void 0,!0),v){case 1:return g.fn.call(g.context),!0;case 2:return g.fn.call(g.context,u),!0;case 3:return g.fn.call(g.context,u,c),!0;case 4:return g.fn.call(g.context,u,c,h),!0;case 5:return g.fn.call(g.context,u,c,h,f),!0;case 6:return g.fn.call(g.context,u,c,h,f,m),!0}for(y=1,b=new Array(v-1);y<v;y++)b[y-1]=arguments[y];g.fn.apply(g.context,b)}else{var T=g.length,A;for(y=0;y<T;y++)switch(g[y].once&&this.removeListener(d,g[y].fn,void 0,!0),v){case 1:g[y].fn.call(g[y].context);break;case 2:g[y].fn.call(g[y].context,u);break;case 3:g[y].fn.call(g[y].context,u,c);break;case 4:g[y].fn.call(g[y].context,u,c,h);break;default:if(!b)for(A=1,b=new Array(v-1);A<v;A++)b[A-1]=arguments[A];g[y].fn.apply(g[y].context,b)}}return!0},o.prototype.on=function(d,u,c){return n(this,d,u,c,!1)},o.prototype.once=function(d,u,c){return n(this,d,u,c,!0)},o.prototype.removeListener=function(d,u,c,h){var f=t?t+d:d;if(!this._events[f])return this;if(!u)return a(this,f),this;var m=this._events[f];if(m.fn)m.fn===u&&(!h||m.once)&&(!c||m.context===c)&&a(this,f);else{for(var p=0,g=[],v=m.length;p<v;p++)(m[p].fn!==u||h&&!m[p].once||c&&m[p].context!==c)&&g.push(m[p]);g.length?this._events[f]=g.length===1?g[0]:g:a(this,f)}return this},o.prototype.removeAllListeners=function(d){var u;return d?(u=t?t+d:d,this._events[u]&&a(this,u)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,i.exports=o}(gm)),gm.exports}var Jx=Zx(),sg=MR(Jx),Vo="1.6.15",aa={};function ek(){return typeof __HLS_WORKER_BUNDLE__=="function"}function tk(){let i=aa[Vo];if(i)return i.clientCount++,i;let e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e),r={worker:new self.Worker(t),objectURL:t,clientCount:1};return aa[Vo]=r,r}function ik(i){let e=aa[i];if(e)return e.clientCount++,e;let t=new self.URL(i,self.location.href).href,r={worker:new self.Worker(t),scriptURL:t,clientCount:1};return aa[i]=r,r}function sk(i){let e=aa[i||Vo];if(e&&e.clientCount--===1){let{worker:s,objectURL:r}=e;delete aa[i||Vo],r&&self.URL.revokeObjectURL(r),s.terminate()}}function Cb(i,e){return e+10<=i.length&&i[e]===51&&i[e+1]===68&&i[e+2]===73&&i[e+3]<255&&i[e+4]<255&&i[e+6]<128&&i[e+7]<128&&i[e+8]<128&&i[e+9]<128}function rg(i,e){return e+10<=i.length&&i[e]===73&&i[e+1]===68&&i[e+2]===51&&i[e+3]<255&&i[e+4]<255&&i[e+6]<128&&i[e+7]<128&&i[e+8]<128&&i[e+9]<128}function Nu(i,e){let t=0;return t=(i[e]&127)<<21,t|=(i[e+1]&127)<<14,t|=(i[e+2]&127)<<7,t|=i[e+3]&127,t}function Wo(i,e){let t=e,s=0;for(;rg(i,e);){s+=10;let r=Nu(i,e+6);s+=r,Cb(i,e+10)&&(s+=10),e+=s}if(s>0)return i.subarray(t,t+s)}function rk(i,e,t,s){let r=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],n=e[t+2],a=n>>2&15;if(a>12){let f=new Error(`invalid ADTS sampling index:${a}`);i.emit(E.ERROR,E.ERROR,{type:se.MEDIA_ERROR,details:M.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.message});return}let o=(n>>6&3)+1,l=e[t+3]>>6&3|(n&1)<<2,d="mp4a.40."+o,u=r[a],c=a;(o===5||o===29)&&(c-=3);let h=[o<<3|(c&14)>>1,(c&1)<<7|l<<3];return Be.log(`manifest codec:${s}, parsed codec:${d}, channels:${l}, rate:${u} (ADTS object type:${o} sampling index:${a})`),{config:h,samplerate:u,channelCount:l,codec:d,parsedCodec:d,manifestCodec:s}}function wb(i,e){return i[e]===255&&(i[e+1]&246)===240}function Mb(i,e){return i[e+1]&1?7:9}function ng(i,e){return(i[e+3]&3)<<11|i[e+4]<<3|(i[e+5]&224)>>>5}function nk(i,e){return e+5<i.length}function Au(i,e){return e+1<i.length&&wb(i,e)}function ak(i,e){return nk(i,e)&&wb(i,e)&&ng(i,e)<=i.length-e}function ok(i,e){if(Au(i,e)){let t=Mb(i,e);if(e+t>=i.length)return!1;let s=ng(i,e);if(s<=t)return!1;let r=e+s;return r===i.length||Au(i,r)}return!1}function Pb(i,e,t,s,r){if(!i.samplerate){let n=rk(e,t,s,r);if(!n)return;$e(i,n)}}function Ob(i){return 1024*9e4/i}function lk(i,e){let t=Mb(i,e);if(e+t<=i.length){let s=ng(i,e)-t;if(s>0)return{headerLength:t,frameLength:s}}}function Nb(i,e,t,s,r){let n=Ob(i.samplerate),a=s+r*n,o=lk(e,t),l;if(o){let{frameLength:c,headerLength:h}=o,f=h+c,m=Math.max(0,t+f-e.length);m?(l=new Uint8Array(f-h),l.set(e.subarray(t+h,e.length),0)):l=e.subarray(t+h,t+f);let p={unit:l,pts:a};return m||i.samples.push(p),{sample:p,length:f,missing:m}}let d=e.length-t;return l=new Uint8Array(d),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:a},length:d,missing:-1}}function dk(i,e){return rg(i,e)&&Nu(i,e+6)+10<=i.length-e}function uk(i){return i instanceof ArrayBuffer?i:i.byteOffset==0&&i.byteLength==i.buffer.byteLength?i.buffer:new Uint8Array(i).buffer}function vm(i,e=0,t=1/0){return ck(i,e,t,Uint8Array)}function ck(i,e,t,s){let r=hk(i),n=1;"BYTES_PER_ELEMENT"in s&&(n=s.BYTES_PER_ELEMENT);let a=fk(i)?i.byteOffset:0,o=(a+i.byteLength)/n,l=(a+e)/n,d=Math.floor(Math.max(0,Math.min(l,o))),u=Math.floor(Math.min(d+Math.max(t,0),o));return new s(r,d,u-d)}function hk(i){return i instanceof ArrayBuffer?i:i.buffer}function fk(i){return i&&i.buffer instanceof ArrayBuffer&&i.byteLength!==void 0&&i.byteOffset!==void 0}function mk(i){let e={key:i.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(i.size<2)return;if(i.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}let s=i.data.subarray(1).indexOf(0);if(s===-1)return;let r=li(vm(i.data,1,s)),n=i.data[2+s],a=i.data.subarray(3+s).indexOf(0);if(a===-1)return;let o=li(vm(i.data,3+s,a)),l;return r==="-->"?l=li(vm(i.data,4+s+a)):l=uk(i.data.subarray(4+s+a)),e.mimeType=r,e.pictureType=n,e.description=o,e.data=l,e}function pk(i){if(i.size<2)return;let e=li(i.data,!0),t=new Uint8Array(i.data.subarray(e.length+1));return{key:i.type,info:e,data:t.buffer}}function gk(i){if(i.size<2)return;if(i.type==="TXXX"){let t=1,s=li(i.data.subarray(t),!0);t+=s.length+1;let r=li(i.data.subarray(t));return{key:i.type,info:s,data:r}}let e=li(i.data.subarray(1));return{key:i.type,info:"",data:e}}function vk(i){if(i.type==="WXXX"){if(i.size<2)return;let t=1,s=li(i.data.subarray(t),!0);t+=s.length+1;let r=li(i.data.subarray(t));return{key:i.type,info:s,data:r}}let e=li(i.data);return{key:i.type,info:"",data:e}}function Ek(i){return i.type==="PRIV"?pk(i):i.type[0]==="W"?vk(i):i.type==="APIC"?mk(i):gk(i)}function yk(i){let e=String.fromCharCode(i[0],i[1],i[2],i[3]),t=Nu(i,4),s=10;return{type:e,size:t,data:i.subarray(s,s+t)}}var qd=10,bk=10;function Ub(i){let e=0,t=[];for(;rg(i,e);){let s=Nu(i,e+6);i[e+5]>>6&1&&(e+=qd),e+=qd;let r=e+s;for(;e+bk<r;){let n=yk(i.subarray(e)),a=Ek(n);a&&t.push(a),e+=n.size+qd}Cb(i,e)&&(e+=qd)}return t}function Fb(i){return i&&i.key==="PRIV"&&i.info==="com.apple.streaming.transportStreamTimestamp"}function Tk(i){if(i.data.byteLength===8){let e=new Uint8Array(i.data),t=e[3]&1,s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,t&&(s+=4772185884e-2),Math.round(s)}}function ag(i){let e=Ub(i);for(let t=0;t<e.length;t++){let s=e[t];if(Fb(s))return Tk(s)}}var oi=function(i){return i.audioId3="org.id3",i.dateRange="com.apple.quicktime.HLS",i.emsg="https://aomedia.org/emsg/ID3",i.misbklv="urn:misb:KLV:bin:1910.1",i}({});function Zi(i="",e=9e4){return{type:i,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}var qo=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,s,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,s){}demux(e,t){this.cachedData&&(e=pi(this.cachedData,e),this.cachedData=null);let s=Wo(e,0),r=s?s.length:0,n,a=this._audioTrack,o=this._id3Track,l=s?ag(s):void 0,d=e.length;for((this.basePTS===null||this.frameIndex===0&&Q(l))&&(this.basePTS=_k(l,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),s&&s.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:oi.audioId3,duration:Number.POSITIVE_INFINITY});r<d;){if(this.canParse(e,r)){let u=this.appendFrame(a,e,r);u?(this.frameIndex++,this.lastPTS=u.sample.pts,r+=u.length,n=r):r=d}else dk(e,r)?(s=Wo(e,r),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:oi.audioId3,duration:Number.POSITIVE_INFINITY}),r+=s.length,n=r):r++;if(r===d&&n!==d){let u=e.slice(n);this.cachedData?this.cachedData=pi(this.cachedData,u):this.cachedData=u}}return{audioTrack:a,videoTrack:Zi(),id3Track:o,textTrack:Zi()}}demuxSampleAes(e,t,s){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:Zi(),id3Track:this._id3Track,textTrack:Zi()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}},_k=(i,e,t)=>{if(Q(i))return i*90;let s=t?t.baseTime*9e4/t.timescale:0;return e*9e4+s},Yd=null,Ak=[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],Sk=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Ik=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Lk=[0,1,1,4];function Bb(i,e,t,s,r){if(t+24>e.length)return;let n=$b(e,t);if(n&&t+n.frameLength<=e.length){let a=n.samplesPerFrame*9e4/n.sampleRate,o=s+r*a,l={unit:e.subarray(t,t+n.frameLength),pts:o,dts:o};return i.config=[],i.channelCount=n.channelCount,i.samplerate=n.sampleRate,i.samples.push(l),{sample:l,length:n.frameLength,missing:0}}}function $b(i,e){let t=i[e+1]>>3&3,s=i[e+1]>>1&3,r=i[e+2]>>4&15,n=i[e+2]>>2&3;if(t!==1&&r!==0&&r!==15&&n!==3){let a=i[e+2]>>1&1,o=i[e+3]>>6,l=t===3?3-s:s===3?3:4,d=Ak[l*14+r-1]*1e3,c=Sk[(t===3?0:t===2?1:2)*3+n],h=o===3?1:2,f=Ik[t][s],m=Lk[s],p=f*8*m,g=Math.floor(f*d/c+a)*m;if(Yd===null){let y=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Yd=y?parseInt(y[1]):0}return!!Yd&&Yd<=87&&s===2&&d>=224e3&&o===0&&(i[e+3]=i[e+3]|128),{sampleRate:c,channelCount:h,frameLength:g,samplesPerFrame:p}}}function og(i,e){return i[e]===255&&(i[e+1]&224)===224&&(i[e+1]&6)!==0}function Hb(i,e){return e+1<i.length&&og(i,e)}function Rk(i,e){return og(i,e)&&4<=i.length-e}function Gb(i,e){if(e+1<i.length&&og(i,e)){let s=$b(i,e),r=4;s!=null&&s.frameLength&&(r=s.frameLength);let n=e+r;return n===i.length||Hb(i,n)}return!1}var Xm=class extends qo{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,s,r){super.resetInitSegment(e,t,s,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;let s=Wo(e,0),r=(s==null?void 0:s.length)||0;if(Gb(e,r))return!1;for(let n=e.length;r<n;r++)if(ok(e,r))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return ak(e,t)}appendFrame(e,t,s){Pb(e,this.observer,t,s,e.manifestCodec);let r=Nb(e,t,s,this.basePTS,this.frameIndex);if(r&&r.missing===0)return r}},Kb=(i,e)=>{let t=0,s=5;e+=s;let r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;s>0;){a[0]=i[e];let o=Math.min(s,8),l=8-o;n[0]=4278190080>>>24+l<<l,r[0]=(a[0]&n[0])>>l,t=t?t<<o|r[0]:r[0],e+=1,s-=o}return t},Zm=class extends qo{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,r){super.resetInitSegment(e,t,s,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,s){let r=Vb(e,t,s,this.basePTS,this.frameIndex);if(r!==-1)return{sample:e.samples[e.samples.length-1],length:r,missing:0}}static probe(e){if(!e)return!1;let t=Wo(e,0);if(!t)return!1;let s=t.length;return e[s]===11&&e[s+1]===119&&ag(t)!==void 0&&Kb(e,s)<16}};function Vb(i,e,t,s,r){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;let n=e[t+4]>>6;if(n>=3)return-1;let o=[48e3,44100,32e3][n],l=e[t+4]&63,u=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][l*3+n]*2;if(t+u>e.length)return-1;let c=e[t+6]>>5,h=0;c===2?h+=2:(c&1&&c!==1&&(h+=2),c&4&&(h+=2));let f=(e[t+6]<<8|e[t+7])>>12-h&1,p=[2,1,2,3,3,4,4,5][c]+f,g=e[t+5]>>3,v=e[t+5]&7,b=new Uint8Array([n<<6|g<<1|v>>2,(v&3)<<6|c<<3|f<<2|l>>4,l<<4&224]),y=1536/o*9e4,T=s+r*y,A=e.subarray(t,t+u);return i.config=b,i.channelCount=p,i.samplerate=o,i.samples.push({unit:A,pts:T}),u}var Jm=class extends qo{resetInitSegment(e,t,s,r){super.resetInitSegment(e,t,s,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=Wo(e,0),s=(t==null?void 0:t.length)||0;if(t&&e[s]===11&&e[s+1]===119&&ag(t)!==void 0&&Kb(e,s)<=16)return!1;for(let r=e.length;s<r;s++)if(Gb(e,s))return Be.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return Rk(e,t)}appendFrame(e,t,s){if(this.basePTS!==null)return Bb(e,t,s,this.basePTS,this.frameIndex)}},xk=/\/emsg[-/]ID3/i,ep=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,s,r){let n=this.videoTrack=Zi("video",1),a=this.audioTrack=Zi("audio",1),o=this.txtTrack=Zi("text",1);if(this.id3Track=Zi("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;let l=sb(e);if(l.video){let{id:d,timescale:u,codec:c,supplemental:h}=l.video;n.id=d,n.timescale=o.timescale=u,n.codec=c,n.supplemental=h}if(l.audio){let{id:d,timescale:u,codec:c}=l.audio;a.id=d,a.timescale=u,a.codec=c}o.id=eb.text,n.sampleDuration=0,n.duration=a.duration=r}resetContiguity(){this.remainderData=null}static probe(e){return UR(e)}demux(e,t){this.timeOffset=t;let s=e,r=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=pi(this.remainderData,e));let o=VR(s);this.remainderData=o.remainder,r.samples=o.valid||new Uint8Array}else r.samples=s;let a=this.extractID3Track(r,t);return n.samples=VE(t,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){let e=this.timeOffset,t=this.videoTrack,s=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;let r=this.extractID3Track(t,this.timeOffset);return s.samples=VE(e,t),{videoTrack:t,audioTrack:Zi(),id3Track:r,textTrack:Zi()}}extractID3Track(e,t){let s=this.id3Track;if(e.samples.length){let r=Te(e.samples,["emsg"]);r&&r.forEach(n=>{let a=qR(n);if(xk.test(a.schemeIdUri)){let o=Ly(a,t),l=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);let d=a.payload;s.samples.push({data:d,len:d.byteLength,dts:o,pts:o,type:oi.emsg,duration:l})}else if(this.config.enableEmsgKLVMetadata&&a.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){let o=Ly(a,t);s.samples.push({data:a.payload,len:a.payload.byteLength,dts:o,pts:o,type:oi.misbklv,duration:Number.POSITIVE_INFINITY})}})}return s}demuxSampleAes(e,t,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}};function Ly(i,e){return Q(i.presentationTime)?i.presentationTime/i.timeScale:e+i.presentationTimeDelta/i.timeScale}var tp=class{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Ho(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,ar.cbc)}decryptAacSample(e,t,s){let r=e[t].unit;if(r.length<=16)return;let n=r.subarray(16,r.length-r.length%16),a=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(a).then(o=>{let l=new Uint8Array(o);r.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)}).catch(s)}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length){s();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){let t=Math.floor((e.length-48)/160)*16+16,s=new Int8Array(t),r=0;for(let n=32;n<e.length-16;n+=160,r+=16)s.set(e.subarray(n,n+16),r);return s}getAvcDecryptedUnit(e,t){let s=new Uint8Array(t),r=0;for(let n=32;n<e.length-16;n+=160,r+=16)e.set(s.subarray(r,r+16),n);return e}decryptAvcSample(e,t,s,r,n){let a=ab(n.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(l=>{n.data=this.getAvcDecryptedUnit(a,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,r)}).catch(r)}decryptAvcSamples(e,t,s,r){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length){r();return}let n=e[t].units;for(;!(s>=n.length);s++){let a=n[s];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,s,r,a),!this.decrypter.isSync()))return}}}},Su=class{constructor(){this.VideoSample=null}createVideoSample(e,t,s){return{key:e,frame:!1,pts:t,dts:s,units:[],length:0}}getLastNalUnit(e){var t;let s=this.VideoSample,r;if((!s||s.units.length===0)&&(s=e[e.length-1]),(t=s)!=null&&t.units){let n=s.units;r=n[n.length-1]}return r}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){let s=t.samples,r=s.length;if(r){let n=s[r-1];e.pts=n.pts,e.dts=n.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,s){let r=t.byteLength,n=e.naluState||0,a=n,o=[],l=0,d,u,c,h=-1,f=0;for(n===-1&&(h=0,f=this.getNALuType(t,0),n=0,l=1);l<r;){if(d=t[l++],!n){n=d?0:1;continue}if(n===1){n=d?0:2;continue}if(!d)n=3;else if(d===1){if(u=l-n-1,h>=0){let m={data:t.subarray(h,u),type:f};o.push(m)}else{let m=this.getLastNalUnit(e.samples);m&&(a&&l<=4-a&&m.state&&(m.data=m.data.subarray(0,m.data.byteLength-a)),u>0&&(m.data=pi(m.data,t.subarray(0,u)),m.state=0))}l<r?(c=this.getNALuType(t,l),h=l,f=c,n=0):n=-1}else n=0}if(h>=0&&n>=0){let m={data:t.subarray(h,r),type:f,state:n};o.push(m)}if(o.length===0){let m=this.getLastNalUnit(e.samples);m&&(m.data=pi(m.data,t))}return e.naluState=n,o}},en=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,s=e.byteLength-t,r=new Uint8Array(4),n=Math.min(4,t);if(n===0)throw new Error("no bytes available");r.set(e.subarray(s,s+n)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=n*8,this.bytesAvailable-=n}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e),s=this.word>>>32-t;if(e>32&&Be.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?s<<t|this.readBits(t):s}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if((this.word&2147483648>>>e)!==0)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){let e=this.skipLZ();return this.readBits(e+1)-1}readEG(){let e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}},ip=class extends Su{parsePES(e,t,s,r){let n=this.parseNALu(e,s.data,r),a=this.VideoSample,o,l=!1;s.data=null,a&&n.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),n.forEach(d=>{var u,c;switch(d.type){case 1:{let p=!1;o=!0;let g=d.data;if(l&&g.length>4){let v=this.readSliceType(g);(v===2||v===4||v===7||v===9)&&(p=!0)}if(p){var h;(h=a)!=null&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.frame=!0,a.key=p;break}case 5:o=!0,(u=a)!=null&&u.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 6:{o=!0,Xp(d.data,1,s.pts,t.samples);break}case 7:{var f,m;o=!0,l=!0;let p=d.data,g=this.readSPS(p);if(!e.sps||e.width!==g.width||e.height!==g.height||((f=e.pixelRatio)==null?void 0:f[0])!==g.pixelRatio[0]||((m=e.pixelRatio)==null?void 0:m[1])!==g.pixelRatio[1]){e.width=g.width,e.height=g.height,e.pixelRatio=g.pixelRatio,e.sps=[p];let v=p.subarray(1,4),b="avc1.";for(let y=0;y<3;y++){let T=v[y].toString(16);T.length<2&&(T="0"+T),b+=T}e.codec=b}break}case 8:o=!0,e.pps=[d.data];break;case 9:o=!0,e.audFound=!0,(c=a)!=null&&c.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:o=!0;break;default:o=!1;break}a&&o&&a.units.push(d)}),r&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){let t=new en(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s=8,r=8,n;for(let a=0;a<e;a++)r!==0&&(n=t.readEG(),r=(s+n+256)%256),s=r===0?s:r}readSPS(e){let t=new en(e),s=0,r=0,n=0,a=0,o,l,d,u=t.readUByte.bind(t),c=t.readBits.bind(t),h=t.readUEG.bind(t),f=t.readBoolean.bind(t),m=t.skipBits.bind(t),p=t.skipEG.bind(t),g=t.skipUEG.bind(t),v=this.skipScalingList.bind(this);u();let b=u();if(c(5),m(3),u(),g(),b===100||b===110||b===122||b===244||b===44||b===83||b===86||b===118||b===128){let x=h();if(x===3&&m(1),g(),g(),m(1),f())for(l=x!==3?8:12,d=0;d<l;d++)f()&&(d<6?v(16,t):v(64,t))}g();let y=h();if(y===0)h();else if(y===1)for(m(1),p(),p(),o=h(),d=0;d<o;d++)p();g(),m(1);let T=h(),A=h(),R=c(1);R===0&&m(1),m(1),f()&&(s=h(),r=h(),n=h(),a=h());let I=[1,1];if(f()&&f())switch(u()){case 1:I=[1,1];break;case 2:I=[12,11];break;case 3:I=[10,11];break;case 4:I=[16,11];break;case 5:I=[40,33];break;case 6:I=[24,11];break;case 7:I=[20,11];break;case 8:I=[32,11];break;case 9:I=[80,33];break;case 10:I=[18,11];break;case 11:I=[15,11];break;case 12:I=[64,33];break;case 13:I=[160,99];break;case 14:I=[4,3];break;case 15:I=[3,2];break;case 16:I=[2,1];break;case 255:{I=[u()<<8|u(),u()<<8|u()];break}}return{width:Math.ceil((T+1)*16-s*2-r*2),height:(2-R)*(A+1)*16-(R?2:4)*(n+a),pixelRatio:I}}},sp=class extends Su{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,s,r){let n=this.parseNALu(e,s.data,r),a=this.VideoSample,o,l=!1;s.data=null,a&&n.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),n.forEach(d=>{var u,c;switch(d.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),a.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:if(o=!0,l){var h;(h=a)!=null&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:o=!0,(u=a)!=null&&u.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 39:o=!0,Xp(d.data,2,s.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=$e(e.params,this.readVPS(d.data)),this.initVPS=d.data),e.vps=[d.data];break;case 33:if(o=!0,l=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],d.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){let f=this.readSPS(d.data);e.width=f.width,e.height=f.height,e.pixelRatio=f.pixelRatio,e.codec=f.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(let m in f.params)e.params[m]=f.params[m]}this.pushParameterSet(e.sps,d.data,e.vps),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0;break;case 34:if(o=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];let f=this.readPPS(d.data);for(let m in f)e.params[m]=f[m]}this.pushParameterSet(e.pps,d.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(c=a)!=null&&c.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;default:o=!1;break}a&&o&&a.units.push(d)}),r&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,s){(s&&s[0]===this.initVPS||!s&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){let t=new Uint8Array(e.byteLength),s=0;for(let r=0;r<e.byteLength;r++)r>=2&&e[r]===3&&e[r-1]===0&&e[r-2]===0||(t[s]=e[r],s++);return new Uint8Array(t.buffer,0,s)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){let t=new en(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);let s=t.readBits(3),r=t.readBoolean();return{numTemporalLayers:s+1,temporalIdNested:r}}readSPS(e){let t=new en(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);let s=t.readBits(3);t.readBoolean();let r=t.readBits(2),n=t.readBoolean(),a=t.readBits(5),o=t.readUByte(),l=t.readUByte(),d=t.readUByte(),u=t.readUByte(),c=t.readUByte(),h=t.readUByte(),f=t.readUByte(),m=t.readUByte(),p=t.readUByte(),g=t.readUByte(),v=t.readUByte(),b=[],y=[];for(let ke=0;ke<s;ke++)b.push(t.readBoolean()),y.push(t.readBoolean());if(s>0)for(let ke=s;ke<8;ke++)t.readBits(2);for(let ke=0;ke<s;ke++)b[ke]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),y[ke]&&t.readUByte();t.readUEG();let T=t.readUEG();T==3&&t.skipBits(1);let A=t.readUEG(),R=t.readUEG(),I=t.readBoolean(),x=0,D=0,S=0,C=0;I&&(x+=t.readUEG(),D+=t.readUEG(),S+=t.readUEG(),C+=t.readUEG());let P=t.readUEG(),N=t.readUEG(),$=t.readUEG(),H=t.readBoolean();for(let ke=H?0:s;ke<=s;ke++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let Et=0;Et<4;Et++)for(let Bt=0;Bt<(Et===3?2:6);Bt++)if(!t.readBoolean())t.readUEG();else{let fi=Math.min(64,1<<4+(Et<<1));Et>1&&t.readEG();for(let De=0;De<fi;De++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());let q=t.readUEG(),Z=0;for(let ke=0;ke<q;ke++){let Et=!1;if(ke!==0&&(Et=t.readBoolean()),Et){ke===q&&t.readUEG(),t.readBoolean(),t.readUEG();let Bt=0;for(let Yi=0;Yi<=Z;Yi++){let fi=t.readBoolean(),De=!1;fi||(De=t.readBoolean()),(fi||De)&&Bt++}Z=Bt}else{let Bt=t.readUEG(),Yi=t.readUEG();Z=Bt+Yi;for(let fi=0;fi<Bt;fi++)t.readUEG(),t.readBoolean();for(let fi=0;fi<Yi;fi++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){let ke=t.readUEG();for(let Et=0;Et<ke;Et++){for(let Bt=0;Bt<$+4;Bt++)t.readBits(1);t.readBits(1)}}let V=0,G=1,ce=1,Se=!0,he=1,be=0;t.readBoolean(),t.readBoolean();let vt=!1;if(t.readBoolean()){if(t.readBoolean()){let ri=t.readUByte(),Rd=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],Kn=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];ri>0&&ri<16?(G=Rd[ri-1],ce=Kn[ri-1]):ri===255&&(G=t.readBits(16),ce=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),vt=t.readBoolean(),vt&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(he=t.readBits(32),be=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){let Kn=t.readBoolean(),xd=t.readBoolean(),Kr=!1;(Kn||xd)&&(Kr=t.readBoolean(),Kr&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),Kr&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let kd=0;kd<=s;kd++){Se=t.readBoolean();let Yf=Se||t.readBoolean(),Dd=!1;Yf?t.readEG():Dd=t.readBoolean();let Nt=Dd?1:t.readUEG()+1;if(Kn)for(let Je=0;Je<Nt;Je++)t.readUEG(),t.readUEG(),Kr&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(xd)for(let Je=0;Je<Nt;Je++)t.readUEG(),t.readUEG(),Kr&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),V=t.readUEG())}let Ft=A,si=R;if(I){let ke=1,Et=1;T===1?ke=Et=2:T==2&&(ke=2),Ft=A-ke*D-ke*x,si=R-Et*C-Et*S}let Ii=r?["A","B","C"][r]:"",Js=o<<24|l<<16|d<<8|u,Hn=0;for(let ke=0;ke<32;ke++)Hn=(Hn|(Js>>ke&1)<<31-ke)>>>0;let Gn=Hn.toString(16);return a===1&&Gn==="2"&&(Gn="6"),{codecString:`hvc1.${Ii}${a}.${Gn}.${n?"H":"L"}${v}.B0`,params:{general_tier_flag:n,general_profile_idc:a,general_profile_space:r,general_profile_compatibility_flags:[o,l,d,u],general_constraint_indicator_flags:[c,h,f,m,p,g],general_level_idc:v,bit_depth:P+8,bit_depth_luma_minus8:P,bit_depth_chroma_minus8:N,min_spatial_segmentation_idc:V,chroma_format_idc:T,frame_rate:{fixed:Se,fps:be/he}},width:Ft,height:si,pixelRatio:[G,ce]}}readPPS(e){let t=new en(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);let r=t.readBoolean(),n=t.readBoolean(),a=1;return n&&r?a=0:n?a=3:r&&(a=2),{parallelismType:a}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}},Lt=188,rp=class i{constructor(e,t,s,r){this.logger=void 0,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._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=s,this.logger=r,this.videoParser=null}static probe(e,t){let s=i.syncOffset(e);return s>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),s!==-1}static syncOffset(e){let t=e.length,s=Math.min(Lt*5,t-Lt)+1,r=0;for(;r<s;){let n=!1,a=-1,o=0;for(let l=r;l<t;l+=Lt)if(e[l]===71&&(t-l===Lt||e[l+Lt]===71)){if(o++,a===-1&&(a=l,a!==0&&(s=Math.min(a+Lt*99,e.length-Lt)+1)),n||(n=np(e,l)===0),n&&o>1&&(a===0&&o>2||l+Lt>s))return a}else{if(o)return-1;break}r++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:eb[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,s,r){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=i.createTrack("video"),this._videoTrack.duration=r,this._audioTrack=i.createTrack("audio",r),this._id3Track=i.createTrack("id3"),this._txtTrack=i.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s}resetTimeStamp(){}resetContiguity(){let{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s=!1,r=!1){s||(this.sampleAes=null);let n,a=this._videoTrack,o=this._audioTrack,l=this._id3Track,d=this._txtTrack,u=a.pid,c=a.pesData,h=o.pid,f=l.pid,m=o.pesData,p=l.pesData,g=null,v=this.pmtParsed,b=this._pmtId,y=e.length;if(this.remainderData&&(e=pi(this.remainderData,e),y=e.length,this.remainderData=null),y<Lt&&!r)return this.remainderData=e,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:d};let T=Math.max(0,i.syncOffset(e));y-=(y-T)%Lt,y<e.byteLength&&!r&&(this.remainderData=new Uint8Array(e.buffer,y,e.buffer.byteLength-y));let A=0;for(let I=T;I<y;I+=Lt)if(e[I]===71){let x=!!(e[I+1]&64),D=np(e,I),S=(e[I+3]&48)>>4,C;if(S>1){if(C=I+5+e[I+4],C===I+Lt)continue}else C=I+4;switch(D){case u:x&&(c&&(n=zn(c,this.logger))&&(this.readyVideoParser(a.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(a,d,n,!1)),c={data:[],size:0}),c&&(c.data.push(e.subarray(C,I+Lt)),c.size+=I+Lt-C);break;case h:if(x){if(m&&(n=zn(m,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,n);break;case"mp3":this.parseMPEGPES(o,n);break;case"ac3":this.parseAC3PES(o,n);break}m={data:[],size:0}}m&&(m.data.push(e.subarray(C,I+Lt)),m.size+=I+Lt-C);break;case f:x&&(p&&(n=zn(p,this.logger))&&this.parseID3PES(l,n),p={data:[],size:0}),p&&(p.data.push(e.subarray(C,I+Lt)),p.size+=I+Lt-C);break;case 0:x&&(C+=e[C]+1),b=this._pmtId=kk(e,C);break;case b:{x&&(C+=e[C]+1);let P=Dk(e,C,this.typeSupported,s,this.observer,this.logger);u=P.videoPid,u>0&&(a.pid=u,a.segmentCodec=P.segmentVideoCodec),h=P.audioPid,h>0&&(o.pid=h,o.segmentCodec=P.segmentAudioCodec),f=P.id3Pid,f>0&&(l.pid=f),g!==null&&!v&&(this.logger.warn(`MPEG-TS PMT found at ${I} after unknown PID '${g}'. Backtracking to sync byte @${T} to parse all TS packets.`),g=null,I=T-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:g=D;break}}else A++;A>0&&ap(this.observer,new Error(`Found ${A} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=c,o.pesData=m,l.pesData=p;let R={audioTrack:o,videoTrack:a,id3Track:l,textTrack:d};return r&&this.extractRemainingSamples(R),R}flush(){let{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){let{audioTrack:t,videoTrack:s,id3Track:r,textTrack:n}=e,a=s.pesData,o=t.pesData,l=r.pesData,d;if(a&&(d=zn(a,this.logger))?(this.readyVideoParser(s.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(s,n,d,!0),s.pesData=null)):s.pesData=a,o&&(d=zn(o,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,d);break;case"mp3":this.parseMPEGPES(t,d);break;case"ac3":this.parseAC3PES(t,d);break}t.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;l&&(d=zn(l,this.logger))?(this.parseID3PES(r,d),r.pesData=null):r.pesData=l}demuxSampleAes(e,t,s){let r=this.demux(e,s,!0,!this.config.progressive),n=this.sampleAes=new tp(this.observer,this.config,t);return this.decrypt(r,n)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new ip:e==="hevc"&&(this.videoParser=new sp))}decrypt(e,t){return new Promise(s=>{let{audioTrack:r,videoTrack:n}=e;r.samples&&r.segmentCodec==="aac"?t.decryptAacSamples(r.samples,0,()=>{n.samples?t.decryptAvcSamples(n.samples,0,0,()=>{s(e)}):s(e)}):n.samples&&t.decryptAvcSamples(n.samples,0,0,()=>{s(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let s=0,r=this.aacOverFlow,n=t.data;if(r){this.aacOverFlow=null;let c=r.missing,h=r.sample.unit.byteLength;if(c===-1)n=pi(r.sample.unit,n);else{let f=h-c;r.sample.unit.set(n.subarray(0,c),f),e.samples.push(r.sample),s=r.missing}}let a,o;for(a=s,o=n.length;a<o-1&&!Au(n,a);a++);if(a!==s){let c,h=a<o-1;if(h?c=`AAC PES did not start with ADTS header,offset:${a}`:c="No ADTS header found in AAC PES",ap(this.observer,new Error(c),h,this.logger),!h)return}Pb(e,this.observer,n,a,this.audioCodec);let l;if(t.pts!==void 0)l=t.pts;else if(r){let c=Ob(e.samplerate);l=r.sample.pts+c}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let d=0,u;for(;a<o;)if(u=Nb(e,n,a,l,d),a+=u.length,u.missing){this.aacOverFlow=u;break}else for(d++;a<o-1&&!Au(n,a);a++);}parseMPEGPES(e,t){let s=t.data,r=s.length,n=0,a=0,o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<r;)if(Hb(s,a)){let l=Bb(e,s,a,o,n);if(l)a+=l.length,n++;else break}else a++}parseAC3PES(e,t){{let s=t.data,r=t.pts;if(r===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}let n=s.length,a=0,o=0,l;for(;o<n&&(l=Vb(e,s,o,r,a++))>0;)o+=l}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}let s=$e({},t,{type:this._videoTrack?oi.emsg:oi.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}};function np(i,e){return((i[e+1]&31)<<8)+i[e+2]}function kk(i,e){return(i[e+10]&31)<<8|i[e+11]}function Dk(i,e,t,s,r,n){let a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(i[e+1]&15)<<8|i[e+2],l=e+3+o-4,d=(i[e+10]&15)<<8|i[e+11];for(e+=12+d;e<l;){let u=np(i,e),c=(i[e+3]&15)<<8|i[e+4];switch(i[e]){case 207:if(!s){Em("ADTS AAC",n);break}case 15:a.audioPid===-1&&(a.audioPid=u);break;case 21:a.id3Pid===-1&&(a.id3Pid=u);break;case 219:if(!s){Em("H.264",n);break}case 27:a.videoPid===-1&&(a.videoPid=u);break;case 3:case 4:!t.mpeg&&!t.mp3?n.log("MPEG audio found, not supported in this browser"):a.audioPid===-1&&(a.audioPid=u,a.segmentAudioCodec="mp3");break;case 193:if(!s){Em("AC-3",n);break}case 129:t.ac3?a.audioPid===-1&&(a.audioPid=u,a.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(a.audioPid===-1&&c>0){let h=e+5,f=c;for(;f>2;){switch(i[h]){case 106:t.ac3!==!0?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=u,a.segmentAudioCodec="ac3");break}let p=i[h+1]+2;h+=p,f-=p}}break;case 194:case 135:return ap(r,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:a.videoPid===-1&&(a.videoPid=u,a.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"));break}e+=c+5}return a}function ap(i,e,t,s){s.warn(`parsing error: ${e.message}`),i.emit(E.ERROR,E.ERROR,{type:se.MEDIA_ERROR,details:M.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function Em(i,e){e.log(`${i} with AES-128-CBC encryption found in unencrypted stream`)}function zn(i,e){let t=0,s,r,n,a,o,l=i.data;if(!i||i.size===0)return null;for(;l[0].length<19&&l.length>1;)l[0]=pi(l[0],l[1]),l.splice(1,1);if(s=l[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(r=(s[4]<<8)+s[5],r&&r>i.size-6)return null;let u=s[7];u&192&&(a=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,u&64?(o=(s[14]&14)*536870912+(s[15]&255)*4194304+(s[16]&254)*16384+(s[17]&255)*128+(s[18]&254)/2,a-o>60*9e4&&(e.warn(`${Math.round((a-o)/9e4)}s delta between PTS and DTS, align them`),a=o)):o=a),n=s[8];let c=n+9;if(i.size<=c)return null;i.size-=c;let h=new Uint8Array(i.size);for(let f=0,m=l.length;f<m;f++){s=l[f];let p=s.byteLength;if(c)if(c>p){c-=p;continue}else s=s.subarray(c),p-=c,c=0;h.set(s,t),t+=p}return r&&(r-=n+3),{data:h,pts:a,dts:o,len:r}}return null}var op=class{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}},tr=Math.pow(2,32)-1,_t=class i{static init(){i.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in i.types)i.types.hasOwnProperty(e)&&(i.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);let t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),s=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]);i.HDLR_TYPES={video:t,audio:s};let r=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),n=new Uint8Array([0,0,0,0,0,0,0,0]);i.STTS=i.STSC=i.STCO=n,i.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),i.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),i.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),i.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]);i.FTYP=i.box(i.types.ftyp,a,l,a,o),i.DINF=i.box(i.types.dinf,i.box(i.types.dref,r))}static box(e,...t){let s=8,r=t.length,n=r;for(;r--;)s+=t[r].byteLength;let a=new Uint8Array(s);for(a[0]=s>>24&255,a[1]=s>>16&255,a[2]=s>>8&255,a[3]=s&255,a.set(e,4),r=0,s=8;r<n;r++)a.set(t[r],s),s+=t[r].byteLength;return a}static hdlr(e){return i.box(i.types.hdlr,i.HDLR_TYPES[e])}static mdat(e){return i.box(i.types.mdat,e)}static mdhd(e,t){t*=e;let s=Math.floor(t/(tr+1)),r=Math.floor(t%(tr+1));return i.box(i.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,s>>24,s>>16&255,s>>8&255,s&255,r>>24,r>>16&255,r>>8&255,r&255,85,196,0,0]))}static mdia(e){return i.box(i.types.mdia,i.mdhd(e.timescale||0,e.duration||0),i.hdlr(e.type),i.minf(e))}static mfhd(e){return i.box(i.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?i.box(i.types.minf,i.box(i.types.smhd,i.SMHD),i.DINF,i.stbl(e)):i.box(i.types.minf,i.box(i.types.vmhd,i.VMHD),i.DINF,i.stbl(e))}static moof(e,t,s){return i.box(i.types.moof,i.mfhd(e),i.traf(s,t))}static moov(e){let t=e.length,s=[];for(;t--;)s[t]=i.trak(e[t]);return i.box.apply(null,[i.types.moov,i.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(i.mvex(e)))}static mvex(e){let t=e.length,s=[];for(;t--;)s[t]=i.trex(e[t]);return i.box.apply(null,[i.types.mvex,...s])}static mvhd(e,t){t*=e;let s=Math.floor(t/(tr+1)),r=Math.floor(t%(tr+1)),n=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,s>>24,s>>16&255,s>>8&255,s&255,r>>24,r>>16&255,r>>8&255,r&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return i.box(i.types.mvhd,n)}static sdtp(e){let t=e.samples||[],s=new Uint8Array(4+t.length),r,n;for(r=0;r<t.length;r++)n=t[r].flags,s[r+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return i.box(i.types.sdtp,s)}static stbl(e){return i.box(i.types.stbl,i.stsd(e),i.box(i.types.stts,i.STTS),i.box(i.types.stsc,i.STSC),i.box(i.types.stsz,i.STSZ),i.box(i.types.stco,i.STCO))}static avc1(e){let t=[],s=[],r,n,a;for(r=0;r<e.sps.length;r++)n=e.sps[r],a=n.byteLength,t.push(a>>>8&255),t.push(a&255),t=t.concat(Array.prototype.slice.call(n));for(r=0;r<e.pps.length;r++)n=e.pps[r],a=n.byteLength,s.push(a>>>8&255),s.push(a&255),s=s.concat(Array.prototype.slice.call(n));let o=i.box(i.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(s))),l=e.width,d=e.height,u=e.pixelRatio[0],c=e.pixelRatio[1];return i.box(i.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&255,d>>8&255,d&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,i.box(i.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),i.box(i.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,c>>24,c>>16&255,c>>8&255,c&255])))}static esds(e){let t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){let t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return i.box(i.types.mp4a,i.audioStsd(e),i.box(i.types.esds,i.esds(e)))}static mp3(e){return i.box(i.types[".mp3"],i.audioStsd(e))}static ac3(e){return i.box(i.types["ac-3"],i.audioStsd(e),i.box(i.types.dac3,e.config))}static stsd(e){let{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return i.box(i.types.stsd,i.STSD,i.mp4a(e));if(t==="ac3"&&e.config)return i.box(i.types.stsd,i.STSD,i.ac3(e));if(t==="mp3"&&e.codec==="mp3")return i.box(i.types.stsd,i.STSD,i.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return i.box(i.types.stsd,i.STSD,i.avc1(e));if(t==="hevc"&&e.vps)return i.box(i.types.stsd,i.STSD,i.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){let t=e.id,s=(e.duration||0)*(e.timescale||0),r=e.width||0,n=e.height||0,a=Math.floor(s/(tr+1)),o=Math.floor(s%(tr+1));return i.box(i.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,r>>8&255,r&255,0,0,n>>8&255,n&255,0,0]))}static traf(e,t){let s=i.sdtp(e),r=e.id,n=Math.floor(t/(tr+1)),a=Math.floor(t%(tr+1));return i.box(i.types.traf,i.box(i.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,r&255])),i.box(i.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,a>>24,a>>16&255,a>>8&255,a&255])),i.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,i.box(i.types.trak,i.tkhd(e),i.mdia(e))}static trex(e){let t=e.id;return i.box(i.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){let s=e.samples||[],r=s.length,n=12+16*r,a=new Uint8Array(n),o,l,d,u,c,h;for(t+=8+n,a.set([e.type==="video"?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,r&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<r;o++)l=s[o],d=l.duration,u=l.size,c=l.flags,h=l.cts,a.set([d>>>24&255,d>>>16&255,d>>>8&255,d&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,c.isLeading<<2|c.dependsOn,c.isDependedOn<<6|c.hasRedundancy<<4|c.paddingValue<<1|c.isNonSync,c.degradPrio&61440,c.degradPrio&15,h>>>24&255,h>>>16&255,h>>>8&255,h&255],12+16*o);return i.box(i.types.trun,a)}static initSegment(e){i.types||i.init();let t=i.moov(e);return pi(i.FTYP,t)}static hvc1(e){let t=e.params,s=[e.vps,e.sps,e.pps],r=4,n=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),r-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),s.length]),a=n.length;for(let m=0;m<s.length;m+=1){a+=3;for(let p=0;p<s[m].length;p+=1)a+=2+s[m][p].length}let o=new Uint8Array(a);o.set(n,0),a=n.length;let l=s.length-1;for(let m=0;m<s.length;m+=1){o.set(new Uint8Array([32+m|(m===l?128:0),0,s[m].length]),a),a+=3;for(let p=0;p<s[m].length;p+=1)o.set(new Uint8Array([s[m][p].length>>8,s[m][p].length&255]),a),a+=2,o.set(s[m][p],a),a+=s[m][p].length}let d=i.box(i.types.hvcC,o),u=e.width,c=e.height,h=e.pixelRatio[0],f=e.pixelRatio[1];return i.box(i.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,u>>8&255,u&255,c>>8&255,c&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),d,i.box(i.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),i.box(i.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,f>>24,f>>16&255,f>>8&255,f&255])))}};_t.types=void 0;_t.HDLR_TYPES=void 0;_t.STTS=void 0;_t.STSC=void 0;_t.STCO=void 0;_t.STSZ=void 0;_t.VMHD=void 0;_t.SMHD=void 0;_t.STSD=void 0;_t.FTYP=void 0;_t.DINF=void 0;var Wb=9e4;function lg(i,e,t=1,s=!1){let r=i*e*t;return s?Math.round(r):r}function Ck(i,e,t=1,s=!1){return lg(i,e,1/t,s)}function wo(i,e=!1){return lg(i,1e3,1/Wb,e)}function wk(i,e=1){return lg(i,Wb,1/e)}function Ry(i){let{baseTime:e,timescale:t,trackId:s}=i;return`${e/t} (${e}/${t}) trackId: ${s}`}var Mk=10*1e3,Pk=1024,Ok=1152,Nk=1536,Qn=null,ym=null;function xy(i,e,t,s){return{duration:e,size:t,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:i?2:1,isNonSync:i?0:1}}}var ia=class extends Qt{constructor(e,t,s,r){if(super("mp4-remuxer",r),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.ISGenerated=!1,Qn===null){let a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Qn=a?parseInt(a[1]):0}if(ym===null){let n=navigator.userAgent.match(/Safari\/(\d+)/i);ym=n?parseInt(n[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){let t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&Ry(t)} > ${e&&Ry(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1,s=e[0].pts,r=e.reduce((n,a)=>{let o=a.pts,l=o-n;return l<-4294967296&&(t=!0,o=ai(o,s),l=o-n),l>0?n:o},s);return t&&this.debug("PTS rollover detected"),r}remux(e,t,s,r,n,a,o,l){let d,u,c,h,f,m,p=n,g=n,v=e.pid>-1,b=t.pid>-1,y=t.samples.length,T=e.samples.length>0,A=o&&y>0||y>1;if((!v||T)&&(!b||A)||this.ISGenerated||o){if(this.ISGenerated){var I,x,D,S;let $=this.videoTrackConfig;($&&(t.width!==$.width||t.height!==$.height||((I=t.pixelRatio)==null?void 0:I[0])!==((x=$.pixelRatio)==null?void 0:x[0])||((D=t.pixelRatio)==null?void 0:D[1])!==((S=$.pixelRatio)==null?void 0:S[1]))||!$&&A||this.nextAudioTs===null&&T)&&this.resetInitSegment()}this.ISGenerated||(c=this.generateIS(e,t,n,a));let C=this.isVideoContiguous,P=-1,N;if(A&&(P=Uk(t.samples),!C&&this.config.forceKeyFrameOnDiscontinuity))if(m=!0,P>0){this.warn(`Dropped ${P} out of ${y} video samples due to a missing keyframe`);let $=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(P),t.dropped+=P,g+=(t.samples[0].pts-$)/t.inputTimeScale,N=g}else P===-1&&(this.warn(`No keyframe found out of ${y} video samples`),m=!1);if(this.ISGenerated){if(T&&A){let $=this.getVideoStartPts(t.samples),U=(ai(e.samples[0].pts,$)-$)/t.inputTimeScale;p+=Math.max(0,U),g+=Math.max(0,-U)}if(T){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),c=this.generateIS(e,t,n,a)),u=this.remuxAudio(e,p,this.isAudioContiguous,a,b||A||l===J.AUDIO?g:void 0),A){let $=u?u.endPTS-u.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),c=this.generateIS(e,t,n,a)),d=this.remuxVideo(t,g,C,$)}}else A&&(d=this.remuxVideo(t,g,C,0));d&&(d.firstKeyFrame=P,d.independent=P!==-1,d.firstKeyFramePTS=N)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(f=qb(s,n,this._initPTS,this._initDTS)),r.samples.length&&(h=Yb(r,n,this._initPTS))),{audio:u,video:d,initSegment:c,independent:m,text:h,id3:f}}computeInitPts(e,t,s,r){let n=Math.round(s*t),a=ai(e,n);if(a<n+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(n-a)/t} ${r}`);a<n+t;)a+=8589934592;return a-n}generateIS(e,t,s,r){let n=e.samples,a=t.samples,o=this.typeSupported,l={},d=this._initPTS,u=!d||r,c="audio/mp4",h,f,m,p=-1;if(u&&(h=f=1/0),e.config&&n.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(c="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}l.audio={id:"audio",container:c,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):_t.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(p=e.id,m=e.inputTimeScale,!d||m!==d.timescale?h=f=this.computeInitPts(n[0].pts,m,s,"audio"):u=!1)}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:_t.initSegment([t]),metadata:{width:t.width,height:t.height}},u)if(p=t.id,m=t.inputTimeScale,!d||m!==d.timescale){let g=this.getVideoStartPts(a),v=ai(a[0].dts,g),b=this.computeInitPts(v,m,s,"video"),y=this.computeInitPts(g,m,s,"video");f=Math.min(f,b),h=Math.min(h,y)}else u=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,u?(d&&this.warn(`Timestamps at playlist time: ${r?"":"~"}${s} ${h/m} != initPTS: ${d.baseTime/d.timescale} (${d.baseTime}/${d.timescale}) trackId: ${d.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${h/m} (${h}/${m}) trackId: ${p}`),this._initPTS={baseTime:h,timescale:m,trackId:p},this._initDTS={baseTime:f,timescale:m,trackId:p}):h=m=void 0,{tracks:l,initPTS:h,timescale:m,trackId:p}}remuxVideo(e,t,s,r){let n=e.inputTimeScale,a=e.samples,o=[],l=a.length,d=this._initPTS,u=d.baseTime*n/d.timescale,c=this.nextVideoTs,h=8,f=this.videoSampleDuration,m,p,g=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY,b=!1;if(!s||c===null){let V=u+t*n,G=a[0].pts-ai(a[0].dts,a[0].pts);Qn&&c!==null&&Math.abs(V-G-(c+u))<15e3?s=!0:c=V-G-u}let y=c+u;for(let V=0;V<l;V++){let G=a[V];G.pts=ai(G.pts,y),G.dts=ai(G.dts,y),G.dts<a[V>0?V-1:V].dts&&(b=!0)}b&&a.sort(function(V,G){let ce=V.dts-G.dts,Se=V.pts-G.pts;return ce||Se}),m=a[0].dts,p=a[a.length-1].dts;let T=p-m,A=T?Math.round(T/(l-1)):f||e.inputTimeScale/30;if(s){let V=m-y,G=V>A,ce=V<-1;if((G||ce)&&(G?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${wo(V,!0)} ms (${V}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${wo(-V,!0)} ms (${V}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!ce||y>=a[0].pts||Qn)){m=y;let Se=a[0].pts-V;if(G)a[0].dts=m,a[0].pts=Se;else{let he=!0;for(let be=0;be<a.length&&!(a[be].dts>Se&&he);be++){let vt=a[be].pts;if(a[be].dts-=V,a[be].pts-=V,be<a.length-1){let ut=a[be+1].pts,Ft=a[be].pts,si=ut<=Ft,Ii=ut<=vt;he=si==Ii}}}this.log(`Video: Initial PTS/DTS adjusted: ${wo(Se,!0)}/${wo(m,!0)}, delta: ${wo(V,!0)} ms`)}}m=Math.max(0,m);let R=0,I=0,x=m;for(let V=0;V<l;V++){let G=a[V],ce=G.units,Se=ce.length,he=0;for(let be=0;be<Se;be++)he+=ce[be].data.length;I+=he,R+=Se,G.length=he,G.dts<x?(G.dts=x,x+=A/4|0||1):x=G.dts,g=Math.min(G.pts,g),v=Math.max(G.pts,v)}p=a[l-1].dts;let D=I+4*R+8,S;try{S=new Uint8Array(D)}catch(V){this.observer.emit(E.ERROR,E.ERROR,{type:se.MUX_ERROR,details:M.REMUX_ALLOC_ERROR,fatal:!1,error:V,bytes:D,reason:`fail allocating video mdat ${D}`});return}let C=new DataView(S.buffer);C.setUint32(0,D),S.set(_t.types.mdat,4);let P=!1,N=Number.POSITIVE_INFINITY,$=Number.POSITIVE_INFINITY,H=Number.NEGATIVE_INFINITY,U=Number.NEGATIVE_INFINITY;for(let V=0;V<l;V++){let G=a[V],ce=G.units,Se=0;for(let vt=0,ut=ce.length;vt<ut;vt++){let Ft=ce[vt],si=Ft.data,Ii=Ft.data.byteLength;C.setUint32(h,Ii),h+=4,S.set(si,h),h+=Ii,Se+=4+Ii}let he;if(V<l-1)f=a[V+1].dts-G.dts,he=a[V+1].pts-G.pts;else{let vt=this.config,ut=V>0?G.dts-a[V-1].dts:A;if(he=V>0?G.pts-a[V-1].pts:A,vt.stretchShortVideoTrack&&this.nextAudioTs!==null){let Ft=Math.floor(vt.maxBufferHole*n),si=(r?g+r*n:this.nextAudioTs+u)-G.pts;si>Ft?(f=si-ut,f<0?f=ut:P=!0,this.log(`It is approximately ${si/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=ut}else f=ut}let be=Math.round(G.pts-G.dts);N=Math.min(N,f),H=Math.max(H,f),$=Math.min($,he),U=Math.max(U,he),o.push(xy(G.key,f,Se,be))}if(o.length){if(Qn){if(Qn<70){let V=o[0].flags;V.dependsOn=2,V.isNonSync=0}}else if(ym&&U-$<H-N&&A/H<.025&&o[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let V=m;for(let G=0,ce=o.length;G<ce;G++){let Se=V+o[G].duration,he=V+o[G].cts;if(G<ce-1){let be=Se+o[G+1].cts;o[G].duration=be-he}else o[G].duration=G?o[G-1].duration:A;o[G].cts=0,V=Se}}}f=P||!f?A:f;let j=p+f;this.nextVideoTs=c=j-u,this.videoSampleDuration=f,this.isVideoContiguous=!0;let re={data1:_t.moof(e.sequenceNumber++,m,$e(e,{samples:o})),data2:S,startPTS:(g-u)/n,endPTS:(v+f-u)/n,startDTS:(m-u)/n,endDTS:c/n,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,re}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return Ok;case"ac3":return Nk;default:return Pk}}remuxAudio(e,t,s,r,n){let a=e.inputTimeScale,o=e.samplerate?e.samplerate:a,l=a/o,d=this.getSamplesPerFrame(e),u=d*l,c=this._initPTS,h=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],m=n!==void 0,p=e.samples,g=h?0:8,v=this.nextAudioTs||-1,b=c.baseTime*a/c.timescale,y=b+t*a;if(this.isAudioContiguous=s=s||p.length&&v>0&&(r&&Math.abs(y-(v+b))<9e3||Math.abs(ai(p[0].pts,y)-(v+b))<20*u),p.forEach(function(U){U.pts=ai(U.pts,y)}),!s||v<0){let U=p.length;if(p=p.filter(j=>j.pts>=0),U!==p.length&&this.warn(`Removed ${p.length-U} of ${U} samples (initPTS ${b} / ${a})`),!p.length)return;n===0?v=0:r&&!m?v=Math.max(0,y-b):v=p[0].pts-b}if(e.segmentCodec==="aac"){let U=this.config.maxAudioFramesDrift;for(let j=0,q=v+b;j<p.length;j++){let Z=p[j],re=Z.pts,V=re-q,G=Math.abs(1e3*V/a);if(V<=-U*u&&m)j===0&&(this.warn(`Audio frame @ ${(re/a).toFixed(3)}s overlaps marker by ${Math.round(1e3*V/a)} ms.`),this.nextAudioTs=v=re-b,q=re);else if(V>=U*u&&G<Mk&&m){let ce=Math.round(V/u);for(q=re-ce*u;q<0&&ce&&u;)ce--,q+=u;j===0&&(this.nextAudioTs=v=q-b),this.warn(`Injecting ${ce} audio frames @ ${((q-b)/a).toFixed(3)}s due to ${Math.round(1e3*V/a)} ms gap.`);for(let Se=0;Se<ce;Se++){let he=op.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);he||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),he=Z.unit.subarray()),p.splice(j,0,{unit:he,pts:q}),q+=u,j++}}Z.pts=q,q+=u}}let T=null,A=null,R,I=0,x=p.length;for(;x--;)I+=p[x].unit.byteLength;for(let U=0,j=p.length;U<j;U++){let q=p[U],Z=q.unit,re=q.pts;if(A!==null){let G=f[U-1];G.duration=Math.round((re-A)/l)}else if(s&&e.segmentCodec==="aac"&&(re=v+b),T=re,I>0){I+=g;try{R=new Uint8Array(I)}catch(G){this.observer.emit(E.ERROR,E.ERROR,{type:se.MUX_ERROR,details:M.REMUX_ALLOC_ERROR,fatal:!1,error:G,bytes:I,reason:`fail allocating audio mdat ${I}`});return}h||(new DataView(R.buffer).setUint32(0,I),R.set(_t.types.mdat,4))}else return;R.set(Z,g);let V=Z.byteLength;g+=V,f.push(xy(!0,d,V,0)),A=re}let D=f.length;if(!D)return;let S=f[f.length-1];v=A-b,this.nextAudioTs=v+l*S.duration;let C=h?new Uint8Array(0):_t.moof(e.sequenceNumber++,T/l,$e({},e,{samples:f}));e.samples=[];let P=(T-b)/a,N=this.nextAudioTs/a,H={data1:C,data2:R,startPTS:P,endPTS:N,startDTS:P,endDTS:N,type:"audio",hasAudio:!0,hasVideo:!1,nb:D};return this.isAudioContiguous=!0,H}};function ai(i,e){let t;if(e===null)return i;for(e<i?t=-8589934592:t=8589934592;Math.abs(i-e)>4294967296;)i+=t;return i}function Uk(i){for(let e=0;e<i.length;e++)if(i[e].key)return e;return-1}function qb(i,e,t,s){let r=i.samples.length;if(!r)return;let n=i.inputTimeScale;for(let o=0;o<r;o++){let l=i.samples[o];l.pts=ai(l.pts-t.baseTime*n/t.timescale,e*n)/n,l.dts=ai(l.dts-s.baseTime*n/s.timescale,e*n)/n}let a=i.samples;return i.samples=[],{samples:a}}function Yb(i,e,t){let s=i.samples.length;if(!s)return;let r=i.inputTimeScale;for(let a=0;a<s;a++){let o=i.samples[a];o.pts=ai(o.pts-t.baseTime*r/t.timescale,e*r)/r}i.samples.sort((a,o)=>a.pts-o.pts);let n=i.samples;return i.samples=[],{samples:n}}var lp=class extends Qt{constructor(e,t,s,r){super("passthrough-remuxer",r),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,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;let t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,s,r){this.audioCodec=t,this.videoCodec=s,this.generateInitSegment(e,r),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:s,videoCodec:r}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}let{audio:n,video:a}=this.initData=sb(e);if(t)HR(e,t);else{let l=n||a;l!=null&&l.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${l.codec}")!`)}n&&(s=ky(n,We.AUDIO,this)),a&&(r=ky(a,We.VIDEO,this));let o={};n&&a?o.audiovideo={container:"video/mp4",codec:s+","+r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:n?o.audio={container:"audio/mp4",codec:s,encrypted:n.encrypted,initSegment:e,id:"audio"}:a?o.video={container:"video/mp4",codec:r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(e,t,s,r,n,a){var o,l;let{initPTS:d,lastEndTime:u}=this,c={audio:void 0,video:void 0,text:r,id3:s,initSegment:void 0};Q(u)||(u=this.lastEndTime=n||0);let h=t.samples;if(!h.length)return c;let f={initPTS:void 0,timescale:void 0,trackId:void 0},m=this.initData;if((o=m)!=null&&o.length||(this.generateInitSegment(h),m=this.initData),!((l=m)!=null&&l.length))return this.warn("Failed to generate initSegment."),c;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);let p=KR(h,m,this),g=m.audio?p[m.audio.id]:null,v=m.video?p[m.video.id]:null,b=jd(v,1/0),y=jd(g,1/0),T=jd(v,0,!0),A=jd(g,0,!0),R=n,I=0,x=g&&(!v||!d&&y<b||d&&d.trackId===m.audio.id),D=x?g:v;if(D){let q=D.timescale,Z=D.start-n*q,re=x?m.audio.id:m.video.id;R=D.start/q,I=x?A-y:T-b,(a||!d)&&(Fk(d,R,n,I)||q!==d.timescale)&&(d&&this.warn(`Timestamps at playlist time: ${a?"":"~"}${n} ${Z/q} != initPTS: ${d.baseTime/d.timescale} (${d.baseTime}/${d.timescale}) trackId: ${d.trackId}`),this.log(`Found initPTS at playlist time: ${n} offset: ${R-n} (${Z}/${q}) trackId: ${re}`),d=null,f.initPTS=Z,f.timescale=q,f.trackId=re)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${n}`);d?(f.initPTS=d.baseTime,f.timescale=d.timescale,f.trackId=d.trackId):((!f.timescale||f.trackId===void 0||f.initPTS===void 0)&&(this.warn("Could not set initPTS"),f.initPTS=R,f.timescale=1,f.trackId=-1),this.initPTS=d={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});let S=R-d.baseTime/d.timescale,C=S+I;I>0?this.lastEndTime=C:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());let P=!!m.audio,N=!!m.video,$="";P&&($+="audio"),N&&($+="video");let H=(m.audio?m.audio.encrypted:!1)||(m.video?m.video.encrypted:!1),U={data1:h,startPTS:S,startDTS:S,endPTS:C,endDTS:C,type:$,hasAudio:P,hasVideo:N,nb:1,dropped:0,encrypted:H};c.audio=P&&!N?U:void 0,c.video=N?U:void 0;let j=v==null?void 0:v.sampleCount;if(j){let q=v.keyFrameIndex,Z=q!==-1;U.nb=j,U.dropped=q===0||this.isVideoContiguous?0:Z?q:j,U.independent=Z,U.firstKeyFrame=q,Z&&v.keyFrameStart&&(U.firstKeyFramePTS=(v.keyFrameStart-d.baseTime)/d.timescale),this.isVideoContiguous||(c.independent=Z),this.isVideoContiguous||(this.isVideoContiguous=Z),U.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${q}/${j} dropped: ${U.dropped} start: ${U.firstKeyFramePTS||"NA"}`)}return c.initSegment=f,c.id3=qb(s,n,d,d),r.samples.length&&(c.text=Yb(r,n,d)),c}};function jd(i,e,t=!1){return(i==null?void 0:i.start)!==void 0?(i.start+(t?i.duration:0))/i.timescale:e}function Fk(i,e,t,s){if(i===null)return!0;let r=Math.max(s,1),n=e-i.baseTime/i.timescale;return Math.abs(n-t)>r}function ky(i,e,t){let s=i.codec;return s&&s.length>4?s:e===We.AUDIO?s==="ec-3"||s==="ac-3"||s==="alac"?s:s==="fLaC"||s==="Opus"?cu(s,!1):(t.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"):(t.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1")}var ks;try{ks=self.performance.now.bind(self.performance)}catch{ks=Date.now}var nu=[{demux:ep,remux:lp},{demux:rp,remux:ia},{demux:Xm,remux:ia},{demux:Jm,remux:ia}];nu.splice(2,0,{demux:Zm,remux:ia});var Iu=class{constructor(e,t,s,r,n,a){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=s,this.id=n,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,r){let n=s.transmuxing;n.executeStart=ks();let a=new Uint8Array(e),{currentTransmuxState:o,transmuxConfig:l}=this;r&&(this.currentTransmuxState=r);let{contiguous:d,discontinuity:u,trackSwitch:c,accurateTimeOffset:h,timeOffset:f,initSegmentChange:m}=r||o,{audioCodec:p,videoCodec:g,defaultInitPts:v,duration:b,initSegmentData:y}=l,T=Bk(a,t);if(T&&ta(T.method)){let x=this.getDecrypter(),D=tg(T.method);if(x.isSync()){let S=x.softwareDecrypt(a,T.key.buffer,T.iv.buffer,D);if(s.part>-1){let P=x.flush();S=P&&P.buffer}if(!S)return n.executeEnd=ks(),bm(s);a=new Uint8Array(S)}else return this.asyncResult=!0,this.decryptionPromise=x.webCryptoDecrypt(a,T.key.buffer,T.iv.buffer,D).then(S=>{let C=this.push(S,null,s);return this.decryptionPromise=null,C}),this.decryptionPromise}let A=this.needsProbing(u,c);if(A){let x=this.configureTransmuxer(a);if(x)return this.logger.warn(`[transmuxer] ${x.message}`),this.observer.emit(E.ERROR,E.ERROR,{type:se.MEDIA_ERROR,details:M.FRAG_PARSING_ERROR,fatal:!1,error:x,reason:x.message}),n.executeEnd=ks(),bm(s)}(u||c||m||A)&&this.resetInitSegment(y,p,g,b,t),(u||m||A)&&this.resetInitialTimestamp(v),d||this.resetContiguity();let R=this.transmux(a,T,f,h,s);this.asyncResult=Yo(R);let I=this.currentTransmuxState;return I.contiguous=!0,I.discontinuity=!1,I.trackSwitch=!1,n.executeEnd=ks(),R}flush(e){let t=e.transmuxing;t.executeStart=ks();let{decrypter:s,currentTransmuxState:r,decryptionPromise:n}=this;if(n)return this.asyncResult=!0,n.then(()=>this.flush(e));let a=[],{timeOffset:o}=r;if(s){let c=s.flush();c&&a.push(this.push(c.buffer,null,e))}let{demuxer:l,remuxer:d}=this;if(!l||!d){t.executeEnd=ks();let c=[bm(e)];return this.asyncResult?Promise.resolve(c):c}let u=l.flush(o);return Yo(u)?(this.asyncResult=!0,u.then(c=>(this.flushRemux(a,c,e),a))):(this.flushRemux(a,u,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,s){let{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=t,{accurateTimeOffset:l,timeOffset:d}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===J.MAIN?"level":"track"} ${s.level}`);let u=this.remuxer.remux(r,n,a,o,d,l,!0,this.id);e.push({remuxResult:u,chunkMeta:s}),s.transmuxing.executeEnd=ks()}resetInitialTimestamp(e){let{demuxer:t,remuxer:s}=this;!t||!s||(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){let{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,r,n){let{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(e,t,s,r),o.resetInitSegment(e,t,s,n))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,s,r,n){let a;return t&&t.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,s,r,n):a=this.transmuxUnencrypted(e,s,r,n),a}transmuxUnencrypted(e,t,s,r){let{audioTrack:n,videoTrack:a,id3Track:o,textTrack:l}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(n,a,o,l,t,s,!1,this.id),chunkMeta:r}}transmuxSampleAes(e,t,s,r,n){return this.demuxer.demuxSampleAes(e,t,s).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,s,r,!1,this.id),chunkMeta:n}))}configureTransmuxer(e){let{config:t,observer:s,typeSupported:r}=this,n;for(let c=0,h=nu.length;c<h;c++){var a;if((a=nu[c].demux)!=null&&a.probe(e,this.logger)){n=nu[c];break}}if(!n)return new Error("Failed to find demuxer by probing fragment data");let o=this.demuxer,l=this.remuxer,d=n.remux,u=n.demux;(!l||!(l instanceof d))&&(this.remuxer=new d(s,t,r,this.logger)),(!o||!(o instanceof u))&&(this.demuxer=new u(s,t,r,this.logger),this.probe=u.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Ho(this.config)),e}};function Bk(i,e){let t=null;return i.byteLength>0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(t=e),t}var bm=i=>({remuxResult:{},chunkMeta:i});function Yo(i){return"then"in i&&i.then instanceof Function}var dp=class{constructor(e,t,s,r,n){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=s,this.duration=r,this.defaultInitPts=n||null}},up=class{constructor(e,t,s,r,n,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=s,this.trackSwitch=r,this.timeOffset=n,this.initSegmentChange=a}},Dy=0,Lu=class{constructor(e,t,s,r){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Dy++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=l=>{let d=l.data,u=this.hls;if(!(!u||!(d!=null&&d.event)||d.instanceNo!==this.instanceNo))switch(d.event){case"init":{var c;let h=(c=this.workerContext)==null?void 0:c.objectURL;h&&self.URL.revokeObjectURL(h);break}case"transmuxComplete":{this.handleTransmuxComplete(d.data);break}case"flush":{this.onFlush(d.data);break}case"workerLog":{u.logger[d.data.logType]&&u.logger[d.data.logType](d.data.message);break}default:{d.data=d.data||{},d.data.frag=this.frag,d.data.part=this.part,d.data.id=this.id,u.trigger(d.event,d.data);break}}},this.onWorkerError=l=>{if(!this.hls)return;let d=new Error(`${l.message} (${l.filename}:${l.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(E.ERROR,{type:se.OTHER_ERROR,details:M.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:d})};let n=e.config;this.hls=e,this.id=t,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=s,this.onFlush=r;let a=(l,d)=>{d=d||{},d.frag=this.frag||void 0,l===E.ERROR&&(d=d,d.parent=this.id,d.part=this.part,this.error=d.error),this.hls.trigger(l,d)};this.observer=new sg,this.observer.on(E.FRAG_DECRYPTED,a),this.observer.on(E.ERROR,a);let o=YE(n.preferManagedMediaSource);if(this.useWorker&&typeof Worker!="undefined"){let l=this.hls.logger;if(n.workerPath||ek()){try{n.workerPath?(l.log(`loading Web Worker ${n.workerPath} for "${t}"`),this.workerContext=ik(n.workerPath)):(l.log(`injecting Web Worker for "${t}"`),this.workerContext=tk());let{worker:u}=this.workerContext;u.addEventListener("message",this.onWorkerMessage),u.addEventListener("error",this.onWorkerError),u.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:qe(n)})}catch(u){l.warn(`Error setting up "${t}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new Iu(this.observer,o,n,"",t,e.logger)}return}}this.transmuxer=new Iu(this.observer,o,n,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){let e=this.instanceNo;this.instanceNo=Dy++;let t=this.hls.config,s=YE(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:qe(t)})}}terminateWorker(){if(this.workerContext){let{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),sk(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{let t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}let e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,s,r,n,a,o,l,d,u){var c,h;d.transmuxing.start=self.performance.now();let{instanceNo:f,transmuxer:m}=this,p=a?a.start:n.start,g=n.decryptdata,v=this.frag,b=!(v&&n.cc===v.cc),y=!(v&&d.level===v.level),T=v?d.sn-v.sn:-1,A=this.part?d.part-this.part.index:-1,R=T===0&&d.id>1&&d.id===(v==null?void 0:v.stats.chunkCount),I=!y&&(T===1||T===0&&(A===1||R&&A<=0)),x=self.performance.now();(y||T||n.stats.parsing.start===0)&&(n.stats.parsing.start=x),a&&(A||!I)&&(a.stats.parsing.start=x);let D=!(v&&((c=n.initSegment)==null?void 0:c.url)===((h=v.initSegment)==null?void 0:h.url)),S=new up(b,I,l,y,p,D);if(!I||b||D){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${n.type} sn: ${d.sn}${d.part>-1?" part: "+d.part:""} ${this.id===J.MAIN?"level":"track"}: ${d.level} id: ${d.id}
32
+ discontinuity: ${b}
33
33
  trackSwitch: ${y}
34
34
  contiguous: ${I}
35
35
  accurateTimeOffset: ${l}
36
36
  timeOffset: ${p}
37
- initSegmentChange: ${D}`);let C=new dp(s,r,t,o,u);this.configureTransmuxer(C)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:g,chunkMeta:d,state:S},e instanceof ArrayBuffer?[e]:[]);else if(m){let C=m.push(e,g,d,S);Yo(C)?C.then(P=>{this.handleTransmuxComplete(P)}).catch(P=>{this.transmuxerError(P,d,"transmuxer-interface push error")}):this.handleTransmuxComplete(C)}}flush(e){e.transmuxing.start=self.performance.now();let{instanceNo:t,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(s){let r=s.flush(e);Yo(r)?r.then(n=>{this.handleFlushResult(n,e)}).catch(n=>{this.transmuxerError(n,e,"transmuxer-interface flush error")}):this.handleFlushResult(r,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger(E.ERROR,{type:se.MEDIA_ERROR,details:M.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach(s=>{this.handleTransmuxComplete(s)}),this.onFlush(t)}configureTransmuxer(e){let{instanceNo:t,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):s&&s.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}},Cy=100,cp=class extends Ko{constructor(e,t,s){super(e,t,s,"audio-stream-controller",J.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!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.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(E.BUFFER_RESET,this.onBufferReset,this),e.on(E.BUFFER_CREATED,this.onBufferCreated,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){let{hls:e}=this;e&&(super.unregisterListeners(),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(E.BUFFER_RESET,this.onBufferReset,this),e.off(E.BUFFER_CREATED,this.onBufferCreated,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:s,initPTS:r,timescale:n,trackId:a}){if(s===J.MAIN){let o=t.cc,l=this.fragCurrent;if(this.initPTS[o]={baseTime:r,timescale:n,trackId:a},this.log(`InitPTS for cc: ${o} found from main: ${r/n} (${r}/${n}) trackId: ${a}`),this.mainAnchor=t,this.state===O.WAITING_INIT_PTS){let d=this.waitingData;(!d&&!this.loadingParts||d&&d.frag.cc!==o)&&this.syncWithAnchor(t,d==null?void 0:d.frag)}else!this.hls.hasEnoughToStart&&l&&l.cc!==o?(l.abortRequests(),this.syncWithAnchor(t,l)):this.state===O.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var s;let r=((s=this.mainFragLoading)==null?void 0:s.frag)||null;if(t&&(r==null?void 0:r.cc)===t.cc)return;let n=(r||e).cc,a=this.getLevelDetails(),o=this.getLoadPosition(),l=mT(a,n,o);l&&(this.log(`Syncing with main frag at ${l.start} cc ${l.cc}`),this.startFragRequested=!1,this.nextLoadPosition=l.start,this.resetLoadingState(),this.state===O.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=O.STOPPED;return}let s=this.lastCurrentTime;this.stopLoad(),this.setInterval(Cy),s>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s,this.state=O.IDLE):this.state=O.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case O.IDLE:this.doTickIdle();break;case O.WAITING_TRACK:{let{levels:e,trackId:t}=this,s=e==null?void 0:e[t],r=s==null?void 0:s.details;if(r&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(r))break;this.state=O.WAITING_INIT_PTS}break}case O.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case O.WAITING_INIT_PTS:{let e=this.waitingData;if(e){let{frag:t,part:s,cache:r,complete:n}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=O.FRAG_LOADING;let o=r.flush().buffer,l={frag:t,part:s,payload:o,networkDetails:null};this._handleFragmentLoadProgress(l),n&&super._handleFragmentLoadComplete(l)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=O.IDLE}}this.onTickEnd()}resetLoadingState(){let e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){let{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;let{hls:t,levels:s,media:r,trackId:n}=this,a=t.config;if(!this.buffering||!r&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(s!=null&&s[n]))return;let o=s[n],l=o.details;if(!l||this.waitForLive(o)||this.waitForCdnTuneIn(l)){this.state=O.WAITING_TRACK,this.startFragRequested=!1;return}let d=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,We.AUDIO,J.AUDIO));let u=this.getFwdBufferInfo(d,J.AUDIO);if(u===null)return;if(!this.switchingTrack&&this._streamEnded(u,l)){t.trigger(E.BUFFER_EOS,{type:"audio"}),this.state=O.ENDED;return}let c=u.len,h=t.maxBufferLength,f=l.fragments,m=f[0].start,p=this.getLoadPosition(),g=this.flushing?p:u.end;if(this.switchingTrack&&r){let y=p;l.PTSKnown&&y<m&&(u.end>m||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),r.currentTime=m+.05)}if(c>=h&&!this.switchingTrack&&g<f[f.length-1].start)return;let v=this.getNextFragment(g,l);if(v&&this.isLoopLoading(v,g)&&(v=this.getNextFragmentLoopLoading(v,l,u,J.MAIN,h)),!v){this.bufferFlushed=!0;return}let T=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&T&&at(v)&&!v.endList&&(!l.live||!this.loadingParts&&g<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(T)===bt.OK&&(this.mainFragLoading=T=null),T&&at(T))){if(v.start>T.end){let b=this.fragmentTracker.getFragAtPos(g,J.MAIN);b&&b.end>T.end&&(T=b,this.mainFragLoading={frag:b,targetBufferTime:null})}if(v.start>T.end)return}this.loadFragment(v,o,g)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(s=>new tn(s))}onAudioTrackSwitching(e,t){let s=!!t.url;this.trackId=t.id;let{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),s?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==O.STOPPED&&(this.setInterval(Cy),this.state=O.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;let s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(E.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(e,t){var s;let{levels:r}=this,{details:n,id:a,groupId:o,track:l}=t;if(!r){this.warn(`Audio tracks reset while loading track ${a} "${l.name}" of "${o}"`);return}let d=this.mainDetails;if(!d||n.endCC>d.endCC||d.expired){this.cachedTrackLoadedData=t,this.state!==O.STOPPED&&(this.state=O.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${l.name}" of "${o}" loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);let u=r[a],c=0;if(n.live||(s=u.details)!=null&&s.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;if(u.details){var h;c=this.alignPlaylists(n,u.details,(h=this.levelLastLoaded)==null?void 0:h.details)}n.alignedSliding||(DT(n,d),n.alignedSliding||bu(n,d),c=n.fragmentStart)}u.details=n,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(d,c),this.hls.trigger(E.AUDIO_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.state===O.WAITING_TRACK&&!this.waitForCdnTuneIn(n)&&(this.state=O.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;let s=e.frag,{part:r,payload:n}=e,{config:a,trackId:o,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}let d=l[o];if(!d){this.warn("Audio track is undefined on fragment load progress");return}let u=d.details;if(!u){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(s.start);return}let c=a.defaultAudioCodec||d.audioCodec||"mp4a.40.2",h=this.transmuxer;h||(h=this.transmuxer=new Lu(this.hls,J.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));let f=this.initPTS[s.cc],m=(t=s.initSegment)==null?void 0:t.data;if(f!==void 0){let g=r?r.index:-1,v=g!==-1,T=new Go(s.level,s.sn,s.stats.chunkCount,n.byteLength,g,v);h.push(n,m,c,"",s,r,u.totalduration,!1,T,f)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${u.startSN} ,${u.endSN}],track ${o}`);let{cache:p}=this.waitingData=this.waitingData||{frag:s,part:r,cache:new _u,complete:!1};p.push(new Uint8Array(n)),this.state!==O.STOPPED&&(this.state=O.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;let s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===J.MAIN&&at(t.frag)&&(this.mainFragLoading=t,this.state===O.IDLE&&this.tick())}onFragBuffered(e,t){let{frag:s,part:r}=t;if(s.type!==J.AUDIO){!this.audioOnly&&s.type===J.MAIN&&!s.elementaryStreams.video&&!s.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${r?" p: "+r.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(at(s)){this.fragPrevious=s;let n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(E.AUDIO_TRACK_SWITCHED,Fe({},n)))}this.fragBufferedComplete(s,r),this.media&&this.tick()}onError(e,t){var s;if(t.fatal){this.state=O.ERROR;return}switch(t.details){case M.FRAG_GAP:case M.FRAG_PARSING_ERROR:case M.FRAG_DECRYPT_ERROR:case M.FRAG_LOAD_ERROR:case M.FRAG_LOAD_TIMEOUT:case M.KEY_LOAD_ERROR:case M.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(J.AUDIO,t);break;case M.AUDIO_TRACK_LOAD_ERROR:case M.AUDIO_TRACK_LOAD_TIMEOUT:case M.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===O.WAITING_TRACK&&((s=t.context)==null?void 0:s.type)===Le.AUDIO_TRACK&&(this.state=O.IDLE);break;case M.BUFFER_ADD_CODEC_ERROR:case M.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case M.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case M.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==We.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==We.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===O.ENDED&&(this.state=O.IDLE);let s=this.mediaBuffer||this.media;s&&(this.afterBufferFlushed(s,t,J.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;let s="audio",{hls:r}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}let{frag:l,part:d,level:u}=o,{details:c}=u,{audio:h,text:f,id3:m,initSegment:p}=n;if(this.fragContextChanged(l)||!c){this.fragmentTracker.removeFragment(l);return}if(this.state=O.PARSING,this.switchingTrack&&h&&this.completeAudioSwitch(this.switchingTrack),p!=null&&p.tracks){let g=l.initSegment||l;if(this.unhandledEncryptionError(p,l))return;this._bufferInitSegment(u,p.tracks,g,a),r.trigger(E.FRAG_PARSING_INIT_SEGMENT,{frag:g,id:s,tracks:p.tracks})}if(h){let{startPTS:g,endPTS:v,startDTS:T,endDTS:y}=h;d&&(d.elementaryStreams[We.AUDIO]={startPTS:g,endPTS:v,startDTS:T,endDTS:y}),l.setElementaryStreamInfo(We.AUDIO,g,v,T,y),this.bufferFragmentData(h,l,d,a)}if(m!=null&&(t=m.samples)!=null&&t.length){let g=$e({id:s,frag:l,details:c},m);r.trigger(E.FRAG_PARSING_METADATA,g)}if(f){let g=$e({id:s,frag:l,details:c},f);r.trigger(E.FRAG_PARSING_USERDATA,g)}}_bufferInitSegment(e,t,s,r){if(this.state!==O.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;let n=t.audio;n.id=J.AUDIO;let a=e.audioCodec;this.log(`Init audio buffer, container:${n.container}, codecs[level/parsed]=[${a}/${n.codec}]`),a&&a.split(",").length===1&&(n.levelCodec=a),this.hls.trigger(E.BUFFER_CODECS,t);let o=n.initSegment;if(o!=null&&o.byteLength){let l={type:"audio",frag:s,part:null,chunkMeta:r,parent:s.type,data:o};this.hls.trigger(E.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,t,s){let r=this.fragmentTracker.getState(e);if(this.switchingTrack||r===bt.NOT_LOADED||r===bt.PARTIAL){var n;if(!at(e))this._loadInitSegment(e,t);else if((n=t.details)!=null&&n.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=O.WAITING_INIT_PTS;let a=this.mainDetails;a&&a.fragmentStart!==t.details.fragmentStart&&bu(t.details,a)}else super.loadFragment(e,t,s)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){let{name:t,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o}=this.bufferedTrack;Jr({name:t,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o},e,Xr)||(mu(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){let{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(E.AUDIO_TRACK_SWITCHED,Fe({},e))}},jo=class extends Qt{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,s){let r=t==null?void 0:t.renditionReports;if(r){let n=-1;for(let a=0;a<r.length;a++){let o=r[a],l;try{l=new self.URL(o.URI,t.url).href}catch(d){this.warn(`Could not construct new URL for Rendition Report: ${d}`),l=o.URI||""}if(l===e){n=a;break}else l===e.substring(0,l.length)&&(n=a)}if(n!==-1){let a=r[n],o=parseInt(a["LAST-MSN"])||t.lastPartSn,l=parseInt(a["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){let u=Math.min(t.age-t.partTarget,t.targetduration);l>=0&&u>t.partTarget&&(l+=1)}let d=s&&jE(s);return new fu(o,l>=0?l:void 0,d)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(s){this.warn(`Could not construct new URL with HLS Delivery Directives: ${s}`)}return e}playlistLoaded(e,t,s){let{details:r,stats:n}=t,a=self.performance.now(),o=n.loading.first?Math.max(0,a-n.loading.first):0;r.advancedDateTime=Date.now()-o;let l=this.hls.config.timelineOffset;if(l!==r.appliedTimelineOffset){let u=Math.max(l||0,0);r.appliedTimelineOffset=u,r.fragments.forEach(c=>{c.setStart(c.playlistOffset+u)})}if(r.live||s!=null&&s.live){let u="levelInfo"in t?t.levelInfo:t.track;if(r.reloaded(s),s&&r.fragments.length>0){Kx(s,r,this);let T=r.playlistParsingError;if(T){this.warn(T);let y=this.hls;if(!y.config.ignorePlaylistParsingErrors){var d;let{networkDetails:b}=t;y.trigger(E.ERROR,{type:se.NETWORK_ERROR,details:M.LEVEL_PARSING_ERROR,fatal:!1,url:r.url,error:T,reason:T.message,level:t.level||void 0,parent:(d=r.fragments[0])==null?void 0:d.type,networkDetails:b,stats:n});return}r.playlistParsingError=null}}r.requestScheduled===-1&&(r.requestScheduled=n.loading.start);let c=this.hls.mainForwardBufferInfo,h=c?c.end-c.len:0,f=(r.edge-h)*1e3,m=IT(r,f);if(r.requestScheduled+m<a?r.requestScheduled=a:r.requestScheduled+=m,this.log(`live playlist ${e} ${r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED"}`),!this.canLoad||!r.live)return;let p,g,v;if(r.canBlockReload&&r.endSN&&r.advanced){let T=this.hls.config.lowLatencyMode,y=r.lastPartSn,b=r.endSN,A=r.lastPartIndex,R=A!==-1,I=y===b;R?I?(g=b+1,v=T?0:A):(g=y,v=T?A+1:r.maxPartIndex):g=b+1;let x=r.age,D=x+r.ageHeader,S=Math.min(D-r.partTarget,r.targetduration*1.5);if(S>0){if(D>r.targetduration*3)this.log(`Playlist last advanced ${x.toFixed(2)}s ago. Omitting segment and part directives.`),g=void 0,v=void 0;else if(s!=null&&s.tuneInGoal&&D-r.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${S} with playlist age: ${r.age}`),S=0;else{let C=Math.floor(S/r.targetduration);if(g+=C,v!==void 0){let P=Math.round(S%r.targetduration/r.partTarget);v+=P}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${x.toFixed(2)}s goal: ${S} skip sn ${C} to part ${v}`)}r.tuneInGoal=S}if(p=this.getDeliveryDirectives(r,t.deliveryDirectives,g,v),T||!I){r.requestScheduled=a,this.loadingPlaylist(u,p);return}}else(r.canBlockReload||r.canSkipUntil)&&(p=this.getDeliveryDirectives(r,t.deliveryDirectives,g,v));p&&g!==void 0&&r.canBlockReload&&(r.requestScheduled=n.loading.first+Math.max(m-o*2,m/2)),this.scheduleLoading(u,p,r)}else this.clearTimer()}scheduleLoading(e,t,s){let r=s||e.details;if(!r){this.loadingPlaylist(e,t);return}let n=self.performance.now(),a=r.requestScheduled;if(n>=a){this.loadingPlaylist(e,t);return}let o=a-n;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o)}getDeliveryDirectives(e,t,s,r){let n=jE(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,r=t.part,n=su.No),new fu(s,r,n)}checkRetry(e){let t=e.details,s=pu(e),r=e.errorAction,{action:n,retryCount:a=0,retryConfig:o}=r||{},l=!!r&&!!o&&(n===Rt.RetryRequest||!r.resolved&&n===Rt.SendAlternateToPenaltyBox);if(l){var d;if(a>=o.maxNumRetry)return!1;if(s&&(d=e.context)!=null&&d.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{let u=eg(o,a);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),u),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${u}ms`)}e.levelRetry=!0,r.resolved=!0}return l}};function jT(i,e){if(i.length!==e.length)return!1;for(let t=0;t<i.length;t++)if(!zo(i[t].attrs,e[t].attrs))return!1;return!0}function zo(i,e,t){let s=i["STABLE-RENDITION-ID"];return s&&!t?s===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(r=>i[r]!==e[r])}function hp(i,e){return e.label.toLowerCase()===i.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(i.lang||"").toLowerCase())}var fp=class extends jo{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(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(E.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:s,groupId:r,details:n}=t,a=this.tracksInGroup[s];if(!a||a.groupId!==r){this.warn(`Audio track with id:${s} and group:${r} not found in active group ${a==null?void 0:a.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Audio track ${s} "${a.name}" lang:${a.lang} group:${r} loaded [${n.startSN}-${n.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let s=t.audioGroups||null,r=this.groupIds,n=this.currentTrack;if(!s||(r==null?void 0:r.length)!==(s==null?void 0:s.length)||s!=null&&s.some(o=>(r==null?void 0:r.indexOf(o))===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;let o=this.tracks.filter(h=>!s||s.indexOf(h.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(h=>h.default)&&(this.selectDefaultTrack=!1),o.forEach((h,f)=>{h.id=f});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=o;let l=this.hls.config.audioPreference;if(!n&&l){let h=Ji(l,o,Xr);if(h>-1)n=o[h];else{let f=Ji(l,this.tracks);n=this.tracks[f]}}let d=this.findTrackId(n);d===-1&&n&&(d=this.findTrackId(null));let u={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${s==null?void 0:s.join(",")}`),this.hls.trigger(E.AUDIO_TRACKS_UPDATED,u);let c=this.trackId;if(d!==-1&&c===-1)this.setAudioTrack(d);else if(o.length&&c===-1){var a;let h=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${o.length}`);this.warn(h.message),this.hls.trigger(E.ERROR,{type:se.MEDIA_ERROR,details:M.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:h})}}}onError(e,t){t.fatal||!t.context||t.context.type===Le.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){let t=this.hls;if(t.config.audioPreference=e,e){let s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){let r=this.currentTrack;if(r&&Jr(e,r,Xr))return r;let n=Ji(e,this.tracksInGroup,Xr);if(n>-1){let a=this.tracksInGroup[n];return this.setAudioTrack(n),a}else if(r){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);let o=Ex(e,t.levels,s,a,Xr);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){let a=Ji(e,s);if(a>-1)return s[a]}}}return null}setAudioTrack(e){let t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;let s=this.currentTrack,r=t[e],n=r.details&&!r.details.live;if(e===this.trackId&&r===s&&n||(this.log(`Switching to audio-track ${e} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=e,this.currentTrack=r,this.hls.trigger(E.AUDIO_TRACK_SWITCHING,Fe({},r)),n))return;let a=this.switchParams(r.url,s==null?void 0:s.details,r.details);this.loadPlaylist(a)}findTrackId(e){let t=this.tracksInGroup;for(let s=0;s<t.length;s++){let r=t[s];if(!(this.selectDefaultTrack&&!r.default)&&(!e||Jr(e,r,Xr)))return s}if(e){let{name:s,lang:r,assocLang:n,characteristics:a,audioCodec:o,channels:l}=e;for(let d=0;d<t.length;d++){let u=t[d];if(Jr({name:s,lang:r,assocLang:n,characteristics:a,audioCodec:o,channels:l},u,Xr))return d}for(let d=0;d<t.length;d++){let u=t[d];if(zo(e.attrs,u.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return d}for(let d=0;d<t.length;d++){let u=t[d];if(zo(e.attrs,u.attrs,["LANGUAGE"]))return d}}return-1}loadPlaylist(e){super.loadPlaylist();let t=this.currentTrack;this.shouldLoadPlaylist(t)&&mu(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let s=e.id,r=e.groupId,n=this.getUrlWithDirectives(e.url,t),a=e.details,o=a==null?void 0:a.age;this.log(`Loading audio-track ${s} "${e.name}" lang:${e.lang} group:${r}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${n}`),this.hls.trigger(E.AUDIO_TRACK_LOADING,{url:n,id:s,groupId:r,deliveryDirectives:t||null,track:e})}},mp=class{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,s){if(this.queues===null||this.tracks===null)return;let r=this.queues[t];r.push(e),r.length===1&&!s&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{let s={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){let s={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(s)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;let s=(t=e[0])==null?void 0:t.label;(s==="async-blocker"||s==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(this.queues===null)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;let t=this.queues[e];if(t.length){let r=t[0];try{r.execute()}catch(n){var s;if(r.onError(n),this.queues===null||this.tracks===null)return;let a=(s=this.tracks[e])==null?void 0:s.buffer;a!=null&&a.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){let{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
37
+ initSegmentChange: ${D}`);let C=new dp(s,r,t,o,u);this.configureTransmuxer(C)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:g,chunkMeta:d,state:S},e instanceof ArrayBuffer?[e]:[]);else if(m){let C=m.push(e,g,d,S);Yo(C)?C.then(P=>{this.handleTransmuxComplete(P)}).catch(P=>{this.transmuxerError(P,d,"transmuxer-interface push error")}):this.handleTransmuxComplete(C)}}flush(e){e.transmuxing.start=self.performance.now();let{instanceNo:t,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(s){let r=s.flush(e);Yo(r)?r.then(n=>{this.handleFlushResult(n,e)}).catch(n=>{this.transmuxerError(n,e,"transmuxer-interface flush error")}):this.handleFlushResult(r,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger(E.ERROR,{type:se.MEDIA_ERROR,details:M.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach(s=>{this.handleTransmuxComplete(s)}),this.onFlush(t)}configureTransmuxer(e){let{instanceNo:t,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):s&&s.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}},Cy=100,cp=class extends Ko{constructor(e,t,s){super(e,t,s,"audio-stream-controller",J.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!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.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(E.BUFFER_RESET,this.onBufferReset,this),e.on(E.BUFFER_CREATED,this.onBufferCreated,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){let{hls:e}=this;e&&(super.unregisterListeners(),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(E.BUFFER_RESET,this.onBufferReset,this),e.off(E.BUFFER_CREATED,this.onBufferCreated,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:s,initPTS:r,timescale:n,trackId:a}){if(s===J.MAIN){let o=t.cc,l=this.fragCurrent;if(this.initPTS[o]={baseTime:r,timescale:n,trackId:a},this.log(`InitPTS for cc: ${o} found from main: ${r/n} (${r}/${n}) trackId: ${a}`),this.mainAnchor=t,this.state===O.WAITING_INIT_PTS){let d=this.waitingData;(!d&&!this.loadingParts||d&&d.frag.cc!==o)&&this.syncWithAnchor(t,d==null?void 0:d.frag)}else!this.hls.hasEnoughToStart&&l&&l.cc!==o?(l.abortRequests(),this.syncWithAnchor(t,l)):this.state===O.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var s;let r=((s=this.mainFragLoading)==null?void 0:s.frag)||null;if(t&&(r==null?void 0:r.cc)===t.cc)return;let n=(r||e).cc,a=this.getLevelDetails(),o=this.getLoadPosition(),l=mb(a,n,o);l&&(this.log(`Syncing with main frag at ${l.start} cc ${l.cc}`),this.startFragRequested=!1,this.nextLoadPosition=l.start,this.resetLoadingState(),this.state===O.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=O.STOPPED;return}let s=this.lastCurrentTime;this.stopLoad(),this.setInterval(Cy),s>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s,this.state=O.IDLE):this.state=O.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case O.IDLE:this.doTickIdle();break;case O.WAITING_TRACK:{let{levels:e,trackId:t}=this,s=e==null?void 0:e[t],r=s==null?void 0:s.details;if(r&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(r))break;this.state=O.WAITING_INIT_PTS}break}case O.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case O.WAITING_INIT_PTS:{let e=this.waitingData;if(e){let{frag:t,part:s,cache:r,complete:n}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=O.FRAG_LOADING;let o=r.flush().buffer,l={frag:t,part:s,payload:o,networkDetails:null};this._handleFragmentLoadProgress(l),n&&super._handleFragmentLoadComplete(l)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=O.IDLE}}this.onTickEnd()}resetLoadingState(){let e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){let{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;let{hls:t,levels:s,media:r,trackId:n}=this,a=t.config;if(!this.buffering||!r&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(s!=null&&s[n]))return;let o=s[n],l=o.details;if(!l||this.waitForLive(o)||this.waitForCdnTuneIn(l)){this.state=O.WAITING_TRACK,this.startFragRequested=!1;return}let d=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,We.AUDIO,J.AUDIO));let u=this.getFwdBufferInfo(d,J.AUDIO);if(u===null)return;if(!this.switchingTrack&&this._streamEnded(u,l)){t.trigger(E.BUFFER_EOS,{type:"audio"}),this.state=O.ENDED;return}let c=u.len,h=t.maxBufferLength,f=l.fragments,m=f[0].start,p=this.getLoadPosition(),g=this.flushing?p:u.end;if(this.switchingTrack&&r){let y=p;l.PTSKnown&&y<m&&(u.end>m||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),r.currentTime=m+.05)}if(c>=h&&!this.switchingTrack&&g<f[f.length-1].start)return;let v=this.getNextFragment(g,l);if(v&&this.isLoopLoading(v,g)&&(v=this.getNextFragmentLoopLoading(v,l,u,J.MAIN,h)),!v){this.bufferFlushed=!0;return}let b=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&b&&at(v)&&!v.endList&&(!l.live||!this.loadingParts&&g<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(b)===Tt.OK&&(this.mainFragLoading=b=null),b&&at(b))){if(v.start>b.end){let T=this.fragmentTracker.getFragAtPos(g,J.MAIN);T&&T.end>b.end&&(b=T,this.mainFragLoading={frag:T,targetBufferTime:null})}if(v.start>b.end)return}this.loadFragment(v,o,g)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(s=>new tn(s))}onAudioTrackSwitching(e,t){let s=!!t.url;this.trackId=t.id;let{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),s?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==O.STOPPED&&(this.setInterval(Cy),this.state=O.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;let s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(E.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(e,t){var s;let{levels:r}=this,{details:n,id:a,groupId:o,track:l}=t;if(!r){this.warn(`Audio tracks reset while loading track ${a} "${l.name}" of "${o}"`);return}let d=this.mainDetails;if(!d||n.endCC>d.endCC||d.expired){this.cachedTrackLoadedData=t,this.state!==O.STOPPED&&(this.state=O.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${l.name}" of "${o}" loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);let u=r[a],c=0;if(n.live||(s=u.details)!=null&&s.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;if(u.details){var h;c=this.alignPlaylists(n,u.details,(h=this.levelLastLoaded)==null?void 0:h.details)}n.alignedSliding||(Db(n,d),n.alignedSliding||Tu(n,d),c=n.fragmentStart)}u.details=n,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(d,c),this.hls.trigger(E.AUDIO_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.state===O.WAITING_TRACK&&!this.waitForCdnTuneIn(n)&&(this.state=O.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;let s=e.frag,{part:r,payload:n}=e,{config:a,trackId:o,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}let d=l[o];if(!d){this.warn("Audio track is undefined on fragment load progress");return}let u=d.details;if(!u){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(s.start);return}let c=a.defaultAudioCodec||d.audioCodec||"mp4a.40.2",h=this.transmuxer;h||(h=this.transmuxer=new Lu(this.hls,J.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));let f=this.initPTS[s.cc],m=(t=s.initSegment)==null?void 0:t.data;if(f!==void 0){let g=r?r.index:-1,v=g!==-1,b=new Go(s.level,s.sn,s.stats.chunkCount,n.byteLength,g,v);h.push(n,m,c,"",s,r,u.totalduration,!1,b,f)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${u.startSN} ,${u.endSN}],track ${o}`);let{cache:p}=this.waitingData=this.waitingData||{frag:s,part:r,cache:new _u,complete:!1};p.push(new Uint8Array(n)),this.state!==O.STOPPED&&(this.state=O.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;let s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===J.MAIN&&at(t.frag)&&(this.mainFragLoading=t,this.state===O.IDLE&&this.tick())}onFragBuffered(e,t){let{frag:s,part:r}=t;if(s.type!==J.AUDIO){!this.audioOnly&&s.type===J.MAIN&&!s.elementaryStreams.video&&!s.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${r?" p: "+r.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(at(s)){this.fragPrevious=s;let n=this.switchingTrack;n&&(this.bufferedTrack=n,this.switchingTrack=null,this.hls.trigger(E.AUDIO_TRACK_SWITCHED,Fe({},n)))}this.fragBufferedComplete(s,r),this.media&&this.tick()}onError(e,t){var s;if(t.fatal){this.state=O.ERROR;return}switch(t.details){case M.FRAG_GAP:case M.FRAG_PARSING_ERROR:case M.FRAG_DECRYPT_ERROR:case M.FRAG_LOAD_ERROR:case M.FRAG_LOAD_TIMEOUT:case M.KEY_LOAD_ERROR:case M.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(J.AUDIO,t);break;case M.AUDIO_TRACK_LOAD_ERROR:case M.AUDIO_TRACK_LOAD_TIMEOUT:case M.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===O.WAITING_TRACK&&((s=t.context)==null?void 0:s.type)===Le.AUDIO_TRACK&&(this.state=O.IDLE);break;case M.BUFFER_ADD_CODEC_ERROR:case M.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case M.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case M.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==We.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==We.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===O.ENDED&&(this.state=O.IDLE);let s=this.mediaBuffer||this.media;s&&(this.afterBufferFlushed(s,t,J.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;let s="audio",{hls:r}=this,{remuxResult:n,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}let{frag:l,part:d,level:u}=o,{details:c}=u,{audio:h,text:f,id3:m,initSegment:p}=n;if(this.fragContextChanged(l)||!c){this.fragmentTracker.removeFragment(l);return}if(this.state=O.PARSING,this.switchingTrack&&h&&this.completeAudioSwitch(this.switchingTrack),p!=null&&p.tracks){let g=l.initSegment||l;if(this.unhandledEncryptionError(p,l))return;this._bufferInitSegment(u,p.tracks,g,a),r.trigger(E.FRAG_PARSING_INIT_SEGMENT,{frag:g,id:s,tracks:p.tracks})}if(h){let{startPTS:g,endPTS:v,startDTS:b,endDTS:y}=h;d&&(d.elementaryStreams[We.AUDIO]={startPTS:g,endPTS:v,startDTS:b,endDTS:y}),l.setElementaryStreamInfo(We.AUDIO,g,v,b,y),this.bufferFragmentData(h,l,d,a)}if(m!=null&&(t=m.samples)!=null&&t.length){let g=$e({id:s,frag:l,details:c},m);r.trigger(E.FRAG_PARSING_METADATA,g)}if(f){let g=$e({id:s,frag:l,details:c},f);r.trigger(E.FRAG_PARSING_USERDATA,g)}}_bufferInitSegment(e,t,s,r){if(this.state!==O.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;let n=t.audio;n.id=J.AUDIO;let a=e.audioCodec;this.log(`Init audio buffer, container:${n.container}, codecs[level/parsed]=[${a}/${n.codec}]`),a&&a.split(",").length===1&&(n.levelCodec=a),this.hls.trigger(E.BUFFER_CODECS,t);let o=n.initSegment;if(o!=null&&o.byteLength){let l={type:"audio",frag:s,part:null,chunkMeta:r,parent:s.type,data:o};this.hls.trigger(E.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,t,s){let r=this.fragmentTracker.getState(e);if(this.switchingTrack||r===Tt.NOT_LOADED||r===Tt.PARTIAL){var n;if(!at(e))this._loadInitSegment(e,t);else if((n=t.details)!=null&&n.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=O.WAITING_INIT_PTS;let a=this.mainDetails;a&&a.fragmentStart!==t.details.fragmentStart&&Tu(t.details,a)}else super.loadFragment(e,t,s)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){let{name:t,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o}=this.bufferedTrack;Jr({name:t,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o},e,Xr)||(mu(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){let{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(E.AUDIO_TRACK_SWITCHED,Fe({},e))}},jo=class extends Qt{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,s){let r=t==null?void 0:t.renditionReports;if(r){let n=-1;for(let a=0;a<r.length;a++){let o=r[a],l;try{l=new self.URL(o.URI,t.url).href}catch(d){this.warn(`Could not construct new URL for Rendition Report: ${d}`),l=o.URI||""}if(l===e){n=a;break}else l===e.substring(0,l.length)&&(n=a)}if(n!==-1){let a=r[n],o=parseInt(a["LAST-MSN"])||t.lastPartSn,l=parseInt(a["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){let u=Math.min(t.age-t.partTarget,t.targetduration);l>=0&&u>t.partTarget&&(l+=1)}let d=s&&jE(s);return new fu(o,l>=0?l:void 0,d)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(s){this.warn(`Could not construct new URL with HLS Delivery Directives: ${s}`)}return e}playlistLoaded(e,t,s){let{details:r,stats:n}=t,a=self.performance.now(),o=n.loading.first?Math.max(0,a-n.loading.first):0;r.advancedDateTime=Date.now()-o;let l=this.hls.config.timelineOffset;if(l!==r.appliedTimelineOffset){let u=Math.max(l||0,0);r.appliedTimelineOffset=u,r.fragments.forEach(c=>{c.setStart(c.playlistOffset+u)})}if(r.live||s!=null&&s.live){let u="levelInfo"in t?t.levelInfo:t.track;if(r.reloaded(s),s&&r.fragments.length>0){Kx(s,r,this);let b=r.playlistParsingError;if(b){this.warn(b);let y=this.hls;if(!y.config.ignorePlaylistParsingErrors){var d;let{networkDetails:T}=t;y.trigger(E.ERROR,{type:se.NETWORK_ERROR,details:M.LEVEL_PARSING_ERROR,fatal:!1,url:r.url,error:b,reason:b.message,level:t.level||void 0,parent:(d=r.fragments[0])==null?void 0:d.type,networkDetails:T,stats:n});return}r.playlistParsingError=null}}r.requestScheduled===-1&&(r.requestScheduled=n.loading.start);let c=this.hls.mainForwardBufferInfo,h=c?c.end-c.len:0,f=(r.edge-h)*1e3,m=Ib(r,f);if(r.requestScheduled+m<a?r.requestScheduled=a:r.requestScheduled+=m,this.log(`live playlist ${e} ${r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED"}`),!this.canLoad||!r.live)return;let p,g,v;if(r.canBlockReload&&r.endSN&&r.advanced){let b=this.hls.config.lowLatencyMode,y=r.lastPartSn,T=r.endSN,A=r.lastPartIndex,R=A!==-1,I=y===T;R?I?(g=T+1,v=b?0:A):(g=y,v=b?A+1:r.maxPartIndex):g=T+1;let x=r.age,D=x+r.ageHeader,S=Math.min(D-r.partTarget,r.targetduration*1.5);if(S>0){if(D>r.targetduration*3)this.log(`Playlist last advanced ${x.toFixed(2)}s ago. Omitting segment and part directives.`),g=void 0,v=void 0;else if(s!=null&&s.tuneInGoal&&D-r.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${S} with playlist age: ${r.age}`),S=0;else{let C=Math.floor(S/r.targetduration);if(g+=C,v!==void 0){let P=Math.round(S%r.targetduration/r.partTarget);v+=P}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${x.toFixed(2)}s goal: ${S} skip sn ${C} to part ${v}`)}r.tuneInGoal=S}if(p=this.getDeliveryDirectives(r,t.deliveryDirectives,g,v),b||!I){r.requestScheduled=a,this.loadingPlaylist(u,p);return}}else(r.canBlockReload||r.canSkipUntil)&&(p=this.getDeliveryDirectives(r,t.deliveryDirectives,g,v));p&&g!==void 0&&r.canBlockReload&&(r.requestScheduled=n.loading.first+Math.max(m-o*2,m/2)),this.scheduleLoading(u,p,r)}else this.clearTimer()}scheduleLoading(e,t,s){let r=s||e.details;if(!r){this.loadingPlaylist(e,t);return}let n=self.performance.now(),a=r.requestScheduled;if(n>=a){this.loadingPlaylist(e,t);return}let o=a-n;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o)}getDeliveryDirectives(e,t,s,r){let n=jE(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,r=t.part,n=su.No),new fu(s,r,n)}checkRetry(e){let t=e.details,s=pu(e),r=e.errorAction,{action:n,retryCount:a=0,retryConfig:o}=r||{},l=!!r&&!!o&&(n===Rt.RetryRequest||!r.resolved&&n===Rt.SendAlternateToPenaltyBox);if(l){var d;if(a>=o.maxNumRetry)return!1;if(s&&(d=e.context)!=null&&d.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{let u=eg(o,a);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),u),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${u}ms`)}e.levelRetry=!0,r.resolved=!0}return l}};function jb(i,e){if(i.length!==e.length)return!1;for(let t=0;t<i.length;t++)if(!zo(i[t].attrs,e[t].attrs))return!1;return!0}function zo(i,e,t){let s=i["STABLE-RENDITION-ID"];return s&&!t?s===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(r=>i[r]!==e[r])}function hp(i,e){return e.label.toLowerCase()===i.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(i.lang||"").toLowerCase())}var fp=class extends jo{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(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(E.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:s,groupId:r,details:n}=t,a=this.tracksInGroup[s];if(!a||a.groupId!==r){this.warn(`Audio track with id:${s} and group:${r} not found in active group ${a==null?void 0:a.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Audio track ${s} "${a.name}" lang:${a.lang} group:${r} loaded [${n.startSN}-${n.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let s=t.audioGroups||null,r=this.groupIds,n=this.currentTrack;if(!s||(r==null?void 0:r.length)!==(s==null?void 0:s.length)||s!=null&&s.some(o=>(r==null?void 0:r.indexOf(o))===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;let o=this.tracks.filter(h=>!s||s.indexOf(h.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(h=>h.default)&&(this.selectDefaultTrack=!1),o.forEach((h,f)=>{h.id=f});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=o;let l=this.hls.config.audioPreference;if(!n&&l){let h=Ji(l,o,Xr);if(h>-1)n=o[h];else{let f=Ji(l,this.tracks);n=this.tracks[f]}}let d=this.findTrackId(n);d===-1&&n&&(d=this.findTrackId(null));let u={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${s==null?void 0:s.join(",")}`),this.hls.trigger(E.AUDIO_TRACKS_UPDATED,u);let c=this.trackId;if(d!==-1&&c===-1)this.setAudioTrack(d);else if(o.length&&c===-1){var a;let h=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${o.length}`);this.warn(h.message),this.hls.trigger(E.ERROR,{type:se.MEDIA_ERROR,details:M.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:h})}}}onError(e,t){t.fatal||!t.context||t.context.type===Le.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){let t=this.hls;if(t.config.audioPreference=e,e){let s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){let r=this.currentTrack;if(r&&Jr(e,r,Xr))return r;let n=Ji(e,this.tracksInGroup,Xr);if(n>-1){let a=this.tracksInGroup[n];return this.setAudioTrack(n),a}else if(r){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);let o=Ex(e,t.levels,s,a,Xr);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){let a=Ji(e,s);if(a>-1)return s[a]}}}return null}setAudioTrack(e){let t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;let s=this.currentTrack,r=t[e],n=r.details&&!r.details.live;if(e===this.trackId&&r===s&&n||(this.log(`Switching to audio-track ${e} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=e,this.currentTrack=r,this.hls.trigger(E.AUDIO_TRACK_SWITCHING,Fe({},r)),n))return;let a=this.switchParams(r.url,s==null?void 0:s.details,r.details);this.loadPlaylist(a)}findTrackId(e){let t=this.tracksInGroup;for(let s=0;s<t.length;s++){let r=t[s];if(!(this.selectDefaultTrack&&!r.default)&&(!e||Jr(e,r,Xr)))return s}if(e){let{name:s,lang:r,assocLang:n,characteristics:a,audioCodec:o,channels:l}=e;for(let d=0;d<t.length;d++){let u=t[d];if(Jr({name:s,lang:r,assocLang:n,characteristics:a,audioCodec:o,channels:l},u,Xr))return d}for(let d=0;d<t.length;d++){let u=t[d];if(zo(e.attrs,u.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return d}for(let d=0;d<t.length;d++){let u=t[d];if(zo(e.attrs,u.attrs,["LANGUAGE"]))return d}}return-1}loadPlaylist(e){super.loadPlaylist();let t=this.currentTrack;this.shouldLoadPlaylist(t)&&mu(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let s=e.id,r=e.groupId,n=this.getUrlWithDirectives(e.url,t),a=e.details,o=a==null?void 0:a.age;this.log(`Loading audio-track ${s} "${e.name}" lang:${e.lang} group:${r}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${n}`),this.hls.trigger(E.AUDIO_TRACK_LOADING,{url:n,id:s,groupId:r,deliveryDirectives:t||null,track:e})}},mp=class{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,s){if(this.queues===null||this.tracks===null)return;let r=this.queues[t];r.push(e),r.length===1&&!s&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{let s={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){let s={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(s)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;let s=(t=e[0])==null?void 0:t.label;(s==="async-blocker"||s==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(this.queues===null)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;let t=this.queues[e];if(t.length){let r=t[0];try{r.execute()}catch(n){var s;if(r.onError(n),this.queues===null||this.tracks===null)return;let a=(s=this.tracks[e])==null?void 0:s.buffer;a!=null&&a.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){let{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
38
38
  ${this.list("video")}
39
39
  ${this.list("audio")}
40
- ${this.list("audiovideo")}}`}list(e){var t,s;return(t=this.queues)!=null&&t[e]||(s=this.tracks)!=null&&s[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;let s=(t=this.tracks)==null?void 0:t[e],r=s==null?void 0:s.buffer;return r?`SourceBuffer${r.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(s=>s.label).join(", "))||""}},wy=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,zT="HlsJsTrackRemovedError",pp=class extends Error{constructor(e){super(e),this.name=zT}},gp=class extends Qt{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=s=>{var r;this.hls&&((r=this.mediaSource)==null?void 0:r.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=s=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=s=>{let{media:r,mediaSource:n}=this;s&&this.log("Media source opened"),!(!r||!n)&&(n.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(E.MEDIA_ATTACHED,{media:r,mediaSource:n}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{let{mediaSrc:s,_objectUrl:r}=this;s!==r&&this.error(`Media element src was set while attaching MediaSource (${r} > ${s})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=wR(nr(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){let{hls:e}=this;e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.BUFFER_RESET,this.onBufferReset,this),e.on(E.BUFFER_APPENDING,this.onBufferAppending,this),e.on(E.BUFFER_CODECS,this.onBufferCodecs,this),e.on(E.BUFFER_EOS,this.onBufferEos,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.FRAG_PARSED,this.onFragParsed,this),e.on(E.FRAG_CHANGED,this.onFragChanged,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.BUFFER_RESET,this.onBufferReset,this),e.off(E.BUFFER_APPENDING,this.onBufferAppending,this),e.off(E.BUFFER_CODECS,this.onBufferCodecs,this),e.off(E.BUFFER_EOS,this.onBufferEos,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.FRAG_PARSED,this.onFragParsed,this),e.off(E.FRAG_CHANGED,this.onFragChanged,this),e.off(E.ERROR,this.onError,this)}transferMedia(){let{media:e,mediaSource:t}=this;if(!e)return null;let s={};if(this.operationQueue){let n=this.isUpdating();n||this.operationQueue.removeBlockers();let a=this.isQueued();(n||a)&&this.warn(`Transfering MediaSource with${a?" operations in queue":""}${n?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}let r=this.transferData;return!this.sourceBufferCount&&r&&r.mediaSource===t?$e(s,r.tracks):this.sourceBuffers.forEach(n=>{let[a]=n;a&&(s[a]=$e({},this.tracks[a]),this.removeBuffer(a)),n[0]=n[1]=null}),{media:e,mediaSource:t,tracks:s}}initTracks(){let e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var s;let r=2;(t.audio&&!t.video||!t.altAudio)&&(r=1),this.bufferCodecEventsTotal=r,this.log(`${r} bufferCodec event(s) expected.`),(s=this.transferData)!=null&&s.mediaSource&&this.sourceBufferCount&&r&&this.bufferCreated()}onMediaAttaching(e,t){let s=this.media=t.media;this.transferData=this.overrides=void 0;let r=nr(this.appendSource);if(r){let n=!!t.mediaSource;(n||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);let a=this.mediaSource=t.mediaSource||new r;if(this.assignMediaSource(a),n)this._objectUrl=s.src,this.attachTransferred();else{let o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{s.removeAttribute("src");let l=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||l&&a instanceof l,My(s),$k(s,o),s.load()}catch{s.src=o}else s.src=o}s.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,s;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(s=e.constructor)==null?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))}attachTransferred(){let e=this.media,t=this.transferData;if(!t||!e)return;let s=this.tracks,r=t.tracks,n=r?Object.keys(r):null,a=n?n.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(r&&n&&a){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
40
+ ${this.list("audiovideo")}}`}list(e){var t,s;return(t=this.queues)!=null&&t[e]||(s=this.tracks)!=null&&s[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;let s=(t=this.tracks)==null?void 0:t[e],r=s==null?void 0:s.buffer;return r?`SourceBuffer${r.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(s=>s.label).join(", "))||""}},wy=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,zb="HlsJsTrackRemovedError",pp=class extends Error{constructor(e){super(e),this.name=zb}},gp=class extends Qt{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=s=>{var r;this.hls&&((r=this.mediaSource)==null?void 0:r.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=s=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=s=>{let{media:r,mediaSource:n}=this;s&&this.log("Media source opened"),!(!r||!n)&&(n.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(E.MEDIA_ATTACHED,{media:r,mediaSource:n}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{let{mediaSrc:s,_objectUrl:r}=this;s!==r&&this.error(`Media element src was set while attaching MediaSource (${r} > ${s})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=wR(nr(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){let{hls:e}=this;e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.BUFFER_RESET,this.onBufferReset,this),e.on(E.BUFFER_APPENDING,this.onBufferAppending,this),e.on(E.BUFFER_CODECS,this.onBufferCodecs,this),e.on(E.BUFFER_EOS,this.onBufferEos,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.FRAG_PARSED,this.onFragParsed,this),e.on(E.FRAG_CHANGED,this.onFragChanged,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.BUFFER_RESET,this.onBufferReset,this),e.off(E.BUFFER_APPENDING,this.onBufferAppending,this),e.off(E.BUFFER_CODECS,this.onBufferCodecs,this),e.off(E.BUFFER_EOS,this.onBufferEos,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.FRAG_PARSED,this.onFragParsed,this),e.off(E.FRAG_CHANGED,this.onFragChanged,this),e.off(E.ERROR,this.onError,this)}transferMedia(){let{media:e,mediaSource:t}=this;if(!e)return null;let s={};if(this.operationQueue){let n=this.isUpdating();n||this.operationQueue.removeBlockers();let a=this.isQueued();(n||a)&&this.warn(`Transfering MediaSource with${a?" operations in queue":""}${n?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}let r=this.transferData;return!this.sourceBufferCount&&r&&r.mediaSource===t?$e(s,r.tracks):this.sourceBuffers.forEach(n=>{let[a]=n;a&&(s[a]=$e({},this.tracks[a]),this.removeBuffer(a)),n[0]=n[1]=null}),{media:e,mediaSource:t,tracks:s}}initTracks(){let e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var s;let r=2;(t.audio&&!t.video||!t.altAudio)&&(r=1),this.bufferCodecEventsTotal=r,this.log(`${r} bufferCodec event(s) expected.`),(s=this.transferData)!=null&&s.mediaSource&&this.sourceBufferCount&&r&&this.bufferCreated()}onMediaAttaching(e,t){let s=this.media=t.media;this.transferData=this.overrides=void 0;let r=nr(this.appendSource);if(r){let n=!!t.mediaSource;(n||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);let a=this.mediaSource=t.mediaSource||new r;if(this.assignMediaSource(a),n)this._objectUrl=s.src,this.attachTransferred();else{let o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{s.removeAttribute("src");let l=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||l&&a instanceof l,My(s),$k(s,o),s.load()}catch{s.src=o}else s.src=o}s.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,s;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(s=e.constructor)==null?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))}attachTransferred(){let e=this.media,t=this.transferData;if(!t||!e)return;let s=this.tracks,r=t.tracks,n=r?Object.keys(r):null,a=n?n.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(r&&n&&a){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
41
41
  required tracks: ${qe(s,(l,d)=>l==="initSegment"?void 0:d)};
42
- transfer tracks: ${qe(r,(l,d)=>l==="initSegment"?void 0:d)}}`),!Xy(r,s)){t.mediaSource=null,t.tracks=void 0;let l=e.currentTime,d=this.details,u=Math.max(l,(d==null?void 0:d.fragments[0].start)||0);if(u-l>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${l} -> ${u}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(r)}"->"${Object.keys(s)}") start time: ${u} currentTime: ${l}`),this.onMediaDetaching(E.MEDIA_DETACHING,{}),this.onMediaAttaching(E.MEDIA_ATTACHING,t),e.currentTime=u;return}this.transferData=void 0,n.forEach(l=>{let d=l,u=r[d];if(u){let c=u.buffer;if(c){let h=this.fragmentTracker,f=u.id;if(h.hasFragments(f)||h.hasParts(f)){let g=Ee.getBuffered(c);h.detectEvictedFragments(d,g,f,null,!0)}let m=bm(d),p=[d,c];this.sourceBuffers[m]=p,c.updating&&this.operationQueue&&this.operationQueue.prependBlocker(d),this.trackSourceBuffer(d,u)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var e;let t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){let s=!!t.transferMedia;this.transferData=this.overrides=void 0;let{media:r,mediaSource:n,_objectUrl:a}=this;if(n){if(this.log(`media source ${s?"transferring":"detaching"}`),s)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){let o=n.readyState==="open";try{let l=n.sourceBuffers;for(let d=l.length;d--;)o&&l[d].abort(),n.removeSourceBuffer(l[d]);o&&n.endOfStream()}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}n.removeEventListener("sourceopen",this._onMediaSourceOpen),n.removeEventListener("sourceended",this._onMediaSourceEnded),n.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(n.removeEventListener("startstreaming",this._onStartStreaming),n.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}r&&(r.removeEventListener("emptied",this._onMediaEmptied),s||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(r.removeAttribute("src"),this.appendSource&&My(r),r.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(E.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;let s=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),s)try{var r;(r=this.mediaSource)!=null&&r.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(n){this.warn(`onBufferReset ${e}`,n)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[bm(e)]=[null,null];let t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new mp(this.tracks)}onBufferCodecs(e,t){var s;let r=this.tracks,n=Object.keys(t);this.log(`BUFFER_CODECS: "${n}" (current SB count ${this.sourceBufferCount})`);let a="audiovideo"in t&&(r.audio||r.video)||r.audiovideo&&("audio"in t||"video"in t),o=!a&&this.sourceBufferCount&&this.media&&n.some(l=>!r[l]);if(a||o){this.warn(`Unsupported transition between "${Object.keys(r)}" and "${n}" SourceBuffers`);return}n.forEach(l=>{var d,u;let c=t[l],{id:h,codec:f,levelCodec:m,container:p,metadata:g,supplemental:v}=c,T=r[l],y=(d=this.transferData)==null||(d=d.tracks)==null?void 0:d[l],b=y!=null&&y.buffer?y:T,A=(b==null?void 0:b.pendingCodec)||(b==null?void 0:b.codec),R=b==null?void 0:b.levelCodec;T||(T=r[l]={buffer:void 0,listeners:[],codec:f,supplemental:v,container:p,levelCodec:m,metadata:g,id:h});let I=iu(A,R),x=I==null?void 0:I.replace(wy,"$1"),D=iu(f,m),S=(u=D)==null?void 0:u.replace(wy,"$1");D&&I&&x!==S&&(l.slice(0,5)==="audio"&&(D=cu(D,this.appendSource)),this.log(`switching codec ${A} to ${D}`),D!==(T.pendingCodec||T.codec)&&(T.pendingCodec=D),T.container=p,this.appendChangeType(l,p,D))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((s=t.audio)==null?void 0:s.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{let s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e},{})}appendChangeType(e,t,s){let r=`${t};codecs=${s}`,n={label:`change-type=${r}`,execute:()=>{let a=this.tracks[e];if(a){let o=a.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${r}`),o.changeType(r),a.codec=s,a.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn(`Failed to change ${e} SourceBuffer type`,a)}};this.append(n,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;let s=e.start,r=s+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(s,J.MAIN))==null?void 0:t.gap)===!0)return;let a={label:"block-audio",execute:()=>{var o;let l=this.tracks.video;(this.lastVideoAppendEnd>r||l!=null&&l.buffer&&Ee.isBuffered(l.buffer,r)||((o=this.fragmentTracker.getAppendedFrag(r,J.MAIN))==null?void 0:o.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.blockedAudioAppend={op:a,frag:e},this.append(a,"audio",!0)}unblockAudio(){let{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){let{tracks:s}=this,{data:r,type:n,parent:a,frag:o,part:l,chunkMeta:d,offset:u}=t,c=d.buffering[n],{sn:h,cc:f}=o,m=self.performance.now();c.start=m;let p=o.stats.buffering,g=l?l.stats.buffering:null;p.start===0&&(p.start=m),g&&g.start===0&&(g.start=m);let v=s.audio,T=!1;n==="audio"&&(v==null?void 0:v.container)==="audio/mpeg"&&(T=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);let y=s.video,b=y==null?void 0:y.buffer;if(b&&h!=="initSegment"){let I=l||o,x=this.blockedAudioAppend;if(n==="audio"&&a!=="main"&&!this.blockedAudioAppend&&!(y.ending||y.ended)){let S=I.start+I.duration*.05,C=b.buffered,P=this.currentOp("video");!C.length&&!P?this.blockAudio(I):!P&&!Ee.isBuffered(b,S)&&this.lastVideoAppendEnd<S&&this.blockAudio(I)}else if(n==="video"){let D=I.end;if(x){let S=x.frag.start;(D>S||D<this.lastVideoAppendEnd||Ee.isBuffered(b,S))&&this.unblockAudio()}this.lastVideoAppendEnd=D}}let A=(l||o).start,R={label:`append-${n}`,execute:()=>{var I;c.executeStart=self.performance.now();let x=(I=this.tracks[n])==null?void 0:I.buffer;x&&(T?this.updateTimestampOffset(x,A,.1,n,h,f):u!==void 0&&Q(u)&&this.updateTimestampOffset(x,u,1e-6,n,h,f)),this.appendExecutor(r,n)},onStart:()=>{},onComplete:()=>{let I=self.performance.now();c.executeEnd=c.end=I,p.first===0&&(p.first=I),g&&g.first===0&&(g.first=I);let x={};this.sourceBuffers.forEach(([D,S])=>{D&&(x[D]=Ee.getBuffered(S))}),this.appendErrors[n]=0,n==="audio"||n==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(E.BUFFER_APPENDED,{type:n,frag:o,part:l,chunkMeta:d,parent:o.type,timeRanges:x})},onError:I=>{var x;let D={type:se.MEDIA_ERROR,parent:o.type,details:M.BUFFER_APPEND_ERROR,sourceBufferName:n,frag:o,part:l,chunkMeta:d,error:I,err:I,fatal:!1},S=(x=this.media)==null?void 0:x.error;if(I.code===DOMException.QUOTA_EXCEEDED_ERR||I.name=="QuotaExceededError"||"quota"in I)D.details=M.BUFFER_FULL_ERROR;else if(I.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!S)D.errorAction=ea(!0);else if(I.name===zT&&this.sourceBufferCount===0)D.errorAction=ea(!0);else{let C=++this.appendErrors[n];this.warn(`Failed ${C}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${n}" sourceBuffer (${S||"no media error"})`),(C>=this.hls.config.appendErrorMaxRetry||S)&&(D.fatal=!0)}this.hls.trigger(E.ERROR,D)}};this.log(`queuing "${n}" append sn: ${h}${l?" p: "+l.index:""} of ${o.type===J.MAIN?"level":"track"} ${o.level} cc: ${f}`),this.append(R,n,this.isPending(this.tracks[n]))}getFlushOp(e,t,s){return this.log(`queuing "${e}" remove ${t}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{this.hls.trigger(E.BUFFER_FLUSHED,{type:e})},onError:r=>{this.warn(`Failed to remove ${t}-${s} from "${e}" SourceBuffer`,r)}}}onBufferFlushing(e,t){let{type:s,startOffset:r,endOffset:n}=t;s?this.append(this.getFlushOp(s,r,n),s):this.sourceBuffers.forEach(([a])=>{a&&this.append(this.getFlushOp(a,r,n),a)})}onFragParsed(e,t){let{frag:s,part:r}=t,n=[],a=r?r.elementaryStreams:s.elementaryStreams;a[We.AUDIOVIDEO]?n.push("audiovideo"):(a[We.AUDIO]&&n.push("audio"),a[We.VIDEO]&&n.push("video"));let o=()=>{let l=self.performance.now();s.stats.buffering.end=l,r&&(r.stats.buffering.end=l);let d=r?r.stats:s.stats;this.hls.trigger(E.FRAG_BUFFERED,{frag:s,part:r,stats:d,id:s.type})};n.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers(o,n).catch(l=>{this.warn(`Fragment buffered callback ${l}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){let t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var s;this.sourceBuffers.forEach(([a])=>{if(a){let o=this.tracks[a];(!t.type||t.type===a)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${a} buffer reached EOS`)))}});let r=((s=this.overrides)==null?void 0:s.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([a])=>{var o;return a&&!((o=this.tracks[a])!=null&&o.ended)})?r?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();let{mediaSource:a}=this;if(!a||a.readyState!=="open"){a&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${a.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),a.endOfStream(),this.hls.trigger(E.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(E.BUFFERED_TO_END,void 0)):t.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){let t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{let e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===M.BUFFER_APPEND_ERROR&&t.frag){var s;let r=(s=t.errorAction)==null?void 0:s.nextAutoLevel;Q(r)&&r!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){let{hls:e,details:t,media:s}=this;if(!s||t===null||!this.sourceBufferCount)return;let r=e.config,n=s.currentTime,a=t.levelTargetDuration,o=t.live&&r.liveBackBufferLength!==null?r.liveBackBufferLength:r.backBufferLength;if(Q(o)&&o>=0){let d=Math.max(o,a),u=Math.floor(n/a)*a-d;this.flushBackBuffer(n,a,u)}let l=r.frontBufferFlushThreshold;if(Q(l)&&l>0){let d=Math.max(r.maxBufferLength,l),u=Math.max(d,a),c=Math.floor(n/a)*a+u;this.flushFrontBuffer(n,a,c)}}flushBackBuffer(e,t,s){this.sourceBuffers.forEach(([r,n])=>{if(n){let o=Ee.getBuffered(n);if(o.length>0&&s>o.start(0)){var a;this.hls.trigger(E.BACK_BUFFER_REACHED,{bufferEnd:s});let l=this.tracks[r];if((a=this.details)!=null&&a.live)this.hls.trigger(E.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(l!=null&&l.ended){this.log(`Cannot flush ${r} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:r})}}})}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach(([r,n])=>{if(n){let a=Ee.getBuffered(n),o=a.length;if(o<2)return;let l=a.start(o-1),d=a.end(o-1);if(s>l||e>=l&&e<=d)return;this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:r})}})}getDurationAndRange(){var e;let{details:t,mediaSource:s}=this;if(!t||!this.media||(s==null?void 0:s.readyState)!=="open")return null;let r=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&s.setLiveSeekableRange){let d=Math.max(0,t.fragmentStart),u=Math.max(d,r);return{duration:1/0,start:d,end:u}}return{duration:1/0}}let n=(e=this.overrides)==null?void 0:e.duration;if(n)return Q(n)?{duration:n}:null;let a=this.media.duration,o=Q(s.duration)?s.duration:0;return r>o&&r>a||!Q(a)?{duration:r}:null}updateMediaSource({duration:e,start:t,end:s}){let r=this.mediaSource;!this.media||!r||r.readyState!=="open"||(r.duration!==e&&(Q(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),r.duration=e),t!==void 0&&s!==void 0&&(this.log(`MediaSource duration is set to ${r.duration}. Setting seekable range to ${t}-${s}.`),r.setLiveSeekableRange(t,s)))}get tracksReady(){let e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){let{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${qe(s)}`),this.tracksReady){var r;let n=(r=this.transferData)==null?void 0:r.tracks;n&&Object.keys(n).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){let e={};this.sourceBuffers.forEach(([t,s])=>{if(t){let r=this.tracks[t];e[t]={buffer:s,container:r.container,codec:r.codec,supplemental:r.supplemental,levelCodec:r.levelCodec,id:r.id,metadata:r.metadata}}}),this.hls.trigger(E.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{let e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(E.ERROR,{type:se.MEDIA_ERROR,details:M.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){let{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(let n in e){let a=n,o=e[a];if(this.isPending(o)){let l=this.getTrackCodec(o,a),d=`${o.container};codecs=${l}`;o.codec=l,this.log(`creating sourceBuffer(${d})${this.currentOp(a)?" Queued":""} ${qe(o)}`);try{let u=s.addSourceBuffer(d),c=bm(a),h=[a,u];t[c]=h,o.buffer=u}catch(u){var r;this.error(`error while trying to add sourceBuffer: ${u.message}`),this.shiftAndExecuteNext(a),(r=this.operationQueue)==null||r.removeBlockers(),delete this.tracks[a],this.hls.trigger(E.ERROR,{type:se.MEDIA_ERROR,details:M.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:u,sourceBufferName:a,mimeType:d,parent:o.id});return}this.trackSourceBuffer(a,o)}}this.bufferCreated()}getTrackCodec(e,t){let s=e.supplemental,r=e.codec;s&&(t==="video"||t==="audiovideo")&&Bo(s,"video")&&(r=JR(r,s));let n=iu(r,e.levelCodec);return n?t.slice(0,5)==="audio"?cu(n,this.appendSource):n:""}trackSourceBuffer(e,t){let s=t.buffer;if(!s)return;let r=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,codec:r,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(n,a)=>{let o=a.removedRanges;o!=null&&o.length&&this.hls.trigger(E.BUFFER_FLUSHED,{type:n})})}get mediaSrc(){var e,t;let s=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return s==null?void 0:s.src}onSBUpdateStart(e){let t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}let s=this.currentOp(e);s&&(s.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var s;let r=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(s=this.mediaSource)==null?void 0:s.readyState}`);this.error(`${r}`,t),this.hls.trigger(E.ERROR,{type:se.MEDIA_ERROR,details:M.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});let n=this.currentOp(e);n&&n.onError(r)}updateTimestampOffset(e,t,s,r,n,a){let o=t-e.timestampOffset;Math.abs(o)>=s&&(this.log(`Updating ${r} SourceBuffer timestampOffset to ${t} (sn: ${n} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,s){let{media:r,mediaSource:n}=this,a=this.tracks[e],o=a==null?void 0:a.buffer;if(!r||!n||!o){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}let l=Q(r.duration)?r.duration:1/0,d=Q(n.duration)?n.duration:1/0,u=Math.max(0,t),c=Math.min(s,l,d);c>u&&(!a.ending||a.ended)?(a.ended=!1,this.log(`Removing [${u},${c}] from the ${e} SourceBuffer`),o.remove(u,c)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){let s=this.tracks[t],r=s==null?void 0:s.buffer;if(!r)throw new pp(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);s.ending=!1,s.ended=!1,r.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);let{operationQueue:s}=this,r=t.map(a=>this.appendBlocker(a));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(r).then(a=>{s===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var s;let r=(s=this.tracks[t])==null?void 0:s.buffer;!r||r.updating||this.shiftAndExecuteNext(t)})}append(e,t,s){this.operationQueue&&this.operationQueue.append(e,t,s)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,s){let r=this.tracks[e];if(!r)return;let n=r.buffer;if(!n)return;let a=s.bind(this,e);r.listeners.push({event:t,listener:a}),n.addEventListener(t,a)}removeBufferListeners(e){let t=this.tracks[e];if(!t)return;let s=t.buffer;s&&(t.listeners.forEach(r=>{s.removeEventListener(r.event,r.listener)}),t.listeners.length=0)}};function My(i){let e=i.querySelectorAll("source");[].slice.call(e).forEach(t=>{i.removeChild(t)})}function $k(i,e){let t=self.document.createElement("source");t.type="video/mp4",t.src=e,i.appendChild(t)}function bm(i){return i==="audio"?1:0}var Qo=class i{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(E.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.BUFFER_CODECS,this.onBufferCodecs,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){let{hls:e}=this;e.off(E.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.BUFFER_CODECS,this.onBufferCodecs,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){let s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.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 s=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,s.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&Q(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}let e=this.hls.levels;if(e.length){let t=this.hls,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){let t=this.hls.levels;if(!t.length)return-1;let s=t.filter((r,n)=>this.isLevelAllowed(r)&&n<=e);return this.clientRect=null,i.getMaxLevelByMediaSize(s,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 s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,!t.width&&!t.height&&(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(s=>e.bitrate===s.bitrate&&e.width===s.width&&e.height===s.height)}static getMaxLevelByMediaSize(e,t,s){if(!(e!=null&&e.length))return-1;let r=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0,n=e.length-1,a=Math.max(t,s);for(let o=0;o<e.length;o+=1){let l=e[o];if((l.width>=a||l.height>=a)&&r(l,e[o+1])){n=o;break}}return n}},Hk={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},jt=Hk,Gk={HLS:"h"},Kk=Gk,Ds=class i{constructor(e,t){Array.isArray(e)&&(e=e.map(s=>s instanceof i?s:new i(s))),this.value=e,this.params=t}},Vk="Dict";function Wk(i){return Array.isArray(i)?JSON.stringify(i):i instanceof Map?"Map{}":i instanceof Set?"Set{}":typeof i=="object"?JSON.stringify(i):String(i)}function qk(i,e,t,s){return new Error(`failed to ${i} "${Wk(e)}" as ${t}`,{cause:s})}function es(i,e,t){return qk("serialize",i,e,t)}var Ru=class{constructor(e){this.description=e}},Py="Bare Item",Yk="Boolean";function jk(i){if(typeof i!="boolean")throw es(i,Yk);return i?"?1":"?0"}function zk(i){return btoa(String.fromCharCode(...i))}var Qk="Byte Sequence";function Xk(i){if(ArrayBuffer.isView(i)===!1)throw es(i,Qk);return`:${zk(i)}:`}var Zk="Integer";function Jk(i){return i<-999999999999999||999999999999999<i}function QT(i){if(Jk(i))throw es(i,Zk);return i.toString()}function eD(i){return`@${QT(i.getTime()/1e3)}`}function XT(i,e){if(i<0)return-XT(-i,e);let t=Math.pow(10,e);if(Math.abs(i*t%1-.5)<Number.EPSILON){let r=Math.floor(i*t);return(r%2===0?r:r+1)/t}else return Math.round(i*t)/t}var tD="Decimal";function iD(i){let e=XT(i,3);if(Math.floor(Math.abs(e)).toString().length>12)throw es(i,tD);let t=e.toString();return t.includes(".")?t:`${t}.0`}var sD="String",rD=/[\x00-\x1f\x7f]+/;function nD(i){if(rD.test(i))throw es(i,sD);return`"${i.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function aD(i){return i.description||i.toString().slice(7,-1)}var oD="Token";function Oy(i){let e=aD(i);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw es(e,oD);return e}function vp(i){switch(typeof i){case"number":if(!Q(i))throw es(i,Py);return Number.isInteger(i)?QT(i):iD(i);case"string":return nD(i);case"symbol":return Oy(i);case"boolean":return jk(i);case"object":if(i instanceof Date)return eD(i);if(i instanceof Uint8Array)return Xk(i);if(i instanceof Ru)return Oy(i);default:throw es(i,Py)}}var lD="Key";function Ep(i){if(/^[a-z*][a-z0-9\-_.*]*$/.test(i)===!1)throw es(i,lD);return i}function dg(i){return i==null?"":Object.entries(i).map(([e,t])=>t===!0?`;${Ep(e)}`:`;${Ep(e)}=${vp(t)}`).join("")}function ZT(i){return i instanceof Ds?`${vp(i.value)}${dg(i.params)}`:vp(i)}function dD(i){return`(${i.value.map(ZT).join(" ")})${dg(i.params)}`}function uD(i,e={whitespace:!0}){if(typeof i!="object"||i==null)throw es(i,Vk);let t=i instanceof Map?i.entries():Object.entries(i),s=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([r,n])=>{n instanceof Ds||(n=new Ds(n));let a=Ep(r);return n.value===!0?a+=dg(n.params):(a+="=",Array.isArray(n.value)?a+=dD(n):a+=ZT(n)),a}).join(`,${s}`)}function JT(i,e){return uD(i,e)}var Qi="CMCD-Object",nt="CMCD-Request",zr="CMCD-Session",ir="CMCD-Status",cD={br:Qi,ab:Qi,d:Qi,ot:Qi,tb:Qi,tpb:Qi,lb:Qi,tab:Qi,lab:Qi,url:Qi,pb:nt,bl:nt,tbl:nt,dl:nt,ltc:nt,mtp:nt,nor:nt,nrr:nt,rc:nt,sn:nt,sta:nt,su:nt,ttfb:nt,ttfbb:nt,ttlb:nt,cmsdd:nt,cmsds:nt,smrt:nt,df:nt,cs:nt,ts:nt,cid:zr,pr:zr,sf:zr,sid:zr,st:zr,v:zr,msd:zr,bs:ir,bsd:ir,cdn:ir,rtp:ir,bg:ir,pt:ir,ec:ir,e:ir},hD={REQUEST:nt};function fD(i){return Object.keys(i).reduce((e,t)=>{var s;return(s=i[t])===null||s===void 0||s.forEach(r=>e[r]=t),e},{})}function mD(i,e){let t={};if(!i)return t;let s=Object.keys(i),r=e?fD(e):{};return s.reduce((n,a)=>{var o;let l=cD[a]||r[a]||hD.REQUEST,d=(o=n[l])!==null&&o!==void 0?o:n[l]={};return d[a]=i[a],n},t)}function pD(i){return["ot","sf","st","e","sta"].includes(i)}function gD(i){return typeof i=="number"?Q(i):i!=null&&i!==""&&i!==!1}var eb="event";function vD(i,e){let t=new URL(i),s=new URL(e);if(t.origin!==s.origin)return i;let r=t.pathname.split("/").slice(1),n=s.pathname.split("/").slice(1,-1);for(;r[0]===n[0];)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")+t.search+t.hash}var au=i=>Math.round(i),yp=(i,e)=>Array.isArray(i)?i.map(t=>yp(t,e)):i instanceof Ds&&typeof i.value=="string"?new Ds(yp(i.value,e),i.params):(e.baseUrl&&(i=vD(i,e.baseUrl)),e.version===1?encodeURIComponent(i):i),zd=i=>au(i/100)*100,ED=(i,e)=>{let t=i;return e.version>=2&&(i instanceof Ds&&typeof i.value=="string"?t=new Ds([i]):typeof i=="string"&&(t=[i])),yp(t,e)},yD={br:au,d:au,bl:zd,dl:zd,mtp:zd,nor:ED,rtp:zd,tb:au},tb="request",ib="response",ug=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],TD=["e"],bD=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Uu(i){return bD.test(i)}function _D(i){return ug.includes(i)||TD.includes(i)||Uu(i)}var sb=["d","dl","nor","ot","rtp","su"];function AD(i){return ug.includes(i)||sb.includes(i)||Uu(i)}var SD=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function ID(i){return ug.includes(i)||sb.includes(i)||SD.includes(i)||Uu(i)}var LD=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function RD(i){return LD.includes(i)||Uu(i)}var xD={[ib]:ID,[eb]:_D,[tb]:AD};function rb(i,e={}){let t={};if(i==null||typeof i!="object")return t;let s=e.version||i.v||1,r=e.reportingMode||tb,n=s===1?RD:xD[r],a=Object.keys(i).filter(n),o=e.filter;typeof o=="function"&&(a=a.filter(o));let l=r===ib||r===eb;l&&!a.includes("ts")&&a.push("ts"),s>1&&!a.includes("v")&&a.push("v");let d=$e({},yD,e.formatters),u={version:s,reportingMode:r,baseUrl:e.baseUrl};return a.sort().forEach(c=>{let h=i[c],f=d[c];if(typeof f=="function"&&(h=f(h,u)),c==="v"){if(s===1)return;h=s}c=="pr"&&h===1||(l&&c==="ts"&&!Q(h)&&(h=Date.now()),gD(h)&&(pD(c)&&typeof h=="string"&&(h=new Ru(h)),t[c]=h))}),t}function kD(i,e={}){let t={};if(!i)return t;let s=rb(i,e),r=mD(s,e==null?void 0:e.customHeaderMap);return Object.entries(r).reduce((n,[a,o])=>{let l=JT(o,{whitespace:!1});return l&&(n[a]=l),n},t)}function DD(i,e,t){return $e(i,kD(e,t))}var CD="CMCD";function wD(i,e={}){return i?JT(rb(i,e),{whitespace:!1}):""}function MD(i,e={}){if(!i)return"";let t=wD(i,e);return encodeURIComponent(t)}function PD(i,e={}){if(!i)return"";let t=MD(i,e);return`${CD}=${t}`}var Ny=/CMCD=[^&#]+/;function OD(i,e,t){let s=PD(e,t);if(!s)return i;if(Ny.test(i))return i.replace(Ny,s);let r=i.includes("?")?"&":"?";return`${i}${r}${s}`}var Tp=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=r=>{try{this.apply(r,{ot:jt.MANIFEST,su:!this.initialized})}catch(n){this.hls.logger.warn("Could not generate manifest CMCD data.",n)}},this.applyFragmentData=r=>{try{let{frag:n,part:a}=r,o=this.hls.levels[n.level],l=this.getObjectType(n),d={d:(a||n).duration*1e3,ot:l};(l===jt.VIDEO||l===jt.AUDIO||l==jt.MUXED)&&(d.br=o.bitrate/1e3,d.tb=this.getTopBandwidth(l)/1e3,d.bl=this.getBufferLength(l));let u=a?this.getNextPart(a):this.getNextFrag(n);u!=null&&u.url&&u.url!==n.url&&(d.nor=u.url),this.apply(r,d)}catch(n){this.hls.logger.warn("Could not generate segment CMCD data.",n)}},this.hls=e;let t=this.config=e.config,{cmcd:s}=t;s!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||e.sessionId,this.cid=s.contentId,this.useHeaders=s.useHeaders===!0,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){let e=this.hls;e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHED,this.onMediaDetached,this),e.on(E.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){let e=this.hls;e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHED,this.onMediaDetached,this),e.off(E.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var s,r;this.audioBuffer=(s=t.tracks.audio)==null?void 0:s.buffer,this.videoBuffer=(r=t.tracks.video)==null?void 0:r.buffer}createData(){var e;return{v:1,sf:Kk.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){$e(t,this.createData());let s=t.ot===jt.INIT||t.ot===jt.VIDEO||t.ot===jt.MUXED;this.starved&&s&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);let{includeKeys:r}=this;r&&(t=Object.keys(t).reduce((a,o)=>(r.includes(o)&&(a[o]=t[o]),a),{}));let n={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),DD(e.headers,t,n)):e.url=OD(e.url,t,n)}getNextFrag(e){var t;let s=(t=this.hls.levels[e.level])==null?void 0:t.details;if(s){let r=e.sn-s.startSN;return s.fragments[r+1]}}getNextPart(e){var t;let{index:s,fragment:r}=e,n=(t=this.hls.levels[r.level])==null||(t=t.details)==null?void 0:t.partList;if(n){let{sn:a}=r;for(let o=n.length-1;o>=0;o--){let l=n[o];if(l.index===s&&l.fragment.sn===a)return n[o+1]}}}getObjectType(e){let{type:t}=e;if(t==="subtitle")return jt.TIMED_TEXT;if(e.sn==="initSegment")return jt.INIT;if(t==="audio")return jt.AUDIO;if(t==="main")return this.hls.audioTracks.length?jt.VIDEO:jt.MUXED}getTopBandwidth(e){let t=0,s,r=this.hls;if(e===jt.AUDIO)s=r.audioTracks;else{let n=r.maxAutoLevel,a=n>-1?n+1:r.levels.length;s=r.levels.slice(0,a)}return s.forEach(n=>{n.bitrate>t&&(t=n.bitrate)}),t>0?t:NaN}getBufferLength(e){let t=this.media,s=e===jt.AUDIO?this.audioBuffer:this.videoBuffer;return!s||!t?NaN:Ee.bufferInfo(s,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new s(n)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(n,a,o){t(n),this.loader.load(n,a,o)}}}createFragmentLoader(){let{fLoader:e}=this.config,t=this.applyFragmentData,s=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new s(n)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(n,a,o){t(n),this.loader.load(n,a,o)}}}},ND=3e5,bp=class extends Qt{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){let e=this.hls;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){let e=this.hls;e&&(e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){let e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){let t=this.levels;t&&(this.levels=t.filter(s=>s!==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:s}=t;s!==null&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){let{errorAction:s}=t;if((s==null?void 0:s.action)===Rt.SendAlternateToPenaltyBox&&s.flags===ni.MoveAllAlternatesMatchingHost){let r=this.levels,n=this._pathwayPriority,a=this.pathwayId;if(t.context){let{groupId:o,pathwayId:l,type:d}=t.context;o&&r?a=this.getPathwayForGroupId(o,d,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&r&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),s.resolved=this.pathwayId!==a),t.details===M.BUFFER_APPEND_ERROR&&!t.fatal?s.resolved=!0:s.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${r&&r.length} priorities: ${qe(n)} penalized: ${qe(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){let s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t,s=this.penalizedPathways,r=performance.now();Object.keys(s).forEach(n=>{r-s[n]>ND&&delete s[n]});for(let n=0;n<e.length;n++){let a=e[n];if(a in s)continue;if(a===this.pathwayId)return;let o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,xT(t),this.hls.trigger(E.LEVELS_UPDATED,{levels:t});let d=this.hls.levels[o];l&&d&&this.levels&&(d.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&d.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${d.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,s){let r=this.getLevelsForPathway(s).concat(this.levels||[]);for(let n=0;n<r.length;n++)if(t===Le.AUDIO_TRACK&&r[n].hasAudioGroup(e)||t===Le.SUBTITLE_TRACK&&r[n].hasSubtitleGroup(e))return r[n].pathwayId;return s}clonePathways(e){let t=this.levels;if(!t)return;let s={},r={};e.forEach(n=>{let{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=n;if(t.some(u=>u.pathwayId===a))return;let d=this.getLevelsForPathway(o).map(u=>{let c=new tt(u.attrs);c["PATHWAY-ID"]=a;let h=c.AUDIO&&`${c.AUDIO}_clone_${a}`,f=c.SUBTITLES&&`${c.SUBTITLES}_clone_${a}`;h&&(s[c.AUDIO]=h,c.AUDIO=h),f&&(r[c.SUBTITLES]=f,c.SUBTITLES=f);let m=nb(u.uri,c["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),p=new tn({attrs:c,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:m,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let g=1;g<u.audioGroups.length;g++)p.addGroupId("audio",`${u.audioGroups[g]}_clone_${a}`);if(u.subtitleGroups)for(let g=1;g<u.subtitleGroups.length;g++)p.addGroupId("text",`${u.subtitleGroups[g]}_clone_${a}`);return p});t.push(...d),Uy(this.audioTracks,s,l,a),Uy(this.subtitleTracks,r,l,a)})}loadSteeringManifest(e){let t=this.hls.config,s=t.loader;this.loader&&this.loader.destroy(),this.loader=new s(t);let r;try{r=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(r.protocol!=="data:"){let u=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;r.searchParams.set("_HLS_pathway",this.pathwayId),r.searchParams.set("_HLS_throughput",""+u)}let n={responseType:"json",url:r.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},d={onSuccess:(u,c,h,f)=>{this.log(`Loaded steering manifest: "${r}"`);let m=u.data;if((m==null?void 0:m.VERSION)!==1){this.log(`Steering VERSION ${m.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=m.TTL;let{"RELOAD-URI":p,"PATHWAY-CLONES":g,"PATHWAY-PRIORITY":v}=m;if(p)try{this.uri=new self.URL(p,r).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${p}`);return}this.scheduleRefresh(this.uri||h.url),g&&this.clonePathways(g);let T={steeringManifest:m,url:r.toString()};this.hls.trigger(E.STEERING_MANIFEST_LOADED,T),v&&this.updatePathwayPriority(v)},onError:(u,c,h,f)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${c.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${c.url} no longer available`);return}let m=this.timeToLoad*1e3;if(u.code===429){let p=this.loader;if(typeof(p==null?void 0:p.getResponseHeader)=="function"){let g=p.getResponseHeader("Retry-After");g&&(m=parseFloat(g)*1e3)}this.log(`Steering manifest ${c.url} rate limited`);return}this.scheduleRefresh(this.uri||c.url,m)},onTimeout:(u,c,h)=>{this.log(`Timeout loading steering manifest (${c.url})`),this.scheduleRefresh(this.uri||c.url)}};this.log(`Requesting steering manifest: ${r}`),this.loader.load(n,l,d)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var s;let r=(s=this.hls)==null?void 0:s.media;if(r&&!r.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}};function Uy(i,e,t,s){i&&Object.keys(e).forEach(r=>{let n=i.filter(a=>a.groupId===r).map(a=>{let o=$e({},a);return o.details=void 0,o.attrs=new tt(o.attrs),o.url=o.attrs.URI=nb(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[r],o.attrs["PATHWAY-ID"]=s,o});i.push(...n)})}function nb(i,e,t,s){let{HOST:r,PARAMS:n,[t]:a}=s,o;e&&(o=a==null?void 0:a[e],o&&(i=o));let l=new self.URL(i);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach(d=>{d&&l.searchParams.set(d,n[d])}),l.href}var xu=class i extends Qt{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=i.CDMCleanupPromise?[i.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{let{initDataType:s,initData:r}=t,n=`"${t.type}" event: init data type: "${s}"`;if(this.debug(n),r!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=Mo(this.config));let o=a.map(fm).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{let o=ru(a);if(s!=="sinf"||o!==it.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${s}" for selected key-system ${o}`);return}let l;try{let f=Tt(new Uint8Array(r)),m=ig(JSON.parse(f).sinf),p=nT(m);if(!p)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");l=new Uint8Array(p.subarray(8,24))}catch(f){this.warn(`${n} Failed to parse sinf: ${f}`);return}let d=Dt(l),{keyIdToKeySessionPromise:u,mediaKeySessions:c}=this,h=u[d];for(let f=0;f<c.length;f++){let m=c[f],p=m.decryptdata;if(!p.keyId)continue;let g=Dt(p.keyId);if(yu(l,p.keyId)||p.uri.replace(/-/g,"").indexOf(d)!==-1){if(h=u[g],!h)continue;if(p.pssh)break;delete u[g],p.pssh=new Uint8Array(r),p.keyId=l,h=u[d]=h.then(()=>this.generateRequestWithPreferredKeySession(m,s,r,"encrypted-event-key-match")),h.catch(v=>this.handleError(v));break}}h||this.handleError(new Error(`Key ID ${d} not encountered in playlist. Key-system sessions ${c.length}.`))}).catch(a=>this.handleError(a))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();let e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(E.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(E.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(E.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(E.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(E.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(E.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){let{drmSystems:t,widevineLicenseUrl:s}=this.config,r=t==null?void 0:t[e];if(r)return r.licenseUrl;if(e===it.WIDEVINE&&s)return s}getLicenseServerUrlOrThrow(e){let t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){let{drmSystems:t}=this.config,s=t==null?void 0:t[e];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){let t=this.hls.levels,s=(a,o,l)=>!!a&&l.indexOf(a)===o,r=t.map(a=>a.audioCodec).filter(s),n=t.map(a=>a.videoCodec).filter(s);return r.length+n.length===0&&n.push("avc1.42e01e"),new Promise((a,o)=>{let l=d=>{let u=d.shift();this.getMediaKeysPromise(u,r,n).then(c=>a({keySystem:u,mediaKeys:c})).catch(c=>{d.length?l(d):c instanceof $t?o(c):o(new $t({type:se.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_NO_ACCESS,error:c,fatal:!0},c.message))})};l(e)})}requestMediaKeySystemAccess(e,t){let{requestMediaKeySystemAccessFunc:s}=this.config;if(typeof s!="function"){let r=`Configured requestMediaKeySystemAccess is not a function ${s}`;return TT===null&&self.location.protocol==="http:"&&(r=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(r))}return s(e,t)}getMediaKeysPromise(e,t,s){var r;let n=Px(e,t,s,this.config.drmSystemOptions||{}),a=this.keySystemAccessPromises[e],o=(r=a)==null?void 0:r.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${qe(n)}`),o=this.requestMediaKeySystemAccess(e,n);let l=a=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(d=>{this.log(`Failed to obtain access to key-system "${e}": ${d}`)}),o.then(d=>{this.log(`Access for key-system "${d.keySystem}" obtained`);let u=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);let c=l.mediaKeys=d.createMediaKeys().then(h=>(this.log(`Media-keys created for "${e}"`),l.hasMediaKeys=!0,u.then(f=>f?this.setMediaKeysServerCertificate(h,e,f):h)));return c.catch(h=>{this.error(`Failed to create media-keys for "${e}"}: ${h}`)}),c})}return o.then(()=>a.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:s}){this.log(`Creating key-system session "${t}" keyId: ${Dt(e.keyId||[])} keyUri: ${e.uri}`);let r=s.createSession(),n={decryptdata:e,keySystem:t,mediaKeys:s,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n}renewKeySession(e){let t=e.decryptdata;if(t.pssh){let s=this.createMediaKeySessionContext(e),r=Qd(t),n="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(s,n,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){let s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyId ${Dt(e.decryptdata.keyId||[])}
43
- } (data length: ${t.byteLength})`),s.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>fm(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:s})=>this.attemptSetMediaKeys(t,s))}selectKeySystem(e){return new Promise((t,s)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:r})=>{let n=fm(r);n?t(n):s(new Error(`Unable to find format for key-system "${r}"`))}).catch(s)})}selectKeySystemFormat(e){let t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){let t=Mo(this.config),s=e.map(ru).filter(r=>!!r&&t.indexOf(r)!==-1);return this.selectKeySystem(s)}getKeyStatus(e){let{mediaKeySessions:t}=this;for(let s=0;s<t.length;s++){let r=UD(e,t[s]);if(r)return r}}loadKey(e){let t=e.keyInfo.decryptdata,s=Qd(t),r=this.bannedKeyIds[s];if(r||this.getKeyStatus(t)==="internal-error"){let o=Fy(r||"internal-error",t);return this.handleError(o,e.frag),Promise.reject(o)}let n=`(keyId: ${s} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${n}`);let a=this.keyIdToKeySessionPromise[s];if(!a){let o=this.getKeySystemForKeyPromise(t).then(({keySystem:l,mediaKeys:d})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${n}`),this.attemptSetMediaKeys(l,d).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:l,mediaKeys:d,decryptdata:t}))))).then(l=>{let d="cenc",u=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(l,d,u,"playlist-key")});return o.catch(l=>this.handleError(l,e.frag)),this.keyIdToKeySessionPromise[s]=o,o}return a.catch(o=>{if(o instanceof $t){let l=Fe({},o.data);this.getKeyStatus(t)==="internal-error"&&(l.decryptdata=t);let d=new $t(l,o.message);this.handleError(d,e.frag)}}),a}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof $t){t&&(e.data.frag=t);let s=e.data.decryptdata;this.error(`${e.message}${s?` (${Dt(s.keyId||[])})`:""}`),this.hls.trigger(E.ERROR,e.data)}else this.error(e.message),this.hls.trigger(E.ERROR,{type:se.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){let t=Qd(e),s=this.keyIdToKeySessionPromise[t];if(!s){let r=ru(e.keyFormat),n=r?[r]:Mo(this.config);return this.attemptKeySystemAccess(n)}return s}getKeySystemSelectionPromise(e){if(e.length||(e=Mo(this.config)),e.length===0)throw new $t({type:se.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${qe({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();let s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);let r=Promise.all(s).then(()=>this.media?this.media.setMediaKeys(t):new Promise((n,a)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return a(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(n).catch(a)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(r),r.then(()=>{this.log(`Media-keys set for "${e}"`),s.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>s.indexOf(n)===-1)})}generateRequestWithPreferredKeySession(e,t,s,r){var n;let a=(n=this.config.drmSystems)==null||(n=n[e.keySystem])==null?void 0:n.generateRequest;if(a)try{let m=a.call(this.hls,t,s,e);if(!m)throw new Error("Invalid response from configured generateRequest filter");t=m.initDataType,s=m.initData?m.initData:null,e.decryptdata.pssh=s?new Uint8Array(s):null}catch(m){if(this.warn(m.message),this.hls&&this.hls.config.debug)throw m}if(s===null)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);let o=Qd(e.decryptdata),l=e.decryptdata.uri;this.log(`Generating key-session request for "${r}" keyId: ${o} URI: ${l} (init data type: ${t} length: ${s.byteLength})`);let d=new sg,u=e._onmessage=m=>{let p=e.mediaKeysSession;if(!p){d.emit("error",new Error("invalid state"));return}let{messageType:g,message:v}=m;this.log(`"${g}" message event for session "${p.sessionId}" message size: ${v.byteLength}`),g==="license-request"||g==="license-renewal"?this.renewLicense(e,v).catch(T=>{d.eventNames().length?d.emit("error",T):this.handleError(T)}):g==="license-release"?e.keySystem===it.FAIRPLAY&&this.updateKeySession(e,jm("acknowledged")).then(()=>this.removeSession(e)).catch(T=>this.handleError(T)):this.warn(`unhandled media key message type "${g}"`)},c=(m,p)=>{p.keyStatus=m;let g;m.startsWith("usable")?d.emit("resolved"):m==="internal-error"||m==="output-restricted"||m==="output-downscaled"?g=Fy(m,p.decryptdata):m==="expired"?g=new Error(`key expired (keyId: ${o})`):m==="released"?g=new Error("key released"):m==="status-pending"||this.warn(`unhandled key status change "${m}" (keyId: ${o})`),g&&(d.eventNames().length?d.emit("error",g):this.handleError(g))},h=e._onkeystatuseschange=m=>{if(!e.mediaKeysSession){d.emit("error",new Error("invalid state"));return}let g=this.getKeyStatuses(e);if(!Object.keys(g).some(b=>g[b]!=="status-pending"))return;if(g[o]==="expired"){this.log(`Expired key ${qe(g)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let T=g[o];if(T)c(T,e);else{var y;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(y=e.keyStatusTimeouts)[o]||(y[o]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;let A=this.getKeyStatus(e.decryptdata);if(A&&A!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${A} from other session.`),c(A,e);this.log(`key status for ${o} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),T="internal-error",c(T,e)},1e3)),this.log(`No status for keyId ${o} (${qe(g)}).`)}};Ht(e.mediaKeysSession,"message",u),Ht(e.mediaKeysSession,"keystatuseschange",h);let f=new Promise((m,p)=>{d.on("error",p),d.on("resolved",m)});return e.mediaKeysSession.generateRequest(t,s).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o} URI: ${l}`)}).catch(m=>{throw new $t({type:se.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_NO_SESSION,error:m,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${m}`)}).then(()=>f).catch(m=>(d.removeAllListeners(),this.removeSession(e).then(()=>{throw m}))).then(()=>(d.removeAllListeners(),e))}getKeyStatuses(e){let t={};return e.mediaKeysSession.keyStatuses.forEach((s,r)=>{if(typeof r=="string"&&typeof s=="object"){let o=r;r=s,s=o}let n="buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);if(e.keySystem===it.PLAYREADY&&n.length===16){let o=Dt(n);t[o]=s,ET(n)}let a=Dt(n);s==="internal-error"&&(this.bannedKeyIds[a]=s),this.log(`key status change "${s}" for keyStatuses keyId: ${a} key-session "${e.mediaKeysSession.sessionId}"`),t[a]=s}),t}fetchServerCertificate(e){let t=this.config,s=t.loader,r=new s(t),n=this.getServerCertificateUrl(e);return n?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{let l={responseType:"arraybuffer",url:n},d=t.certLoadPolicy.default,u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(h,f,m,p)=>{a(h.data)},onError:(h,f,m,p)=>{o(new $t({type:se.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:m,response:Fe({url:l.url,data:void 0},h)},`"${e}" certificate request failed (${n}). Status: ${h.code} (${h.text})`))},onTimeout:(h,f,m)=>{o(new $t({type:se.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:m,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${n})`))},onAbort:(h,f,m)=>{o(new Error("aborted"))}};r.load(l,u,c)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,s){return new Promise((r,n)=>{e.setServerCertificate(s).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${s.byteLength}) on "${t}"`),r(e)}).catch(a=>{n(new $t({type:se.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(s=>this.updateKeySession(e,new Uint8Array(s)).catch(r=>{throw new $t({type:se.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:r,fatal:!1},r.message)}))}unpackPlayReadyKeyMessage(e,t){let s=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!s.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;let r=new DOMParser().parseFromString(s,"application/xml"),n=r.querySelectorAll("HttpHeader");if(n.length>0){let u;for(let c=0,h=n.length;c<h;c++){var a,o;u=n[c];let f=(a=u.querySelector("name"))==null?void 0:a.textContent,m=(o=u.querySelector("value"))==null?void 0:o.textContent;f&&m&&e.setRequestHeader(f,m)}}let l=r.querySelector("Challenge"),d=l==null?void 0:l.textContent;if(!d)throw new Error("Cannot find <Challenge> in key message");return jm(atob(d))}setupLicenseXHR(e,t,s,r){let n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return n.call(this.hls,e,t,s,r)}).catch(a=>{if(!s.decryptdata)throw a;return e.open("POST",t,!0),n.call(this.hls,e,t,s,r)}).then(a=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:a||r})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){let s=this.config.keyLoadPolicy.default;return new Promise((r,n)=>{let a=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${a}`);let o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return n(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let l=o.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);let d=this.config.licenseResponseCallback;if(d)try{l=d.call(this.hls,o,a,e)}catch(u){this.error(u)}r(l)}else{let l=s.errorRetry,d=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>d||o.status>=400&&o.status<500)n(new $t({type:se.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{let u=d-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${u} attempts left`),this.requestLicense(e,t).then(r,n)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,t).then(({xhr:l,licenseChallenge:d})=>{e.keySystem==it.PLAYREADY&&(d=this.unpackPlayReadyKeyMessage(l,d)),l.send(d)}).catch(n)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let s=t.media;this.media=s,Ht(s,"encrypted",this.onMediaEncrypted),Ht(s,"waitingforkey",this.onWaitingForKey);let r=this.mediaResolved;r?r():this.mediaKeys=s.mediaKeys}onMediaDetached(){let e=this.media;e&&(zt(e,"encrypted",this.onMediaEncrypted),zt(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};let t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;let s=this.media,r=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,na.clearKeyUriToKeyIdMap();let n=r.length;i.CDMCleanupPromise=Promise.all(r.map(a=>this.removeSession(a)).concat((s==null||(e=s.setMediaKeys(null))==null?void 0:e.catch(a=>{this.log(`Could not clear media keys: ${a}`),this.hls&&this.hls.trigger(E.ERROR,{type:se.OTHER_ERROR,details:M.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${a}`)})}))||Promise.resolve())).catch(a=>{this.log(`Could not close sessions and clear media keys: ${a}`),this.hls&&this.hls.trigger(E.ERROR,{type:se.OTHER_ERROR,details:M.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${a}`)})}).then(()=>{n&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){let s=t.reduce((r,n)=>(r.indexOf(n.keyFormat)===-1&&r.push(n.keyFormat),r),[]);this.log(`Selecting key-system from session-keys ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s)}}removeSession(e){let{mediaKeysSession:t,licenseXhr:s,decryptdata:r}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${Dt((r==null?void 0:r.keyId)||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;let n=this.mediaKeySessions.indexOf(e);n>-1&&this.mediaKeySessions.splice(n,1);let{keyStatusTimeouts:a}=e;a&&Object.keys(a).forEach(d=>self.clearTimeout(a[d]));let{drmSystemOptions:o}=this.config;return(Nx(o)?new Promise((d,u)=>{self.setTimeout(()=>u(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(d).catch(u)}):Promise.resolve()).catch(d=>{this.log(`Could not remove session: ${d}`),this.hls&&this.hls.trigger(E.ERROR,{type:se.OTHER_ERROR,details:M.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${d}`)})}).then(()=>t.close()).catch(d=>{this.log(`Could not close session: ${d}`),this.hls&&this.hls.trigger(E.ERROR,{type:se.OTHER_ERROR,details:M.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${d}`)})})}return Promise.resolve()}};xu.CDMCleanupPromise=void 0;function Qd(i){if(!i)throw new Error("Could not read keyId of undefined decryptdata");if(i.keyId===null)throw new Error("keyId is null");return Dt(i.keyId)}function UD(i,e){if(i.keyId&&e.mediaKeysSession.keyStatuses.has(i.keyId))return e.mediaKeysSession.keyStatuses.get(i.keyId);if(i.matches(e.decryptdata))return e.keyStatus}var $t=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 Fy(i,e){let t=i==="output-restricted",s=t?M.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:M.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new $t({type:se.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${i}"`)}var _p=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(E.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(E.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(E.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){let s=this.hls.config;if(s.capLevelOnFPSDrop){let r=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=r,r&&typeof r.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){let r=performance.now();if(t){if(this.lastTime){let n=r-this.lastTime,a=s-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*a/n,d=this.hls;if(d.trigger(E.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:s}),l>0&&a>d.config.fpsDroppedMonitoringThreshold*o){let u=d.currentLevel;d.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(d.autoLevelCapping===-1||d.autoLevelCapping>=u)&&(u=u-1,d.trigger(E.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:d.currentLevel}),d.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=s,this.lastDecodedFrames=t}}checkFPSInterval(){let e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){let t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}};function ab(i,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=i,e.dispatchEvent(t)}function ob(i,e){let t=i.mode;if(t==="disabled"&&(i.mode="hidden"),i.cues&&!i.cues.getCueById(e.id))try{if(i.addCue(e),!i.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(s){Be.debug(`[texttrack-utils]: ${s}`);try{let r=new self.TextTrackCue(e.startTime,e.endTime,e.text);r.id=e.id,i.addCue(r)}catch(r){Be.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${r}`)}}t==="disabled"&&(i.mode=t)}function Zn(i,e){let t=i.mode;if(t==="disabled"&&(i.mode="hidden"),i.cues)for(let s=i.cues.length;s--;)e&&i.cues[s].removeEventListener("enter",e),i.removeCue(i.cues[s]);t==="disabled"&&(i.mode=t)}function Ap(i,e,t,s){let r=i.mode;if(r==="disabled"&&(i.mode="hidden"),i.cues&&i.cues.length>0){let n=BD(i.cues,e,t);for(let a=0;a<n.length;a++)(!s||s(n[a]))&&i.removeCue(n[a])}r==="disabled"&&(i.mode=r)}function FD(i,e){if(e<=i[0].startTime)return 0;let t=i.length-1;if(e>i[t].endTime)return-1;let s=0,r=t,n;for(;s<=r;)if(n=Math.floor((r+s)/2),e<i[n].startTime)r=n-1;else if(e>i[n].startTime&&s<t)s=n+1;else return n;return i[s].startTime-e<e-i[r].startTime?s:r}function BD(i,e,t){let s=[],r=FD(i,e);if(r>-1)for(let n=r,a=i.length;n<a;n++){let o=i[n];if(o.startTime>=e&&o.endTime<=t)s.push(o);else if(o.startTime>t)return s}return s}function ou(i){let e=[];for(let t=0;t<i.length;t++){let s=i[t];(s.kind==="subtitles"||s.kind==="captions")&&s.label&&e.push(i[t])}return e}var Sp=class extends jo{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.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null,s=ou(this.media.textTracks);for(let n=0;n<s.length;n++)if(s[n].mode==="hidden")t=s[n];else if(s[n].mode==="showing"){t=s[n];break}let r=this.findTrackForTextTrack(t);this.subtitleTrack!==r&&this.setSubtitleTrack(r)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){let{hls:e}=this;e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(E.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){let s=this.media;if(!s)return;let r=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,r)return;ou(s.textTracks).forEach(a=>{Zn(a)})}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:s,groupId:r,details:n}=t,a=this.tracksInGroup[s];if(!a||a.groupId!==r){this.warn(`Subtitle track with id:${s} and group:${r} not found in active group ${a==null?void 0:a.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Subtitle track ${s} "${a.name}" lang:${a.lang} group:${r} loaded [${n.startSN}-${n.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let s=t.subtitleGroups||null,r=this.groupIds,n=this.currentTrack;if(!s||(r==null?void 0:r.length)!==(s==null?void 0:s.length)||s!=null&&s.some(a=>(r==null?void 0:r.indexOf(a))===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;let a=this.tracks.filter(u=>!s||s.indexOf(u.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(u=>u.default)&&(this.selectDefaultTrack=!1),a.forEach((u,c)=>{u.id=c});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=a;let o=this.hls.config.subtitlePreference;if(!n&&o){this.selectDefaultTrack=!1;let u=Ji(o,a);if(u>-1)n=a[u];else{let c=Ji(o,this.tracks);n=this.tracks[c]}}let l=this.findTrackId(n);l===-1&&n&&(l=this.findTrackId(null));let d={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${s==null?void 0:s.join(",")}" group-id`),this.hls.trigger(E.SUBTITLE_TRACKS_UPDATED,d),l!==-1&&this.trackId===-1&&this.setSubtitleTrack(l)}}findTrackId(e){let t=this.tracksInGroup,s=this.selectDefaultTrack;for(let r=0;r<t.length;r++){let n=t[r];if(!(s&&!n.default||!s&&!e)&&(!e||Jr(n,e)))return r}if(e){for(let r=0;r<t.length;r++){let n=t[r];if(zo(e.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return r}for(let r=0;r<t.length;r++){let n=t[r];if(zo(e.attrs,n.attrs,["LANGUAGE"]))return r}}return-1}findTrackForTextTrack(e){if(e){let t=this.tracksInGroup;for(let s=0;s<t.length;s++){let r=t[s];if(hp(r,e))return s}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===Le.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;let t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){let s=this.currentTrack;if(s&&Jr(e,s))return s;let r=Ji(e,this.tracksInGroup);if(r>-1){let n=this.tracksInGroup[r];return this.setSubtitleTrack(r),n}else{if(s)return null;{let n=Ji(e,t);if(n>-1)return t[n]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let s=e.id,r=e.groupId,n=this.getUrlWithDirectives(e.url,t),a=e.details,o=a==null?void 0:a.age;this.log(`Loading subtitle ${s} "${e.name}" lang:${e.lang} group:${r}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${n}`),this.hls.trigger(E.SUBTITLE_TRACK_LOADING,{url:n,id:s,groupId:r,deliveryDirectives:t||null,track:e})}toggleTrackModes(){let{media:e}=this;if(!e)return;let t=ou(e.textTracks),s=this.currentTrack,r;if(s&&(r=t.filter(n=>hp(s,n))[0],r||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(t).forEach(n=>{n.mode!=="disabled"&&n!==r&&(n.mode="disabled")}),r){let n=this.subtitleDisplay?"showing":"hidden";r.mode!==n&&(r.mode=n)}}setSubtitleTrack(e){let t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!Q(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;let s=this.currentTrack,r=t[e]||null;if(this.trackId=e,this.currentTrack=r,this.toggleTrackModes(),!r){this.hls.trigger(E.SUBTITLE_TRACK_SWITCH,{id:e});return}let n=!!r.details&&!r.details.live;if(e===this.trackId&&r===s&&n)return;this.log(`Switching to subtitle-track ${e}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));let{id:a,groupId:o="",name:l,type:d,url:u}=r;this.hls.trigger(E.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:d,url:u});let c=this.switchParams(r.url,s==null?void 0:s.details,r.details);this.loadPlaylist(c)}};function $D(){try{return crypto.randomUUID()}catch{try{let e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let n=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(r=="x"?n:n&3|8).toString(16)})}}}function No(i){let e=5381,t=i.length;for(;t;)e=e*33^i.charCodeAt(--t);return(e>>>0).toString()}var sa=.025,ku=function(i){return i[i.Point=0]="Point",i[i.Range=1]="Range",i}({});function HD(i,e,t){return`${i.identifier}-${t+1}-${No(e)}`}var Ip=class{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;let s=this.playoutLimit;return e<=0||isNaN(s)?!1:s===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>s}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){let e=this.dateRange.startTime;if(this.snapOptions.out){let t=this.dateRange.tagAnchor;if(t)return _m(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;let e=this.dateRange.tagAnchor;if(e){let t=this.dateRange.startTime,s=_m(t,e);return t-s<.1}return!1}get resumptionOffset(){let e=this.resumeOffset,t=Q(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){let e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){let t=this.resumeAnchor;if(t)return _m(e,t)}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<sa))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){let e=this.playoutLimit,t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?ku.Range:ku.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return GD(this)}};function _m(i,e){return i-e.start<e.duration/2&&!(Math.abs(i-(e.start+e.duration))<sa)?e.start:e.start+e.duration}function lb(i,e,t){let s=new self.URL(i,t);return s.protocol!=="data:"&&s.searchParams.set("_HLS_primary_id",e),s}function Am(i,e){for(;(t=i.assetList[++e])!=null&&t.error;)var t;return e}function GD(i){return`["${i.identifier}" ${i.cue.pre?"<pre>":i.cue.post?"<post>":""}${i.timelineStart.toFixed(2)}-${i.resumeTime.toFixed(2)}]`}function Xn(i){let e=i.timelineStart,t=i.duration||0;return`["${i.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}var Lp=class{constructor(e,t,s,r){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(E.PLAYOUT_LIMIT_REACHED,{})};let n=this.hls=new e(t);this.interstitial=s,this.assetItem=r;let a=()=>{this.hasDetails=!0};n.once(E.LEVEL_LOADED,a),n.once(E.AUDIO_TRACK_LOADED,a),n.once(E.SUBTITLE_TRACK_LOADED,a),n.on(E.MEDIA_ATTACHING,(o,{media:l})=>{this.removeMediaListeners(),this.mediaAttached=l,this.interstitial.playoutLimit&&(l.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&n.on(E.BUFFER_APPENDED,()=>{let u=this.bufferedEnd;this.reachedPlayout(u)&&(this._bufferedEosTime=u,n.trigger(E.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){let e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=lb(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e)return!1;let s=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset,n=Ee.bufferInfo(e,r,0);return this.getAssetTime(n.end)>=s-.02}reachedPlayout(e){let s=this.interstitial.playoutLimit;return this.startOffset+e>=s}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){let e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;let t=Ee.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){let e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){let e=this.assetItem.duration;if(!e)return 0;let t=this.interstitial.playoutLimit;if(t){let s=t-this.startOffset;if(s>0&&s<e)return s}return e}get remaining(){let e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){let t=this.timelineOffset;if(e!==t){let s=e-t;if(Math.abs(s)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){let t=this.timelineOffset,s=this.duration;return Math.min(Math.max(0,e-t),s)}removeMediaListeners(){let e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){let e=this.hls;if(e&&this.hasDetails){e.stopLoad();let t=s=>delete s.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,s){var r;(r=this.hls)==null||r.on(e,t)}once(e,t,s){var r;(r=this.hls)==null||r.once(e,t)}off(e,t,s){var r;(r=this.hls)==null||r.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${Xn(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}},By=.033,Rp=class extends Qt{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((s,r)=>e<=r.startOffset&&t>r.startOffset?(delete r.error,s+1):s,0):0}get duration(){let e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let s=-1;e.nextEvent?s=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(s=this.findEventIndex(e.previousEvent.identifier)+1);let r=this.items;if(r)for(r[s]||(t===void 0&&(t=e.start),s=this.findItemIndexAtTime(t));s>=0&&(n=r[s])!=null&&n.event;){var n;s--}return s}findItemIndexAtTime(e,t){let s=this.items;if(s)for(let r=0;r<s.length;r++){let n=s[r];if(t&&t!=="primary"&&(n=n[t]),e===n.start||e>n.start&&e<n.end)return r}return-1}findJumpRestrictedIndex(e,t){let s=this.items;if(s)for(let r=e;r<=t&&s[r];r++){let n=s[r].event;if(n!=null&&n.restrictions.jump&&!n.appendInPlace)return r}return-1}findEventIndex(e){let t=this.items;if(t)for(let r=t.length;r--;){var s;if(((s=t[r].event)==null?void 0:s.identifier)===e)return r}return-1}findAssetIndex(e,t){let s=e.assetList,r=s.length;if(r>1)for(let n=0;n<r;n++){let a=s[n];if(!a.error){let o=a.timelineStart;if(t===o||t>o&&(t<o+(a.duration||0)||n===r-1))return n}}return 0}get assetIdAtEnd(){var e;let t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){let s=t.assetList,r=s[s.length-1];if(r)return r.identifier}return null}parseInterstitialDateRanges(e,t){let s=e.main.details,{dateRanges:r}=s,n=this.events,a=this.parseDateRanges(r,{url:s.url},t),o=Object.keys(r),l=n?n.filter(d=>!o.includes(d.identifier)):[];a.length&&a.sort((d,u)=>{let c=d.cue.pre,h=d.cue.post,f=u.cue.pre,m=u.cue.post;if(c&&!f)return-1;if(f&&!c||h&&!m)return 1;if(m&&!h)return-1;if(!c&&!f&&!h&&!m){let p=d.startTime,g=u.startTime;if(p!==g)return p-g}return d.dateRange.tagOrder-u.dateRange.tagOrder}),this.events=a,l.forEach(d=>{this.removeEvent(d)}),this.updateSchedule(e,l)}updateSchedule(e,t=[],s=!1){let r=this.events||[];if(r.length||t.length||this.length<2){let n=this.items,a=this.parseSchedule(r,e);(s||t.length||(n==null?void 0:n.length)!==a.length||a.some((l,d)=>Math.abs(l.playout.start-n[d].playout.start)>.005||Math.abs(l.playout.end-n[d].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(t,n))}}parseDateRanges(e,t,s){let r=[],n=Object.keys(e);for(let a=0;a<n.length;a++){let o=n[a],l=e[o];if(l.isInterstitial){let d=this.eventMap[o];d?d.setDateRange(l):(d=new Ip(l,t),this.eventMap[o]=d,s===!1&&(d.appendInPlace=s)),r.push(d)}}return r}parseSchedule(e,t){let s=[],r=t.main.details,n=r.live?1/0:r.edge,a=0;if(e=e.filter(l=>!l.error&&!(l.cue.once&&l.hasPlayed)),e.length){this.resolveOffsets(e,t);let l=0,d=0;if(e.forEach((u,c)=>{let h=u.cue.pre,f=u.cue.post,m=e[c-1]||null,p=u.appendInPlace,g=f?n:u.startOffset,v=u.duration,T=u.timelineOccupancy===ku.Range?v:0,y=u.resumptionOffset,b=(m==null?void 0:m.startTime)===g,A=g+u.cumulativeDuration,R=p?A+v:g+y;if(h||!f&&g<=0){let x=d;d+=T,u.timelineStart=A;let D=a;a+=v,s.push({event:u,start:A,end:R,playout:{start:D,end:a},integrated:{start:x,end:d}})}else if(g<=n){if(!b){let S=g-l;if(S>By){let C=l,P=d;d+=S;let N=a;a+=S;let $={previousEvent:e[c-1]||null,nextEvent:u,start:C,end:C+S,playout:{start:N,end:a},integrated:{start:P,end:d}};s.push($)}else S>0&&m&&(m.cumulativeDuration+=S,s[s.length-1].end=g)}f&&(R=A),u.timelineStart=A;let x=d;d+=T;let D=a;a+=v,s.push({event:u,start:A,end:R,playout:{start:D,end:a},integrated:{start:x,end:d}})}else return;let I=u.resumeTime;f||I>n?l=n:l=I}),l<n){var o;let u=l,c=d,h=n-l;d+=h;let f=a;a+=h,s.push({previousEvent:((o=s[s.length-1])==null?void 0:o.event)||null,nextEvent:null,start:l,end:u+h,playout:{start:f,end:a},integrated:{start:c,end:d}})}this.setDurations(n,a,d)}else s.push({previousEvent:null,nextEvent:null,start:0,end:n,playout:{start:0,end:n},integrated:{start:0,end:n}}),this.setDurations(n,n,n);return s}setDurations(e,t,s){this.durations={primary:e,playout:t,integrated:s}}resolveOffsets(e,t){let s=t.main.details,r=s.live?1/0:s.edge,n=0,a=-1;e.forEach((o,l)=>{let d=o.cue.pre,u=o.cue.post,c=d?0:u?r:o.startTime;this.updateAssetDurations(o),a===c?o.cumulativeDuration=n:(n=0,a=c),!u&&o.snapOptions.in&&(o.resumeAnchor=sn(null,s.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&l+1<e.length&&e[l+1].startTime-e[l].resumeTime<By&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));let f=Q(o.resumeOffset)?o.resumeOffset:o.duration;n+=f})}primaryCanResumeInPlaceAt(e,t){let s=e.resumeTime,r=e.startTime+e.resumptionOffset;return Math.abs(s-r)>sa?(this.log(`"${e.identifier}" resumption ${s} not aligned with estimated timeline end ${r}`),!1):!Object.keys(t).some(a=>{let o=t[a].details,l=o.edge;if(s>=l)return this.log(`"${e.identifier}" resumption ${s} past ${a} playlist end ${l}`),!1;let d=sn(null,o.fragments,s);if(!d)return this.log(`"${e.identifier}" resumption ${s} does not align with any fragments in ${a} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;let u=a==="audio"?.175:0;return Math.abs(d.start-s)<sa+u||Math.abs(d.end-s)<sa+u?!1:(this.log(`"${e.identifier}" resumption ${s} not aligned with ${a} fragment bounds (${d.start}-${d.end} sn: ${d.sn} cc: ${d.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;let t=e.timelineStart,s=0,r=!1,n=!1;for(let a=0;a<e.assetList.length;a++){let o=e.assetList[a],l=t+s;o.startOffset=s,o.timelineStart=l,r||(r=o.duration===null),n||(n=!!o.error);let d=o.error?0:o.duration||0;s+=d}r&&!n?e.duration=Math.max(s,e.duration):e.duration=s}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}};function Ci(i){return`[${i.event?'"'+i.event.identifier+'"':"primary"}: ${i.start.toFixed(2)}-${i.end.toFixed(2)}]`}var xp=class{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){let s=e.assetListUrl,r;try{r=lb(s,this.hls.sessionId,e.baseUrl)}catch(h){let f=this.assignAssetListError(e,M.ASSET_LIST_LOAD_ERROR,h,s);this.hls.trigger(E.ERROR,f);return}t&&r.protocol!=="data:"&&r.searchParams.set("_HLS_start_offset",""+t);let n=this.hls.config,a=n.loader,o=new a(n),l={responseType:"json",url:r.href},d=n.interstitialAssetListLoadPolicy.default,u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(h,f,m,p)=>{let g=h.data,v=g==null?void 0:g.ASSETS;if(!Array.isArray(v)){let T=this.assignAssetListError(e,M.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),m.url,f,p);this.hls.trigger(E.ERROR,T);return}e.assetListResponse=g,this.hls.trigger(E.ASSET_LIST_LOADED,{event:e,assetListResponse:g,networkDetails:p})},onError:(h,f,m,p)=>{let g=this.assignAssetListError(e,M.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${h.code} ${h.text} (${f.url})`),f.url,p,m);this.hls.trigger(E.ERROR,g)},onTimeout:(h,f,m)=>{let p=this.assignAssetListError(e,M.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,h,m);this.hls.trigger(E.ERROR,p)}};return o.load(l,u,c),this.hls.trigger(E.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,s,r,n,a){return e.error=s,{type:se.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:r,error:s,networkDetails:a,stats:n}}};function $y(i){var e;i==null||(e=i.play())==null||e.catch(()=>{})}function Xd(i,e){return`[${i}] Advancing timeline position to ${e}`}var kp=class extends Qt{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{let s=this.currentTime;if(s===void 0||this.playbackDisabled||!this.schedule)return;let r=s-this.timelinePos;if(Math.abs(r)<1/7056e5)return;let a=r<=-.01;this.timelinePos=s,this.bufferedPos=s;let o=this.playingItem;if(!o){this.checkBuffer();return}if(a&&this.schedule.resetErrorsInRange(s,s-r)&&this.updateSchedule(!0),this.checkBuffer(),a&&s<o.start||s>=o.end){var l;let f=this.findItemIndex(o),m=this.schedule.findItemIndexAtTime(s);if(m===-1&&(m=f+(a?-1:1),this.log(`seeked ${a?"back ":""}to position not covered by schedule ${s} (resolving from ${f} to ${m})`)),!this.isInterstitial(o)&&(l=this.media)!=null&&l.paused&&(this.shouldPlay=!1),!a&&m>f){let p=this.schedule.findJumpRestrictedIndex(f+1,m);if(p>f){this.setSchedulePosition(p);return}}this.setSchedulePosition(m);return}let d=this.playingAsset;if(!d){if(this.playingLastItem&&this.isInterstitial(o)){let f=o.event.assetList[0];f&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(s,f))}return}let u=d.timelineStart,c=d.duration||0;if(a&&s<u||s>=u+c){var h;(h=o.event)!=null&&h.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(s)),this.setScheduleToAssetAtTime(s,d)}},this.onTimeupdate=()=>{let s=this.currentTime;if(s===void 0||this.playbackDisabled)return;if(s>this.timelinePos)this.timelinePos=s,s>this.bufferedPos&&this.checkBuffer();else return;let r=this.playingItem;if(!r||this.playingLastItem)return;if(s>=r.end){this.timelinePos=r.end;let o=this.findItemIndex(r);this.setSchedulePosition(o+1)}let n=this.playingAsset;if(!n)return;let a=n.timelineStart+(n.duration||0);s>=a&&this.setScheduleToAssetAtTime(s,n)},this.onScheduleUpdate=(s,r)=>{let n=this.schedule;if(!n)return;let a=this.playingItem,o=n.events||[],l=n.items||[],d=n.durations,u=s.map(p=>p.identifier),c=!!(o.length||u.length);(c||r)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
44
- Schedule: ${l.map(p=>Ci(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Removed events ${u}`);let h=null,f=null;a&&(h=this.updateItem(a,this.timelinePos),this.itemsMatch(a,h)?this.playingItem=h:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);let m=this.bufferingItem;if(m&&(f=this.updateItem(m,this.bufferedPos),this.itemsMatch(m,f)?this.bufferingItem=f:m.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(m.event,null))),s.forEach(p=>{p.assetList.forEach(g=>{this.clearAssetPlayer(g.identifier,null)})}),this.playerQueue.forEach(p=>{if(p.interstitial.appendInPlace){let g=p.assetItem.timelineStart,v=p.timelineOffset-g;if(v)try{p.timelineOffset=g}catch(T){Math.abs(v)>sa&&this.warn(`${T} ("${p.assetId}" ${p.timelineOffset}->${g})`)}}}),c||r){if(this.hls.trigger(E.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:l.slice(0),durations:d,removedIds:u}),this.isInterstitial(a)&&u.includes(a.event.identifier)){this.warn(`Interstitial "${a.event.identifier}" removed while playing`),this.primaryFallback(a.event);return}a&&this.trimInPlace(h,a),m&&f!==h&&this.trimInPlace(f,m),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new xp(e),this.schedule=new Rp(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){let e=this.hls;e&&(e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(E.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(E.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(E.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(E.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(E.BUFFER_APPENDED,this.onBufferAppended,this),e.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(E.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(E.MEDIA_ENDED,this.onMediaEnded,this),e.on(E.ERROR,this.onError,this),e.on(E.DESTROYING,this.onDestroying,this))}unregisterListeners(){let e=this.hls;e&&(e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(E.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(E.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(E.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(E.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(E.BUFFER_CODECS,this.onBufferCodecs,this),e.off(E.BUFFER_APPENDED,this.onBufferAppended,this),e.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(E.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(E.MEDIA_ENDED,this.onMediaEnded,this),e.off(E.ERROR,this.onError,this),e.off(E.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){let e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){zt(e,"play",this.onPlay),zt(e,"pause",this.onPause),zt(e,"seeking",this.onSeeking),zt(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){let s=this.media=t.media;Ht(s,"seeking",this.onSeeking),Ht(s,"timeupdate",this.onTimeupdate),Ht(s,"play",this.onPlay),Ht(s,"pause",this.onPause)}onMediaAttached(e,t){let s=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,s===null)this.checkStart();else if(!r){this.clearScheduleState();let n=this.findItemIndex(s);this.setSchedulePosition(n)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){let s=!!t.transferMedia,r=this.media;if(this.media=null,!s&&(r&&this.removeMediaListeners(r),this.detachedData)){let n=this.getBufferingPlayer();n&&(this.log(`Removing schedule state for detachedData and ${n}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,n.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;let e=this,t=()=>e.bufferingItem||e.waitingItem,s=c=>c&&e.getAssetPlayer(c.identifier),r=(c,h,f,m,p)=>{if(c){let g=c[h].start,v=c.event;if(v){if(h==="playout"||v.timelineOccupancy!==ku.Point){let T=s(f);(T==null?void 0:T.interstitial)===v&&(g+=T.assetItem.startOffset+T[p])}}else{let T=m==="bufferedPos"?a():e[m];g+=T-c.start}return g}return 0},n=(c,h)=>{var f;if(c!==0&&h!=="primary"&&(f=e.schedule)!=null&&f.length){var m;let p=e.schedule.findItemIndexAtTime(c),g=(m=e.schedule.items)==null?void 0:m[p];if(g){let v=g[h].start-g.start;return c+v}}return c},a=()=>{let c=e.bufferedPos;return c===Number.MAX_VALUE?o("primary"):Math.max(c,0)},o=c=>{var h,f;return(h=e.primaryDetails)!=null&&h.live?e.primaryDetails.edge:((f=e.schedule)==null?void 0:f.durations[c])||0},l=(c,h)=>{var f,m;let p=e.effectivePlayingItem;if(p!=null&&(f=p.event)!=null&&f.restrictions.skip||!e.schedule)return;e.log(`seek to ${c} "${h}"`);let g=e.effectivePlayingItem,v=e.schedule.findItemIndexAtTime(c,h),T=(m=e.schedule.items)==null?void 0:m[v],y=e.getBufferingPlayer(),b=y==null?void 0:y.interstitial,A=b==null?void 0:b.appendInPlace,R=g&&e.itemsMatch(g,T);if(g&&(A||R)){let I=s(e.playingAsset),x=(I==null?void 0:I.media)||e.primaryMedia;if(x){let D=h==="primary"?x.currentTime:r(g,h,e.playingAsset,"timelinePos","currentTime"),S=c-D,C=(A?D:x.currentTime)+S;if(C>=0&&(!I||A||C<=I.duration)){x.currentTime=C;return}}}if(T){let I=c;if(h!=="primary"){let D=T[h].start,S=c-D;I=T.start+S}let x=!e.isInterstitial(T);if((!e.isInterstitial(g)||g.event.appendInPlace)&&(x||T.event.appendInPlace)){let D=e.media||(A?y==null?void 0:y.media:null);D&&(D.currentTime=I)}else if(g){let D=e.findItemIndex(g);if(v>D){let C=e.schedule.findJumpRestrictedIndex(D+1,v);if(C>D){e.setSchedulePosition(C);return}}let S=0;if(x)e.timelinePos=I,e.checkBuffer();else{let C=T.event.assetList,P=c-(T[h]||T).start;for(let N=C.length;N--;){let $=C[N];if($.duration&&P>=$.startOffset&&P<$.startOffset+$.duration){S=N;break}}}e.setSchedulePosition(v,S)}}},d=()=>{let c=e.effectivePlayingItem;if(e.isInterstitial(c))return c;let h=t();return e.isInterstitial(h)?h:null},u={get bufferedEnd(){let c=t(),h=e.bufferingItem;if(h&&h===c){var f;return r(h,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-h.playout.start||((f=e.bufferingAsset)==null?void 0:f.startOffset)||0}return 0},get currentTime(){let c=d(),h=e.effectivePlayingItem;return h&&h===c?r(h,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-h.playout.start:0},set currentTime(c){let h=d(),f=e.effectivePlayingItem;f&&f===h&&l(c+f.playout.start,"playout")},get duration(){let c=d();return c?c.playout.end-c.playout.start:0},get assetPlayers(){var c;let h=(c=d())==null?void 0:c.event.assetList;return h?h.map(f=>e.getAssetPlayer(f.identifier)):[]},get playingIndex(){var c;let h=(c=d())==null?void 0:c.event;return h&&e.effectivePlayingAsset?h.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return d()}};return this.manager={get events(){var c;return((c=e.schedule)==null||(c=c.events)==null?void 0:c.slice(0))||[]},get schedule(){var c;return((c=e.schedule)==null||(c=c.items)==null?void 0:c.slice(0))||[]},get interstitialPlayer(){return d()?u:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){let c=t();return e.findItemIndex(c)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){let c=e.effectivePlayingItem;return e.findItemIndex(c)},primary:{get bufferedEnd(){return a()},get currentTime(){let c=e.timelinePos;return c>0?c:0},set currentTime(c){l(c,"primary")},get duration(){return o("primary")},get seekableStart(){var c;return((c=e.primaryDetails)==null?void 0:c.fragmentStart)||0}},integrated:{get bufferedEnd(){return r(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return r(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(c){l(c,"integrated")},get duration(){return o("integrated")},get seekableStart(){var c;return n(((c=e.primaryDetails)==null?void 0:c.fragmentStart)||0,"integrated")}},skip:()=>{let c=e.effectivePlayingItem,h=c==null?void 0:c.event;if(h&&!h.restrictions.skip){let f=e.findItemIndex(c);if(h.appendInPlace){let m=c.playout.start+c.event.duration;l(m+.001,"playout")}else e.advanceAfterAssetEnded(h,f,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;let t=this.playingItem,s=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!s?!1:this.findItemIndex(t)===s.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;let s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let r=this.media;!r&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(r=this.primaryMedia);let n=(t=r)==null?void 0:t.currentTime;if(!(n===void 0||!Q(n)))return n}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){let s=this.getAssetPlayer(e);s&&this.transferMediaFromPlayer(s,t)}transferMediaFromPlayer(e,t){let s=e.interstitial.appendInPlace,r=e.media;if(s&&r===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&r){this.detachedData={media:r};return}let n=e.transferMedia();this.log(`transfer MediaSource from ${e} ${qe(n)}`),this.detachedData=n}else t&&r&&(this.shouldPlay||(this.shouldPlay=!r.paused))}transferMediaTo(e,t){var s,r;if(e.media===t)return;let n=null,a=this.hls,o=e!==a,l=o&&e.interstitial.appendInPlace,d=(s=this.detachedData)==null?void 0:s.mediaSource,u;if(a.media)l&&(n=a.transferMedia(),this.detachedData=n),u="Primary";else if(d){let m=this.getBufferingPlayer();m?(n=m.transferMedia(),u=`${m}`):u="detached MediaSource"}else u="detached media";if(!n){if(d)n=this.detachedData,this.log(`using detachedData: MediaSource ${qe(n)}`);else if(!this.detachedData||a.media===t){let m=this.playerQueue;m.length>1&&m.forEach(p=>{if(o&&p.interstitial.appendInPlace!==l){let g=p.interstitial;this.clearInterstitial(p.interstitial,null),g.appendInPlace=!1,g.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${g}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}let c=n&&"mediaSource"in n&&((r=n.mediaSource)==null?void 0:r.readyState)!=="closed",h=c&&n?n:t;this.log(`${c?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${u} (media.currentTime: ${t.currentTime})`);let f=this.schedule;if(h===n&&f){let m=o&&e.assetId===f.assetIdAtEnd;h.overrides={duration:f.duration,endOfStream:!o||m,cueRemoval:!o}}e.attachMedia(h)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){let e=this.schedule,t=e==null?void 0:e.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);let s=this.timelinePos,r=this.effectivePlayingItem;if(s===-1){let n=this.hls.startPosition;if(this.log(Xd("checkStart",n)),this.timelinePos=n,t.length&&t[0].cue.pre){let a=e.findEventIndex(t[0].identifier);this.setSchedulePosition(a)}else if(n>=0||!this.primaryLive){let a=this.timelinePos=n>0?n:0,o=e.findItemIndexAtTime(a);this.setSchedulePosition(o)}}else if(r&&!this.playingItem){let n=e.findItemIndex(r);this.setSchedulePosition(n)}}advanceAssetBuffering(e,t){let s=e.event,r=s.findAssetIndex(t),n=Am(s,r);if(!s.isAssetPastPlayoutLimit(n))this.bufferedToEvent(e,n);else if(this.schedule){var a;let o=(a=this.schedule.items)==null?void 0:a[this.findItemIndex(e)+1];o&&this.bufferedToItem(o)}}advanceAfterAssetEnded(e,t,s){let r=Am(e,s);if(e.isAssetPastPlayoutLimit(r)){if(this.schedule){let n=this.schedule.items;if(n){let a=t+1,o=n.length;if(a>=o){this.setSchedulePosition(-1);return}let l=e.resumeTime;this.timelinePos<l&&(this.log(Xd("advanceAfterAssetEnded",l)),this.timelinePos=l,e.appendInPlace&&this.advanceInPlace(l),this.checkBuffer(this.bufferedPos<l)),this.setSchedulePosition(a)}}}else{if(e.appendInPlace){let n=e.assetList[r];n&&this.advanceInPlace(n.timelineStart)}this.setSchedulePosition(t,r)}}setScheduleToAssetAtTime(e,t){let s=this.schedule;if(!s)return;let r=t.parentIdentifier,n=s.getEvent(r);if(n){let a=s.findEventIndex(r),o=s.findAssetIndex(n,e);this.advanceAfterAssetEnded(n,a,o-1)}}setSchedulePosition(e,t){var s;let r=(s=this.schedule)==null?void 0:s.items;if(!r||this.playbackDisabled)return;let n=e>=0?r[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${n&&Ci(n)}) pos: ${this.timelinePos}`);let a=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(a)){let u=a.event,c=this.playingAsset,h=c==null?void 0:c.identifier,f=h?this.getAssetPlayer(h):null;if(f&&h&&(!this.eventItemsMatch(a,n)||t!==void 0&&h!==u.assetList[t].identifier)){var l;let m=u.findAssetIndex(c);if(this.log(`INTERSTITIAL_ASSET_ENDED ${m+1}/${u.assetList.length} ${Xn(c)}`),this.endedAsset=c,this.playingAsset=null,this.hls.trigger(E.INTERSTITIAL_ASSET_ENDED,{asset:c,assetListIndex:m,event:u,schedule:r.slice(0),scheduleIndex:e,player:f}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(u,this.findItemIndex(this.playingItem),m);return}this.retreiveMediaSource(h,n),f.media&&!((l=this.detachedData)!=null&&l.mediaSource)&&f.detachMedia()}if(!this.eventItemsMatch(a,n)&&(this.endedItem=a,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${u} ${Ci(a)}`),u.hasPlayed=!0,this.hls.trigger(E.INTERSTITIAL_ENDED,{event:u,schedule:r.slice(0),scheduleIndex:e}),u.cue.once)){var d;this.updateSchedule();let m=(d=this.schedule)==null?void 0:d.items;if(n&&m){let p=this.findItemIndex(n);this.advanceSchedule(p,m,t,a,o)}return}}this.advanceSchedule(e,r,t,a,o)}advanceSchedule(e,t,s,r,n){let a=this.schedule;if(!a)return;let o=t[e]||null,l=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(u=>{let c=u.interstitial,h=a.findEventIndex(c.identifier);(h<e||h>e+1)&&this.clearInterstitial(c,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);let u=o.event;if(s===void 0){s=a.findAssetIndex(u,this.timelinePos);let m=Am(u,s-1);if(u.isAssetPastPlayoutLimit(m)||u.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(u,e,s);return}s=m}let c=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);let h=this.preloadAssets(u,s);if(this.eventItemsMatch(o,c||r)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${Ci(o)} ${u.appendInPlace?"append in place":""}`),this.hls.trigger(E.INTERSTITIAL_STARTED,{event:u,schedule:t.slice(0),scheduleIndex:e})),!u.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${u}`);return}if(u.assetListLoader&&(u.assetListLoader.destroy(),u.assetListLoader=void 0),!l){this.log(`Waiting for attachMedia to start Interstitial ${u}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;let f=u.assetList[s];if(!f){this.advanceAfterAssetEnded(u,e,s||0);return}if(h||(h=this.getAssetPlayer(f.identifier)),h===null||h.destroyed){let m=u.assetList.length;this.warn(`asset ${s+1}/${m} player destroyed ${u}`),h=this.createAssetPlayer(u,f,s),h.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&u.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(h,s,t,e,l),this.shouldPlay&&$y(h.media)}else o?(this.resumePrimary(o,e,r),this.shouldPlay&&$y(this.hls.media)):n&&this.isInterstitial(r)&&(this.endedItem=null,this.playingItem=r,r.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,s){var r,n;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${Ci(e)}`),!((r=this.detachedData)!=null&&r.mediaSource)){let o=this.timelinePos;(o<e.start||o>=e.end)&&(o=this.getPrimaryResumption(e,t),this.log(Xd("resumePrimary",o)),this.timelinePos=o),this.attachPrimary(o,e)}if(!s)return;let a=(n=this.schedule)==null?void 0:n.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Ci(e)}`),this.hls.trigger(E.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){let s=e.start;if(this.primaryLive){let r=this.primaryDetails;if(t===0)return this.hls.startPosition;if(r&&(s<r.fragmentStart||s>r.edge))return this.hls.liveSyncPosition||-1}return s}isAssetBuffered(e){let t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:Ee.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,s){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;let r=this.primaryMedia;if(!r)return;let n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,r),s&&this.startLoadingPrimaryAt(e,s)),s||(this.log(Xd("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,s))}startLoadingPrimaryAt(e,t){var s;let r=this.hls;!r.loadingEnabled||!r.media||Math.abs((((s=r.mainForwardBufferInfo)==null?void 0:s.start)||r.media.currentTime)-e)>.5?r.startLoad(e,t):r.bufferingEnabled||r.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(E.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(E.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;let s=this.hls.levels[t.level];if(!s.details)return;let r=Fe(Fe({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=r,this.schedule.parseInterstitialDateRanges(r,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){let s=this.hls.audioTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=Fe(Fe({},this.altSelection),{},{audio:s});return}let n=Fe(Fe({},r),{},{audio:s});this.mediaSelection=n}onSubtitleTrackUpdated(e,t){let s=this.hls.subtitleTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=Fe(Fe({},this.altSelection),{},{subtitles:s});return}let n=Fe(Fe({},r),{},{subtitles:s});this.mediaSelection=n}onAudioTrackSwitching(e,t){let s=QE(t);this.playerQueue.forEach(({hls:r})=>r&&(r.setAudioOption(t)||r.setAudioOption(s)))}onSubtitleTrackSwitch(e,t){let s=QE(t);this.playerQueue.forEach(({hls:r})=>r&&(r.setSubtitleOption(t)||t.id!==-1&&r.setSubtitleOption(s)))}onBufferCodecs(e,t){let s=t.tracks;s&&(this.requiredTracks=s)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){let s=this.playingItem;if(s&&!this.itemsMatch(s,this.bufferingItem)&&!this.isInterstitial(s)){let r=this.timelinePos;this.bufferedPos=r,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;let t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let r=0;r<t.length;r++){let n=t[r];if(n.cue.post){var s;let a=this.schedule.findEventIndex(n.identifier),o=(s=this.schedule.items)==null?void 0:s[a];this.isInterstitial(o)&&this.eventItemsMatch(o,this.bufferingItem)&&this.bufferedToItem(o,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){let t=this.playingItem;if(!this.playingLastItem&&t){let s=this.findItemIndex(t);this.setSchedulePosition(s+1)}else this.shouldPlay=!1}updateItem(e,t){var s;let r=(s=this.schedule)==null?void 0:s.items;if(e&&r){let n=this.findItemIndex(e,t);return r[n]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((n,a)=>{e.event.isAssetPastPlayoutLimit(a)&&this.clearAssetPlayer(n.identifier,null)});let s=e.end+.25,r=Ee.bufferInfo(this.primaryMedia,s,0);(r.end>s||(r.nextStart||0)>s)&&(this.log(`trim buffered interstitial ${Ci(e)} (was ${Ci(t)})`),this.attachPrimary(s,null,!0),this.flushFrontBuffer(s))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var s;return!!t&&(e===t||e.event.identifier===((s=t.event)==null?void 0:s.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;let s=this.mediaSelection;s&&((t=this.schedule)==null||t.updateSchedule(s,[],e))}checkBuffer(e){var t;let s=(t=this.schedule)==null?void 0:t.items;if(!s)return;let r=Ee.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=r.len<1),this.updateBufferedPos(r.end,s,e)}updateBufferedPos(e,t,s){let r=this.schedule,n=this.bufferingItem;if(this.bufferedPos>e||!r)return;if(t.length===1&&this.itemsMatch(t[0],n)){this.bufferedPos=e;return}let a=this.playingItem,o=this.findItemIndex(a),l=r.findItemIndexAtTime(e);if(this.bufferedPos<e){var d;let u=this.findItemIndex(n),c=Math.min(u+1,t.length-1),h=t[c];if((l===-1&&n&&e>=n.end||(d=h.event)!=null&&d.appendInPlace&&e+.01>=h.start)&&(l=c),this.isInterstitial(n)){let f=n.event;if(c-o>1&&f.appendInPlace===!1||f.assetList.length===0&&f.assetListLoader)return}if(this.bufferedPos=e,l>u&&l>o)this.bufferedToItem(h);else{let f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&h.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(h)&&this.preloadAssets(h.event,0)}}else s&&a&&!this.itemsMatch(a,n)&&(l===o?this.bufferedToItem(a):l===o+1&&this.bufferedToItem(t[l]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(r=>{let n=this.getAssetPlayer(r.identifier);return!(n!=null&&n.bufferedInPlaceToEnd(t))})}setBufferingItem(e){let t=this.bufferingItem,s=this.schedule;if(!this.itemsMatch(e,t)&&s){let{items:r,events:n}=s;if(!r||!n)return t;let a=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));let l=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Ci(e)}`+(t?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){let d=s.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((u,c)=>{let h=this.getAssetPlayer(u.identifier);h&&(c===d&&h.loadSource(),h.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(d=>d.pauseBuffering());this.hls.trigger(E.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:n.slice(0),schedule:r.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){let s=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(s!==null){this.bufferingAsset=null;let r=this.detachedData;r?r.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){let t=this.findItemIndex(e),s=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(s)}bufferedToEvent(e,t){let s=e.event,r=s.assetList.length===0&&!s.assetListLoader,n=s.cue.once;if(r||!n){let a=this.preloadAssets(s,t);if(a!=null&&a.interstitial.appendInPlace){let o=this.primaryMedia;o&&this.bufferAssetPlayer(a,o)}}}preloadAssets(e,t){let s=e.assetUrl,r=e.assetList.length,n=r===0&&!e.assetListLoader,a=e.cue.once;if(n){let l=e.timelineStart;if(e.appendInPlace){var o;let h=this.playingItem;!this.isInterstitial(h)&&(h==null||(o=h.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(l+.25)}let d,u=0;if(!this.playingItem&&this.primaryLive&&(u=this.hls.startPosition,u===-1&&(u=this.hls.liveSyncPosition||0)),u&&!(e.cue.pre||e.cue.post)){let h=u-l;h>0&&(d=Math.round(h*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${s?1:r} ${e}${d?` live-start: ${u} start-offset: ${d}`:""}`),s)return this.createAsset(e,0,0,l,e.duration,s);let c=this.assetListLoader.loadAssetList(e,d);c&&(e.assetListLoader=c)}else if(!a&&r){for(let d=t;d<r;d++){let u=e.assetList[d],c=this.getAssetPlayerQueueIndex(u.identifier);(c===-1||this.playerQueue[c].destroyed)&&!u.error&&this.createAssetPlayer(e,u,d)}let l=e.assetList[t];if(l){let d=this.getAssetPlayer(l.identifier);return d&&d.loadSource(),d}}return null}flushFrontBuffer(e){let t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(r=>{this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:r})})}getAssetPlayerQueueIndex(e){let t=this.playerQueue;for(let s=0;s<t.length;s++)if(e===t[s].assetId)return s;return-1}getAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){let{playerQueue:e,primaryMedia:t}=this;if(t){for(let s=0;s<e.length;s++)if(e[s].media===t)return e[s]}return null}createAsset(e,t,s,r,n,a){let o={parentIdentifier:e.identifier,identifier:HD(e,a,t),duration:n,startOffset:s,timelineStart:r,uri:a};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,s){let r=this.hls,n=r.userConfig,a=n.videoPreference,o=r.loadLevelObj||r.levels[r.currentLevel];(a||o)&&(a=$e({},a),o.videoCodec&&(a.videoCodec=o.videoCodec),o.videoRange&&(a.allowedVideoRanges=[o.videoRange]));let l=r.audioTracks[r.audioTrack],d=r.subtitleTracks[r.subtitleTrack],u=0;if(this.primaryLive||e.appendInPlace){let b=this.timelinePos-t.timelineStart;if(b>1){let A=t.duration;A&&b<A&&(u=b)}}let c=t.identifier,h=Fe(Fe({},n),{},{maxMaxBufferLength:Math.min(180,r.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:r.sessionId,assetPlayerId:c,abrEwmaDefaultEstimate:r.bandwidthEstimate,interstitialsController:void 0,startPosition:u,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:a,audioPreference:l||n.audioPreference,subtitlePreference:d||n.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(h.timelineOffset=t.timelineStart));let f=h.cmcd;f!=null&&f.sessionId&&f.contentId&&(h.cmcd=$e({},f,{contentId:No(t.uri)})),this.getAssetPlayer(c)&&this.warn(`Duplicate date range identifier ${e} and asset ${c}`);let m=new Lp(this.HlsPlayerClass,h,e,t);this.playerQueue.push(m),e.assetList[s]=t;let p=!0,g=b=>{if(b.live){var A;let x=new Error(`Interstitials MUST be VOD assets ${e}`),D={fatal:!0,type:se.OTHER_ERROR,details:M.INTERSTITIAL_ASSET_ITEM_ERROR,error:x},S=((A=this.schedule)==null?void 0:A.findEventIndex(e.identifier))||-1;this.handleAssetItemError(D,e,S,s,x.message);return}let R=b.edge-b.fragmentStart,I=t.duration;(p||I===null||R>I)&&(p=!1,this.log(`Interstitial asset "${c}" duration change ${I} > ${R}`),t.duration=R,this.updateSchedule())};m.on(E.LEVEL_UPDATED,(b,{details:A})=>g(A)),m.on(E.LEVEL_PTS_UPDATED,(b,{details:A})=>g(A)),m.on(E.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());let v=(b,A)=>{let R=this.getAssetPlayer(c);if(R&&A.tracks){R.off(E.BUFFER_CODECS,v),R.tracks=A.tracks;let I=this.primaryMedia;this.bufferingAsset===R.assetItem&&I&&!R.media&&this.bufferAssetPlayer(R,I)}};m.on(E.BUFFER_CODECS,v);let T=()=>{var b;let A=this.getAssetPlayer(c);if(this.log(`buffered to end of asset ${A}`),!A||!this.schedule)return;let R=this.schedule.findEventIndex(e.identifier),I=(b=this.schedule.items)==null?void 0:b[R];this.isInterstitial(I)&&this.advanceAssetBuffering(I,t)};m.on(E.BUFFERED_TO_END,T);let y=b=>()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;this.shouldPlay=!0;let R=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,R,b)};return m.once(E.MEDIA_ENDED,y(s)),m.once(E.PLAYOUT_LIMIT_REACHED,y(1/0)),m.on(E.ERROR,(b,A)=>{if(!this.schedule)return;let R=this.getAssetPlayer(c);if(A.details===M.BUFFER_STALLED_ERROR){if(R!=null&&R.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(A,e,this.schedule.findEventIndex(e.identifier),s,`Asset player error ${A.error} ${e}`)}),m.on(E.DESTROYING,()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;let A=new Error(`Asset player destroyed unexpectedly ${c}`),R={fatal:!0,type:se.OTHER_ERROR,details:M.INTERSTITIAL_ASSET_ITEM_ERROR,error:A};this.handleAssetItemError(R,e,this.schedule.findEventIndex(e.identifier),s,A.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Xn(t)}`),this.hls.trigger(E.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:m}),m}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(s=>{this.clearAssetPlayer(s.identifier,t)})}resetAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);let s=this.playerQueue[t];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(e,t){let s=this.getAssetPlayerQueueIndex(e);if(s!==-1){let r=this.playerQueue[s];this.log(`clear ${r} toSegment: ${t&&Ci(t)}`),this.transferMediaFromPlayer(r,t),this.playerQueue.splice(s,1),r.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,s,r,n){let{interstitial:a,assetItem:o,assetId:l}=e,d=a.assetList.length,u=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!u||u.identifier!==l)&&(u&&(this.clearAssetPlayer(u.identifier,s[r]),delete u.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${d} ${Xn(o)}`),this.hls.trigger(E.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:a,schedule:s.slice(0),scheduleIndex:r,player:e})),this.bufferAssetPlayer(e,n)}bufferAssetPlayer(e,t){var s,r;if(!this.schedule)return;let{interstitial:n,assetItem:a}=e,o=this.schedule.findEventIndex(n.identifier),l=(s=this.schedule.items)==null?void 0:s[o];if(!l)return;e.loadSource(),this.setBufferingItem(l),this.bufferingAsset=a;let d=this.getBufferingPlayer();if(d===e)return;let u=n.appendInPlace;if(u&&(d==null?void 0:d.interstitial.appendInPlace)===!1)return;let c=(d==null?void 0:d.tracks)||((r=this.detachedData)==null?void 0:r.tracks)||this.requiredTracks;if(u&&a!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(c&&!Xy(c,e.tracks)){let h=new Error(`Asset ${Xn(a)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(c)}')`),f={fatal:!0,type:se.OTHER_ERROR,details:M.INTERSTITIAL_ASSET_ITEM_ERROR,error:h},m=n.findAssetIndex(a);this.handleAssetItemError(f,n,o,m,h.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){let t=this.schedule,s=this.primaryMedia;if(!t||!s)return;let r=s.currentTime,n=t.findAssetIndex(e,r),a=e.assetList[n];if(a){let o=this.getAssetPlayer(a.identifier);if(o){let l=o.currentTime||r-a.timelineStart,d=o.duration-l;if(this.warn(`Stalled at ${l} of ${l+d} in ${o} ${e} (media.currentTime: ${r})`),l&&(d/s.playbackRate<.5||o.bufferedInPlaceToEnd(s))&&o.hls){let u=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,u,n)}}}}advanceInPlace(e){let t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,s,r,n){if(e.details===M.BUFFER_STALLED_ERROR)return;let a=t.assetList[r]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&Xn(a)} ${e.error}`),!this.schedule)return;let o=(a==null?void 0:a.identifier)||"",l=this.getAssetPlayerQueueIndex(o),d=this.playerQueue[l]||null,u=this.schedule.items,c=$e({},e,{fatal:!1,errorAction:ea(!0),asset:a,assetListIndex:r,event:t,schedule:u,scheduleIndex:s,player:d});if(this.hls.trigger(E.INTERSTITIAL_ASSET_ERROR,c),!e.fatal)return;let h=this.playingAsset,f=this.bufferingAsset,m=new Error(n);if(a&&(this.clearAssetPlayer(o,null),a.error=m),!t.assetList.some(p=>!p.error))t.error=m;else for(let p=r;p<t.assetList.length;p++)this.resetAssetPlayer(t.assetList[p].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):h&&h.identifier===o?this.advanceAfterAssetEnded(t,s,r):f&&f.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){let t=e.timelineStart,s=this.effectivePlayingItem,r=this.timelinePos;if(s){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${r} playing: ${Ci(s)} error: ${e.error}`),r===-1&&(r=this.hls.startPosition);let a=this.updateItem(s,r);this.itemsMatch(s,a)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(r===-1){this.checkStart();return}if(!this.schedule)return;let n=this.schedule.findItemIndexAtTime(r);this.setSchedulePosition(n)}onAssetListLoaded(e,t){var s,r;let n=t.event,a=n.identifier,o=t.assetListResponse.ASSETS;if(!((s=this.schedule)!=null&&s.hasEvent(a)))return;let l=n.timelineStart,d=n.duration,u=0;o.forEach((p,g)=>{let v=parseFloat(p.DURATION);this.createAsset(n,g,u,l+u,v,p.URI),u+=v}),n.duration=u,this.log(`Loaded asset-list with duration: ${u} (was: ${d}) ${n}`);let c=this.waitingItem,h=(c==null?void 0:c.event.identifier)===a;this.updateSchedule();let f=(r=this.bufferingItem)==null?void 0:r.event;if(h){var m;let p=this.schedule.findEventIndex(a),g=(m=this.schedule.items)==null?void 0:m[p];if(g){if(!this.playingItem&&this.timelinePos>g.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==p){n.error=new Error(`Interstitial ${o.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${n}`),this.log(n.error.message),this.updateSchedule(!0),this.primaryFallback(n);return}this.setBufferingItem(g)}this.setSchedulePosition(p)}else if((f==null?void 0:f.identifier)===a){let p=n.assetList[0];if(p){let g=this.getAssetPlayer(p.identifier);if(f.appendInPlace){let v=this.primaryMedia;g&&v&&this.bufferAssetPlayer(g,v)}else g&&g.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case M.ASSET_LIST_PARSING_ERROR:case M.ASSET_LIST_LOAD_ERROR:case M.ASSET_LIST_LOAD_TIMEOUT:{let s=t.interstitial;s&&(this.updateSchedule(!0),this.primaryFallback(s));break}case M.BUFFER_STALLED_ERROR:{let s=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&s.event.appendInPlace){this.handleInPlaceStall(s.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}},Hy=500,Dp=class extends Ko{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",J.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(E.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(E.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=O.IDLE,this.setInterval(Hy),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){let{frag:s,success:r}=t;if(this.fragContextChanged(s)||(at(s)&&(this.fragPrevious=s),this.state=O.IDLE),!r)return;let n=this.tracksBuffered[this.currentTrackId];if(!n)return;let a,o=s.start;for(let d=0;d<n.length;d++)if(o>=n[d].start&&o<=n[d].end){a=n[d];break}let l=s.start+s.duration;a?a.end=l:(a={start:o,end:l},n.push(a)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null),this.media&&this.tick()}onBufferFlushing(e,t){let{startOffset:s,endOffset:r}=t;if(s===0&&r!==Number.POSITIVE_INFINITY){let n=r-1;if(n<=0)return;t.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach(a=>{for(let o=0;o<a.length;){if(a[o].end<=n){a.shift();continue}else if(a[o].start<n)a[o].start=n;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(s,n,J.SUBTITLE)}}onError(e,t){let s=t.frag;(s==null?void 0:s.type)===J.SUBTITLE&&(t.details===M.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==O.STOPPED&&(this.state=O.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&jT(this.levels,t)){this.levels=t.map(s=>new tn(s));return}this.tracksBuffered=[],this.levels=t.map(s=>{let r=new tn(s);return this.tracksBuffered[r.id]=[],r}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,J.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,!((s=this.levels)!=null&&s.length)||this.currentTrackId===-1){this.clearInterval();return}let r=this.levels[this.currentTrackId];r!=null&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.state!==O.STOPPED&&this.setInterval(Hy)}onSubtitleTrackLoaded(e,t){var s;let{currentTrackId:r,levels:n}=this,{details:a,id:o}=t;if(!n){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}let l=n[o];if(o>=n.length||!l)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let d=0;if(a.live||(s=l.details)!=null&&s.live){if(a.deltaUpdateFailed)return;let c=this.mainDetails;if(!c){this.startFragRequested=!1;return}let h=c.fragments[0];if(!l.details)a.hasProgramDateTime&&c.hasProgramDateTime?(bu(a,c),d=a.fragmentStart):h&&(d=h.start,Qm(a,d));else{var u;d=this.alignPlaylists(a,l.details,(u=this.levelLastLoaded)==null?void 0:u.details),d===0&&h&&(d=h.start,Qm(a,d))}c&&!this.startFragRequested&&this.setStartPosition(c,d)}l.details=a,this.levelLastLoaded=l,o===r&&(this.hls.trigger(E.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:t.groupId}),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===O.IDLE&&(sn(null,a.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0)))}_handleFragmentLoadComplete(e){let{frag:t,payload:s}=e,r=t.decryptdata,n=this.hls;if(!this.fragContextChanged(t)&&s&&s.byteLength>0&&r!=null&&r.key&&r.iv&&ta(r.method)){let a=performance.now();this.decrypter.decrypt(new Uint8Array(s),r.key.buffer,r.iv.buffer,tg(r.method)).catch(o=>{throw n.trigger(E.ERROR,{type:se.MEDIA_ERROR,details:M.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:t}),o}).then(o=>{let l=performance.now();n.trigger(E.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:a,tdecrypt:l}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=O.IDLE})}}doTick(){if(!this.media){this.state=O.IDLE;return}if(this.state===O.IDLE){let{currentTrackId:e,levels:t}=this,s=t==null?void 0:t[e];if(!s||!t.length||!s.details||this.waitForLive(s))return;let{config:r}=this,n=this.getLoadPosition(),a=Ee.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,r.maxBufferHole),{end:o,len:l}=a,d=s.details,u=this.hls.maxBufferLength+d.levelTargetDuration;if(l>u)return;let c=d.fragments,h=c.length,f=d.edge,m=null,p=this.fragPrevious;if(o<f){let T=r.maxFragLookUpTolerance,y=o>f-T?0:T;m=sn(p,c,Math.max(c[0].start,o),y),!m&&p&&p.start<c[0].start&&(m=c[0])}else m=c[h-1];if(m=this.filterReplacedPrimary(m,s.details),!m)return;let g=m.sn-d.startSN,v=c[g-1];if(v&&v.cc===m.cc&&this.fragmentTracker.getState(v)===bt.NOT_LOADED&&(m=v),this.fragmentTracker.getState(m)===bt.NOT_LOADED){let T=this.mapToInitFragWhenRequired(m);T&&this.loadFragment(T,s,o)}}}loadFragment(e,t,s){at(e)?super.loadFragment(e,t,s):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new Cp(this.tracksBuffered[this.currentTrackId]||[])}},Cp=class{constructor(e){this.buffered=void 0;let t=(s,r,n)=>{if(r=r>>>0,r>n-1)throw new DOMException(`Failed to execute '${s}' on 'TimeRanges': The index provided (${r}) is greater than the maximum bound (${n})`);return e[r][s]};this.buffered={get length(){return e.length},end(s){return t("end",s,e.length)},start(s){return t("start",s,e.length)}}}},KD={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},db=i=>String.fromCharCode(KD[i]||i),wi=15,xs=100,VD={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},WD={17:2,18:4,21:6,22:8,23:10,19:13,20:15},qD={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},YD={25:2,26:4,29:6,30:8,31:10,27:13,28:15},jD=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],wp=class{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){let s=typeof t=="function"?t():t;Be.log(`${this.time} [${e}] ${s}`)}}},Qr=function(e){let t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t},Du=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 s=0;s<t.length;s++){let r=t[s];e.hasOwnProperty(r)&&(this[r]=e[r])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}},Mp=class{constructor(){this.uchar=" ",this.penState=new Du}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()}},Pp=class{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Du,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<xs;t++)this.chars.push(new Mp);this.logger=e}equals(e){for(let t=0;t<xs;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<xs;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<xs;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>xs&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=xs)}moveCursor(e){let t=this.pos+e;if(e>1)for(let s=this.pos+1;s<t+1;s++)this.chars[s].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=db(e);if(this.pos>=xs){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t<xs;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 s=0;s<xs;s++){let r=this.chars[s].uchar;r!==" "&&(t=!1),e.push(r)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}},Uo=class{constructor(e){this.rows=[],this.currRow=wi-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<wi;t++)this.rows.push(new Pp(e));this.logger=e}reset(){for(let e=0;e<wi;e++)this.rows[e].clear();this.currRow=wi-1}equals(e){let t=!0;for(let s=0;s<wi;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<wi;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<wi;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 = "+qe(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let o=0;o<wi;o++)this.rows[o].clear();let n=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){let o=a.rows[n].cueStartTime,l=this.logger.time;if(o!==null&&l!==null&&o<l)for(let d=0;d<this.nrRollUpRows;d++)this.rows[t-this.nrRollUpRows+d+1].copy(a.rows[n+d])}}this.currRow=t;let s=this.rows[this.currRow];if(e.indent!==null){let n=e.indent,a=Math.max(n-1,0);s.setCursor(e.indent),e.color=s.chars[a].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 = "+qe(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());let e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;let t=[],s="",r=-1;for(let n=0;n<wi;n++){let a=this.rows[n].getTextString();a&&(r=n+1,e?t.push("Row "+r+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(e?s="["+t.join(" | ")+"]":s=t.join(`
45
- `)),s}getTextAndFormat(){return this.rows}},Cu=class{constructor(e,t,s){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 Uo(s),this.nonDisplayedMemory=new Uo(s),this.lastOutputScreen=new Uo(s),this.currRollUpRow=this.displayedMemory.rows[wi-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[wi-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let s=0;s<e.length;s++)this.writeScreen.insertChar(e[s]);let t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(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"),this.mode==="MODE_POP-ON"){let e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!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 s=Math.floor(e/2)-16,r=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=r[s]}this.logger.log(2,"MIDROW: "+qe(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){let t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}},wu=class{constructor(e,t,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory=QD(),this.logger=void 0;let r=this.logger=new wp;this.channels=[null,new Cu(e,t,r),new Cu(e+1,s,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 s=0;s<t.length;s+=2){let r=t[s]&127,n=t[s+1]&127,a=!1,o=null;if(r===0&&n===0)continue;this.logger.log(3,()=>"["+Qr([t[s],t[s+1]])+"] -> ("+Qr([r,n])+")");let l=this.cmdHistory;if(r>=16&&r<=31){if(zD(r,n,l)){Zd(null,null,l),this.logger.log(3,()=>"Repeated command ("+Qr([r,n])+") is dropped");continue}Zd(r,n,this.cmdHistory),a=this.parseCmd(r,n),a||(a=this.parseMidrow(r,n)),a||(a=this.parsePAC(r,n)),a||(a=this.parseBackgroundAttributes(r,n))}else Zd(null,null,l);if(!a&&(o=this.parseChars(r,n),o)){let u=this.currentChannel;u&&u>0?this.channels[u].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+Qr([r,n])+" orig: "+Qr([t[s],t[s+1]]))}}parseCmd(e,t){let s=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,r=(e===23||e===31)&&t>=33&&t<=35;if(!(s||r))return!1;let n=e===20||e===21||e===23?1:2,a=this.channels[n];return e===20||e===21||e===28||e===29?t===32?a.ccRCL():t===33?a.ccBS():t===34?a.ccAOF():t===35?a.ccAON():t===36?a.ccDER():t===37?a.ccRU(2):t===38?a.ccRU(3):t===39?a.ccRU(4):t===40?a.ccFON():t===41?a.ccRDC():t===42?a.ccTR():t===43?a.ccRTD():t===44?a.ccEDM():t===45?a.ccCR():t===46?a.ccENM():t===47&&a.ccEOC():a.ccTO(t-32),this.currentChannel=n,!0}parseMidrow(e,t){let s=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?s=1:s=2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;let r=this.channels[s];return r?(r.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+Qr([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let s,r=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,n=(e===16||e===24)&&t>=64&&t<=95;if(!(r||n))return!1;let a=e<=23?1:2;t>=64&&t<=95?s=a===1?VD[e]:qD[e]:s=a===1?WD[e]:YD[e];let o=this.channels[a];return o?(o.setPAC(this.interpretPAC(s,t)),this.currentChannel=a,!0):!1}interpretPAC(e,t){let s,r={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?s=t-96:s=t-64,r.underline=(s&1)===1,s<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(r.italics=!0,r.color="white"):r.indent=Math.floor((s-16)/2)*4,r}parseChars(e,t){let s,r=null,n=null;if(e>=25?(s=2,n=e-8):(s=1,n=e),n>=17&&n<=19){let a;n===17?a=t+80:n===18?a=t+112:a=t+144,this.logger.log(2,()=>"Special char '"+db(a)+"' in channel "+s),r=[a]}else e>=32&&e<=127&&(r=t===0?[e]:[e,t]);return r&&this.logger.log(3,()=>"Char codes = "+Qr(r).join(",")),r}parseBackgroundAttributes(e,t){let s=(e===16||e===24)&&t>=32&&t<=47,r=(e===23||e===31)&&t>=45&&t<=47;if(!(s||r))return!1;let n,a={};e===16||e===24?(n=Math.floor((t-32)/2),a.background=jD[n],t%2===1&&(a.background=a.background+"_semi")):t===45?a.background="transparent":(a.foreground="black",t===47&&(a.underline=!0));let o=e<=23?1:2;return this.channels[o].setBkgData(a),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){let t=this.channels[e];t&&t.reset()}Zd(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){let s=this.channels[t];s&&s.cueSplitAtTime(e)}}};function Zd(i,e,t){t.a=i,t.b=e}function zD(i,e,t){return t.a===i&&t.b===e}function QD(){return{a:null,b:null}}var cg=function(){if(Tu!=null&&Tu.VTTCue)return self.VTTCue;let i=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,l){if(typeof l!="string"||!Array.isArray(o))return!1;let d=l.toLowerCase();return~o.indexOf(d)?d:!1}function s(o){return t(i,o)}function r(o){return t(e,o)}function n(o,...l){let d=1;for(;d<arguments.length;d++){let u=arguments[d];for(let c in u)o[c]=u[c]}return o}function a(o,l,d){let u=this,c={enumerable:!0};u.hasBeenReset=!1;let h="",f=!1,m=o,p=l,g=d,v=null,T="",y=!0,b="auto",A="start",R=50,I="middle",x=50,D="middle";Object.defineProperty(u,"id",n({},c,{get:function(){return h},set:function(S){h=""+S}})),Object.defineProperty(u,"pauseOnExit",n({},c,{get:function(){return f},set:function(S){f=!!S}})),Object.defineProperty(u,"startTime",n({},c,{get:function(){return m},set:function(S){if(typeof S!="number")throw new TypeError("Start time must be set to a number.");m=S,this.hasBeenReset=!0}})),Object.defineProperty(u,"endTime",n({},c,{get:function(){return p},set:function(S){if(typeof S!="number")throw new TypeError("End time must be set to a number.");p=S,this.hasBeenReset=!0}})),Object.defineProperty(u,"text",n({},c,{get:function(){return g},set:function(S){g=""+S,this.hasBeenReset=!0}})),Object.defineProperty(u,"region",n({},c,{get:function(){return v},set:function(S){v=S,this.hasBeenReset=!0}})),Object.defineProperty(u,"vertical",n({},c,{get:function(){return T},set:function(S){let C=s(S);if(C===!1)throw new SyntaxError("An invalid or illegal string was specified.");T=C,this.hasBeenReset=!0}})),Object.defineProperty(u,"snapToLines",n({},c,{get:function(){return y},set:function(S){y=!!S,this.hasBeenReset=!0}})),Object.defineProperty(u,"line",n({},c,{get:function(){return b},set:function(S){if(typeof S!="number"&&S!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");b=S,this.hasBeenReset=!0}})),Object.defineProperty(u,"lineAlign",n({},c,{get:function(){return A},set:function(S){let C=r(S);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");A=C,this.hasBeenReset=!0}})),Object.defineProperty(u,"position",n({},c,{get:function(){return R},set:function(S){if(S<0||S>100)throw new Error("Position must be between 0 and 100.");R=S,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",n({},c,{get:function(){return I},set:function(S){let C=r(S);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");I=C,this.hasBeenReset=!0}})),Object.defineProperty(u,"size",n({},c,{get:function(){return x},set:function(S){if(S<0||S>100)throw new Error("Size must be between 0 and 100.");x=S,this.hasBeenReset=!0}})),Object.defineProperty(u,"align",n({},c,{get:function(){return D},set:function(S){let C=r(S);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");D=C,this.hasBeenReset=!0}})),u.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}(),Op=class{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}};function ub(i){function e(s,r,n,a){return(s|0)*3600+(r|0)*60+(n|0)+parseFloat(a||0)}let t=i.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}var Np=class{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,s){return s?this.has(e)?this.values[e]:t[s]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,s){for(let r=0;r<s.length;++r)if(t===s[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 s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}};function cb(i,e,t,s){let r=s?i.split(s):[i];for(let n in r){if(typeof r[n]!="string")continue;let a=r[n].split(t);if(a.length!==2)continue;let o=a[0],l=a[1];e(o,l)}}var Up=new cg(0,0,""),Jd=Up.align==="middle"?"middle":"center";function XD(i,e,t){let s=i;function r(){let o=ub(i);if(o===null)throw new Error("Malformed timestamp: "+s);return i=i.replace(/^[^\sa-zA-Z-]+/,""),o}function n(o,l){let d=new Np;cb(o,function(h,f){let m;switch(h){case"region":for(let p=t.length-1;p>=0;p--)if(t[p].id===f){d.set(h,t[p].region);break}break;case"vertical":d.alt(h,f,["rl","lr"]);break;case"line":m=f.split(","),d.integer(h,m[0]),d.percent(h,m[0])&&d.set("snapToLines",!1),d.alt(h,m[0],["auto"]),m.length===2&&d.alt("lineAlign",m[1],["start",Jd,"end"]);break;case"position":m=f.split(","),d.percent(h,m[0]),m.length===2&&d.alt("positionAlign",m[1],["start",Jd,"end","line-left","line-right","auto"]);break;case"size":d.percent(h,f);break;case"align":d.alt(h,f,["start",Jd,"end","left","right"]);break}},/:/,/\s/),l.region=d.get("region",null),l.vertical=d.get("vertical","");let u=d.get("line","auto");u==="auto"&&Up.line===-1&&(u=-1),l.line=u,l.lineAlign=d.get("lineAlign","start"),l.snapToLines=d.get("snapToLines",!0),l.size=d.get("size",100),l.align=d.get("align",Jd);let c=d.get("position","auto");c==="auto"&&Up.position===50&&(c=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=c}function a(){i=i.replace(/^\s+/,"")}if(a(),e.startTime=r(),a(),i.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+s);i=i.slice(3),a(),e.endTime=r(),a(),n(i,e)}function hb(i){return i.replace(/<br(?: \/)?>/gi,`
46
- `)}var Fp=class{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Op,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){let t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function s(){let n=t.buffer,a=0;for(n=hb(n);a<n.length&&n[a]!=="\r"&&n[a]!==`
42
+ transfer tracks: ${qe(r,(l,d)=>l==="initSegment"?void 0:d)}}`),!Xy(r,s)){t.mediaSource=null,t.tracks=void 0;let l=e.currentTime,d=this.details,u=Math.max(l,(d==null?void 0:d.fragments[0].start)||0);if(u-l>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${l} -> ${u}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(r)}"->"${Object.keys(s)}") start time: ${u} currentTime: ${l}`),this.onMediaDetaching(E.MEDIA_DETACHING,{}),this.onMediaAttaching(E.MEDIA_ATTACHING,t),e.currentTime=u;return}this.transferData=void 0,n.forEach(l=>{let d=l,u=r[d];if(u){let c=u.buffer;if(c){let h=this.fragmentTracker,f=u.id;if(h.hasFragments(f)||h.hasParts(f)){let g=Ee.getBuffered(c);h.detectEvictedFragments(d,g,f,null,!0)}let m=Tm(d),p=[d,c];this.sourceBuffers[m]=p,c.updating&&this.operationQueue&&this.operationQueue.prependBlocker(d),this.trackSourceBuffer(d,u)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var e;let t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){let s=!!t.transferMedia;this.transferData=this.overrides=void 0;let{media:r,mediaSource:n,_objectUrl:a}=this;if(n){if(this.log(`media source ${s?"transferring":"detaching"}`),s)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){let o=n.readyState==="open";try{let l=n.sourceBuffers;for(let d=l.length;d--;)o&&l[d].abort(),n.removeSourceBuffer(l[d]);o&&n.endOfStream()}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}n.removeEventListener("sourceopen",this._onMediaSourceOpen),n.removeEventListener("sourceended",this._onMediaSourceEnded),n.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(n.removeEventListener("startstreaming",this._onStartStreaming),n.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}r&&(r.removeEventListener("emptied",this._onMediaEmptied),s||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(r.removeAttribute("src"),this.appendSource&&My(r),r.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(E.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;let s=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),s)try{var r;(r=this.mediaSource)!=null&&r.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(n){this.warn(`onBufferReset ${e}`,n)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Tm(e)]=[null,null];let t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new mp(this.tracks)}onBufferCodecs(e,t){var s;let r=this.tracks,n=Object.keys(t);this.log(`BUFFER_CODECS: "${n}" (current SB count ${this.sourceBufferCount})`);let a="audiovideo"in t&&(r.audio||r.video)||r.audiovideo&&("audio"in t||"video"in t),o=!a&&this.sourceBufferCount&&this.media&&n.some(l=>!r[l]);if(a||o){this.warn(`Unsupported transition between "${Object.keys(r)}" and "${n}" SourceBuffers`);return}n.forEach(l=>{var d,u;let c=t[l],{id:h,codec:f,levelCodec:m,container:p,metadata:g,supplemental:v}=c,b=r[l],y=(d=this.transferData)==null||(d=d.tracks)==null?void 0:d[l],T=y!=null&&y.buffer?y:b,A=(T==null?void 0:T.pendingCodec)||(T==null?void 0:T.codec),R=T==null?void 0:T.levelCodec;b||(b=r[l]={buffer:void 0,listeners:[],codec:f,supplemental:v,container:p,levelCodec:m,metadata:g,id:h});let I=iu(A,R),x=I==null?void 0:I.replace(wy,"$1"),D=iu(f,m),S=(u=D)==null?void 0:u.replace(wy,"$1");D&&I&&x!==S&&(l.slice(0,5)==="audio"&&(D=cu(D,this.appendSource)),this.log(`switching codec ${A} to ${D}`),D!==(b.pendingCodec||b.codec)&&(b.pendingCodec=D),b.container=p,this.appendChangeType(l,p,D))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((s=t.audio)==null?void 0:s.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{let s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e},{})}appendChangeType(e,t,s){let r=`${t};codecs=${s}`,n={label:`change-type=${r}`,execute:()=>{let a=this.tracks[e];if(a){let o=a.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${r}`),o.changeType(r),a.codec=s,a.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn(`Failed to change ${e} SourceBuffer type`,a)}};this.append(n,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;let s=e.start,r=s+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(s,J.MAIN))==null?void 0:t.gap)===!0)return;let a={label:"block-audio",execute:()=>{var o;let l=this.tracks.video;(this.lastVideoAppendEnd>r||l!=null&&l.buffer&&Ee.isBuffered(l.buffer,r)||((o=this.fragmentTracker.getAppendedFrag(r,J.MAIN))==null?void 0:o.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.blockedAudioAppend={op:a,frag:e},this.append(a,"audio",!0)}unblockAudio(){let{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){let{tracks:s}=this,{data:r,type:n,parent:a,frag:o,part:l,chunkMeta:d,offset:u}=t,c=d.buffering[n],{sn:h,cc:f}=o,m=self.performance.now();c.start=m;let p=o.stats.buffering,g=l?l.stats.buffering:null;p.start===0&&(p.start=m),g&&g.start===0&&(g.start=m);let v=s.audio,b=!1;n==="audio"&&(v==null?void 0:v.container)==="audio/mpeg"&&(b=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);let y=s.video,T=y==null?void 0:y.buffer;if(T&&h!=="initSegment"){let I=l||o,x=this.blockedAudioAppend;if(n==="audio"&&a!=="main"&&!this.blockedAudioAppend&&!(y.ending||y.ended)){let S=I.start+I.duration*.05,C=T.buffered,P=this.currentOp("video");!C.length&&!P?this.blockAudio(I):!P&&!Ee.isBuffered(T,S)&&this.lastVideoAppendEnd<S&&this.blockAudio(I)}else if(n==="video"){let D=I.end;if(x){let S=x.frag.start;(D>S||D<this.lastVideoAppendEnd||Ee.isBuffered(T,S))&&this.unblockAudio()}this.lastVideoAppendEnd=D}}let A=(l||o).start,R={label:`append-${n}`,execute:()=>{var I;c.executeStart=self.performance.now();let x=(I=this.tracks[n])==null?void 0:I.buffer;x&&(b?this.updateTimestampOffset(x,A,.1,n,h,f):u!==void 0&&Q(u)&&this.updateTimestampOffset(x,u,1e-6,n,h,f)),this.appendExecutor(r,n)},onStart:()=>{},onComplete:()=>{let I=self.performance.now();c.executeEnd=c.end=I,p.first===0&&(p.first=I),g&&g.first===0&&(g.first=I);let x={};this.sourceBuffers.forEach(([D,S])=>{D&&(x[D]=Ee.getBuffered(S))}),this.appendErrors[n]=0,n==="audio"||n==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(E.BUFFER_APPENDED,{type:n,frag:o,part:l,chunkMeta:d,parent:o.type,timeRanges:x})},onError:I=>{var x;let D={type:se.MEDIA_ERROR,parent:o.type,details:M.BUFFER_APPEND_ERROR,sourceBufferName:n,frag:o,part:l,chunkMeta:d,error:I,err:I,fatal:!1},S=(x=this.media)==null?void 0:x.error;if(I.code===DOMException.QUOTA_EXCEEDED_ERR||I.name=="QuotaExceededError"||"quota"in I)D.details=M.BUFFER_FULL_ERROR;else if(I.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!S)D.errorAction=ea(!0);else if(I.name===zb&&this.sourceBufferCount===0)D.errorAction=ea(!0);else{let C=++this.appendErrors[n];this.warn(`Failed ${C}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${n}" sourceBuffer (${S||"no media error"})`),(C>=this.hls.config.appendErrorMaxRetry||S)&&(D.fatal=!0)}this.hls.trigger(E.ERROR,D)}};this.log(`queuing "${n}" append sn: ${h}${l?" p: "+l.index:""} of ${o.type===J.MAIN?"level":"track"} ${o.level} cc: ${f}`),this.append(R,n,this.isPending(this.tracks[n]))}getFlushOp(e,t,s){return this.log(`queuing "${e}" remove ${t}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{this.hls.trigger(E.BUFFER_FLUSHED,{type:e})},onError:r=>{this.warn(`Failed to remove ${t}-${s} from "${e}" SourceBuffer`,r)}}}onBufferFlushing(e,t){let{type:s,startOffset:r,endOffset:n}=t;s?this.append(this.getFlushOp(s,r,n),s):this.sourceBuffers.forEach(([a])=>{a&&this.append(this.getFlushOp(a,r,n),a)})}onFragParsed(e,t){let{frag:s,part:r}=t,n=[],a=r?r.elementaryStreams:s.elementaryStreams;a[We.AUDIOVIDEO]?n.push("audiovideo"):(a[We.AUDIO]&&n.push("audio"),a[We.VIDEO]&&n.push("video"));let o=()=>{let l=self.performance.now();s.stats.buffering.end=l,r&&(r.stats.buffering.end=l);let d=r?r.stats:s.stats;this.hls.trigger(E.FRAG_BUFFERED,{frag:s,part:r,stats:d,id:s.type})};n.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers(o,n).catch(l=>{this.warn(`Fragment buffered callback ${l}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){let t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var s;this.sourceBuffers.forEach(([a])=>{if(a){let o=this.tracks[a];(!t.type||t.type===a)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${a} buffer reached EOS`)))}});let r=((s=this.overrides)==null?void 0:s.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([a])=>{var o;return a&&!((o=this.tracks[a])!=null&&o.ended)})?r?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();let{mediaSource:a}=this;if(!a||a.readyState!=="open"){a&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${a.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),a.endOfStream(),this.hls.trigger(E.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(E.BUFFERED_TO_END,void 0)):t.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){let t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{let e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===M.BUFFER_APPEND_ERROR&&t.frag){var s;let r=(s=t.errorAction)==null?void 0:s.nextAutoLevel;Q(r)&&r!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){let{hls:e,details:t,media:s}=this;if(!s||t===null||!this.sourceBufferCount)return;let r=e.config,n=s.currentTime,a=t.levelTargetDuration,o=t.live&&r.liveBackBufferLength!==null?r.liveBackBufferLength:r.backBufferLength;if(Q(o)&&o>=0){let d=Math.max(o,a),u=Math.floor(n/a)*a-d;this.flushBackBuffer(n,a,u)}let l=r.frontBufferFlushThreshold;if(Q(l)&&l>0){let d=Math.max(r.maxBufferLength,l),u=Math.max(d,a),c=Math.floor(n/a)*a+u;this.flushFrontBuffer(n,a,c)}}flushBackBuffer(e,t,s){this.sourceBuffers.forEach(([r,n])=>{if(n){let o=Ee.getBuffered(n);if(o.length>0&&s>o.start(0)){var a;this.hls.trigger(E.BACK_BUFFER_REACHED,{bufferEnd:s});let l=this.tracks[r];if((a=this.details)!=null&&a.live)this.hls.trigger(E.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(l!=null&&l.ended){this.log(`Cannot flush ${r} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:r})}}})}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach(([r,n])=>{if(n){let a=Ee.getBuffered(n),o=a.length;if(o<2)return;let l=a.start(o-1),d=a.end(o-1);if(s>l||e>=l&&e<=d)return;this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:r})}})}getDurationAndRange(){var e;let{details:t,mediaSource:s}=this;if(!t||!this.media||(s==null?void 0:s.readyState)!=="open")return null;let r=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&s.setLiveSeekableRange){let d=Math.max(0,t.fragmentStart),u=Math.max(d,r);return{duration:1/0,start:d,end:u}}return{duration:1/0}}let n=(e=this.overrides)==null?void 0:e.duration;if(n)return Q(n)?{duration:n}:null;let a=this.media.duration,o=Q(s.duration)?s.duration:0;return r>o&&r>a||!Q(a)?{duration:r}:null}updateMediaSource({duration:e,start:t,end:s}){let r=this.mediaSource;!this.media||!r||r.readyState!=="open"||(r.duration!==e&&(Q(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),r.duration=e),t!==void 0&&s!==void 0&&(this.log(`MediaSource duration is set to ${r.duration}. Setting seekable range to ${t}-${s}.`),r.setLiveSeekableRange(t,s)))}get tracksReady(){let e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){let{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${qe(s)}`),this.tracksReady){var r;let n=(r=this.transferData)==null?void 0:r.tracks;n&&Object.keys(n).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){let e={};this.sourceBuffers.forEach(([t,s])=>{if(t){let r=this.tracks[t];e[t]={buffer:s,container:r.container,codec:r.codec,supplemental:r.supplemental,levelCodec:r.levelCodec,id:r.id,metadata:r.metadata}}}),this.hls.trigger(E.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{let e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(E.ERROR,{type:se.MEDIA_ERROR,details:M.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){let{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(let n in e){let a=n,o=e[a];if(this.isPending(o)){let l=this.getTrackCodec(o,a),d=`${o.container};codecs=${l}`;o.codec=l,this.log(`creating sourceBuffer(${d})${this.currentOp(a)?" Queued":""} ${qe(o)}`);try{let u=s.addSourceBuffer(d),c=Tm(a),h=[a,u];t[c]=h,o.buffer=u}catch(u){var r;this.error(`error while trying to add sourceBuffer: ${u.message}`),this.shiftAndExecuteNext(a),(r=this.operationQueue)==null||r.removeBlockers(),delete this.tracks[a],this.hls.trigger(E.ERROR,{type:se.MEDIA_ERROR,details:M.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:u,sourceBufferName:a,mimeType:d,parent:o.id});return}this.trackSourceBuffer(a,o)}}this.bufferCreated()}getTrackCodec(e,t){let s=e.supplemental,r=e.codec;s&&(t==="video"||t==="audiovideo")&&Bo(s,"video")&&(r=JR(r,s));let n=iu(r,e.levelCodec);return n?t.slice(0,5)==="audio"?cu(n,this.appendSource):n:""}trackSourceBuffer(e,t){let s=t.buffer;if(!s)return;let r=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,codec:r,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(n,a)=>{let o=a.removedRanges;o!=null&&o.length&&this.hls.trigger(E.BUFFER_FLUSHED,{type:n})})}get mediaSrc(){var e,t;let s=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return s==null?void 0:s.src}onSBUpdateStart(e){let t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}let s=this.currentOp(e);s&&(s.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var s;let r=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(s=this.mediaSource)==null?void 0:s.readyState}`);this.error(`${r}`,t),this.hls.trigger(E.ERROR,{type:se.MEDIA_ERROR,details:M.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});let n=this.currentOp(e);n&&n.onError(r)}updateTimestampOffset(e,t,s,r,n,a){let o=t-e.timestampOffset;Math.abs(o)>=s&&(this.log(`Updating ${r} SourceBuffer timestampOffset to ${t} (sn: ${n} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,s){let{media:r,mediaSource:n}=this,a=this.tracks[e],o=a==null?void 0:a.buffer;if(!r||!n||!o){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}let l=Q(r.duration)?r.duration:1/0,d=Q(n.duration)?n.duration:1/0,u=Math.max(0,t),c=Math.min(s,l,d);c>u&&(!a.ending||a.ended)?(a.ended=!1,this.log(`Removing [${u},${c}] from the ${e} SourceBuffer`),o.remove(u,c)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){let s=this.tracks[t],r=s==null?void 0:s.buffer;if(!r)throw new pp(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);s.ending=!1,s.ended=!1,r.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);let{operationQueue:s}=this,r=t.map(a=>this.appendBlocker(a));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(r).then(a=>{s===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var s;let r=(s=this.tracks[t])==null?void 0:s.buffer;!r||r.updating||this.shiftAndExecuteNext(t)})}append(e,t,s){this.operationQueue&&this.operationQueue.append(e,t,s)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,s){let r=this.tracks[e];if(!r)return;let n=r.buffer;if(!n)return;let a=s.bind(this,e);r.listeners.push({event:t,listener:a}),n.addEventListener(t,a)}removeBufferListeners(e){let t=this.tracks[e];if(!t)return;let s=t.buffer;s&&(t.listeners.forEach(r=>{s.removeEventListener(r.event,r.listener)}),t.listeners.length=0)}};function My(i){let e=i.querySelectorAll("source");[].slice.call(e).forEach(t=>{i.removeChild(t)})}function $k(i,e){let t=self.document.createElement("source");t.type="video/mp4",t.src=e,i.appendChild(t)}function Tm(i){return i==="audio"?1:0}var Qo=class i{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(E.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.BUFFER_CODECS,this.onBufferCodecs,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){let{hls:e}=this;e.off(E.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.BUFFER_CODECS,this.onBufferCodecs,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){let s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.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 s=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,s.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&Q(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}let e=this.hls.levels;if(e.length){let t=this.hls,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){let t=this.hls.levels;if(!t.length)return-1;let s=t.filter((r,n)=>this.isLevelAllowed(r)&&n<=e);return this.clientRect=null,i.getMaxLevelByMediaSize(s,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 s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,!t.width&&!t.height&&(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(s=>e.bitrate===s.bitrate&&e.width===s.width&&e.height===s.height)}static getMaxLevelByMediaSize(e,t,s){if(!(e!=null&&e.length))return-1;let r=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0,n=e.length-1,a=Math.max(t,s);for(let o=0;o<e.length;o+=1){let l=e[o];if((l.width>=a||l.height>=a)&&r(l,e[o+1])){n=o;break}}return n}},Hk={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},jt=Hk,Gk={HLS:"h"},Kk=Gk,Ds=class i{constructor(e,t){Array.isArray(e)&&(e=e.map(s=>s instanceof i?s:new i(s))),this.value=e,this.params=t}},Vk="Dict";function Wk(i){return Array.isArray(i)?JSON.stringify(i):i instanceof Map?"Map{}":i instanceof Set?"Set{}":typeof i=="object"?JSON.stringify(i):String(i)}function qk(i,e,t,s){return new Error(`failed to ${i} "${Wk(e)}" as ${t}`,{cause:s})}function es(i,e,t){return qk("serialize",i,e,t)}var Ru=class{constructor(e){this.description=e}},Py="Bare Item",Yk="Boolean";function jk(i){if(typeof i!="boolean")throw es(i,Yk);return i?"?1":"?0"}function zk(i){return btoa(String.fromCharCode(...i))}var Qk="Byte Sequence";function Xk(i){if(ArrayBuffer.isView(i)===!1)throw es(i,Qk);return`:${zk(i)}:`}var Zk="Integer";function Jk(i){return i<-999999999999999||999999999999999<i}function Qb(i){if(Jk(i))throw es(i,Zk);return i.toString()}function eD(i){return`@${Qb(i.getTime()/1e3)}`}function Xb(i,e){if(i<0)return-Xb(-i,e);let t=Math.pow(10,e);if(Math.abs(i*t%1-.5)<Number.EPSILON){let r=Math.floor(i*t);return(r%2===0?r:r+1)/t}else return Math.round(i*t)/t}var tD="Decimal";function iD(i){let e=Xb(i,3);if(Math.floor(Math.abs(e)).toString().length>12)throw es(i,tD);let t=e.toString();return t.includes(".")?t:`${t}.0`}var sD="String",rD=/[\x00-\x1f\x7f]+/;function nD(i){if(rD.test(i))throw es(i,sD);return`"${i.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function aD(i){return i.description||i.toString().slice(7,-1)}var oD="Token";function Oy(i){let e=aD(i);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw es(e,oD);return e}function vp(i){switch(typeof i){case"number":if(!Q(i))throw es(i,Py);return Number.isInteger(i)?Qb(i):iD(i);case"string":return nD(i);case"symbol":return Oy(i);case"boolean":return jk(i);case"object":if(i instanceof Date)return eD(i);if(i instanceof Uint8Array)return Xk(i);if(i instanceof Ru)return Oy(i);default:throw es(i,Py)}}var lD="Key";function Ep(i){if(/^[a-z*][a-z0-9\-_.*]*$/.test(i)===!1)throw es(i,lD);return i}function dg(i){return i==null?"":Object.entries(i).map(([e,t])=>t===!0?`;${Ep(e)}`:`;${Ep(e)}=${vp(t)}`).join("")}function Zb(i){return i instanceof Ds?`${vp(i.value)}${dg(i.params)}`:vp(i)}function dD(i){return`(${i.value.map(Zb).join(" ")})${dg(i.params)}`}function uD(i,e={whitespace:!0}){if(typeof i!="object"||i==null)throw es(i,Vk);let t=i instanceof Map?i.entries():Object.entries(i),s=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([r,n])=>{n instanceof Ds||(n=new Ds(n));let a=Ep(r);return n.value===!0?a+=dg(n.params):(a+="=",Array.isArray(n.value)?a+=dD(n):a+=Zb(n)),a}).join(`,${s}`)}function Jb(i,e){return uD(i,e)}var Qi="CMCD-Object",nt="CMCD-Request",zr="CMCD-Session",ir="CMCD-Status",cD={br:Qi,ab:Qi,d:Qi,ot:Qi,tb:Qi,tpb:Qi,lb:Qi,tab:Qi,lab:Qi,url:Qi,pb:nt,bl:nt,tbl:nt,dl:nt,ltc:nt,mtp:nt,nor:nt,nrr:nt,rc:nt,sn:nt,sta:nt,su:nt,ttfb:nt,ttfbb:nt,ttlb:nt,cmsdd:nt,cmsds:nt,smrt:nt,df:nt,cs:nt,ts:nt,cid:zr,pr:zr,sf:zr,sid:zr,st:zr,v:zr,msd:zr,bs:ir,bsd:ir,cdn:ir,rtp:ir,bg:ir,pt:ir,ec:ir,e:ir},hD={REQUEST:nt};function fD(i){return Object.keys(i).reduce((e,t)=>{var s;return(s=i[t])===null||s===void 0||s.forEach(r=>e[r]=t),e},{})}function mD(i,e){let t={};if(!i)return t;let s=Object.keys(i),r=e?fD(e):{};return s.reduce((n,a)=>{var o;let l=cD[a]||r[a]||hD.REQUEST,d=(o=n[l])!==null&&o!==void 0?o:n[l]={};return d[a]=i[a],n},t)}function pD(i){return["ot","sf","st","e","sta"].includes(i)}function gD(i){return typeof i=="number"?Q(i):i!=null&&i!==""&&i!==!1}var eT="event";function vD(i,e){let t=new URL(i),s=new URL(e);if(t.origin!==s.origin)return i;let r=t.pathname.split("/").slice(1),n=s.pathname.split("/").slice(1,-1);for(;r[0]===n[0];)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")+t.search+t.hash}var au=i=>Math.round(i),yp=(i,e)=>Array.isArray(i)?i.map(t=>yp(t,e)):i instanceof Ds&&typeof i.value=="string"?new Ds(yp(i.value,e),i.params):(e.baseUrl&&(i=vD(i,e.baseUrl)),e.version===1?encodeURIComponent(i):i),zd=i=>au(i/100)*100,ED=(i,e)=>{let t=i;return e.version>=2&&(i instanceof Ds&&typeof i.value=="string"?t=new Ds([i]):typeof i=="string"&&(t=[i])),yp(t,e)},yD={br:au,d:au,bl:zd,dl:zd,mtp:zd,nor:ED,rtp:zd,tb:au},tT="request",iT="response",ug=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],bD=["e"],TD=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Uu(i){return TD.test(i)}function _D(i){return ug.includes(i)||bD.includes(i)||Uu(i)}var sT=["d","dl","nor","ot","rtp","su"];function AD(i){return ug.includes(i)||sT.includes(i)||Uu(i)}var SD=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function ID(i){return ug.includes(i)||sT.includes(i)||SD.includes(i)||Uu(i)}var LD=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function RD(i){return LD.includes(i)||Uu(i)}var xD={[iT]:ID,[eT]:_D,[tT]:AD};function rT(i,e={}){let t={};if(i==null||typeof i!="object")return t;let s=e.version||i.v||1,r=e.reportingMode||tT,n=s===1?RD:xD[r],a=Object.keys(i).filter(n),o=e.filter;typeof o=="function"&&(a=a.filter(o));let l=r===iT||r===eT;l&&!a.includes("ts")&&a.push("ts"),s>1&&!a.includes("v")&&a.push("v");let d=$e({},yD,e.formatters),u={version:s,reportingMode:r,baseUrl:e.baseUrl};return a.sort().forEach(c=>{let h=i[c],f=d[c];if(typeof f=="function"&&(h=f(h,u)),c==="v"){if(s===1)return;h=s}c=="pr"&&h===1||(l&&c==="ts"&&!Q(h)&&(h=Date.now()),gD(h)&&(pD(c)&&typeof h=="string"&&(h=new Ru(h)),t[c]=h))}),t}function kD(i,e={}){let t={};if(!i)return t;let s=rT(i,e),r=mD(s,e==null?void 0:e.customHeaderMap);return Object.entries(r).reduce((n,[a,o])=>{let l=Jb(o,{whitespace:!1});return l&&(n[a]=l),n},t)}function DD(i,e,t){return $e(i,kD(e,t))}var CD="CMCD";function wD(i,e={}){return i?Jb(rT(i,e),{whitespace:!1}):""}function MD(i,e={}){if(!i)return"";let t=wD(i,e);return encodeURIComponent(t)}function PD(i,e={}){if(!i)return"";let t=MD(i,e);return`${CD}=${t}`}var Ny=/CMCD=[^&#]+/;function OD(i,e,t){let s=PD(e,t);if(!s)return i;if(Ny.test(i))return i.replace(Ny,s);let r=i.includes("?")?"&":"?";return`${i}${r}${s}`}var bp=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=r=>{try{this.apply(r,{ot:jt.MANIFEST,su:!this.initialized})}catch(n){this.hls.logger.warn("Could not generate manifest CMCD data.",n)}},this.applyFragmentData=r=>{try{let{frag:n,part:a}=r,o=this.hls.levels[n.level],l=this.getObjectType(n),d={d:(a||n).duration*1e3,ot:l};(l===jt.VIDEO||l===jt.AUDIO||l==jt.MUXED)&&(d.br=o.bitrate/1e3,d.tb=this.getTopBandwidth(l)/1e3,d.bl=this.getBufferLength(l));let u=a?this.getNextPart(a):this.getNextFrag(n);u!=null&&u.url&&u.url!==n.url&&(d.nor=u.url),this.apply(r,d)}catch(n){this.hls.logger.warn("Could not generate segment CMCD data.",n)}},this.hls=e;let t=this.config=e.config,{cmcd:s}=t;s!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||e.sessionId,this.cid=s.contentId,this.useHeaders=s.useHeaders===!0,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){let e=this.hls;e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHED,this.onMediaDetached,this),e.on(E.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){let e=this.hls;e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHED,this.onMediaDetached,this),e.off(E.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var s,r;this.audioBuffer=(s=t.tracks.audio)==null?void 0:s.buffer,this.videoBuffer=(r=t.tracks.video)==null?void 0:r.buffer}createData(){var e;return{v:1,sf:Kk.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){$e(t,this.createData());let s=t.ot===jt.INIT||t.ot===jt.VIDEO||t.ot===jt.MUXED;this.starved&&s&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);let{includeKeys:r}=this;r&&(t=Object.keys(t).reduce((a,o)=>(r.includes(o)&&(a[o]=t[o]),a),{}));let n={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),DD(e.headers,t,n)):e.url=OD(e.url,t,n)}getNextFrag(e){var t;let s=(t=this.hls.levels[e.level])==null?void 0:t.details;if(s){let r=e.sn-s.startSN;return s.fragments[r+1]}}getNextPart(e){var t;let{index:s,fragment:r}=e,n=(t=this.hls.levels[r.level])==null||(t=t.details)==null?void 0:t.partList;if(n){let{sn:a}=r;for(let o=n.length-1;o>=0;o--){let l=n[o];if(l.index===s&&l.fragment.sn===a)return n[o+1]}}}getObjectType(e){let{type:t}=e;if(t==="subtitle")return jt.TIMED_TEXT;if(e.sn==="initSegment")return jt.INIT;if(t==="audio")return jt.AUDIO;if(t==="main")return this.hls.audioTracks.length?jt.VIDEO:jt.MUXED}getTopBandwidth(e){let t=0,s,r=this.hls;if(e===jt.AUDIO)s=r.audioTracks;else{let n=r.maxAutoLevel,a=n>-1?n+1:r.levels.length;s=r.levels.slice(0,a)}return s.forEach(n=>{n.bitrate>t&&(t=n.bitrate)}),t>0?t:NaN}getBufferLength(e){let t=this.media,s=e===jt.AUDIO?this.audioBuffer:this.videoBuffer;return!s||!t?NaN:Ee.bufferInfo(s,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new s(n)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(n,a,o){t(n),this.loader.load(n,a,o)}}}createFragmentLoader(){let{fLoader:e}=this.config,t=this.applyFragmentData,s=e||this.config.loader;return class{constructor(n){this.loader=void 0,this.loader=new s(n)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(n,a,o){t(n),this.loader.load(n,a,o)}}}},ND=3e5,Tp=class extends Qt{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){let e=this.hls;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){let e=this.hls;e&&(e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){let e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){let t=this.levels;t&&(this.levels=t.filter(s=>s!==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:s}=t;s!==null&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){let{errorAction:s}=t;if((s==null?void 0:s.action)===Rt.SendAlternateToPenaltyBox&&s.flags===ni.MoveAllAlternatesMatchingHost){let r=this.levels,n=this._pathwayPriority,a=this.pathwayId;if(t.context){let{groupId:o,pathwayId:l,type:d}=t.context;o&&r?a=this.getPathwayForGroupId(o,d,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&r&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),s.resolved=this.pathwayId!==a),t.details===M.BUFFER_APPEND_ERROR&&!t.fatal?s.resolved=!0:s.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${r&&r.length} priorities: ${qe(n)} penalized: ${qe(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){let s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t,s=this.penalizedPathways,r=performance.now();Object.keys(s).forEach(n=>{r-s[n]>ND&&delete s[n]});for(let n=0;n<e.length;n++){let a=e[n];if(a in s)continue;if(a===this.pathwayId)return;let o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,xb(t),this.hls.trigger(E.LEVELS_UPDATED,{levels:t});let d=this.hls.levels[o];l&&d&&this.levels&&(d.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&d.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${d.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,s){let r=this.getLevelsForPathway(s).concat(this.levels||[]);for(let n=0;n<r.length;n++)if(t===Le.AUDIO_TRACK&&r[n].hasAudioGroup(e)||t===Le.SUBTITLE_TRACK&&r[n].hasSubtitleGroup(e))return r[n].pathwayId;return s}clonePathways(e){let t=this.levels;if(!t)return;let s={},r={};e.forEach(n=>{let{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=n;if(t.some(u=>u.pathwayId===a))return;let d=this.getLevelsForPathway(o).map(u=>{let c=new tt(u.attrs);c["PATHWAY-ID"]=a;let h=c.AUDIO&&`${c.AUDIO}_clone_${a}`,f=c.SUBTITLES&&`${c.SUBTITLES}_clone_${a}`;h&&(s[c.AUDIO]=h,c.AUDIO=h),f&&(r[c.SUBTITLES]=f,c.SUBTITLES=f);let m=nT(u.uri,c["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),p=new tn({attrs:c,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:m,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let g=1;g<u.audioGroups.length;g++)p.addGroupId("audio",`${u.audioGroups[g]}_clone_${a}`);if(u.subtitleGroups)for(let g=1;g<u.subtitleGroups.length;g++)p.addGroupId("text",`${u.subtitleGroups[g]}_clone_${a}`);return p});t.push(...d),Uy(this.audioTracks,s,l,a),Uy(this.subtitleTracks,r,l,a)})}loadSteeringManifest(e){let t=this.hls.config,s=t.loader;this.loader&&this.loader.destroy(),this.loader=new s(t);let r;try{r=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(r.protocol!=="data:"){let u=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;r.searchParams.set("_HLS_pathway",this.pathwayId),r.searchParams.set("_HLS_throughput",""+u)}let n={responseType:"json",url:r.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},d={onSuccess:(u,c,h,f)=>{this.log(`Loaded steering manifest: "${r}"`);let m=u.data;if((m==null?void 0:m.VERSION)!==1){this.log(`Steering VERSION ${m.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=m.TTL;let{"RELOAD-URI":p,"PATHWAY-CLONES":g,"PATHWAY-PRIORITY":v}=m;if(p)try{this.uri=new self.URL(p,r).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${p}`);return}this.scheduleRefresh(this.uri||h.url),g&&this.clonePathways(g);let b={steeringManifest:m,url:r.toString()};this.hls.trigger(E.STEERING_MANIFEST_LOADED,b),v&&this.updatePathwayPriority(v)},onError:(u,c,h,f)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${c.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${c.url} no longer available`);return}let m=this.timeToLoad*1e3;if(u.code===429){let p=this.loader;if(typeof(p==null?void 0:p.getResponseHeader)=="function"){let g=p.getResponseHeader("Retry-After");g&&(m=parseFloat(g)*1e3)}this.log(`Steering manifest ${c.url} rate limited`);return}this.scheduleRefresh(this.uri||c.url,m)},onTimeout:(u,c,h)=>{this.log(`Timeout loading steering manifest (${c.url})`),this.scheduleRefresh(this.uri||c.url)}};this.log(`Requesting steering manifest: ${r}`),this.loader.load(n,l,d)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var s;let r=(s=this.hls)==null?void 0:s.media;if(r&&!r.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}};function Uy(i,e,t,s){i&&Object.keys(e).forEach(r=>{let n=i.filter(a=>a.groupId===r).map(a=>{let o=$e({},a);return o.details=void 0,o.attrs=new tt(o.attrs),o.url=o.attrs.URI=nT(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[r],o.attrs["PATHWAY-ID"]=s,o});i.push(...n)})}function nT(i,e,t,s){let{HOST:r,PARAMS:n,[t]:a}=s,o;e&&(o=a==null?void 0:a[e],o&&(i=o));let l=new self.URL(i);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach(d=>{d&&l.searchParams.set(d,n[d])}),l.href}var xu=class i extends Qt{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=i.CDMCleanupPromise?[i.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{let{initDataType:s,initData:r}=t,n=`"${t.type}" event: init data type: "${s}"`;if(this.debug(n),r!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=Mo(this.config));let o=a.map(fm).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{let o=ru(a);if(s!=="sinf"||o!==it.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${s}" for selected key-system ${o}`);return}let l;try{let f=bt(new Uint8Array(r)),m=ig(JSON.parse(f).sinf),p=nb(m);if(!p)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");l=new Uint8Array(p.subarray(8,24))}catch(f){this.warn(`${n} Failed to parse sinf: ${f}`);return}let d=Dt(l),{keyIdToKeySessionPromise:u,mediaKeySessions:c}=this,h=u[d];for(let f=0;f<c.length;f++){let m=c[f],p=m.decryptdata;if(!p.keyId)continue;let g=Dt(p.keyId);if(yu(l,p.keyId)||p.uri.replace(/-/g,"").indexOf(d)!==-1){if(h=u[g],!h)continue;if(p.pssh)break;delete u[g],p.pssh=new Uint8Array(r),p.keyId=l,h=u[d]=h.then(()=>this.generateRequestWithPreferredKeySession(m,s,r,"encrypted-event-key-match")),h.catch(v=>this.handleError(v));break}}h||this.handleError(new Error(`Key ID ${d} not encountered in playlist. Key-system sessions ${c.length}.`))}).catch(a=>this.handleError(a))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();let e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(E.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(E.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(E.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(E.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(E.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(E.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){let{drmSystems:t,widevineLicenseUrl:s}=this.config,r=t==null?void 0:t[e];if(r)return r.licenseUrl;if(e===it.WIDEVINE&&s)return s}getLicenseServerUrlOrThrow(e){let t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){let{drmSystems:t}=this.config,s=t==null?void 0:t[e];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){let t=this.hls.levels,s=(a,o,l)=>!!a&&l.indexOf(a)===o,r=t.map(a=>a.audioCodec).filter(s),n=t.map(a=>a.videoCodec).filter(s);return r.length+n.length===0&&n.push("avc1.42e01e"),new Promise((a,o)=>{let l=d=>{let u=d.shift();this.getMediaKeysPromise(u,r,n).then(c=>a({keySystem:u,mediaKeys:c})).catch(c=>{d.length?l(d):c instanceof $t?o(c):o(new $t({type:se.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_NO_ACCESS,error:c,fatal:!0},c.message))})};l(e)})}requestMediaKeySystemAccess(e,t){let{requestMediaKeySystemAccessFunc:s}=this.config;if(typeof s!="function"){let r=`Configured requestMediaKeySystemAccess is not a function ${s}`;return bb===null&&self.location.protocol==="http:"&&(r=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(r))}return s(e,t)}getMediaKeysPromise(e,t,s){var r;let n=Px(e,t,s,this.config.drmSystemOptions||{}),a=this.keySystemAccessPromises[e],o=(r=a)==null?void 0:r.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${qe(n)}`),o=this.requestMediaKeySystemAccess(e,n);let l=a=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(d=>{this.log(`Failed to obtain access to key-system "${e}": ${d}`)}),o.then(d=>{this.log(`Access for key-system "${d.keySystem}" obtained`);let u=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);let c=l.mediaKeys=d.createMediaKeys().then(h=>(this.log(`Media-keys created for "${e}"`),l.hasMediaKeys=!0,u.then(f=>f?this.setMediaKeysServerCertificate(h,e,f):h)));return c.catch(h=>{this.error(`Failed to create media-keys for "${e}"}: ${h}`)}),c})}return o.then(()=>a.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:s}){this.log(`Creating key-system session "${t}" keyId: ${Dt(e.keyId||[])} keyUri: ${e.uri}`);let r=s.createSession(),n={decryptdata:e,keySystem:t,mediaKeys:s,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n}renewKeySession(e){let t=e.decryptdata;if(t.pssh){let s=this.createMediaKeySessionContext(e),r=Qd(t),n="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(s,n,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){let s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyId ${Dt(e.decryptdata.keyId||[])}
43
+ } (data length: ${t.byteLength})`),s.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>fm(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:s})=>this.attemptSetMediaKeys(t,s))}selectKeySystem(e){return new Promise((t,s)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:r})=>{let n=fm(r);n?t(n):s(new Error(`Unable to find format for key-system "${r}"`))}).catch(s)})}selectKeySystemFormat(e){let t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){let t=Mo(this.config),s=e.map(ru).filter(r=>!!r&&t.indexOf(r)!==-1);return this.selectKeySystem(s)}getKeyStatus(e){let{mediaKeySessions:t}=this;for(let s=0;s<t.length;s++){let r=UD(e,t[s]);if(r)return r}}loadKey(e){let t=e.keyInfo.decryptdata,s=Qd(t),r=this.bannedKeyIds[s];if(r||this.getKeyStatus(t)==="internal-error"){let o=Fy(r||"internal-error",t);return this.handleError(o,e.frag),Promise.reject(o)}let n=`(keyId: ${s} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${n}`);let a=this.keyIdToKeySessionPromise[s];if(!a){let o=this.getKeySystemForKeyPromise(t).then(({keySystem:l,mediaKeys:d})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${n}`),this.attemptSetMediaKeys(l,d).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:l,mediaKeys:d,decryptdata:t}))))).then(l=>{let d="cenc",u=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(l,d,u,"playlist-key")});return o.catch(l=>this.handleError(l,e.frag)),this.keyIdToKeySessionPromise[s]=o,o}return a.catch(o=>{if(o instanceof $t){let l=Fe({},o.data);this.getKeyStatus(t)==="internal-error"&&(l.decryptdata=t);let d=new $t(l,o.message);this.handleError(d,e.frag)}}),a}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof $t){t&&(e.data.frag=t);let s=e.data.decryptdata;this.error(`${e.message}${s?` (${Dt(s.keyId||[])})`:""}`),this.hls.trigger(E.ERROR,e.data)}else this.error(e.message),this.hls.trigger(E.ERROR,{type:se.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){let t=Qd(e),s=this.keyIdToKeySessionPromise[t];if(!s){let r=ru(e.keyFormat),n=r?[r]:Mo(this.config);return this.attemptKeySystemAccess(n)}return s}getKeySystemSelectionPromise(e){if(e.length||(e=Mo(this.config)),e.length===0)throw new $t({type:se.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${qe({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();let s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);let r=Promise.all(s).then(()=>this.media?this.media.setMediaKeys(t):new Promise((n,a)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return a(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(n).catch(a)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(r),r.then(()=>{this.log(`Media-keys set for "${e}"`),s.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>s.indexOf(n)===-1)})}generateRequestWithPreferredKeySession(e,t,s,r){var n;let a=(n=this.config.drmSystems)==null||(n=n[e.keySystem])==null?void 0:n.generateRequest;if(a)try{let m=a.call(this.hls,t,s,e);if(!m)throw new Error("Invalid response from configured generateRequest filter");t=m.initDataType,s=m.initData?m.initData:null,e.decryptdata.pssh=s?new Uint8Array(s):null}catch(m){if(this.warn(m.message),this.hls&&this.hls.config.debug)throw m}if(s===null)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);let o=Qd(e.decryptdata),l=e.decryptdata.uri;this.log(`Generating key-session request for "${r}" keyId: ${o} URI: ${l} (init data type: ${t} length: ${s.byteLength})`);let d=new sg,u=e._onmessage=m=>{let p=e.mediaKeysSession;if(!p){d.emit("error",new Error("invalid state"));return}let{messageType:g,message:v}=m;this.log(`"${g}" message event for session "${p.sessionId}" message size: ${v.byteLength}`),g==="license-request"||g==="license-renewal"?this.renewLicense(e,v).catch(b=>{d.eventNames().length?d.emit("error",b):this.handleError(b)}):g==="license-release"?e.keySystem===it.FAIRPLAY&&this.updateKeySession(e,jm("acknowledged")).then(()=>this.removeSession(e)).catch(b=>this.handleError(b)):this.warn(`unhandled media key message type "${g}"`)},c=(m,p)=>{p.keyStatus=m;let g;m.startsWith("usable")?d.emit("resolved"):m==="internal-error"||m==="output-restricted"||m==="output-downscaled"?g=Fy(m,p.decryptdata):m==="expired"?g=new Error(`key expired (keyId: ${o})`):m==="released"?g=new Error("key released"):m==="status-pending"||this.warn(`unhandled key status change "${m}" (keyId: ${o})`),g&&(d.eventNames().length?d.emit("error",g):this.handleError(g))},h=e._onkeystatuseschange=m=>{if(!e.mediaKeysSession){d.emit("error",new Error("invalid state"));return}let g=this.getKeyStatuses(e);if(!Object.keys(g).some(T=>g[T]!=="status-pending"))return;if(g[o]==="expired"){this.log(`Expired key ${qe(g)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let b=g[o];if(b)c(b,e);else{var y;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(y=e.keyStatusTimeouts)[o]||(y[o]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;let A=this.getKeyStatus(e.decryptdata);if(A&&A!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${A} from other session.`),c(A,e);this.log(`key status for ${o} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),b="internal-error",c(b,e)},1e3)),this.log(`No status for keyId ${o} (${qe(g)}).`)}};Ht(e.mediaKeysSession,"message",u),Ht(e.mediaKeysSession,"keystatuseschange",h);let f=new Promise((m,p)=>{d.on("error",p),d.on("resolved",m)});return e.mediaKeysSession.generateRequest(t,s).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o} URI: ${l}`)}).catch(m=>{throw new $t({type:se.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_NO_SESSION,error:m,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${m}`)}).then(()=>f).catch(m=>(d.removeAllListeners(),this.removeSession(e).then(()=>{throw m}))).then(()=>(d.removeAllListeners(),e))}getKeyStatuses(e){let t={};return e.mediaKeysSession.keyStatuses.forEach((s,r)=>{if(typeof r=="string"&&typeof s=="object"){let o=r;r=s,s=o}let n="buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);if(e.keySystem===it.PLAYREADY&&n.length===16){let o=Dt(n);t[o]=s,Eb(n)}let a=Dt(n);s==="internal-error"&&(this.bannedKeyIds[a]=s),this.log(`key status change "${s}" for keyStatuses keyId: ${a} key-session "${e.mediaKeysSession.sessionId}"`),t[a]=s}),t}fetchServerCertificate(e){let t=this.config,s=t.loader,r=new s(t),n=this.getServerCertificateUrl(e);return n?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{let l={responseType:"arraybuffer",url:n},d=t.certLoadPolicy.default,u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(h,f,m,p)=>{a(h.data)},onError:(h,f,m,p)=>{o(new $t({type:se.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:m,response:Fe({url:l.url,data:void 0},h)},`"${e}" certificate request failed (${n}). Status: ${h.code} (${h.text})`))},onTimeout:(h,f,m)=>{o(new $t({type:se.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:m,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${n})`))},onAbort:(h,f,m)=>{o(new Error("aborted"))}};r.load(l,u,c)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,s){return new Promise((r,n)=>{e.setServerCertificate(s).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${s.byteLength}) on "${t}"`),r(e)}).catch(a=>{n(new $t({type:se.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(s=>this.updateKeySession(e,new Uint8Array(s)).catch(r=>{throw new $t({type:se.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:r,fatal:!1},r.message)}))}unpackPlayReadyKeyMessage(e,t){let s=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!s.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;let r=new DOMParser().parseFromString(s,"application/xml"),n=r.querySelectorAll("HttpHeader");if(n.length>0){let u;for(let c=0,h=n.length;c<h;c++){var a,o;u=n[c];let f=(a=u.querySelector("name"))==null?void 0:a.textContent,m=(o=u.querySelector("value"))==null?void 0:o.textContent;f&&m&&e.setRequestHeader(f,m)}}let l=r.querySelector("Challenge"),d=l==null?void 0:l.textContent;if(!d)throw new Error("Cannot find <Challenge> in key message");return jm(atob(d))}setupLicenseXHR(e,t,s,r){let n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return n.call(this.hls,e,t,s,r)}).catch(a=>{if(!s.decryptdata)throw a;return e.open("POST",t,!0),n.call(this.hls,e,t,s,r)}).then(a=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:a||r})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){let s=this.config.keyLoadPolicy.default;return new Promise((r,n)=>{let a=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${a}`);let o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return n(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let l=o.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);let d=this.config.licenseResponseCallback;if(d)try{l=d.call(this.hls,o,a,e)}catch(u){this.error(u)}r(l)}else{let l=s.errorRetry,d=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>d||o.status>=400&&o.status<500)n(new $t({type:se.KEY_SYSTEM_ERROR,details:M.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{let u=d-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${u} attempts left`),this.requestLicense(e,t).then(r,n)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,t).then(({xhr:l,licenseChallenge:d})=>{e.keySystem==it.PLAYREADY&&(d=this.unpackPlayReadyKeyMessage(l,d)),l.send(d)}).catch(n)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let s=t.media;this.media=s,Ht(s,"encrypted",this.onMediaEncrypted),Ht(s,"waitingforkey",this.onWaitingForKey);let r=this.mediaResolved;r?r():this.mediaKeys=s.mediaKeys}onMediaDetached(){let e=this.media;e&&(zt(e,"encrypted",this.onMediaEncrypted),zt(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};let t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;let s=this.media,r=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,na.clearKeyUriToKeyIdMap();let n=r.length;i.CDMCleanupPromise=Promise.all(r.map(a=>this.removeSession(a)).concat((s==null||(e=s.setMediaKeys(null))==null?void 0:e.catch(a=>{this.log(`Could not clear media keys: ${a}`),this.hls&&this.hls.trigger(E.ERROR,{type:se.OTHER_ERROR,details:M.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${a}`)})}))||Promise.resolve())).catch(a=>{this.log(`Could not close sessions and clear media keys: ${a}`),this.hls&&this.hls.trigger(E.ERROR,{type:se.OTHER_ERROR,details:M.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${a}`)})}).then(()=>{n&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){let s=t.reduce((r,n)=>(r.indexOf(n.keyFormat)===-1&&r.push(n.keyFormat),r),[]);this.log(`Selecting key-system from session-keys ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s)}}removeSession(e){let{mediaKeysSession:t,licenseXhr:s,decryptdata:r}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${Dt((r==null?void 0:r.keyId)||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;let n=this.mediaKeySessions.indexOf(e);n>-1&&this.mediaKeySessions.splice(n,1);let{keyStatusTimeouts:a}=e;a&&Object.keys(a).forEach(d=>self.clearTimeout(a[d]));let{drmSystemOptions:o}=this.config;return(Nx(o)?new Promise((d,u)=>{self.setTimeout(()=>u(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(d).catch(u)}):Promise.resolve()).catch(d=>{this.log(`Could not remove session: ${d}`),this.hls&&this.hls.trigger(E.ERROR,{type:se.OTHER_ERROR,details:M.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${d}`)})}).then(()=>t.close()).catch(d=>{this.log(`Could not close session: ${d}`),this.hls&&this.hls.trigger(E.ERROR,{type:se.OTHER_ERROR,details:M.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${d}`)})})}return Promise.resolve()}};xu.CDMCleanupPromise=void 0;function Qd(i){if(!i)throw new Error("Could not read keyId of undefined decryptdata");if(i.keyId===null)throw new Error("keyId is null");return Dt(i.keyId)}function UD(i,e){if(i.keyId&&e.mediaKeysSession.keyStatuses.has(i.keyId))return e.mediaKeysSession.keyStatuses.get(i.keyId);if(i.matches(e.decryptdata))return e.keyStatus}var $t=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 Fy(i,e){let t=i==="output-restricted",s=t?M.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:M.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new $t({type:se.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${i}"`)}var _p=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(E.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(E.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(E.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){let s=this.hls.config;if(s.capLevelOnFPSDrop){let r=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=r,r&&typeof r.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){let r=performance.now();if(t){if(this.lastTime){let n=r-this.lastTime,a=s-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*a/n,d=this.hls;if(d.trigger(E.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:s}),l>0&&a>d.config.fpsDroppedMonitoringThreshold*o){let u=d.currentLevel;d.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(d.autoLevelCapping===-1||d.autoLevelCapping>=u)&&(u=u-1,d.trigger(E.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:d.currentLevel}),d.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=s,this.lastDecodedFrames=t}}checkFPSInterval(){let e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){let t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}};function aT(i,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=i,e.dispatchEvent(t)}function oT(i,e){let t=i.mode;if(t==="disabled"&&(i.mode="hidden"),i.cues&&!i.cues.getCueById(e.id))try{if(i.addCue(e),!i.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(s){Be.debug(`[texttrack-utils]: ${s}`);try{let r=new self.TextTrackCue(e.startTime,e.endTime,e.text);r.id=e.id,i.addCue(r)}catch(r){Be.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${r}`)}}t==="disabled"&&(i.mode=t)}function Zn(i,e){let t=i.mode;if(t==="disabled"&&(i.mode="hidden"),i.cues)for(let s=i.cues.length;s--;)e&&i.cues[s].removeEventListener("enter",e),i.removeCue(i.cues[s]);t==="disabled"&&(i.mode=t)}function Ap(i,e,t,s){let r=i.mode;if(r==="disabled"&&(i.mode="hidden"),i.cues&&i.cues.length>0){let n=BD(i.cues,e,t);for(let a=0;a<n.length;a++)(!s||s(n[a]))&&i.removeCue(n[a])}r==="disabled"&&(i.mode=r)}function FD(i,e){if(e<=i[0].startTime)return 0;let t=i.length-1;if(e>i[t].endTime)return-1;let s=0,r=t,n;for(;s<=r;)if(n=Math.floor((r+s)/2),e<i[n].startTime)r=n-1;else if(e>i[n].startTime&&s<t)s=n+1;else return n;return i[s].startTime-e<e-i[r].startTime?s:r}function BD(i,e,t){let s=[],r=FD(i,e);if(r>-1)for(let n=r,a=i.length;n<a;n++){let o=i[n];if(o.startTime>=e&&o.endTime<=t)s.push(o);else if(o.startTime>t)return s}return s}function ou(i){let e=[];for(let t=0;t<i.length;t++){let s=i[t];(s.kind==="subtitles"||s.kind==="captions")&&s.label&&e.push(i[t])}return e}var Sp=class extends jo{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.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null,s=ou(this.media.textTracks);for(let n=0;n<s.length;n++)if(s[n].mode==="hidden")t=s[n];else if(s[n].mode==="showing"){t=s[n];break}let r=this.findTrackForTextTrack(t);this.subtitleTrack!==r&&this.setSubtitleTrack(r)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){let{hls:e}=this;e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(E.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(E.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){let s=this.media;if(!s)return;let r=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,r)return;ou(s.textTracks).forEach(a=>{Zn(a)})}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:s,groupId:r,details:n}=t,a=this.tracksInGroup[s];if(!a||a.groupId!==r){this.warn(`Subtitle track with id:${s} and group:${r} not found in active group ${a==null?void 0:a.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Subtitle track ${s} "${a.name}" lang:${a.lang} group:${r} loaded [${n.startSN}-${n.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let s=t.subtitleGroups||null,r=this.groupIds,n=this.currentTrack;if(!s||(r==null?void 0:r.length)!==(s==null?void 0:s.length)||s!=null&&s.some(a=>(r==null?void 0:r.indexOf(a))===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;let a=this.tracks.filter(u=>!s||s.indexOf(u.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(u=>u.default)&&(this.selectDefaultTrack=!1),a.forEach((u,c)=>{u.id=c});else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=a;let o=this.hls.config.subtitlePreference;if(!n&&o){this.selectDefaultTrack=!1;let u=Ji(o,a);if(u>-1)n=a[u];else{let c=Ji(o,this.tracks);n=this.tracks[c]}}let l=this.findTrackId(n);l===-1&&n&&(l=this.findTrackId(null));let d={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${s==null?void 0:s.join(",")}" group-id`),this.hls.trigger(E.SUBTITLE_TRACKS_UPDATED,d),l!==-1&&this.trackId===-1&&this.setSubtitleTrack(l)}}findTrackId(e){let t=this.tracksInGroup,s=this.selectDefaultTrack;for(let r=0;r<t.length;r++){let n=t[r];if(!(s&&!n.default||!s&&!e)&&(!e||Jr(n,e)))return r}if(e){for(let r=0;r<t.length;r++){let n=t[r];if(zo(e.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return r}for(let r=0;r<t.length;r++){let n=t[r];if(zo(e.attrs,n.attrs,["LANGUAGE"]))return r}}return-1}findTrackForTextTrack(e){if(e){let t=this.tracksInGroup;for(let s=0;s<t.length;s++){let r=t[s];if(hp(r,e))return s}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===Le.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;let t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){let s=this.currentTrack;if(s&&Jr(e,s))return s;let r=Ji(e,this.tracksInGroup);if(r>-1){let n=this.tracksInGroup[r];return this.setSubtitleTrack(r),n}else{if(s)return null;{let n=Ji(e,t);if(n>-1)return t[n]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let s=e.id,r=e.groupId,n=this.getUrlWithDirectives(e.url,t),a=e.details,o=a==null?void 0:a.age;this.log(`Loading subtitle ${s} "${e.name}" lang:${e.lang} group:${r}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${n}`),this.hls.trigger(E.SUBTITLE_TRACK_LOADING,{url:n,id:s,groupId:r,deliveryDirectives:t||null,track:e})}toggleTrackModes(){let{media:e}=this;if(!e)return;let t=ou(e.textTracks),s=this.currentTrack,r;if(s&&(r=t.filter(n=>hp(s,n))[0],r||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(t).forEach(n=>{n.mode!=="disabled"&&n!==r&&(n.mode="disabled")}),r){let n=this.subtitleDisplay?"showing":"hidden";r.mode!==n&&(r.mode=n)}}setSubtitleTrack(e){let t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!Q(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;let s=this.currentTrack,r=t[e]||null;if(this.trackId=e,this.currentTrack=r,this.toggleTrackModes(),!r){this.hls.trigger(E.SUBTITLE_TRACK_SWITCH,{id:e});return}let n=!!r.details&&!r.details.live;if(e===this.trackId&&r===s&&n)return;this.log(`Switching to subtitle-track ${e}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));let{id:a,groupId:o="",name:l,type:d,url:u}=r;this.hls.trigger(E.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:d,url:u});let c=this.switchParams(r.url,s==null?void 0:s.details,r.details);this.loadPlaylist(c)}};function $D(){try{return crypto.randomUUID()}catch{try{let e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let n=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(r=="x"?n:n&3|8).toString(16)})}}}function No(i){let e=5381,t=i.length;for(;t;)e=e*33^i.charCodeAt(--t);return(e>>>0).toString()}var sa=.025,ku=function(i){return i[i.Point=0]="Point",i[i.Range=1]="Range",i}({});function HD(i,e,t){return`${i.identifier}-${t+1}-${No(e)}`}var Ip=class{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;let s=this.playoutLimit;return e<=0||isNaN(s)?!1:s===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>s}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){let e=this.dateRange.startTime;if(this.snapOptions.out){let t=this.dateRange.tagAnchor;if(t)return _m(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;let e=this.dateRange.tagAnchor;if(e){let t=this.dateRange.startTime,s=_m(t,e);return t-s<.1}return!1}get resumptionOffset(){let e=this.resumeOffset,t=Q(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){let e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){let t=this.resumeAnchor;if(t)return _m(e,t)}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<sa))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){let e=this.playoutLimit,t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?ku.Range:ku.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return GD(this)}};function _m(i,e){return i-e.start<e.duration/2&&!(Math.abs(i-(e.start+e.duration))<sa)?e.start:e.start+e.duration}function lT(i,e,t){let s=new self.URL(i,t);return s.protocol!=="data:"&&s.searchParams.set("_HLS_primary_id",e),s}function Am(i,e){for(;(t=i.assetList[++e])!=null&&t.error;)var t;return e}function GD(i){return`["${i.identifier}" ${i.cue.pre?"<pre>":i.cue.post?"<post>":""}${i.timelineStart.toFixed(2)}-${i.resumeTime.toFixed(2)}]`}function Xn(i){let e=i.timelineStart,t=i.duration||0;return`["${i.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}var Lp=class{constructor(e,t,s,r){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(E.PLAYOUT_LIMIT_REACHED,{})};let n=this.hls=new e(t);this.interstitial=s,this.assetItem=r;let a=()=>{this.hasDetails=!0};n.once(E.LEVEL_LOADED,a),n.once(E.AUDIO_TRACK_LOADED,a),n.once(E.SUBTITLE_TRACK_LOADED,a),n.on(E.MEDIA_ATTACHING,(o,{media:l})=>{this.removeMediaListeners(),this.mediaAttached=l,this.interstitial.playoutLimit&&(l.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&n.on(E.BUFFER_APPENDED,()=>{let u=this.bufferedEnd;this.reachedPlayout(u)&&(this._bufferedEosTime=u,n.trigger(E.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){let e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=lT(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e)return!1;let s=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset,n=Ee.bufferInfo(e,r,0);return this.getAssetTime(n.end)>=s-.02}reachedPlayout(e){let s=this.interstitial.playoutLimit;return this.startOffset+e>=s}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){let e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;let t=Ee.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){let e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){let e=this.assetItem.duration;if(!e)return 0;let t=this.interstitial.playoutLimit;if(t){let s=t-this.startOffset;if(s>0&&s<e)return s}return e}get remaining(){let e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){let t=this.timelineOffset;if(e!==t){let s=e-t;if(Math.abs(s)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){let t=this.timelineOffset,s=this.duration;return Math.min(Math.max(0,e-t),s)}removeMediaListeners(){let e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){let e=this.hls;if(e&&this.hasDetails){e.stopLoad();let t=s=>delete s.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,s){var r;(r=this.hls)==null||r.on(e,t)}once(e,t,s){var r;(r=this.hls)==null||r.once(e,t)}off(e,t,s){var r;(r=this.hls)==null||r.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${Xn(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}},By=.033,Rp=class extends Qt{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((s,r)=>e<=r.startOffset&&t>r.startOffset?(delete r.error,s+1):s,0):0}get duration(){let e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let s=-1;e.nextEvent?s=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(s=this.findEventIndex(e.previousEvent.identifier)+1);let r=this.items;if(r)for(r[s]||(t===void 0&&(t=e.start),s=this.findItemIndexAtTime(t));s>=0&&(n=r[s])!=null&&n.event;){var n;s--}return s}findItemIndexAtTime(e,t){let s=this.items;if(s)for(let r=0;r<s.length;r++){let n=s[r];if(t&&t!=="primary"&&(n=n[t]),e===n.start||e>n.start&&e<n.end)return r}return-1}findJumpRestrictedIndex(e,t){let s=this.items;if(s)for(let r=e;r<=t&&s[r];r++){let n=s[r].event;if(n!=null&&n.restrictions.jump&&!n.appendInPlace)return r}return-1}findEventIndex(e){let t=this.items;if(t)for(let r=t.length;r--;){var s;if(((s=t[r].event)==null?void 0:s.identifier)===e)return r}return-1}findAssetIndex(e,t){let s=e.assetList,r=s.length;if(r>1)for(let n=0;n<r;n++){let a=s[n];if(!a.error){let o=a.timelineStart;if(t===o||t>o&&(t<o+(a.duration||0)||n===r-1))return n}}return 0}get assetIdAtEnd(){var e;let t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){let s=t.assetList,r=s[s.length-1];if(r)return r.identifier}return null}parseInterstitialDateRanges(e,t){let s=e.main.details,{dateRanges:r}=s,n=this.events,a=this.parseDateRanges(r,{url:s.url},t),o=Object.keys(r),l=n?n.filter(d=>!o.includes(d.identifier)):[];a.length&&a.sort((d,u)=>{let c=d.cue.pre,h=d.cue.post,f=u.cue.pre,m=u.cue.post;if(c&&!f)return-1;if(f&&!c||h&&!m)return 1;if(m&&!h)return-1;if(!c&&!f&&!h&&!m){let p=d.startTime,g=u.startTime;if(p!==g)return p-g}return d.dateRange.tagOrder-u.dateRange.tagOrder}),this.events=a,l.forEach(d=>{this.removeEvent(d)}),this.updateSchedule(e,l)}updateSchedule(e,t=[],s=!1){let r=this.events||[];if(r.length||t.length||this.length<2){let n=this.items,a=this.parseSchedule(r,e);(s||t.length||(n==null?void 0:n.length)!==a.length||a.some((l,d)=>Math.abs(l.playout.start-n[d].playout.start)>.005||Math.abs(l.playout.end-n[d].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(t,n))}}parseDateRanges(e,t,s){let r=[],n=Object.keys(e);for(let a=0;a<n.length;a++){let o=n[a],l=e[o];if(l.isInterstitial){let d=this.eventMap[o];d?d.setDateRange(l):(d=new Ip(l,t),this.eventMap[o]=d,s===!1&&(d.appendInPlace=s)),r.push(d)}}return r}parseSchedule(e,t){let s=[],r=t.main.details,n=r.live?1/0:r.edge,a=0;if(e=e.filter(l=>!l.error&&!(l.cue.once&&l.hasPlayed)),e.length){this.resolveOffsets(e,t);let l=0,d=0;if(e.forEach((u,c)=>{let h=u.cue.pre,f=u.cue.post,m=e[c-1]||null,p=u.appendInPlace,g=f?n:u.startOffset,v=u.duration,b=u.timelineOccupancy===ku.Range?v:0,y=u.resumptionOffset,T=(m==null?void 0:m.startTime)===g,A=g+u.cumulativeDuration,R=p?A+v:g+y;if(h||!f&&g<=0){let x=d;d+=b,u.timelineStart=A;let D=a;a+=v,s.push({event:u,start:A,end:R,playout:{start:D,end:a},integrated:{start:x,end:d}})}else if(g<=n){if(!T){let S=g-l;if(S>By){let C=l,P=d;d+=S;let N=a;a+=S;let $={previousEvent:e[c-1]||null,nextEvent:u,start:C,end:C+S,playout:{start:N,end:a},integrated:{start:P,end:d}};s.push($)}else S>0&&m&&(m.cumulativeDuration+=S,s[s.length-1].end=g)}f&&(R=A),u.timelineStart=A;let x=d;d+=b;let D=a;a+=v,s.push({event:u,start:A,end:R,playout:{start:D,end:a},integrated:{start:x,end:d}})}else return;let I=u.resumeTime;f||I>n?l=n:l=I}),l<n){var o;let u=l,c=d,h=n-l;d+=h;let f=a;a+=h,s.push({previousEvent:((o=s[s.length-1])==null?void 0:o.event)||null,nextEvent:null,start:l,end:u+h,playout:{start:f,end:a},integrated:{start:c,end:d}})}this.setDurations(n,a,d)}else s.push({previousEvent:null,nextEvent:null,start:0,end:n,playout:{start:0,end:n},integrated:{start:0,end:n}}),this.setDurations(n,n,n);return s}setDurations(e,t,s){this.durations={primary:e,playout:t,integrated:s}}resolveOffsets(e,t){let s=t.main.details,r=s.live?1/0:s.edge,n=0,a=-1;e.forEach((o,l)=>{let d=o.cue.pre,u=o.cue.post,c=d?0:u?r:o.startTime;this.updateAssetDurations(o),a===c?o.cumulativeDuration=n:(n=0,a=c),!u&&o.snapOptions.in&&(o.resumeAnchor=sn(null,s.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&l+1<e.length&&e[l+1].startTime-e[l].resumeTime<By&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));let f=Q(o.resumeOffset)?o.resumeOffset:o.duration;n+=f})}primaryCanResumeInPlaceAt(e,t){let s=e.resumeTime,r=e.startTime+e.resumptionOffset;return Math.abs(s-r)>sa?(this.log(`"${e.identifier}" resumption ${s} not aligned with estimated timeline end ${r}`),!1):!Object.keys(t).some(a=>{let o=t[a].details,l=o.edge;if(s>=l)return this.log(`"${e.identifier}" resumption ${s} past ${a} playlist end ${l}`),!1;let d=sn(null,o.fragments,s);if(!d)return this.log(`"${e.identifier}" resumption ${s} does not align with any fragments in ${a} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;let u=a==="audio"?.175:0;return Math.abs(d.start-s)<sa+u||Math.abs(d.end-s)<sa+u?!1:(this.log(`"${e.identifier}" resumption ${s} not aligned with ${a} fragment bounds (${d.start}-${d.end} sn: ${d.sn} cc: ${d.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;let t=e.timelineStart,s=0,r=!1,n=!1;for(let a=0;a<e.assetList.length;a++){let o=e.assetList[a],l=t+s;o.startOffset=s,o.timelineStart=l,r||(r=o.duration===null),n||(n=!!o.error);let d=o.error?0:o.duration||0;s+=d}r&&!n?e.duration=Math.max(s,e.duration):e.duration=s}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}};function Ci(i){return`[${i.event?'"'+i.event.identifier+'"':"primary"}: ${i.start.toFixed(2)}-${i.end.toFixed(2)}]`}var xp=class{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){let s=e.assetListUrl,r;try{r=lT(s,this.hls.sessionId,e.baseUrl)}catch(h){let f=this.assignAssetListError(e,M.ASSET_LIST_LOAD_ERROR,h,s);this.hls.trigger(E.ERROR,f);return}t&&r.protocol!=="data:"&&r.searchParams.set("_HLS_start_offset",""+t);let n=this.hls.config,a=n.loader,o=new a(n),l={responseType:"json",url:r.href},d=n.interstitialAssetListLoadPolicy.default,u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(h,f,m,p)=>{let g=h.data,v=g==null?void 0:g.ASSETS;if(!Array.isArray(v)){let b=this.assignAssetListError(e,M.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),m.url,f,p);this.hls.trigger(E.ERROR,b);return}e.assetListResponse=g,this.hls.trigger(E.ASSET_LIST_LOADED,{event:e,assetListResponse:g,networkDetails:p})},onError:(h,f,m,p)=>{let g=this.assignAssetListError(e,M.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${h.code} ${h.text} (${f.url})`),f.url,p,m);this.hls.trigger(E.ERROR,g)},onTimeout:(h,f,m)=>{let p=this.assignAssetListError(e,M.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,h,m);this.hls.trigger(E.ERROR,p)}};return o.load(l,u,c),this.hls.trigger(E.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,s,r,n,a){return e.error=s,{type:se.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:r,error:s,networkDetails:a,stats:n}}};function $y(i){var e;i==null||(e=i.play())==null||e.catch(()=>{})}function Xd(i,e){return`[${i}] Advancing timeline position to ${e}`}var kp=class extends Qt{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{let s=this.currentTime;if(s===void 0||this.playbackDisabled||!this.schedule)return;let r=s-this.timelinePos;if(Math.abs(r)<1/7056e5)return;let a=r<=-.01;this.timelinePos=s,this.bufferedPos=s;let o=this.playingItem;if(!o){this.checkBuffer();return}if(a&&this.schedule.resetErrorsInRange(s,s-r)&&this.updateSchedule(!0),this.checkBuffer(),a&&s<o.start||s>=o.end){var l;let f=this.findItemIndex(o),m=this.schedule.findItemIndexAtTime(s);if(m===-1&&(m=f+(a?-1:1),this.log(`seeked ${a?"back ":""}to position not covered by schedule ${s} (resolving from ${f} to ${m})`)),!this.isInterstitial(o)&&(l=this.media)!=null&&l.paused&&(this.shouldPlay=!1),!a&&m>f){let p=this.schedule.findJumpRestrictedIndex(f+1,m);if(p>f){this.setSchedulePosition(p);return}}this.setSchedulePosition(m);return}let d=this.playingAsset;if(!d){if(this.playingLastItem&&this.isInterstitial(o)){let f=o.event.assetList[0];f&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(s,f))}return}let u=d.timelineStart,c=d.duration||0;if(a&&s<u||s>=u+c){var h;(h=o.event)!=null&&h.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(s)),this.setScheduleToAssetAtTime(s,d)}},this.onTimeupdate=()=>{let s=this.currentTime;if(s===void 0||this.playbackDisabled)return;if(s>this.timelinePos)this.timelinePos=s,s>this.bufferedPos&&this.checkBuffer();else return;let r=this.playingItem;if(!r||this.playingLastItem)return;if(s>=r.end){this.timelinePos=r.end;let o=this.findItemIndex(r);this.setSchedulePosition(o+1)}let n=this.playingAsset;if(!n)return;let a=n.timelineStart+(n.duration||0);s>=a&&this.setScheduleToAssetAtTime(s,n)},this.onScheduleUpdate=(s,r)=>{let n=this.schedule;if(!n)return;let a=this.playingItem,o=n.events||[],l=n.items||[],d=n.durations,u=s.map(p=>p.identifier),c=!!(o.length||u.length);(c||r)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
44
+ Schedule: ${l.map(p=>Ci(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Removed events ${u}`);let h=null,f=null;a&&(h=this.updateItem(a,this.timelinePos),this.itemsMatch(a,h)?this.playingItem=h:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);let m=this.bufferingItem;if(m&&(f=this.updateItem(m,this.bufferedPos),this.itemsMatch(m,f)?this.bufferingItem=f:m.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(m.event,null))),s.forEach(p=>{p.assetList.forEach(g=>{this.clearAssetPlayer(g.identifier,null)})}),this.playerQueue.forEach(p=>{if(p.interstitial.appendInPlace){let g=p.assetItem.timelineStart,v=p.timelineOffset-g;if(v)try{p.timelineOffset=g}catch(b){Math.abs(v)>sa&&this.warn(`${b} ("${p.assetId}" ${p.timelineOffset}->${g})`)}}}),c||r){if(this.hls.trigger(E.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:l.slice(0),durations:d,removedIds:u}),this.isInterstitial(a)&&u.includes(a.event.identifier)){this.warn(`Interstitial "${a.event.identifier}" removed while playing`),this.primaryFallback(a.event);return}a&&this.trimInPlace(h,a),m&&f!==h&&this.trimInPlace(f,m),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new xp(e),this.schedule=new Rp(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){let e=this.hls;e&&(e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(E.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(E.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(E.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(E.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(E.BUFFER_APPENDED,this.onBufferAppended,this),e.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(E.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(E.MEDIA_ENDED,this.onMediaEnded,this),e.on(E.ERROR,this.onError,this),e.on(E.DESTROYING,this.onDestroying,this))}unregisterListeners(){let e=this.hls;e&&(e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(E.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(E.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(E.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(E.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(E.BUFFER_CODECS,this.onBufferCodecs,this),e.off(E.BUFFER_APPENDED,this.onBufferAppended,this),e.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(E.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(E.MEDIA_ENDED,this.onMediaEnded,this),e.off(E.ERROR,this.onError,this),e.off(E.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){let e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){zt(e,"play",this.onPlay),zt(e,"pause",this.onPause),zt(e,"seeking",this.onSeeking),zt(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){let s=this.media=t.media;Ht(s,"seeking",this.onSeeking),Ht(s,"timeupdate",this.onTimeupdate),Ht(s,"play",this.onPlay),Ht(s,"pause",this.onPause)}onMediaAttached(e,t){let s=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,s===null)this.checkStart();else if(!r){this.clearScheduleState();let n=this.findItemIndex(s);this.setSchedulePosition(n)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){let s=!!t.transferMedia,r=this.media;if(this.media=null,!s&&(r&&this.removeMediaListeners(r),this.detachedData)){let n=this.getBufferingPlayer();n&&(this.log(`Removing schedule state for detachedData and ${n}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,n.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;let e=this,t=()=>e.bufferingItem||e.waitingItem,s=c=>c&&e.getAssetPlayer(c.identifier),r=(c,h,f,m,p)=>{if(c){let g=c[h].start,v=c.event;if(v){if(h==="playout"||v.timelineOccupancy!==ku.Point){let b=s(f);(b==null?void 0:b.interstitial)===v&&(g+=b.assetItem.startOffset+b[p])}}else{let b=m==="bufferedPos"?a():e[m];g+=b-c.start}return g}return 0},n=(c,h)=>{var f;if(c!==0&&h!=="primary"&&(f=e.schedule)!=null&&f.length){var m;let p=e.schedule.findItemIndexAtTime(c),g=(m=e.schedule.items)==null?void 0:m[p];if(g){let v=g[h].start-g.start;return c+v}}return c},a=()=>{let c=e.bufferedPos;return c===Number.MAX_VALUE?o("primary"):Math.max(c,0)},o=c=>{var h,f;return(h=e.primaryDetails)!=null&&h.live?e.primaryDetails.edge:((f=e.schedule)==null?void 0:f.durations[c])||0},l=(c,h)=>{var f,m;let p=e.effectivePlayingItem;if(p!=null&&(f=p.event)!=null&&f.restrictions.skip||!e.schedule)return;e.log(`seek to ${c} "${h}"`);let g=e.effectivePlayingItem,v=e.schedule.findItemIndexAtTime(c,h),b=(m=e.schedule.items)==null?void 0:m[v],y=e.getBufferingPlayer(),T=y==null?void 0:y.interstitial,A=T==null?void 0:T.appendInPlace,R=g&&e.itemsMatch(g,b);if(g&&(A||R)){let I=s(e.playingAsset),x=(I==null?void 0:I.media)||e.primaryMedia;if(x){let D=h==="primary"?x.currentTime:r(g,h,e.playingAsset,"timelinePos","currentTime"),S=c-D,C=(A?D:x.currentTime)+S;if(C>=0&&(!I||A||C<=I.duration)){x.currentTime=C;return}}}if(b){let I=c;if(h!=="primary"){let D=b[h].start,S=c-D;I=b.start+S}let x=!e.isInterstitial(b);if((!e.isInterstitial(g)||g.event.appendInPlace)&&(x||b.event.appendInPlace)){let D=e.media||(A?y==null?void 0:y.media:null);D&&(D.currentTime=I)}else if(g){let D=e.findItemIndex(g);if(v>D){let C=e.schedule.findJumpRestrictedIndex(D+1,v);if(C>D){e.setSchedulePosition(C);return}}let S=0;if(x)e.timelinePos=I,e.checkBuffer();else{let C=b.event.assetList,P=c-(b[h]||b).start;for(let N=C.length;N--;){let $=C[N];if($.duration&&P>=$.startOffset&&P<$.startOffset+$.duration){S=N;break}}}e.setSchedulePosition(v,S)}}},d=()=>{let c=e.effectivePlayingItem;if(e.isInterstitial(c))return c;let h=t();return e.isInterstitial(h)?h:null},u={get bufferedEnd(){let c=t(),h=e.bufferingItem;if(h&&h===c){var f;return r(h,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-h.playout.start||((f=e.bufferingAsset)==null?void 0:f.startOffset)||0}return 0},get currentTime(){let c=d(),h=e.effectivePlayingItem;return h&&h===c?r(h,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-h.playout.start:0},set currentTime(c){let h=d(),f=e.effectivePlayingItem;f&&f===h&&l(c+f.playout.start,"playout")},get duration(){let c=d();return c?c.playout.end-c.playout.start:0},get assetPlayers(){var c;let h=(c=d())==null?void 0:c.event.assetList;return h?h.map(f=>e.getAssetPlayer(f.identifier)):[]},get playingIndex(){var c;let h=(c=d())==null?void 0:c.event;return h&&e.effectivePlayingAsset?h.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return d()}};return this.manager={get events(){var c;return((c=e.schedule)==null||(c=c.events)==null?void 0:c.slice(0))||[]},get schedule(){var c;return((c=e.schedule)==null||(c=c.items)==null?void 0:c.slice(0))||[]},get interstitialPlayer(){return d()?u:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){let c=t();return e.findItemIndex(c)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){let c=e.effectivePlayingItem;return e.findItemIndex(c)},primary:{get bufferedEnd(){return a()},get currentTime(){let c=e.timelinePos;return c>0?c:0},set currentTime(c){l(c,"primary")},get duration(){return o("primary")},get seekableStart(){var c;return((c=e.primaryDetails)==null?void 0:c.fragmentStart)||0}},integrated:{get bufferedEnd(){return r(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return r(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(c){l(c,"integrated")},get duration(){return o("integrated")},get seekableStart(){var c;return n(((c=e.primaryDetails)==null?void 0:c.fragmentStart)||0,"integrated")}},skip:()=>{let c=e.effectivePlayingItem,h=c==null?void 0:c.event;if(h&&!h.restrictions.skip){let f=e.findItemIndex(c);if(h.appendInPlace){let m=c.playout.start+c.event.duration;l(m+.001,"playout")}else e.advanceAfterAssetEnded(h,f,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;let t=this.playingItem,s=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!s?!1:this.findItemIndex(t)===s.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;let s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let r=this.media;!r&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(r=this.primaryMedia);let n=(t=r)==null?void 0:t.currentTime;if(!(n===void 0||!Q(n)))return n}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){let s=this.getAssetPlayer(e);s&&this.transferMediaFromPlayer(s,t)}transferMediaFromPlayer(e,t){let s=e.interstitial.appendInPlace,r=e.media;if(s&&r===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&r){this.detachedData={media:r};return}let n=e.transferMedia();this.log(`transfer MediaSource from ${e} ${qe(n)}`),this.detachedData=n}else t&&r&&(this.shouldPlay||(this.shouldPlay=!r.paused))}transferMediaTo(e,t){var s,r;if(e.media===t)return;let n=null,a=this.hls,o=e!==a,l=o&&e.interstitial.appendInPlace,d=(s=this.detachedData)==null?void 0:s.mediaSource,u;if(a.media)l&&(n=a.transferMedia(),this.detachedData=n),u="Primary";else if(d){let m=this.getBufferingPlayer();m?(n=m.transferMedia(),u=`${m}`):u="detached MediaSource"}else u="detached media";if(!n){if(d)n=this.detachedData,this.log(`using detachedData: MediaSource ${qe(n)}`);else if(!this.detachedData||a.media===t){let m=this.playerQueue;m.length>1&&m.forEach(p=>{if(o&&p.interstitial.appendInPlace!==l){let g=p.interstitial;this.clearInterstitial(p.interstitial,null),g.appendInPlace=!1,g.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${g}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}let c=n&&"mediaSource"in n&&((r=n.mediaSource)==null?void 0:r.readyState)!=="closed",h=c&&n?n:t;this.log(`${c?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${u} (media.currentTime: ${t.currentTime})`);let f=this.schedule;if(h===n&&f){let m=o&&e.assetId===f.assetIdAtEnd;h.overrides={duration:f.duration,endOfStream:!o||m,cueRemoval:!o}}e.attachMedia(h)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){let e=this.schedule,t=e==null?void 0:e.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);let s=this.timelinePos,r=this.effectivePlayingItem;if(s===-1){let n=this.hls.startPosition;if(this.log(Xd("checkStart",n)),this.timelinePos=n,t.length&&t[0].cue.pre){let a=e.findEventIndex(t[0].identifier);this.setSchedulePosition(a)}else if(n>=0||!this.primaryLive){let a=this.timelinePos=n>0?n:0,o=e.findItemIndexAtTime(a);this.setSchedulePosition(o)}}else if(r&&!this.playingItem){let n=e.findItemIndex(r);this.setSchedulePosition(n)}}advanceAssetBuffering(e,t){let s=e.event,r=s.findAssetIndex(t),n=Am(s,r);if(!s.isAssetPastPlayoutLimit(n))this.bufferedToEvent(e,n);else if(this.schedule){var a;let o=(a=this.schedule.items)==null?void 0:a[this.findItemIndex(e)+1];o&&this.bufferedToItem(o)}}advanceAfterAssetEnded(e,t,s){let r=Am(e,s);if(e.isAssetPastPlayoutLimit(r)){if(this.schedule){let n=this.schedule.items;if(n){let a=t+1,o=n.length;if(a>=o){this.setSchedulePosition(-1);return}let l=e.resumeTime;this.timelinePos<l&&(this.log(Xd("advanceAfterAssetEnded",l)),this.timelinePos=l,e.appendInPlace&&this.advanceInPlace(l),this.checkBuffer(this.bufferedPos<l)),this.setSchedulePosition(a)}}}else{if(e.appendInPlace){let n=e.assetList[r];n&&this.advanceInPlace(n.timelineStart)}this.setSchedulePosition(t,r)}}setScheduleToAssetAtTime(e,t){let s=this.schedule;if(!s)return;let r=t.parentIdentifier,n=s.getEvent(r);if(n){let a=s.findEventIndex(r),o=s.findAssetIndex(n,e);this.advanceAfterAssetEnded(n,a,o-1)}}setSchedulePosition(e,t){var s;let r=(s=this.schedule)==null?void 0:s.items;if(!r||this.playbackDisabled)return;let n=e>=0?r[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${n&&Ci(n)}) pos: ${this.timelinePos}`);let a=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(a)){let u=a.event,c=this.playingAsset,h=c==null?void 0:c.identifier,f=h?this.getAssetPlayer(h):null;if(f&&h&&(!this.eventItemsMatch(a,n)||t!==void 0&&h!==u.assetList[t].identifier)){var l;let m=u.findAssetIndex(c);if(this.log(`INTERSTITIAL_ASSET_ENDED ${m+1}/${u.assetList.length} ${Xn(c)}`),this.endedAsset=c,this.playingAsset=null,this.hls.trigger(E.INTERSTITIAL_ASSET_ENDED,{asset:c,assetListIndex:m,event:u,schedule:r.slice(0),scheduleIndex:e,player:f}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(u,this.findItemIndex(this.playingItem),m);return}this.retreiveMediaSource(h,n),f.media&&!((l=this.detachedData)!=null&&l.mediaSource)&&f.detachMedia()}if(!this.eventItemsMatch(a,n)&&(this.endedItem=a,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${u} ${Ci(a)}`),u.hasPlayed=!0,this.hls.trigger(E.INTERSTITIAL_ENDED,{event:u,schedule:r.slice(0),scheduleIndex:e}),u.cue.once)){var d;this.updateSchedule();let m=(d=this.schedule)==null?void 0:d.items;if(n&&m){let p=this.findItemIndex(n);this.advanceSchedule(p,m,t,a,o)}return}}this.advanceSchedule(e,r,t,a,o)}advanceSchedule(e,t,s,r,n){let a=this.schedule;if(!a)return;let o=t[e]||null,l=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(u=>{let c=u.interstitial,h=a.findEventIndex(c.identifier);(h<e||h>e+1)&&this.clearInterstitial(c,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);let u=o.event;if(s===void 0){s=a.findAssetIndex(u,this.timelinePos);let m=Am(u,s-1);if(u.isAssetPastPlayoutLimit(m)||u.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(u,e,s);return}s=m}let c=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);let h=this.preloadAssets(u,s);if(this.eventItemsMatch(o,c||r)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${Ci(o)} ${u.appendInPlace?"append in place":""}`),this.hls.trigger(E.INTERSTITIAL_STARTED,{event:u,schedule:t.slice(0),scheduleIndex:e})),!u.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${u}`);return}if(u.assetListLoader&&(u.assetListLoader.destroy(),u.assetListLoader=void 0),!l){this.log(`Waiting for attachMedia to start Interstitial ${u}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;let f=u.assetList[s];if(!f){this.advanceAfterAssetEnded(u,e,s||0);return}if(h||(h=this.getAssetPlayer(f.identifier)),h===null||h.destroyed){let m=u.assetList.length;this.warn(`asset ${s+1}/${m} player destroyed ${u}`),h=this.createAssetPlayer(u,f,s),h.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&u.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(h,s,t,e,l),this.shouldPlay&&$y(h.media)}else o?(this.resumePrimary(o,e,r),this.shouldPlay&&$y(this.hls.media)):n&&this.isInterstitial(r)&&(this.endedItem=null,this.playingItem=r,r.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,s){var r,n;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${Ci(e)}`),!((r=this.detachedData)!=null&&r.mediaSource)){let o=this.timelinePos;(o<e.start||o>=e.end)&&(o=this.getPrimaryResumption(e,t),this.log(Xd("resumePrimary",o)),this.timelinePos=o),this.attachPrimary(o,e)}if(!s)return;let a=(n=this.schedule)==null?void 0:n.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Ci(e)}`),this.hls.trigger(E.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){let s=e.start;if(this.primaryLive){let r=this.primaryDetails;if(t===0)return this.hls.startPosition;if(r&&(s<r.fragmentStart||s>r.edge))return this.hls.liveSyncPosition||-1}return s}isAssetBuffered(e){let t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:Ee.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,s){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;let r=this.primaryMedia;if(!r)return;let n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,r),s&&this.startLoadingPrimaryAt(e,s)),s||(this.log(Xd("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,s))}startLoadingPrimaryAt(e,t){var s;let r=this.hls;!r.loadingEnabled||!r.media||Math.abs((((s=r.mainForwardBufferInfo)==null?void 0:s.start)||r.media.currentTime)-e)>.5?r.startLoad(e,t):r.bufferingEnabled||r.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(E.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(E.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;let s=this.hls.levels[t.level];if(!s.details)return;let r=Fe(Fe({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=r,this.schedule.parseInterstitialDateRanges(r,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){let s=this.hls.audioTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=Fe(Fe({},this.altSelection),{},{audio:s});return}let n=Fe(Fe({},r),{},{audio:s});this.mediaSelection=n}onSubtitleTrackUpdated(e,t){let s=this.hls.subtitleTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=Fe(Fe({},this.altSelection),{},{subtitles:s});return}let n=Fe(Fe({},r),{},{subtitles:s});this.mediaSelection=n}onAudioTrackSwitching(e,t){let s=QE(t);this.playerQueue.forEach(({hls:r})=>r&&(r.setAudioOption(t)||r.setAudioOption(s)))}onSubtitleTrackSwitch(e,t){let s=QE(t);this.playerQueue.forEach(({hls:r})=>r&&(r.setSubtitleOption(t)||t.id!==-1&&r.setSubtitleOption(s)))}onBufferCodecs(e,t){let s=t.tracks;s&&(this.requiredTracks=s)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){let s=this.playingItem;if(s&&!this.itemsMatch(s,this.bufferingItem)&&!this.isInterstitial(s)){let r=this.timelinePos;this.bufferedPos=r,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;let t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let r=0;r<t.length;r++){let n=t[r];if(n.cue.post){var s;let a=this.schedule.findEventIndex(n.identifier),o=(s=this.schedule.items)==null?void 0:s[a];this.isInterstitial(o)&&this.eventItemsMatch(o,this.bufferingItem)&&this.bufferedToItem(o,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){let t=this.playingItem;if(!this.playingLastItem&&t){let s=this.findItemIndex(t);this.setSchedulePosition(s+1)}else this.shouldPlay=!1}updateItem(e,t){var s;let r=(s=this.schedule)==null?void 0:s.items;if(e&&r){let n=this.findItemIndex(e,t);return r[n]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((n,a)=>{e.event.isAssetPastPlayoutLimit(a)&&this.clearAssetPlayer(n.identifier,null)});let s=e.end+.25,r=Ee.bufferInfo(this.primaryMedia,s,0);(r.end>s||(r.nextStart||0)>s)&&(this.log(`trim buffered interstitial ${Ci(e)} (was ${Ci(t)})`),this.attachPrimary(s,null,!0),this.flushFrontBuffer(s))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var s;return!!t&&(e===t||e.event.identifier===((s=t.event)==null?void 0:s.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;let s=this.mediaSelection;s&&((t=this.schedule)==null||t.updateSchedule(s,[],e))}checkBuffer(e){var t;let s=(t=this.schedule)==null?void 0:t.items;if(!s)return;let r=Ee.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=r.len<1),this.updateBufferedPos(r.end,s,e)}updateBufferedPos(e,t,s){let r=this.schedule,n=this.bufferingItem;if(this.bufferedPos>e||!r)return;if(t.length===1&&this.itemsMatch(t[0],n)){this.bufferedPos=e;return}let a=this.playingItem,o=this.findItemIndex(a),l=r.findItemIndexAtTime(e);if(this.bufferedPos<e){var d;let u=this.findItemIndex(n),c=Math.min(u+1,t.length-1),h=t[c];if((l===-1&&n&&e>=n.end||(d=h.event)!=null&&d.appendInPlace&&e+.01>=h.start)&&(l=c),this.isInterstitial(n)){let f=n.event;if(c-o>1&&f.appendInPlace===!1||f.assetList.length===0&&f.assetListLoader)return}if(this.bufferedPos=e,l>u&&l>o)this.bufferedToItem(h);else{let f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&h.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(h)&&this.preloadAssets(h.event,0)}}else s&&a&&!this.itemsMatch(a,n)&&(l===o?this.bufferedToItem(a):l===o+1&&this.bufferedToItem(t[l]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(r=>{let n=this.getAssetPlayer(r.identifier);return!(n!=null&&n.bufferedInPlaceToEnd(t))})}setBufferingItem(e){let t=this.bufferingItem,s=this.schedule;if(!this.itemsMatch(e,t)&&s){let{items:r,events:n}=s;if(!r||!n)return t;let a=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));let l=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Ci(e)}`+(t?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){let d=s.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((u,c)=>{let h=this.getAssetPlayer(u.identifier);h&&(c===d&&h.loadSource(),h.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(d=>d.pauseBuffering());this.hls.trigger(E.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:n.slice(0),schedule:r.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){let s=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(s!==null){this.bufferingAsset=null;let r=this.detachedData;r?r.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){let t=this.findItemIndex(e),s=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(s)}bufferedToEvent(e,t){let s=e.event,r=s.assetList.length===0&&!s.assetListLoader,n=s.cue.once;if(r||!n){let a=this.preloadAssets(s,t);if(a!=null&&a.interstitial.appendInPlace){let o=this.primaryMedia;o&&this.bufferAssetPlayer(a,o)}}}preloadAssets(e,t){let s=e.assetUrl,r=e.assetList.length,n=r===0&&!e.assetListLoader,a=e.cue.once;if(n){let l=e.timelineStart;if(e.appendInPlace){var o;let h=this.playingItem;!this.isInterstitial(h)&&(h==null||(o=h.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(l+.25)}let d,u=0;if(!this.playingItem&&this.primaryLive&&(u=this.hls.startPosition,u===-1&&(u=this.hls.liveSyncPosition||0)),u&&!(e.cue.pre||e.cue.post)){let h=u-l;h>0&&(d=Math.round(h*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${s?1:r} ${e}${d?` live-start: ${u} start-offset: ${d}`:""}`),s)return this.createAsset(e,0,0,l,e.duration,s);let c=this.assetListLoader.loadAssetList(e,d);c&&(e.assetListLoader=c)}else if(!a&&r){for(let d=t;d<r;d++){let u=e.assetList[d],c=this.getAssetPlayerQueueIndex(u.identifier);(c===-1||this.playerQueue[c].destroyed)&&!u.error&&this.createAssetPlayer(e,u,d)}let l=e.assetList[t];if(l){let d=this.getAssetPlayer(l.identifier);return d&&d.loadSource(),d}}return null}flushFrontBuffer(e){let t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(r=>{this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:r})})}getAssetPlayerQueueIndex(e){let t=this.playerQueue;for(let s=0;s<t.length;s++)if(e===t[s].assetId)return s;return-1}getAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){let{playerQueue:e,primaryMedia:t}=this;if(t){for(let s=0;s<e.length;s++)if(e[s].media===t)return e[s]}return null}createAsset(e,t,s,r,n,a){let o={parentIdentifier:e.identifier,identifier:HD(e,a,t),duration:n,startOffset:s,timelineStart:r,uri:a};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,s){let r=this.hls,n=r.userConfig,a=n.videoPreference,o=r.loadLevelObj||r.levels[r.currentLevel];(a||o)&&(a=$e({},a),o.videoCodec&&(a.videoCodec=o.videoCodec),o.videoRange&&(a.allowedVideoRanges=[o.videoRange]));let l=r.audioTracks[r.audioTrack],d=r.subtitleTracks[r.subtitleTrack],u=0;if(this.primaryLive||e.appendInPlace){let T=this.timelinePos-t.timelineStart;if(T>1){let A=t.duration;A&&T<A&&(u=T)}}let c=t.identifier,h=Fe(Fe({},n),{},{maxMaxBufferLength:Math.min(180,r.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:r.sessionId,assetPlayerId:c,abrEwmaDefaultEstimate:r.bandwidthEstimate,interstitialsController:void 0,startPosition:u,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:a,audioPreference:l||n.audioPreference,subtitlePreference:d||n.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(h.timelineOffset=t.timelineStart));let f=h.cmcd;f!=null&&f.sessionId&&f.contentId&&(h.cmcd=$e({},f,{contentId:No(t.uri)})),this.getAssetPlayer(c)&&this.warn(`Duplicate date range identifier ${e} and asset ${c}`);let m=new Lp(this.HlsPlayerClass,h,e,t);this.playerQueue.push(m),e.assetList[s]=t;let p=!0,g=T=>{if(T.live){var A;let x=new Error(`Interstitials MUST be VOD assets ${e}`),D={fatal:!0,type:se.OTHER_ERROR,details:M.INTERSTITIAL_ASSET_ITEM_ERROR,error:x},S=((A=this.schedule)==null?void 0:A.findEventIndex(e.identifier))||-1;this.handleAssetItemError(D,e,S,s,x.message);return}let R=T.edge-T.fragmentStart,I=t.duration;(p||I===null||R>I)&&(p=!1,this.log(`Interstitial asset "${c}" duration change ${I} > ${R}`),t.duration=R,this.updateSchedule())};m.on(E.LEVEL_UPDATED,(T,{details:A})=>g(A)),m.on(E.LEVEL_PTS_UPDATED,(T,{details:A})=>g(A)),m.on(E.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());let v=(T,A)=>{let R=this.getAssetPlayer(c);if(R&&A.tracks){R.off(E.BUFFER_CODECS,v),R.tracks=A.tracks;let I=this.primaryMedia;this.bufferingAsset===R.assetItem&&I&&!R.media&&this.bufferAssetPlayer(R,I)}};m.on(E.BUFFER_CODECS,v);let b=()=>{var T;let A=this.getAssetPlayer(c);if(this.log(`buffered to end of asset ${A}`),!A||!this.schedule)return;let R=this.schedule.findEventIndex(e.identifier),I=(T=this.schedule.items)==null?void 0:T[R];this.isInterstitial(I)&&this.advanceAssetBuffering(I,t)};m.on(E.BUFFERED_TO_END,b);let y=T=>()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;this.shouldPlay=!0;let R=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,R,T)};return m.once(E.MEDIA_ENDED,y(s)),m.once(E.PLAYOUT_LIMIT_REACHED,y(1/0)),m.on(E.ERROR,(T,A)=>{if(!this.schedule)return;let R=this.getAssetPlayer(c);if(A.details===M.BUFFER_STALLED_ERROR){if(R!=null&&R.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(A,e,this.schedule.findEventIndex(e.identifier),s,`Asset player error ${A.error} ${e}`)}),m.on(E.DESTROYING,()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;let A=new Error(`Asset player destroyed unexpectedly ${c}`),R={fatal:!0,type:se.OTHER_ERROR,details:M.INTERSTITIAL_ASSET_ITEM_ERROR,error:A};this.handleAssetItemError(R,e,this.schedule.findEventIndex(e.identifier),s,A.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Xn(t)}`),this.hls.trigger(E.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:m}),m}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(s=>{this.clearAssetPlayer(s.identifier,t)})}resetAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);let s=this.playerQueue[t];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(e,t){let s=this.getAssetPlayerQueueIndex(e);if(s!==-1){let r=this.playerQueue[s];this.log(`clear ${r} toSegment: ${t&&Ci(t)}`),this.transferMediaFromPlayer(r,t),this.playerQueue.splice(s,1),r.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,s,r,n){let{interstitial:a,assetItem:o,assetId:l}=e,d=a.assetList.length,u=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!u||u.identifier!==l)&&(u&&(this.clearAssetPlayer(u.identifier,s[r]),delete u.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${d} ${Xn(o)}`),this.hls.trigger(E.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:a,schedule:s.slice(0),scheduleIndex:r,player:e})),this.bufferAssetPlayer(e,n)}bufferAssetPlayer(e,t){var s,r;if(!this.schedule)return;let{interstitial:n,assetItem:a}=e,o=this.schedule.findEventIndex(n.identifier),l=(s=this.schedule.items)==null?void 0:s[o];if(!l)return;e.loadSource(),this.setBufferingItem(l),this.bufferingAsset=a;let d=this.getBufferingPlayer();if(d===e)return;let u=n.appendInPlace;if(u&&(d==null?void 0:d.interstitial.appendInPlace)===!1)return;let c=(d==null?void 0:d.tracks)||((r=this.detachedData)==null?void 0:r.tracks)||this.requiredTracks;if(u&&a!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(c&&!Xy(c,e.tracks)){let h=new Error(`Asset ${Xn(a)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(c)}')`),f={fatal:!0,type:se.OTHER_ERROR,details:M.INTERSTITIAL_ASSET_ITEM_ERROR,error:h},m=n.findAssetIndex(a);this.handleAssetItemError(f,n,o,m,h.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){let t=this.schedule,s=this.primaryMedia;if(!t||!s)return;let r=s.currentTime,n=t.findAssetIndex(e,r),a=e.assetList[n];if(a){let o=this.getAssetPlayer(a.identifier);if(o){let l=o.currentTime||r-a.timelineStart,d=o.duration-l;if(this.warn(`Stalled at ${l} of ${l+d} in ${o} ${e} (media.currentTime: ${r})`),l&&(d/s.playbackRate<.5||o.bufferedInPlaceToEnd(s))&&o.hls){let u=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,u,n)}}}}advanceInPlace(e){let t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,s,r,n){if(e.details===M.BUFFER_STALLED_ERROR)return;let a=t.assetList[r]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&Xn(a)} ${e.error}`),!this.schedule)return;let o=(a==null?void 0:a.identifier)||"",l=this.getAssetPlayerQueueIndex(o),d=this.playerQueue[l]||null,u=this.schedule.items,c=$e({},e,{fatal:!1,errorAction:ea(!0),asset:a,assetListIndex:r,event:t,schedule:u,scheduleIndex:s,player:d});if(this.hls.trigger(E.INTERSTITIAL_ASSET_ERROR,c),!e.fatal)return;let h=this.playingAsset,f=this.bufferingAsset,m=new Error(n);if(a&&(this.clearAssetPlayer(o,null),a.error=m),!t.assetList.some(p=>!p.error))t.error=m;else for(let p=r;p<t.assetList.length;p++)this.resetAssetPlayer(t.assetList[p].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):h&&h.identifier===o?this.advanceAfterAssetEnded(t,s,r):f&&f.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){let t=e.timelineStart,s=this.effectivePlayingItem,r=this.timelinePos;if(s){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${r} playing: ${Ci(s)} error: ${e.error}`),r===-1&&(r=this.hls.startPosition);let a=this.updateItem(s,r);this.itemsMatch(s,a)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(r===-1){this.checkStart();return}if(!this.schedule)return;let n=this.schedule.findItemIndexAtTime(r);this.setSchedulePosition(n)}onAssetListLoaded(e,t){var s,r;let n=t.event,a=n.identifier,o=t.assetListResponse.ASSETS;if(!((s=this.schedule)!=null&&s.hasEvent(a)))return;let l=n.timelineStart,d=n.duration,u=0;o.forEach((p,g)=>{let v=parseFloat(p.DURATION);this.createAsset(n,g,u,l+u,v,p.URI),u+=v}),n.duration=u,this.log(`Loaded asset-list with duration: ${u} (was: ${d}) ${n}`);let c=this.waitingItem,h=(c==null?void 0:c.event.identifier)===a;this.updateSchedule();let f=(r=this.bufferingItem)==null?void 0:r.event;if(h){var m;let p=this.schedule.findEventIndex(a),g=(m=this.schedule.items)==null?void 0:m[p];if(g){if(!this.playingItem&&this.timelinePos>g.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==p){n.error=new Error(`Interstitial ${o.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${n}`),this.log(n.error.message),this.updateSchedule(!0),this.primaryFallback(n);return}this.setBufferingItem(g)}this.setSchedulePosition(p)}else if((f==null?void 0:f.identifier)===a){let p=n.assetList[0];if(p){let g=this.getAssetPlayer(p.identifier);if(f.appendInPlace){let v=this.primaryMedia;g&&v&&this.bufferAssetPlayer(g,v)}else g&&g.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case M.ASSET_LIST_PARSING_ERROR:case M.ASSET_LIST_LOAD_ERROR:case M.ASSET_LIST_LOAD_TIMEOUT:{let s=t.interstitial;s&&(this.updateSchedule(!0),this.primaryFallback(s));break}case M.BUFFER_STALLED_ERROR:{let s=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&s.event.appendInPlace){this.handleInPlaceStall(s.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}},Hy=500,Dp=class extends Ko{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",J.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(E.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(E.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(E.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(E.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=O.IDLE,this.setInterval(Hy),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){let{frag:s,success:r}=t;if(this.fragContextChanged(s)||(at(s)&&(this.fragPrevious=s),this.state=O.IDLE),!r)return;let n=this.tracksBuffered[this.currentTrackId];if(!n)return;let a,o=s.start;for(let d=0;d<n.length;d++)if(o>=n[d].start&&o<=n[d].end){a=n[d];break}let l=s.start+s.duration;a?a.end=l:(a={start:o,end:l},n.push(a)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null),this.media&&this.tick()}onBufferFlushing(e,t){let{startOffset:s,endOffset:r}=t;if(s===0&&r!==Number.POSITIVE_INFINITY){let n=r-1;if(n<=0)return;t.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach(a=>{for(let o=0;o<a.length;){if(a[o].end<=n){a.shift();continue}else if(a[o].start<n)a[o].start=n;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(s,n,J.SUBTITLE)}}onError(e,t){let s=t.frag;(s==null?void 0:s.type)===J.SUBTITLE&&(t.details===M.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==O.STOPPED&&(this.state=O.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&jb(this.levels,t)){this.levels=t.map(s=>new tn(s));return}this.tracksBuffered=[],this.levels=t.map(s=>{let r=new tn(s);return this.tracksBuffered[r.id]=[],r}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,J.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,!((s=this.levels)!=null&&s.length)||this.currentTrackId===-1){this.clearInterval();return}let r=this.levels[this.currentTrackId];r!=null&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.state!==O.STOPPED&&this.setInterval(Hy)}onSubtitleTrackLoaded(e,t){var s;let{currentTrackId:r,levels:n}=this,{details:a,id:o}=t;if(!n){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}let l=n[o];if(o>=n.length||!l)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let d=0;if(a.live||(s=l.details)!=null&&s.live){if(a.deltaUpdateFailed)return;let c=this.mainDetails;if(!c){this.startFragRequested=!1;return}let h=c.fragments[0];if(!l.details)a.hasProgramDateTime&&c.hasProgramDateTime?(Tu(a,c),d=a.fragmentStart):h&&(d=h.start,Qm(a,d));else{var u;d=this.alignPlaylists(a,l.details,(u=this.levelLastLoaded)==null?void 0:u.details),d===0&&h&&(d=h.start,Qm(a,d))}c&&!this.startFragRequested&&this.setStartPosition(c,d)}l.details=a,this.levelLastLoaded=l,o===r&&(this.hls.trigger(E.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:t.groupId}),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===O.IDLE&&(sn(null,a.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0)))}_handleFragmentLoadComplete(e){let{frag:t,payload:s}=e,r=t.decryptdata,n=this.hls;if(!this.fragContextChanged(t)&&s&&s.byteLength>0&&r!=null&&r.key&&r.iv&&ta(r.method)){let a=performance.now();this.decrypter.decrypt(new Uint8Array(s),r.key.buffer,r.iv.buffer,tg(r.method)).catch(o=>{throw n.trigger(E.ERROR,{type:se.MEDIA_ERROR,details:M.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:t}),o}).then(o=>{let l=performance.now();n.trigger(E.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:a,tdecrypt:l}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=O.IDLE})}}doTick(){if(!this.media){this.state=O.IDLE;return}if(this.state===O.IDLE){let{currentTrackId:e,levels:t}=this,s=t==null?void 0:t[e];if(!s||!t.length||!s.details||this.waitForLive(s))return;let{config:r}=this,n=this.getLoadPosition(),a=Ee.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,r.maxBufferHole),{end:o,len:l}=a,d=s.details,u=this.hls.maxBufferLength+d.levelTargetDuration;if(l>u)return;let c=d.fragments,h=c.length,f=d.edge,m=null,p=this.fragPrevious;if(o<f){let b=r.maxFragLookUpTolerance,y=o>f-b?0:b;m=sn(p,c,Math.max(c[0].start,o),y),!m&&p&&p.start<c[0].start&&(m=c[0])}else m=c[h-1];if(m=this.filterReplacedPrimary(m,s.details),!m)return;let g=m.sn-d.startSN,v=c[g-1];if(v&&v.cc===m.cc&&this.fragmentTracker.getState(v)===Tt.NOT_LOADED&&(m=v),this.fragmentTracker.getState(m)===Tt.NOT_LOADED){let b=this.mapToInitFragWhenRequired(m);b&&this.loadFragment(b,s,o)}}}loadFragment(e,t,s){at(e)?super.loadFragment(e,t,s):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new Cp(this.tracksBuffered[this.currentTrackId]||[])}},Cp=class{constructor(e){this.buffered=void 0;let t=(s,r,n)=>{if(r=r>>>0,r>n-1)throw new DOMException(`Failed to execute '${s}' on 'TimeRanges': The index provided (${r}) is greater than the maximum bound (${n})`);return e[r][s]};this.buffered={get length(){return e.length},end(s){return t("end",s,e.length)},start(s){return t("start",s,e.length)}}}},KD={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},dT=i=>String.fromCharCode(KD[i]||i),wi=15,xs=100,VD={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},WD={17:2,18:4,21:6,22:8,23:10,19:13,20:15},qD={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},YD={25:2,26:4,29:6,30:8,31:10,27:13,28:15},jD=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],wp=class{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){let s=typeof t=="function"?t():t;Be.log(`${this.time} [${e}] ${s}`)}}},Qr=function(e){let t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t},Du=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 s=0;s<t.length;s++){let r=t[s];e.hasOwnProperty(r)&&(this[r]=e[r])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}},Mp=class{constructor(){this.uchar=" ",this.penState=new Du}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()}},Pp=class{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Du,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<xs;t++)this.chars.push(new Mp);this.logger=e}equals(e){for(let t=0;t<xs;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<xs;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<xs;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>xs&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=xs)}moveCursor(e){let t=this.pos+e;if(e>1)for(let s=this.pos+1;s<t+1;s++)this.chars[s].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=dT(e);if(this.pos>=xs){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t<xs;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 s=0;s<xs;s++){let r=this.chars[s].uchar;r!==" "&&(t=!1),e.push(r)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}},Uo=class{constructor(e){this.rows=[],this.currRow=wi-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<wi;t++)this.rows.push(new Pp(e));this.logger=e}reset(){for(let e=0;e<wi;e++)this.rows[e].clear();this.currRow=wi-1}equals(e){let t=!0;for(let s=0;s<wi;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<wi;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<wi;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 = "+qe(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let o=0;o<wi;o++)this.rows[o].clear();let n=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){let o=a.rows[n].cueStartTime,l=this.logger.time;if(o!==null&&l!==null&&o<l)for(let d=0;d<this.nrRollUpRows;d++)this.rows[t-this.nrRollUpRows+d+1].copy(a.rows[n+d])}}this.currRow=t;let s=this.rows[this.currRow];if(e.indent!==null){let n=e.indent,a=Math.max(n-1,0);s.setCursor(e.indent),e.color=s.chars[a].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 = "+qe(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());let e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;let t=[],s="",r=-1;for(let n=0;n<wi;n++){let a=this.rows[n].getTextString();a&&(r=n+1,e?t.push("Row "+r+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(e?s="["+t.join(" | ")+"]":s=t.join(`
45
+ `)),s}getTextAndFormat(){return this.rows}},Cu=class{constructor(e,t,s){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 Uo(s),this.nonDisplayedMemory=new Uo(s),this.lastOutputScreen=new Uo(s),this.currRollUpRow=this.displayedMemory.rows[wi-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[wi-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let s=0;s<e.length;s++)this.writeScreen.insertChar(e[s]);let t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(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"),this.mode==="MODE_POP-ON"){let e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!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 s=Math.floor(e/2)-16,r=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=r[s]}this.logger.log(2,"MIDROW: "+qe(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){let t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}},wu=class{constructor(e,t,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory=QD(),this.logger=void 0;let r=this.logger=new wp;this.channels=[null,new Cu(e,t,r),new Cu(e+1,s,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 s=0;s<t.length;s+=2){let r=t[s]&127,n=t[s+1]&127,a=!1,o=null;if(r===0&&n===0)continue;this.logger.log(3,()=>"["+Qr([t[s],t[s+1]])+"] -> ("+Qr([r,n])+")");let l=this.cmdHistory;if(r>=16&&r<=31){if(zD(r,n,l)){Zd(null,null,l),this.logger.log(3,()=>"Repeated command ("+Qr([r,n])+") is dropped");continue}Zd(r,n,this.cmdHistory),a=this.parseCmd(r,n),a||(a=this.parseMidrow(r,n)),a||(a=this.parsePAC(r,n)),a||(a=this.parseBackgroundAttributes(r,n))}else Zd(null,null,l);if(!a&&(o=this.parseChars(r,n),o)){let u=this.currentChannel;u&&u>0?this.channels[u].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+Qr([r,n])+" orig: "+Qr([t[s],t[s+1]]))}}parseCmd(e,t){let s=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,r=(e===23||e===31)&&t>=33&&t<=35;if(!(s||r))return!1;let n=e===20||e===21||e===23?1:2,a=this.channels[n];return e===20||e===21||e===28||e===29?t===32?a.ccRCL():t===33?a.ccBS():t===34?a.ccAOF():t===35?a.ccAON():t===36?a.ccDER():t===37?a.ccRU(2):t===38?a.ccRU(3):t===39?a.ccRU(4):t===40?a.ccFON():t===41?a.ccRDC():t===42?a.ccTR():t===43?a.ccRTD():t===44?a.ccEDM():t===45?a.ccCR():t===46?a.ccENM():t===47&&a.ccEOC():a.ccTO(t-32),this.currentChannel=n,!0}parseMidrow(e,t){let s=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?s=1:s=2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;let r=this.channels[s];return r?(r.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+Qr([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let s,r=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,n=(e===16||e===24)&&t>=64&&t<=95;if(!(r||n))return!1;let a=e<=23?1:2;t>=64&&t<=95?s=a===1?VD[e]:qD[e]:s=a===1?WD[e]:YD[e];let o=this.channels[a];return o?(o.setPAC(this.interpretPAC(s,t)),this.currentChannel=a,!0):!1}interpretPAC(e,t){let s,r={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?s=t-96:s=t-64,r.underline=(s&1)===1,s<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(r.italics=!0,r.color="white"):r.indent=Math.floor((s-16)/2)*4,r}parseChars(e,t){let s,r=null,n=null;if(e>=25?(s=2,n=e-8):(s=1,n=e),n>=17&&n<=19){let a;n===17?a=t+80:n===18?a=t+112:a=t+144,this.logger.log(2,()=>"Special char '"+dT(a)+"' in channel "+s),r=[a]}else e>=32&&e<=127&&(r=t===0?[e]:[e,t]);return r&&this.logger.log(3,()=>"Char codes = "+Qr(r).join(",")),r}parseBackgroundAttributes(e,t){let s=(e===16||e===24)&&t>=32&&t<=47,r=(e===23||e===31)&&t>=45&&t<=47;if(!(s||r))return!1;let n,a={};e===16||e===24?(n=Math.floor((t-32)/2),a.background=jD[n],t%2===1&&(a.background=a.background+"_semi")):t===45?a.background="transparent":(a.foreground="black",t===47&&(a.underline=!0));let o=e<=23?1:2;return this.channels[o].setBkgData(a),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){let t=this.channels[e];t&&t.reset()}Zd(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){let s=this.channels[t];s&&s.cueSplitAtTime(e)}}};function Zd(i,e,t){t.a=i,t.b=e}function zD(i,e,t){return t.a===i&&t.b===e}function QD(){return{a:null,b:null}}var cg=function(){if(bu!=null&&bu.VTTCue)return self.VTTCue;let i=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,l){if(typeof l!="string"||!Array.isArray(o))return!1;let d=l.toLowerCase();return~o.indexOf(d)?d:!1}function s(o){return t(i,o)}function r(o){return t(e,o)}function n(o,...l){let d=1;for(;d<arguments.length;d++){let u=arguments[d];for(let c in u)o[c]=u[c]}return o}function a(o,l,d){let u=this,c={enumerable:!0};u.hasBeenReset=!1;let h="",f=!1,m=o,p=l,g=d,v=null,b="",y=!0,T="auto",A="start",R=50,I="middle",x=50,D="middle";Object.defineProperty(u,"id",n({},c,{get:function(){return h},set:function(S){h=""+S}})),Object.defineProperty(u,"pauseOnExit",n({},c,{get:function(){return f},set:function(S){f=!!S}})),Object.defineProperty(u,"startTime",n({},c,{get:function(){return m},set:function(S){if(typeof S!="number")throw new TypeError("Start time must be set to a number.");m=S,this.hasBeenReset=!0}})),Object.defineProperty(u,"endTime",n({},c,{get:function(){return p},set:function(S){if(typeof S!="number")throw new TypeError("End time must be set to a number.");p=S,this.hasBeenReset=!0}})),Object.defineProperty(u,"text",n({},c,{get:function(){return g},set:function(S){g=""+S,this.hasBeenReset=!0}})),Object.defineProperty(u,"region",n({},c,{get:function(){return v},set:function(S){v=S,this.hasBeenReset=!0}})),Object.defineProperty(u,"vertical",n({},c,{get:function(){return b},set:function(S){let C=s(S);if(C===!1)throw new SyntaxError("An invalid or illegal string was specified.");b=C,this.hasBeenReset=!0}})),Object.defineProperty(u,"snapToLines",n({},c,{get:function(){return y},set:function(S){y=!!S,this.hasBeenReset=!0}})),Object.defineProperty(u,"line",n({},c,{get:function(){return T},set:function(S){if(typeof S!="number"&&S!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");T=S,this.hasBeenReset=!0}})),Object.defineProperty(u,"lineAlign",n({},c,{get:function(){return A},set:function(S){let C=r(S);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");A=C,this.hasBeenReset=!0}})),Object.defineProperty(u,"position",n({},c,{get:function(){return R},set:function(S){if(S<0||S>100)throw new Error("Position must be between 0 and 100.");R=S,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",n({},c,{get:function(){return I},set:function(S){let C=r(S);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");I=C,this.hasBeenReset=!0}})),Object.defineProperty(u,"size",n({},c,{get:function(){return x},set:function(S){if(S<0||S>100)throw new Error("Size must be between 0 and 100.");x=S,this.hasBeenReset=!0}})),Object.defineProperty(u,"align",n({},c,{get:function(){return D},set:function(S){let C=r(S);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");D=C,this.hasBeenReset=!0}})),u.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}(),Op=class{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}};function uT(i){function e(s,r,n,a){return(s|0)*3600+(r|0)*60+(n|0)+parseFloat(a||0)}let t=i.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}var Np=class{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,s){return s?this.has(e)?this.values[e]:t[s]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,s){for(let r=0;r<s.length;++r)if(t===s[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 s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}};function cT(i,e,t,s){let r=s?i.split(s):[i];for(let n in r){if(typeof r[n]!="string")continue;let a=r[n].split(t);if(a.length!==2)continue;let o=a[0],l=a[1];e(o,l)}}var Up=new cg(0,0,""),Jd=Up.align==="middle"?"middle":"center";function XD(i,e,t){let s=i;function r(){let o=uT(i);if(o===null)throw new Error("Malformed timestamp: "+s);return i=i.replace(/^[^\sa-zA-Z-]+/,""),o}function n(o,l){let d=new Np;cT(o,function(h,f){let m;switch(h){case"region":for(let p=t.length-1;p>=0;p--)if(t[p].id===f){d.set(h,t[p].region);break}break;case"vertical":d.alt(h,f,["rl","lr"]);break;case"line":m=f.split(","),d.integer(h,m[0]),d.percent(h,m[0])&&d.set("snapToLines",!1),d.alt(h,m[0],["auto"]),m.length===2&&d.alt("lineAlign",m[1],["start",Jd,"end"]);break;case"position":m=f.split(","),d.percent(h,m[0]),m.length===2&&d.alt("positionAlign",m[1],["start",Jd,"end","line-left","line-right","auto"]);break;case"size":d.percent(h,f);break;case"align":d.alt(h,f,["start",Jd,"end","left","right"]);break}},/:/,/\s/),l.region=d.get("region",null),l.vertical=d.get("vertical","");let u=d.get("line","auto");u==="auto"&&Up.line===-1&&(u=-1),l.line=u,l.lineAlign=d.get("lineAlign","start"),l.snapToLines=d.get("snapToLines",!0),l.size=d.get("size",100),l.align=d.get("align",Jd);let c=d.get("position","auto");c==="auto"&&Up.position===50&&(c=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=c}function a(){i=i.replace(/^\s+/,"")}if(a(),e.startTime=r(),a(),i.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+s);i=i.slice(3),a(),e.endTime=r(),a(),n(i,e)}function hT(i){return i.replace(/<br(?: \/)?>/gi,`
46
+ `)}var Fp=class{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Op,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){let t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function s(){let n=t.buffer,a=0;for(n=hT(n);a<n.length&&n[a]!=="\r"&&n[a]!==`
47
47
  `;)++a;let o=n.slice(0,a);return n[a]==="\r"&&++a,n[a]===`
48
- `&&++a,t.buffer=n.slice(a),o}function r(n){cb(n,function(a,o){},/:/)}try{let n="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;n=s();let o=n.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let a=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(a?a=!1:n=s(),t.state){case"HEADER":/:/.test(n)?r(n):n||(t.state="ID");continue;case"NOTE":n||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(n)){t.state="NOTE";break}if(!n)continue;if(t.cue=new cg(0,0,""),t.state="CUE",n.indexOf("-->")===-1){t.cue.id=n;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{XD(n,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{let o=n.indexOf("-->")!==-1;if(!n||o&&(a=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=`
48
+ `&&++a,t.buffer=n.slice(a),o}function r(n){cT(n,function(a,o){},/:/)}try{let n="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;n=s();let o=n.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let a=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(a?a=!1:n=s(),t.state){case"HEADER":/:/.test(n)?r(n):n||(t.state="ID");continue;case"NOTE":n||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(n)){t.state="NOTE";break}if(!n)continue;if(t.cue=new cg(0,0,""),t.state="CUE",n.indexOf("-->")===-1){t.cue.id=n;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{XD(n,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{let o=n.indexOf("-->")!==-1;if(!n||o&&(a=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=`
49
49
  `),t.cue.text+=n}continue;case"BADCUE":n||(t.state="ID")}}}catch{t.state==="CUETEXT"&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){let e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=`
50
50
 
51
51
  `,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}},ZD=/\r\n|\n\r|\n|\r/g,Sm=function(e,t,s=0){return e.slice(s,s+t.length)===t},JD=function(e){let t=parseInt(e.slice(-3)),s=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!Q(t)||!Q(s)||!Q(r)||!Q(n))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*s,t+=60*1e3*r,t+=60*60*1e3*n,t};function hg(i,e,t){return No(i.toString())+No(e.toString())+No(t)}var eC=function(e,t,s){let r=e[t],n=e[r.prevCC];if(!n||!n.new&&r.new){e.ccOffset=e.presentationOffset=r.start,r.new=!1;return}for(;(a=n)!=null&&a.new;){var a;e.ccOffset+=r.start-n.start,r.new=!1,r=n,n=e[r.prevCC]}e.presentationOffset=s};function tC(i,e,t,s,r,n,a){let o=new Fp,l=li(new Uint8Array(i)).trim().replace(ZD,`
52
52
  `).split(`
53
- `),d=[],u=e?wk(e.baseTime,e.timescale):0,c="00:00.000",h=0,f=0,m,p=!0;o.oncue=function(g){let v=t[s],T=t.ccOffset,y=(h-u)/9e4;if(v!=null&&v.new&&(f!==void 0?T=t.ccOffset=v.start:eC(t,s,y)),y){if(!e){m=new Error("Missing initPTS for VTT MPEGTS");return}T=y-t.presentationOffset}let b=g.endTime-g.startTime,A=ai((g.startTime+T-f)*9e4,r*9e4)/9e4;g.startTime=Math.max(A,0),g.endTime=Math.max(A+b,0);let R=g.text.trim();g.text=decodeURIComponent(encodeURIComponent(R)),g.id||(g.id=hg(g.startTime,g.endTime,R)),g.endTime>0&&d.push(g)},o.onparsingerror=function(g){m=g},o.onflush=function(){if(m){a(m);return}n(d)},l.forEach(g=>{if(p)if(Sm(g,"X-TIMESTAMP-MAP=")){p=!1,g.slice(16).split(",").forEach(v=>{Sm(v,"LOCAL:")?c=v.slice(6):Sm(v,"MPEGTS:")&&(h=parseInt(v.slice(7)))});try{f=JD(c)/1e3}catch(v){m=v}return}else g===""&&(p=!1);o.parse(g+`
54
- `)}),o.flush()}var Im="stpp.ttml.im1t",fb=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,mb=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,iC={left:"start",center:"center",right:"end",start:"start",end:"end"};function Gy(i,e,t,s){let r=be(new Uint8Array(i),["mdat"]);if(r.length===0){s(new Error("Could not parse IMSC1 mdat"));return}let n=r.map(o=>li(o)),a=Ck(e.baseTime,1,e.timescale);try{n.forEach(o=>t(sC(o,a)))}catch(o){s(o)}}function sC(i,e){let r=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");let n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(n).reduce((c,h)=>(c[h]=r.getAttribute(`ttp:${h}`)||n[h],c),{}),o=r.getAttribute("xml:space")!=="preserve",l=Ky(Lm(r,"styling","style")),d=Ky(Lm(r,"layout","region")),u=Lm(r,"body","[begin]");return[].map.call(u,c=>{let h=pb(c,o);if(!h||!c.hasAttribute("begin"))return null;let f=xm(c.getAttribute("begin"),a),m=xm(c.getAttribute("dur"),a),p=xm(c.getAttribute("end"),a);if(f===null)throw Vy(c);if(p===null){if(m===null)throw Vy(c);p=f+m}let g=new cg(f-e,p-e,h);g.id=hg(g.startTime,g.endTime,g.text);let v=d[c.getAttribute("region")],T=l[c.getAttribute("style")],y=rC(v,T,l),{textAlign:b}=y;if(b){let A=iC[b];A&&(g.lineAlign=A),g.align=b}return $e(g,y),g}).filter(c=>c!==null)}function Lm(i,e,t){let s=i.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(t)):[]}function Ky(i){return i.reduce((e,t)=>{let s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function pb(i,e){return[].slice.call(i.childNodes).reduce((t,s,r)=>{var n;return s.nodeName==="br"&&r?t+`
55
- `:(n=s.childNodes)!=null&&n.length?pb(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function rC(i,e,t){let s="http://www.w3.org/ns/ttml#styling",r=null,n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=i!=null&&i.hasAttribute("style")?i.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(r=t[a]),n.reduce((o,l)=>{let d=Rm(e,s,l)||Rm(i,s,l)||Rm(r,s,l);return d&&(o[l]=d),o},{})}function Rm(i,e,t){return i&&i.hasAttributeNS(e,t)?i.getAttributeNS(e,t):null}function Vy(i){return new Error(`Could not parse ttml timestamp ${i}`)}function xm(i,e){if(!i)return null;let t=ub(i);return t===null&&(fb.test(i)?t=nC(i,e):mb.test(i)&&(t=aC(i,e))),t}function nC(i,e){let t=fb.exec(i),s=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+s/e.frameRate}function aC(i,e){let t=mb.exec(i),s=Number(t[1]);switch(t[2]){case"h":return s*3600;case"m":return s*60;case"ms":return s*1e3;case"f":return s/e.frameRate;case"t":return s/e.tickRate}return s}var Jn=class{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,s){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},Bp=class{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=qy(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this),e.on(E.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(E.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(E.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){let{hls:e}=this;e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this),e.off(E.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(E.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(E.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){let e=new Jn(this,"textTrack1"),t=new Jn(this,"textTrack2"),s=new Jn(this,"textTrack3"),r=new Jn(this,"textTrack4");this.cea608Parser1=new wu(1,e,t),this.cea608Parser2=new wu(3,s,r)}addCues(e,t,s,r,n){let a=!1;for(let o=n.length;o--;){let l=n[o],d=oC(l[0],l[1],t,s);if(d>=0&&(l[0]=Math.min(l[0],t),l[1]=Math.max(l[1],s),a=!0,d/(s-t)>.5))return}if(a||n.push([t,s]),this.config.renderTextTracksNatively){let o=this.captionsTracks[e];this.Cues.newCue(o,t,s,r)}else{let o=this.Cues.newCue(null,t,s,r);this.hls.trigger(E.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:s,initPTS:r,timescale:n,trackId:a}){let{unparsedVttFrags:o}=this;s===J.MAIN&&(this.initPTS[t.cc]={baseTime:r,timescale:n,trackId:a}),o.length&&(this.unparsedVttFrags=[],o.forEach(l=>{this.initPTS[l.frag.cc]?this.onFragLoaded(E.FRAG_LOADED,l):this.hls.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:l.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){let{media:s}=this;if(s)for(let r=0;r<s.textTracks.length;r++){let n=s.textTracks[r];if(Wy(n,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return n}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;let{captionsProperties:t,captionsTracks:s,media:r}=this,{label:n,languageCode:a}=t[e],o=this.getExistingTrack(n,a);if(o)s[e]=o,Zn(s[e]),ab(s[e],r);else{let l=this.createTextTrack("captions",n,a);l&&(l[e]=!0,s[e]=l)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let s=t.label,r={_id:e,label:s,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=r,this.hls.trigger(E.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[r]})}createTextTrack(e,t,s){let r=this.media;if(r)return r.addTextTrack(e,t,s)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){let s=!!t.transferMedia;if(this.media=null,s)return;let{captionsTracks:r}=this;Object.keys(r).forEach(n=>{Zn(r[n]),delete r[n]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=qy(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){let{media:e}=this;if(!e)return;let t=e.textTracks;if(t)for(let s=0;s<t.length;s++)Zn(t[s])}onSubtitleTracksUpdated(e,t){let s=t.subtitleTracks||[],r=s.some(n=>n.textCodec===Im);if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(jT(this.tracks,s)){this.tracks=s;return}if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){let a=this.media,o=a?ou(a.textTracks):null;if(this.tracks.forEach((l,d)=>{let u;if(o){let c=null;for(let h=0;h<o.length;h++)if(o[h]&&Wy(o[h],l)){c=o[h],o[h]=null;break}c&&(u=c)}if(u)Zn(u);else{let c=gb(l);u=this.createTextTrack(c,l.name,l.lang),u&&(u.mode="disabled")}u&&this.textTracks.push(u)}),o!=null&&o.length){let l=o.filter(d=>d!==null).map(d=>d.label);l.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${l.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){let a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(E.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(s=>{let r=/(?:CC|SERVICE)([1-4])/.exec(s.instreamId);if(!r)return;let n=`textTrack${r[1]}`,a=this.captionsProperties[n];a&&(a.label=s.name,s.lang&&(a.languageCode=s.lang),a.media=s)})}closedCaptionsForLevel(e){let t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===J.MAIN){var s,r;let{cea608Parser1:n,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:d}=t.frag,u=(s=(r=t.part)==null?void 0:r.index)!=null?s:-1;n&&a&&(d!==o+1||d===o&&u!==this.lastPartIndex+1||l!==this.lastCc)&&(n.reset(),a.reset()),this.lastCc=l,this.lastSn=d,this.lastPartIndex=u}}onFragLoaded(e,t){let{frag:s,payload:r}=t;if(s.type===J.SUBTITLE)if(r.byteLength){let n=s.decryptdata,a="stats"in t;if(n==null||!n.encrypted||a){let o=this.tracks[s.level],l=this.vttCCs;l[s.cc]||(l[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),o&&o.textCodec===Im?this._parseIMSC1(s,r):this._parseVTTs(t)}}else this.hls.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){let s=this.hls;Gy(t,this.initPTS[e.cc],r=>{this._appendCues(r,e.level),s.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},r=>{s.logger.log(`Failed to parse IMSC1: ${r}`),s.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:r})})}_parseVTTs(e){var t;let{frag:s,payload:r}=e,{initPTS:n,unparsedVttFrags:a}=this,o=n.length-1;if(!n[s.cc]&&o===-1){a.push(e);return}let l=this.hls,d=(t=s.initSegment)!=null&&t.data?pi(s.initSegment.data,new Uint8Array(r)).buffer:r;tC(d,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,u=>{this._appendCues(u,s.level),l.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})},u=>{let c=u.message==="Missing initPTS for VTT MPEGTS";c?a.push(e):this._fallbackToIMSC1(s,r),l.logger.log(`Failed to parse VTT cue: ${u}`),!(c&&o>s.cc)&&l.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:u})})}_fallbackToIMSC1(e,t){let s=this.tracks[e.level];s.textCodec||Gy(t,this.initPTS[e.cc],()=>{s.textCodec=Im,this._parseIMSC1(e,t)},()=>{s.textCodec="wvtt"})}_appendCues(e,t){let s=this.hls;if(this.config.renderTextTracksNatively){let r=this.textTracks[t];if(!r||r.mode==="disabled")return;e.forEach(n=>ob(r,n))}else{let r=this.tracks[t];if(!r)return;let n=r.default?"default":"subtitles"+t;s.trigger(E.CUES_PARSED,{type:"subtitles",cues:e,track:n})}}onFragDecrypted(e,t){let{frag:s}=t;s.type===J.SUBTITLE&&this.onFragLoaded(E.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;let{frag:s,samples:r}=t;if(!(s.type===J.MAIN&&this.closedCaptionsForLevel(s)==="NONE"))for(let n=0;n<r.length;n++){let a=r[n].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();let o=this.extractCea608Data(a);this.cea608Parser1.addData(r[n].pts,o[0]),this.cea608Parser2.addData(r[n].pts,o[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:s,endOffsetSubtitles:r,type:n}){let{media:a}=this;if(!(!a||a.currentTime<s)){if(!n||n==="video"){let{captionsTracks:o}=this;Object.keys(o).forEach(l=>Ap(o[l],t,s))}if(this.config.renderTextTracksNatively&&t===0&&r!==void 0){let{textTracks:o}=this;Object.keys(o).forEach(l=>Ap(o[l],t,r))}}}extractCea608Data(e){let t=[[],[]],s=e[0]&31,r=2;for(let n=0;n<s;n++){let a=e[r++],o=127&e[r++],l=127&e[r++];if(o===0&&l===0)continue;if((4&a)!==0){let u=3&a;(u===0||u===1)&&(t[u].push(o),t[u].push(l))}}return t}};function gb(i){return i.characteristics&&/transcribes-spoken-dialog/gi.test(i.characteristics)&&/describes-music-and-sound/gi.test(i.characteristics)?"captions":"subtitles"}function Wy(i,e){return!!i&&i.kind===gb(e)&&hp(e,i)}function oC(i,e,t,s){return Math.min(e,s)-Math.max(i,t)}function qy(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var lC=/\s/,dC={newCue(i,e,t,s){let r=[],n,a,o,l,d,u=self.VTTCue||self.TextTrackCue;for(let h=0;h<s.rows.length;h++)if(n=s.rows[h],o=!0,l=0,d="",!n.isEmpty()){var c;for(let p=0;p<n.chars.length;p++)lC.test(n.chars[p].uchar)&&o?l++:(d+=n.chars[p].uchar,o=!1);n.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;let f=hb(d.trim()),m=hg(e,t,f);i!=null&&(c=i.cues)!=null&&c.getCueById(m)||(a=new u(e,t,f),a.id=m,a.line=h+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),r.push(a))}return i&&r.length&&(r.sort((h,f)=>h.line==="auto"||f.line==="auto"?0:h.line>8&&f.line>8?f.line-h.line:h.line-f.line),r.forEach(h=>ob(i,h))),r}};function uC(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var cC=/(\d+)-(\d+)\/(\d+)/,Mu=class{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||pC,this.controller=new self.AbortController,this.stats=new Fo}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,s){let r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();let n=hC(e,this.controller.signal),a=e.responseType==="arraybuffer",o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:d}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=s,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=l&&Q(l)?l:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response))},t.timeout),(Yo(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(c=>{var h;this.response=this.loader=c;let f=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response))},d-(f-r.loading.start)),!c.ok){let{status:p,statusText:g}=c;throw new $p(g||"fetch, bad network response",p,c)}r.loading.first=f,r.total=mC(c.headers)||r.total;let m=(h=this.callbacks)==null?void 0:h.onProgress;return m&&Q(t.highWaterMark)?this.loadProgressively(c,r,e,t.highWaterMark,m):a?c.arrayBuffer():e.responseType==="json"?c.json():c.text()}).then(c=>{var h,f;let m=this.response;if(!m)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);let p=c[o];p&&(r.loaded=r.total=p);let g={url:m.url,data:c,code:m.status},v=(h=this.callbacks)==null?void 0:h.onProgress;v&&!Q(t.highWaterMark)&&v(r,e,c,m),(f=this.callbacks)==null||f.onSuccess(g,r,e,m)}).catch(c=>{var h;if(self.clearTimeout(this.requestTimeout),r.aborted)return;let f=c&&c.code||0,m=c?c.message:null;(h=this.callbacks)==null||h.onError({code:f,text:m},e,c?c.details:null,r)})}getCacheAge(){let e=null;if(this.response){let t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,s,r=0,n){let a=new _u,o=e.body.getReader(),l=()=>o.read().then(d=>{if(d.done)return a.dataLength&&n(t,s,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));let u=d.value,c=u.length;return t.loaded+=c,c<r||a.dataLength?(a.push(u),a.dataLength>=r&&n(t,s,a.flush().buffer,e)):n(t,s,u.buffer,e),l()}).catch(()=>Promise.reject());return l()}};function hC(i,e){let t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers($e({},i.headers))};return i.rangeEnd&&t.headers.set("Range","bytes="+i.rangeStart+"-"+String(i.rangeEnd-1)),t}function fC(i){let e=cC.exec(i);if(e)return parseInt(e[2])-parseInt(e[1])+1}function mC(i){let e=i.get("Content-Range");if(e){let s=fC(e);if(Q(s))return s}let t=i.get("Content-Length");if(t)return parseInt(t)}function pC(i,e){return new self.Request(i.url,e)}var $p=class extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}},gC=/^age:\s*[\d.]+\s*$/im,Pu=class{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new Fo,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){let e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}loadInternal(){let{config:e,context:t}=this;if(!e||!t)return;let s=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;let n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!(this.loader!==s||this.stats.aborted))return n(s,t.url)}).catch(a=>{if(!(this.loader!==s||this.stats.aborted))return s.open("GET",t.url,!0),n(s,t.url)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:s.status,text:a.message},t,s,r)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);let r=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=s.loadPolicy;if(r)for(let o in r)e.setRequestHeader(o,r[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),s.timeout=n&&Q(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:s}=this;if(!e||!t)return;let r=t.readyState,n=this.config;if(!s.aborted&&r>=2&&(s.loading.first===0&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),r===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let d=t.status,u=t.responseType==="text"?t.responseText:null;if(d>=200&&d<300){let m=u!=null?u:t.response;if(m!=null){var a,o;s.loading.end=Math.max(self.performance.now(),s.loading.first);let p=t.responseType==="arraybuffer"?m.byteLength:m.length;s.loaded=s.total=p,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first);let g=(a=this.callbacks)==null?void 0:a.onProgress;g&&g(s,e,m,t);let v={url:t.responseURL,data:m,code:d};(o=this.callbacks)==null||o.onSuccess(v,s,e,t);return}}let c=n.loadPolicy.errorRetry,h=s.retry,f={url:e.url,data:void 0,code:d};if(gu(c,h,!1,f))this.retry(c);else{var l;Be.error(`${d} while loading ${e.url}`),(l=this.callbacks)==null||l.onError({code:d,text:t.statusText},e,t,s)}}}loadtimeout(){if(!this.config)return;let e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(gu(e,t,!0))this.retry(e);else{var s;Be.warn(`timeout while loading ${(s=this.context)==null?void 0:s.url}`);let r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.loader))}}retry(e){let{context:t,stats:s}=this;this.retryDelay=eg(e,s.retry),s.retry++,Be.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&gC.test(this.loader.getAllResponseHeaders())){let t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}},vC={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},EC=Fe(Fe({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:Pu,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Fm,bufferController:gp,capLevelController:Qo,errorController:$m,fpsController:_p,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:TT,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:vC},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},yC()),{},{subtitleStreamController:Dp,subtitleTrackController:Sp,timelineController:Bp,audioStreamController:cp,audioTrackController:fp,emeController:xu,cmcdController:Tp,contentSteeringController:bp,interstitialsController:kp});function yC(){return{cueHandler:dC,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function TC(i,e,t){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');let s=Hp(i),r=["manifest","level","frag"],n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return r.forEach(a=>{let o=`${a==="level"?"playlist":a}LoadPolicy`,l=e[o]===void 0,d=[];n.forEach(u=>{let c=`${a}Loading${u}`,h=e[c];if(h!==void 0&&l){d.push(c);let f=s[o].default;switch(e[o]={default:f},u){case"TimeOut":f.maxLoadTimeMs=h,f.maxTimeToFirstByteMs=h;break;case"MaxRetry":f.errorRetry.maxNumRetry=h,f.timeoutRetry.maxNumRetry=h;break;case"RetryDelay":f.errorRetry.retryDelayMs=h,f.timeoutRetry.retryDelayMs=h;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=h,f.timeoutRetry.maxRetryDelayMs=h;break}}}),d.length&&t.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${o}": ${qe(e[o])}`)}),Fe(Fe({},s),e)}function Hp(i){return i&&typeof i=="object"?Array.isArray(i)?i.map(Hp):Object.keys(i).reduce((e,t)=>(e[t]=Hp(i[t]),e),{}):i}function bC(i,e){let t=i.loader;t!==Mu&&t!==Pu?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),i.progressive=!1):uC()&&(i.loader=Mu,i.progressive=!0,i.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}var lu=2,_C=.1,AC=.05,SC=100,Gp=class extends vu{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var s;(s=this.media)!=null&&s.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var s;this.ended=((s=this.media)==null?void 0:s.currentTime)||1,this.hls.trigger(E.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){let{hls:e}=this;e&&(e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(SC),this.mediaSource=t.mediaSource;let s=this.media=t.media;Ht(s,"playing",this.onMediaPlaying),Ht(s,"waiting",this.onMediaWaiting),Ht(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();let{media:s}=this;s&&(zt(s,"playing",this.onMediaPlaying),zt(s,"waiting",this.onMediaWaiting),zt(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;let t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var s,r;let n=(s=this.hls)==null?void 0:s.config;if(!n)return;let a=this.media;if(!a)return;let{seeking:o}=a,l=this.seeking&&!o,d=!this.seeking&&o,u=a.paused&&!o||a.ended||a.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,n.nudgeOnVideoHole&&!u&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(d||l){l&&this.stallResolved(e);return}if(u){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(E.MEDIA_ENDED,{stalled:!1}));return}if(!Ee.getBuffered(a).length){this.nudgeRetry=0;return}let c=Ee.bufferInfo(a,e,0),h=c.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){let R=Yy(this.hls.inFlightFragments,e),I=c.len>lu,x=!h||R||h-e>lu&&!f.getPartialFragment(e);if(I||x)return;this.moved=!1}let m=(r=this.hls)==null?void 0:r.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(c.len>0)&&!h)return;let I=Math.max(h,c.start||0)-e,D=!!(m!=null&&m.live)?m.targetduration*2:lu,S=eu(e,f);if(I>0&&(I<=D||S)){a.paused||this._trySkipBufferHole(S);return}}let p=n.detectStallWithCurrentTimeMs,g=self.performance.now(),v=this.waiting,T=this.stalled;if(T===null)if(v>0&&g-v<p)T=this.stalled=v;else{this.stalled=g;return}let y=g-T;if(!o&&(y>=p||v)&&this.hls){var b;if(((b=this.mediaSource)==null?void 0:b.readyState)==="ended"&&!(m!=null&&m.live)&&Math.abs(e-((m==null?void 0:m.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(E.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(c),!this.media||!this.hls)return}let A=Ee.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(A,y,e)}stallResolved(e){let t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){let s=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(E.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;let r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(s=this.buffered.audio)!=null&&s.length&&r&&r.length>1&&e>r.end(0)){let n=Ee.bufferedInfo(Ee.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){let a=Ee.timeRangesToArray(r),o=Ee.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&o<a.length-1){let l=Ee.bufferedInfo(a,e,0).bufferedIndex,d=a[o].end,u=a[o+1].start;if((l===-1||l>o)&&u-d<1&&e-d<2){let c=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${d} -> ${u} buffered index: ${l}`);this.warn(c.message),this.media.currentTime+=1e-6;let h=eu(e,this.fragmentTracker);h&&"fragment"in h?h=h.fragment:h||(h=void 0);let f=Ee.bufferInfo(this.media,e,0);this.hls.trigger(E.ERROR,{type:se.MEDIA_ERROR,details:M.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:c,reason:c.message,frag:h,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(e,t,s){var r,n;let{fragmentTracker:a,media:o}=this,l=(r=this.hls)==null?void 0:r.config;if(!o||!a||!l)return;let d=(n=this.hls)==null?void 0:n.latestLevelDetails,u=eu(s,a);if((u||d!=null&&d.live&&s<d.fragmentStart)&&(this._trySkipBufferHole(u)||!this.media))return;let c=e.buffered,h=this.adjacentTraversal(e,s);(c&&c.length>1&&e.len>l.maxBufferHole||e.nextStart&&(e.nextStart-s<l.maxBufferHole||h))&&(t>l.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){let s=this.fragmentTracker,r=e.nextStart;if(s&&r){let n=s.getFragAtPos(t,J.MAIN),a=s.getFragAtPos(r,J.MAIN);if(n&&a)return a.sn-n.sn<2}return!1}_reportStall(e){let{hls:t,media:s,stallReported:r,stalled:n}=this;if(!r&&n!==null&&s&&t){this.stallReported=!0;let a=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${qe(e)})`);this.warn(a.message),t.trigger(E.ERROR,{type:se.MEDIA_ERROR,details:M.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:n}})}}_trySkipBufferHole(e){var t;let{fragmentTracker:s,media:r}=this,n=(t=this.hls)==null?void 0:t.config;if(!r||!s||!n)return 0;let a=r.currentTime,o=Ee.bufferInfo(r,a,0),l=a<o.start?o.start:o.nextStart;if(l&&this.hls){let u=o.len<=n.maxBufferHole,c=o.len>0&&o.len<1&&r.readyState<3,h=l-a;if(h>0&&(u||c)){if(h>n.maxBufferHole){let m=!1;if(a===0){let p=s.getAppendedFrag(0,J.MAIN);p&&l<p.end&&(m=!0)}if(!m&&e){var d;if(!((d=this.hls.loadLevelObj)!=null&&d.details)||Yy(this.hls.inFlightFragments,l))return 0;let g=!1,v=e.end;for(;v<l;){let T=eu(v,s);if(T)v+=T.duration;else{g=!0;break}}if(g)return 0}}let f=Math.max(l+AC,a+_C);if(this.warn(`skipping hole, adjusting currentTime from ${a} to ${f}`),this.moved=!0,r.currentTime=f,!(e!=null&&e.gap)){let m=new Error(`fragment loaded with buffer holes, seeking from ${a} to ${f}`),p={type:se.MEDIA_ERROR,details:M.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:m,reason:m.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?p.part=e:p.frag=e),this.hls.trigger(E.ERROR,p)}return f}}return 0}_tryNudgeBuffer(e){let{hls:t,media:s,nudgeRetry:r}=this,n=t==null?void 0:t.config;if(!s||!n)return 0;let a=s.currentTime;if(this.nudgeRetry++,r<n.nudgeMaxRetry){let o=a+(r+1)*n.nudgeOffset,l=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(l.message),s.currentTime=o,t.trigger(E.ERROR,{type:se.MEDIA_ERROR,details:M.BUFFER_NUDGE_ON_STALL,error:l,fatal:!1,buffer:e.len,bufferInfo:e})}else{let o=new Error(`Playhead still not moving while enough data buffered @${a} after ${n.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(E.ERROR,{type:se.MEDIA_ERROR,details:M.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}};function Yy(i,e){let t=jy(i.main);if(t&&t.start<=e)return t;let s=jy(i.audio);return s&&s.start<=e?s:null}function jy(i){if(!i)return null;switch(i.state){case O.IDLE:case O.STOPPED:case O.ENDED:case O.ERROR:return null}return i.frag}function eu(i,e){return e.getAppendedFrag(i,J.MAIN)||e.getPartialFragment(i)}var IC=.25;function Kp(){if(typeof self!="undefined")return self.VTTCue||self.TextTrackCue}function km(i,e,t,s,r){let n=new i(e,t,"");try{n.value=s,r&&(n.type=r)}catch{n=new i(e,t,qe(r?Fe({type:r},s):s))}return n}var tu=(()=>{let i=Kp();try{i&&new i(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})(),Vp=class{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(E.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){let{hls:e}=this;e&&(e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var s;this.media=t.media,((s=t.overrides)==null?void 0:s.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;let t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&Zn(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){let t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){let s=e[t];if(s.kind==="metadata"&&s.label==="id3")return ab(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;let{enableEmsgMetadataCues:s,enableID3MetadataCues:r}=this.hls.config;if(!s&&!r)return;let{samples:n}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));let a=Kp();if(a)for(let o=0;o<n.length;o++){let l=n[o].type;if(l===oi.emsg&&!s||!r)continue;let d=UT(n[o].data),u=n[o].pts,c=u+n[o].duration;c>tu&&(c=tu),c-u<=0&&(c=u+IC);for(let f=0;f<d.length;f++){let m=d[f];if(!FT(m)){this.updateId3CueEnds(u,l);let p=km(a,u,c,m,l);p&&this.id3Track.addCue(p)}}}}updateId3CueEnds(e,t){var s;let r=(s=this.id3Track)==null?void 0:s.cues;if(r)for(let n=r.length;n--;){let a=r[n];a.type===t&&a.startTime<e&&a.endTime===tu&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:r}){let{id3Track:n,hls:a}=this;if(!a)return;let{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=a;if(n&&(o||l)){let d;r==="audio"?d=u=>u.type===oi.audioId3&&l:r==="video"?d=u=>u.type===oi.emsg&&o:d=u=>u.type===oi.audioId3&&l||u.type===oi.emsg&&o,Ap(n,t,s,d)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;let{assetPlayerId:s,timelineOffset:r,enableDateRangeMetadataCues:n,interstitialsController:a}=this.hls.config;if(!n)return;let o=Kp();if(s&&r&&!a){let{fragmentStart:p,fragmentEnd:g}=e,v=this.assetCue;v?(v.startTime=p,v.endTime=g):o&&(v=this.assetCue=km(o,p,g,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),v&&(v.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(v),v.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;let{id3Track:l}=this,{dateRanges:d}=e,u=Object.keys(d),c=this.dateRangeCuesAppended;if(l&&t){var h;if((h=l.cues)!=null&&h.length){let p=Object.keys(c).filter(g=>!u.includes(g));for(let g=p.length;g--;){var f;let v=p[g],T=(f=c[v])==null?void 0:f.cues;delete c[v],T&&Object.keys(T).forEach(y=>{let b=T[y];if(b){b.removeEventListener("enter",this.onEventCueEnter);try{l.removeCue(b)}catch{}}})}}else c=this.dateRangeCuesAppended={}}let m=e.fragments[e.fragments.length-1];if(!(u.length===0||!Q(m==null?void 0:m.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let p=0;p<u.length;p++){let g=u[p],v=d[g],T=v.startTime,y=c[g],b=(y==null?void 0:y.cues)||{},A=(y==null?void 0:y.durationKnown)||!1,R=tu,{duration:I,endDate:x}=v;if(x&&I!==null)R=T+I,A=!0;else if(v.endOnNext&&!A){let S=u.reduce((C,P)=>{if(P!==v.id){let N=d[P];if(N.class===v.class&&N.startDate>v.startDate&&(!C||v.startDate<C.startDate))return N}return C},null);S&&(R=S.startTime,A=!0)}let D=Object.keys(v.attr);for(let S=0;S<D.length;S++){let C=D[S];if(!Dx(C))continue;let P=b[C];if(P)A&&!(y!=null&&y.durationKnown)?P.endTime=R:Math.abs(P.startTime-T)>.01&&(P.startTime=T,P.endTime=R);else if(o){let N=v.attr[C];Cx(C)&&(N=Zy(N));let H=km(o,T,R,{key:C,data:N},oi.dateRange);H&&(H.id=g,this.id3Track.addCue(H),b[C]=H,a&&(C==="X-ASSET-LIST"||C==="X-ASSET-URL")&&H.addEventListener("enter",this.onEventCueEnter))}}c[g]={cues:b,dateRange:v,durationKnown:A}}}}},Wp=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{let{media:t}=this,s=this.levelDetails;if(!t||!s)return;this.currentTime=t.currentTime;let r=this.computeLatency();if(r===null)return;this._latency=r;let{lowLatencyMode:n,maxLiveSyncPlaybackRate:a}=this.config;if(!n||a===1||!s.live)return;let o=this.targetLatency;if(o===null)return;let l=r-o,d=Math.min(this.maxLatency,o+s.targetduration);if(l<d&&l>.05&&this.forwardBufferLength>1){let c=Math.min(2,Math.max(1,a)),h=Math.round(2/(1+Math.exp(-.75*l-this.edgeStalled))*20)/20,f=Math.min(c,Math.max(1,h));this.changeMediaPlaybackRate(t,f)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){let{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;let t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){let e=this.levelDetails;if(e===null||this.hls===null)return null;let{holdBack:t,partHoldBack:s,targetduration:r}=e,{liveSyncDuration:n,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,l=this.hls.userConfig,d=o&&s||t;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||d===0)&&(d=n!==void 0?n:a*r);let u=r;return d+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,u)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){let e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;let s=this.levelDetails;if(s===null)return null;let r=s.edge,n=e-t-this.edgeStalled,a=r-s.totalduration,o=r-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(a,n),o)}get drift(){let e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){let e=this.levelDetails;if(e===null)return 0;let t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){let{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;let s=e.buffered.length;return(s?e.buffered.end(s-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){let{hls:e}=this;e&&(e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.ERROR,this.onError,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var s;t.details===M.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(s=this.levelDetails)!=null&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var s,r;e.playbackRate!==t&&((s=this.hls)==null||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(r=this.targetLatency)==null?void 0:r.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){let e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){let e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}},qp=class extends jo{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){let{hls:e}=this;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.ERROR,this.onError,this)}_unregisterListeners(){let{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){let s=this.hls.config.preferManagedMediaSource,r=[],n={},a={},o=!1,l=!1,d=!1;t.levels.forEach(u=>{let c=u.attrs,{audioCodec:h,videoCodec:f}=u;h&&(u.audioCodec=h=cu(h,s)||void 0),f&&(f=u.videoCodec=ex(f));let{width:m,height:p,unknownCodecs:g}=u,v=(g==null?void 0:g.length)||0;if(o||(o=!!(m&&p)),l||(l=!!f),d||(d=!!h),v||h&&!this.isAudioSupported(h)||f&&!this.isVideoSupported(f)){this.log(`Some or all CODECS not supported "${c.CODECS}"`);return}let{CODECS:T,"FRAME-RATE":y,"HDCP-LEVEL":b,"PATHWAY-ID":A,RESOLUTION:R,"VIDEO-RANGE":I}=c,D=`${`${A||"."}-`}${u.bitrate}-${R}-${y}-${T}-${I}-${b}`;if(n[D])if(n[D].uri!==u.url&&!u.attrs["PATHWAY-ID"]){let S=a[D]+=1;u.attrs["PATHWAY-ID"]=new Array(S+1).join(".");let C=this.createLevel(u);n[D]=C,r.push(C)}else n[D].addGroupId("audio",c.AUDIO),n[D].addGroupId("text",c.SUBTITLES);else{let S=this.createLevel(u);n[D]=S,a[D]=1,r.push(S)}}),this.filterAndSortMediaOptions(r,t,o,l,d)}createLevel(e){let t=new tn(e),s=e.supplemental;if(s!=null&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){let r=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(r.message),t.supportedResult=dT(r,[])}return t}isAudioSupported(e){return Bo(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Bo(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,s,r,n){var a;let o=[],l=[],d=e,u=((a=t.stats)==null?void 0:a.parsing)||{};if((s||r)&&n&&(d=d.filter(({videoCodec:T,videoRange:y,width:b,height:A})=>(!!T||!!(b&&A))&&ux(y))),d.length===0){Promise.resolve().then(()=>{if(this.hls){let T="no level with compatible codecs found in manifest",y=T;t.levels.length&&(y=`one or more CODECS in variant not supported: ${qe(t.levels.map(A=>A.attrs.CODECS).filter((A,R,I)=>I.indexOf(A)===R))}`,this.warn(y),T+=` (${y})`);let b=new Error(T);this.hls.trigger(E.ERROR,{type:se.MEDIA_ERROR,details:M.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:b,reason:y})}}),u.end=performance.now();return}t.audioTracks&&(o=t.audioTracks.filter(T=>!T.audioCodec||this.isAudioSupported(T.audioCodec)),zy(o)),t.subtitles&&(l=t.subtitles,zy(l));let c=d.slice(0);d.sort((T,y)=>{if(T.attrs["HDCP-LEVEL"]!==y.attrs["HDCP-LEVEL"])return(T.attrs["HDCP-LEVEL"]||"")>(y.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&T.height!==y.height)return T.height-y.height;if(T.frameRate!==y.frameRate)return T.frameRate-y.frameRate;if(T.videoRange!==y.videoRange)return hu.indexOf(T.videoRange)-hu.indexOf(y.videoRange);if(T.videoCodec!==y.videoCodec){let b=WE(T.videoCodec),A=WE(y.videoCodec);if(b!==A)return A-b}if(T.uri===y.uri&&T.codecSet!==y.codecSet){let b=uu(T.codecSet),A=uu(y.codecSet);if(b!==A)return A-b}return T.averageBitrate!==y.averageBitrate?T.averageBitrate-y.averageBitrate:0});let h=c[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==c.length)){for(let T=0;T<c.length;T++)if(c[T].pathwayId===d[0].pathwayId){h=c[T];break}}this._levels=d;for(let T=0;T<d.length;T++)if(d[T]===h){var f;this._firstLevel=T;let y=h.bitrate,b=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${d.length} level(s) found, first bitrate: ${y}`),((f=this.hls.userConfig)==null?void 0:f.abrEwmaDefaultEstimate)===void 0){let A=Math.min(y,this.hls.config.abrEwmaDefaultEstimateMax);A>b&&b===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=A)}break}let m=n&&!r,p=this.hls.config,g=!!(p.audioStreamController&&p.audioTrackController),v={levels:d,audioTracks:o,subtitleTracks:l,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:r,altAudio:g&&!m&&o.some(T=>!!T.url)};u.end=performance.now(),this.hls.trigger(E.MANIFEST_PARSED,v)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){let t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){let u=new Error("invalid level idx"),c=e<0;if(this.hls.trigger(E.ERROR,{type:se.OTHER_ERROR,details:M.LEVEL_SWITCH_ERROR,level:e,fatal:c,error:u,reason:u.message}),c)return;e=Math.min(e,t.length-1)}let s=this.currentLevelIndex,r=this.currentLevel,n=r?r.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,s===e&&r&&n===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${s}${n?" with Pathway "+n:""}`);let l={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(E.LEVEL_SWITCHING,l);let d=a.details;if(!d||d.live){let u=this.switchParams(a.uri,r==null?void 0:r.details,d);this.loadPlaylist(u)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){let e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){let t=this.steering.pathways(),s=e.filter(r=>t.indexOf(r)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=s}}onError(e,t){t.fatal||!t.context||t.context.type===Le.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===J.MAIN){let s=t.elementaryStreams;if(!Object.keys(s).some(n=>!!s[n]))return;let r=this._levels[t.level];r!=null&&r.loadError&&(this.log(`Resetting level error count of ${r.loadError} on frag buffered`),r.loadError=0)}}onLevelLoaded(e,t){var s;let{level:r,details:n}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${r}`),(o=t.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let l=a.details;l===t.details&&l.advanced&&(l=void 0),this.playlistLoaded(r,t,l)}else(s=t.deliveryDirectives)!=null&&s.skip&&(n.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let s=this.getUrlWithDirectives(e.uri,t),r=this.currentLevelIndex,n=e.attrs["PATHWAY-ID"],a=e.details,o=a==null?void 0:a.age;this.log(`Loading level index ${r}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${n?" Pathway "+n:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${s}`),this.hls.trigger(E.LEVEL_LOADING,{url:s,level:r,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;let s=this._levels.filter((n,a)=>a!==e?!0:(this.steering&&this.steering.removeLevel(n),n===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,n.details&&n.details.fragments.forEach(o=>o.level=-1)),!1));xT(s),this._levels=s,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);let r=s.length-1;this._firstLevel=Math.min(this._firstLevel,r),this._startLevel&&(this._startLevel=Math.min(this._startLevel,r)),this.hls.trigger(E.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(E.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}};function zy(i){let e={};i.forEach(t=>{let s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}function vb(){return self.SourceBuffer||self.WebKitSourceBuffer}function Eb(){if(!nr())return!1;let e=vb();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function LC(){if(!Eb())return!1;let i=nr();return typeof(i==null?void 0:i.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>i.isTypeSupported($o(e,"video")))||["mp4a.40.2","fLaC"].some(e=>i.isTypeSupported($o(e,"audio"))))}function RC(){var i;let e=vb();return typeof(e==null||(i=e.prototype)==null?void 0:i.changeType)=="function"}var xC=100,Yp=class extends Ko{constructor(e,t,s){super(e,t,s,"stream-controller",J.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{let r=this.media,n=r?r.currentTime:null;if(n===null||!Q(n)||(this.log(`Media seeked to ${n.toFixed(3)}`),!this.getBufferedFrag(n)))return;let a=this.getFwdBufferInfoAtPos(r,n,J.MAIN,0);if(a===null||a.len===0){this.warn(`Main forward buffer length at ${n} on "seeked" event ${a?a.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(E.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(E.BUFFER_CREATED,this.onBufferCreated,this),e.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(E.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(E.BUFFER_CREATED,this.onBufferCreated,this),e.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){let{lastCurrentTime:s,hls:r}=this;if(this.stopLoad(),this.setInterval(xC),this.level=-1,!this.startFragRequested){let n=r.startLevel;n===-1&&(r.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=!0):n=r.firstAutoLevel),r.nextLoadLevel=n,this.level=r.loadLevel,this._hasEnoughToStart=!!t}s>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=O.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=O.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case O.WAITING_LEVEL:{let{levels:e,level:t}=this,s=e==null?void 0:e[t],r=s==null?void 0:s.details;if(r&&(!r.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(r))break;this.state=O.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=O.IDLE;break}break}case O.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===O.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){let{hls:e,levelLastLoaded:t,levels:s,media:r}=this;if(t===null||!r&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;let n=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(s!=null&&s[n]))return;let a=s[n],o=this.getMainFwdBufferInfo();if(o===null)return;let l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){let p={};this.altAudio===2&&(p.type="video"),this.hls.trigger(E.BUFFER_EOS,p),this.state=O.ENDED;return}if(!this.buffering)return;e.loadLevel!==n&&e.manualLevel===-1&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=e.nextLoadLevel=n;let d=a.details;if(!d||this.state===O.WAITING_LEVEL||this.waitForLive(a)){this.level=n,this.state=O.WAITING_LEVEL,this.startFragRequested=!1;return}let u=o.len,c=this.getMaxBufferLength(a.maxBitrate);if(u>=c)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);let h=this.backtrackFragment?this.backtrackFragment.start:o.end,f=this.getNextFragment(h,d);if(this.couldBacktrack&&!this.fragPrevious&&f&&at(f)&&this.fragmentTracker.getState(f)!==bt.OK){var m;let g=((m=this.backtrackFragment)!=null?m:f).sn-d.startSN,v=d.fragments[g-1];v&&f.cc===v.cc&&(f=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,h)){if(!f.gap){let g=this.audioOnly&&!this.altAudio?We.AUDIO:We.VIDEO,v=(g===We.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,g,J.MAIN)}f=this.getNextFragmentLoopLoading(f,d,o,J.MAIN,c)}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,h))}loadFragment(e,t,s){let r=this.fragmentTracker.getState(e);r===bt.NOT_LOADED||r===bt.PARTIAL?at(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,s):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,J.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){let{levels:e,media:t}=this;if(t!=null&&t.readyState){let s,r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);let n=this.getLevelDetails();if(n!=null&&n.live){let o=this.getMainFwdBufferInfo();if(!o||o.len<n.targetduration*2)return}if(!t.paused&&e){let o=this.hls.nextLoadLevel,l=e[o],d=this.fragLastKbps;d&&this.fragCurrent?s=this.fragCurrent.duration*l.maxBitrate/(1e3*d)+1:s=0}else s=0;let a=this.getBufferedFrag(t.currentTime+s);if(a){let o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();let l=o.maxStartPTS?o.maxStartPTS:o.start,d=o.duration,u=Math.max(a.end,l+Math.min(Math.max(d-this.config.maxFragLookUpTolerance,d*(this.couldBacktrack?.5:.125)),d*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(u,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){let e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case O.KEY_LOADING:case O.FRAG_LOADING:case O.FRAG_LOADING_WAITING_RETRY:case O.PARSING:case O.PARSED:this.state=O.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);let s=t.media;Ht(s,"playing",this.onMediaPlaying),Ht(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){let{media:s}=this;s&&(zt(s,"playing",this.onMediaPlaying),zt(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(E.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let s=!1,r=!1;for(let n=0;n<t.levels.length;n++){let a=t.levels[n].audioCodec;a&&(s=s||a.indexOf("mp4a.40.2")!==-1,r=r||a.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=s&&r&&!RC(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){let{levels:s}=this;if(!s||this.state!==O.IDLE)return;let r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=O.WAITING_LEVEL)}onLevelLoaded(e,t){var s;let{levels:r,startFragRequested:n}=this,a=t.level,o=t.details,l=o.totalduration;if(!r){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${l}`);let d=t.levelInfo,u=this.fragCurrent;u&&(this.state===O.FRAG_LOADING||this.state===O.FRAG_LOADING_WAITING_RETRY)&&u.level!==t.level&&u.loader&&this.abortCurrentFrag();let c=0;if(o.live||(s=d.details)!=null&&s.live){var h;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;c=this.alignPlaylists(o,d.details,(h=this.levelLastLoaded)==null?void 0:h.details)}if(d.details=o,this.levelLastLoaded=d,n||this.setStartPosition(o,c),this.hls.trigger(E.LEVEL_UPDATED,{details:o,level:a}),this.state===O.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=O.IDLE}n&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(e){let{config:t,media:s}=this;if(!s)return;let r=this.hls.liveSyncPosition,n=this.getLoadPosition(),a=e.fragmentStart,o=e.edge,l=n>=a-t.maxFragLookUpTolerance&&n<=o;if(r!==null&&s.duration>r&&(n<r||!l)){let u=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!l&&s.readyState<4||n<o-u)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),s.readyState))if(this.warn(`Playback: ${n.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${r.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var d;let c=Ee.bufferInfo(s,r,0);if(!((d=c.buffered)!=null&&d.length)){s.currentTime=r;return}if(c.start<=n){s.currentTime=r;return}let{nextStart:f}=Ee.bufferedInfo(c.buffered,n,0);f&&(s.currentTime=f)}else s.currentTime=r}}_handleFragmentLoadProgress(e){var t;let s=e.frag,{part:r,payload:n}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}let o=a[s.level];if(!o){this.warn(`Level ${s.level} not found on progress`);return}let l=o.details;if(!l){this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),this.fragmentTracker.removeFragment(s);return}let d=o.videoCodec,u=l.PTSKnown||!l.live,c=(t=s.initSegment)==null?void 0:t.data,h=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new Lu(this.hls,J.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),m=r?r.index:-1,p=m!==-1,g=new Go(s.level,s.sn,s.stats.chunkCount,n.byteLength,m,p),v=this.initPTS[s.cc];f.push(n,c,h,d,s,r,l.totalduration,u,g,v)}onAudioTrackSwitching(e,t){let s=this.hls,r=this.altAudio!==0;if(mu(t.url,s))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;let a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(r){this.altAudio=0,this.fragmentTracker.removeAllFragments(),s.once(E.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(E.AUDIO_TRACK_SWITCHED,t)}),s.trigger(E.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}s.trigger(E.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){let s=mu(t.url,this.hls);if(s){let r=this.videoBuffer;r&&this.mediaBuffer!==r&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=r)}this.altAudio=s?2:0,this.tick()}onBufferCreated(e,t){let s=t.tracks,r,n,a=!1;for(let o in s){let l=s[o];if(l.id==="main"){if(n=o,r=l,o==="video"){let d=s[o];d&&(this.videoBuffer=d.buffer)}}else a=!0}a&&r?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){let{frag:s,part:r}=t,n=s.type===J.MAIN;if(n){if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${r?" p: "+r.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),this.state===O.PARSED&&(this.state=O.IDLE);return}let o=r?r.stats:s.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),at(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,r)}let a=this.media;a&&(!this._hasEnoughToStart&&Ee.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal){this.state=O.ERROR;return}switch(t.details){case M.FRAG_GAP:case M.FRAG_PARSING_ERROR:case M.FRAG_DECRYPT_ERROR:case M.FRAG_LOAD_ERROR:case M.FRAG_LOAD_TIMEOUT:case M.KEY_LOAD_ERROR:case M.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(J.MAIN,t);break;case M.LEVEL_LOAD_ERROR:case M.LEVEL_LOAD_TIMEOUT:case M.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===O.WAITING_LEVEL&&((s=t.context)==null?void 0:s.type)===Le.LEVEL&&(this.state=O.IDLE);break;case M.BUFFER_ADD_CODEC_ERROR:case M.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case M.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case M.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=O.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==We.AUDIO||!this.altAudio){let s=(t===We.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;s&&(this.afterBufferFlushed(s,t,J.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){let{media:e}=this;if(!e)return;let t=e.currentTime,s=this.startPosition;if(s>=0&&t<s){if(e.seeking){this.log(`could not seek to ${s}, already seeking at ${t}`);return}let r=this.timelineOffset;r&&s&&(s+=r);let n=this.getLevelDetails(),a=Ee.getBuffered(e),o=a.length?a.start(0):0,l=o-s,d=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||l>0&&(l<d||this.loadingParts&&l<2*((n==null?void 0:n.partTarget)||0)))&&(this.log(`adjusting start position by ${l} to match buffer start`),s+=l,this.startPosition=s),t<s&&(this.log(`seek to target start position ${s} from current time ${t} buffer start ${o}`),e.currentTime=s)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(s=>{let{hls:r}=this,n=s==null?void 0:s.frag;if(!n||this.fragContextChanged(n))return;t.fragmentError=0,this.state=O.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;let a=n.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),r.trigger(E.FRAG_LOADED,s),n.bitrateTest=!1}).catch(s=>{this.state===O.STOPPED||this.state===O.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){let t=this.playlistType,{hls:s}=this,{remuxResult:r,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a){this.resetWhenMissingContext(n);return}let{frag:o,part:l,level:d}=a,{video:u,text:c,id3:h,initSegment:f}=r,{details:m}=d,p=this.altAudio?void 0:r.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=O.PARSING,f){let g=f.tracks;if(g){let b=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(d,g,b,n),s.trigger(E.FRAG_PARSING_INIT_SEGMENT,{frag:b,id:t,tracks:g})}let v=f.initPTS,T=f.timescale,y=this.initPTS[o.cc];if(Q(v)&&(!y||y.baseTime!==v||y.timescale!==T)){let b=f.trackId;this.initPTS[o.cc]={baseTime:v,timescale:T,trackId:b},s.trigger(E.INIT_PTS_FOUND,{frag:o,id:t,initPTS:v,timescale:T,trackId:b})}}if(u&&m){p&&u.type==="audiovideo"&&this.logMuxedErr(o);let g=m.fragments[o.sn-1-m.startSN],v=o.sn===m.startSN,T=!g||o.cc>g.cc;if(r.independent!==!1){let{startPTS:y,endPTS:b,startDTS:A,endDTS:R}=u;if(l)l.elementaryStreams[u.type]={startPTS:y,endPTS:b,startDTS:A,endDTS:R};else if(u.firstKeyFrame&&u.independent&&n.id===1&&!T&&(this.couldBacktrack=!0),u.dropped&&u.independent){let I=this.getMainFwdBufferInfo(),x=(I?I.end:this.getLoadPosition())+this.config.maxBufferHole,D=u.firstKeyFramePTS?u.firstKeyFramePTS:y;if(!v&&x<D-this.config.maxBufferHole&&!T){this.backtrack(o);return}else T&&(o.gap=!0);o.setElementaryStreamInfo(u.type,o.start,b,o.start,R,!0)}else v&&y-(m.appliedTimelineOffset||0)>lu&&(o.gap=!0);o.setElementaryStreamInfo(u.type,y,b,A,R),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,o,l,n,v||T)}else if(v||T)o.gap=!0;else{this.backtrack(o);return}}if(p){let{startPTS:g,endPTS:v,startDTS:T,endDTS:y}=p;l&&(l.elementaryStreams[We.AUDIO]={startPTS:g,endPTS:v,startDTS:T,endDTS:y}),o.setElementaryStreamInfo(We.AUDIO,g,v,T,y),this.bufferFragmentData(p,o,l,n)}if(m&&h!=null&&h.samples.length){let g={id:t,frag:o,details:m,samples:h.samples};s.trigger(E.FRAG_PARSING_METADATA,g)}if(m&&c){let g={id:t,frag:o,details:m,samples:c.samples};s.trigger(E.FRAG_PARSING_USERDATA,g)}}logMuxedErr(e){this.warn(`${at(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,r){if(this.state!==O.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));let{audio:n,video:a,audiovideo:o}=t;if(n){let d=e.audioCodec,u=iu(n.codec,d);u==="mp4a"&&(u="mp4a.40.5");let c=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){u&&(u.indexOf("mp4a.40.5")!==-1?u="mp4a.40.2":u="mp4a.40.5");let h=n.metadata;h&&"channelCount"in h&&(h.channelCount||1)!==1&&c.indexOf("firefox")===-1&&(u="mp4a.40.5")}u&&u.indexOf("mp4a.40.5")!==-1&&c.indexOf("android")!==-1&&n.container!=="audio/mpeg"&&(u="mp4a.40.2",this.log(`Android: force audio codec to ${u}`)),d&&d!==u&&this.log(`Swapping manifest audio codec "${d}" for "${u}"`),n.levelCodec=u,n.id=J.MAIN,this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${u||""}/${d||""}/${n.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=J.MAIN;let d=a.codec;if((d==null?void 0:d.length)===4)switch(d){case"hvc1":case"hev1":a.codec="hvc1.1.6.L120.90";break;case"av01":a.codec="av01.0.04M.08";break;case"avc1":a.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${d}]${a.codec!==d?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete t.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);let l=Object.keys(t);if(l.length){if(this.hls.trigger(E.BUFFER_CODECS,t),!this.hls)return;l.forEach(d=>{let c=t[d].initSegment;c!=null&&c.byteLength&&this.hls.trigger(E.BUFFER_APPENDING,{type:d,data:c,frag:s,part:null,chunkMeta:r,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){let e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,J.MAIN)}get maxBufferLength(){let{levels:e,level:t}=this,s=e==null?void 0:e[t];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=O.IDLE}checkFragmentChanged(){let e=this.media,t=null;if(e&&e.readyState>1&&e.seeking===!1){let s=e.currentTime;if(Ee.isBuffered(e,s)?t=this.getAppendedFrag(s):Ee.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;let r=this.fragPlaying,n=t.level;(!r||t.sn!==r.sn||r.level!==n)&&(this.fragPlaying=t,this.hls.trigger(E.FRAG_CHANGED,{frag:t}),(!r||r.level!==n)&&this.hls.trigger(E.LEVEL_SWITCHED,{level:n}))}}}get nextLevel(){let e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;let t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return Q(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;let t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(Q(t)){let s=this.getLevelDetails(),r=this.currentFrag||(s?sn(null,s.fragments,t):null);if(r){let n=r.programDateTime;if(n!==null){let a=n+(t-r.start)*1e3;return new Date(a)}}}return null}get currentLevel(){let e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){let e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}},jp=class extends Qt{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(let s in this.keyIdToKeyInfo){let r=this.keyIdToKeyInfo[s].loader;if(r){var t;if(e&&e!==((t=r.context)==null?void 0:t.frag.type))return;r.abort()}}}detach(){for(let e in this.keyIdToKeyInfo){let t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(let e in this.keyIdToKeyInfo){let t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=M.KEY_LOAD_ERROR,s,r,n){return new Mi({type:se.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:s,networkDetails:r})}loadClear(e,t,s){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let r=0,n=t.length;r<n;r++){let a=t[r];if(e.cc<=a.cc&&(!at(e)||!at(a)||e.sn<a.sn)||!s&&r==n-1)return this.emeController.selectKeySystemFormat(a).then(o=>{if(!this.emeController)return;a.setKeyFormat(o);let l=ru(o);if(l)return this.emeController.getKeySystemAccess([l])})}if(this.config.requireKeySystemAccessOnStart){let r=Mo(this.config);if(r.length)return this.emeController.getKeySystemAccess(r)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var s,r;t&&e.setKeyFormat(t);let n=e.decryptdata;if(!n){let d=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,M.KEY_LOAD_ERROR,d))}let a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,M.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));let o=Dm(n),l=this.keyIdToKeyInfo[o];if((s=l)!=null&&s.decryptdata.key)return n.key=l.decryptdata.key,Promise.resolve({frag:e,keyInfo:l});if(this.emeController&&(r=l)!=null&&r.keyLoadPromise)switch(this.emeController.getKeyStatus(l.decryptdata)){case"usable":case"usable-in-future":return l.keyLoadPromise.then(u=>{let{keyInfo:c}=u;return n.key=c.decryptdata.key,{frag:e,keyInfo:c}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${n.keyId?" keyId: "+Dt(n.keyId):""} URI: ${n.uri} from ${e.type} ${e.level}`),l=this.keyIdToKeyInfo[o]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return n.keyFormat==="identity"?this.loadKeyHTTP(l,e):this.loadKeyEME(l,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(l,e);default:return Promise.reject(this.createKeyLoadError(e,M.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(e,t){let s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var r;if(!e.decryptdata.keyId&&(r=t.initSegment)!=null&&r.data){let a=GR(t.initSegment.data);if(a.length){let o=a[0];o.some(l=>l!==0)?(this.log(`Using keyId found in init segment ${Dt(o)}`),na.setKeyIdForUri(e.decryptdata.uri,o)):(o=na.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${Dt(o)}`)),e.decryptdata.keyId=o}}if(!e.decryptdata.keyId&&!at(t))return Promise.resolve(s);let n=this.emeController.loadKey(s);return(e.keyLoadPromise=n.then(a=>(e.mediaKeySessionContext=a,s))).catch(a=>{throw e.keyLoadPromise=null,"data"in a&&(a.data.frag=t),a})}return Promise.resolve(s)}loadKeyHTTP(e,t){let s=this.config,r=s.loader,n=new r(s);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise((a,o)=>{let l={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},d=s.keyLoadPolicy.default,u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(h,f,m,p)=>{let{frag:g,keyInfo:v}=m,T=Dm(v.decryptdata);if(!g.decryptdata||v!==this.keyIdToKeyInfo[T])return o(this.createKeyLoadError(g,M.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),p));v.decryptdata.key=g.decryptdata.key=new Uint8Array(h.data),g.keyLoader=null,v.loader=null,a({frag:g,keyInfo:v})},onError:(h,f,m,p)=>{this.resetLoader(f),o(this.createKeyLoadError(t,M.KEY_LOAD_ERROR,new Error(`HTTP Error ${h.code} loading key ${h.text}`),m,Fe({url:l.url,data:void 0},h)))},onTimeout:(h,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,M.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),m))},onAbort:(h,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,M.INTERNAL_ABORTED,new Error("key loading aborted"),m))}};n.load(l,u,c)})}resetLoader(e){let{frag:t,keyInfo:s,url:r}=e,n=s.loader;t.keyLoader===n&&(t.keyLoader=null,s.loader=null);let a=Dm(s.decryptdata)||r;delete this.keyIdToKeyInfo[a],n&&n.destroy()}};function Dm(i){if(i.keyFormat!==Ct.FAIRPLAY){let e=i.keyId;if(e)return Dt(e)}return i.uri}function Qy(i){let{type:e}=i;switch(e){case Le.AUDIO_TRACK:return J.AUDIO;case Le.SUBTITLE_TRACK:return J.SUBTITLE;default:return J.MAIN}}function Cm(i,e){let t=i.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}var zp=class{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){let{hls:e}=this;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){let{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){let t=this.hls.config,s=t.pLoader,r=t.loader,n=s||r,a=new n(t);return this.loaders[e.type]=a,a}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(let e in this.loaders){let t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){let{url:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Le.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){let{id:s,level:r,pathwayId:n,url:a,deliveryDirectives:o,levelInfo:l}=t;this.load({id:s,level:r,pathwayId:n,responseType:"text",type:Le.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:l})}onAudioTrackLoading(e,t){let{id:s,groupId:r,url:n,deliveryDirectives:a,track:o}=t;this.load({id:s,groupId:r,level:null,responseType:"text",type:Le.AUDIO_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){let{id:s,groupId:r,url:n,deliveryDirectives:a,track:o}=t;this.load({id:s,groupId:r,level:null,responseType:"text",type:Le.SUBTITLE_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){let s=this.loaders[Le.LEVEL];if(s){let r=s.context;r&&!t.levels.some(n=>n===r.levelOrTrack)&&(s.abort(),delete this.loaders[Le.LEVEL])}}load(e){var t;let s=this.hls.config,r=this.getInternalLoader(e);if(r){let d=this.hls.logger,u=r.context;if(u&&u.levelOrTrack===e.levelOrTrack&&(u.url===e.url||u.deliveryDirectives&&!e.deliveryDirectives)){u.url===e.url?d.log(`[playlist-loader]: ignore ${e.url} ongoing request`):d.log(`[playlist-loader]: ignore ${e.url} in favor of ${u.url}`);return}d.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),r.abort()}let n;if(e.type===Le.MANIFEST?n=s.manifestLoadPolicy.default:n=$e({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(e),Q((t=e.deliveryDirectives)==null?void 0:t.part)){let d;if(e.type===Le.LEVEL&&e.level!==null?d=this.hls.levels[e.level].details:e.type===Le.AUDIO_TRACK&&e.id!==null?d=this.hls.audioTracks[e.id].details:e.type===Le.SUBTITLE_TRACK&&e.id!==null&&(d=this.hls.subtitleTracks[e.id].details),d){let u=d.partTarget,c=d.targetduration;if(u&&c){let h=Math.max(u*3,c*.8)*1e3;n=$e({},n,{maxTimeToFirstByteMs:Math.min(h,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(h,n.maxTimeToFirstByteMs)})}}}let a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(d,u,c,h)=>{let f=this.getInternalLoader(c);this.resetInternalLoader(c.type);let m=d.data;u.parsing.start=performance.now(),Zr.isMediaPlaylist(m)||c.type!==Le.MANIFEST?this.handleTrackOrLevelPlaylist(d,u,c,h||null,f):this.handleMasterPlaylist(d,u,c,h)},onError:(d,u,c,h)=>{this.handleNetworkError(u,c,!1,d,h)},onTimeout:(d,u,c)=>{this.handleNetworkError(u,c,!0,void 0,d)}};r.load(e,o,l)}checkAutostartLoad(){if(!this.hls)return;let{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,r){let n=this.hls,a=e.data,o=Cm(e,s),l=Zr.parseMasterPlaylist(a,o);if(l.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,s,l.playlistParsingError,r,t);return}let{contentSteering:d,levels:u,sessionData:c,sessionKeys:h,startTimeOffset:f,variableList:m}=l;this.variableList=m,u.forEach(T=>{let{unknownCodecs:y}=T;if(y){let{preferManagedMediaSource:b}=this.hls.config,{audioCodec:A,videoCodec:R}=T;for(let I=y.length;I--;){let x=y[I];Bo(x,"audio",b)?(T.audioCodec=A=A?`${A},${x}`:x,ra.audio[A.substring(0,4)]=2,y.splice(I,1)):Bo(x,"video",b)&&(T.videoCodec=R=R?`${R},${x}`:x,ra.video[R.substring(0,4)]=2,y.splice(I,1))}}});let{AUDIO:p=[],SUBTITLES:g,"CLOSED-CAPTIONS":v}=Zr.parseMasterPlaylistMedia(a,o,l);p.length&&!p.some(y=>!y.url)&&u[0].audioCodec&&!u[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new tt({}),bitrate:0,url:""})),n.trigger(E.MANIFEST_LOADED,{levels:u,audioTracks:p,subtitles:g,captions:v,contentSteering:d,url:o,stats:t,networkDetails:r,sessionData:c,sessionKeys:h,startTimeOffset:f,variableList:m})}handleTrackOrLevelPlaylist(e,t,s,r,n){let a=this.hls,{id:o,level:l,type:d}=s,u=Cm(e,s),c=Q(l)?l:Q(o)?o:0,h=Qy(s),f=Zr.parseLevelPlaylist(e.data,u,c,h,0,this.variableList);if(d===Le.MANIFEST){let m={attrs:new tt({}),bitrate:0,details:f,name:"",url:u};f.requestScheduled=t.loading.start+IT(f,0),a.trigger(E.MANIFEST_LOADED,{levels:[m],audioTracks:[],url:u,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=f,this.handlePlaylistLoaded(f,e,t,s,r,n)}handleManifestParsingError(e,t,s,r,n){this.hls.trigger(E.ERROR,{type:se.NETWORK_ERROR,details:M.MANIFEST_PARSING_ERROR,fatal:t.type===Le.MANIFEST,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:r,stats:n})}handleNetworkError(e,t,s=!1,r,n){let a=`A network ${s?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${e.type}`;e.type===Le.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===Le.AUDIO_TRACK||e.type===Le.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);let o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let l=M.UNKNOWN,d=!1,u=this.getInternalLoader(e);switch(e.type){case Le.MANIFEST:l=s?M.MANIFEST_LOAD_TIMEOUT:M.MANIFEST_LOAD_ERROR,d=!0;break;case Le.LEVEL:l=s?M.LEVEL_LOAD_TIMEOUT:M.LEVEL_LOAD_ERROR,d=!1;break;case Le.AUDIO_TRACK:l=s?M.AUDIO_TRACK_LOAD_TIMEOUT:M.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case Le.SUBTITLE_TRACK:l=s?M.SUBTITLE_TRACK_LOAD_TIMEOUT:M.SUBTITLE_LOAD_ERROR,d=!1;break}u&&this.resetInternalLoader(e.type);let c={type:se.NETWORK_ERROR,details:l,fatal:d,url:e.url,loader:u,context:e,error:o,networkDetails:t,stats:n};if(r){let h=(t==null?void 0:t.url)||e.url;c.response=Fe({url:h,data:void 0},r)}this.hls.trigger(E.ERROR,c)}handlePlaylistLoaded(e,t,s,r,n,a){let o=this.hls,{type:l,level:d,levelOrTrack:u,id:c,groupId:h,deliveryDirectives:f}=r,m=Cm(t,r),p=Qy(r),g=typeof r.level=="number"&&p===J.MAIN?d:void 0,v=e.playlistParsingError;if(v){if(this.hls.logger.warn(`${v} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(E.ERROR,{type:se.NETWORK_ERROR,details:M.LEVEL_PARSING_ERROR,fatal:!1,url:m,error:v,reason:v.message,response:t,context:r,level:g,parent:p,networkDetails:n,stats:s});return}e.playlistParsingError=null}if(!e.fragments.length){let T=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(E.ERROR,{type:se.NETWORK_ERROR,details:M.LEVEL_EMPTY_ERROR,fatal:!1,url:m,error:T,reason:T.message,response:t,context:r,level:g,parent:p,networkDetails:n,stats:s});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case Le.MANIFEST:case Le.LEVEL:if(g){if(!u)g=0;else if(u!==o.levels[g]){let T=o.levels.indexOf(u);T>-1&&(g=T)}}o.trigger(E.LEVEL_LOADED,{details:e,levelInfo:u||o.levels[0],level:g||0,id:c||0,stats:s,networkDetails:n,deliveryDirectives:f,withoutMultiVariant:l===Le.MANIFEST});break;case Le.AUDIO_TRACK:o.trigger(E.AUDIO_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:h||"",stats:s,networkDetails:n,deliveryDirectives:f});break;case Le.SUBTITLE_TRACK:o.trigger(E.SUBTITLE_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:h||"",stats:s,networkDetails:n,deliveryDirectives:f});break}}},Xo=class i{static get version(){return Vo}static isMSESupported(){return Eb()}static isSupported(){return LC()}static getMediaSource(){return nr()}static get Events(){return E}static get MetadataSchema(){return oi}static get ErrorTypes(){return se}static get ErrorDetails(){return M}static get DefaultConfig(){return i.defaultConfig?i.defaultConfig:EC}static set DefaultConfig(e){i.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new sg,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;let t=this.logger=CR(e.debug||!1,"Hls instance",e.assetPlayerId),s=this.config=TC(i.DefaultConfig,e,t);this.userConfig=e,s.progressive&&bC(s,t);let{abrController:r,bufferController:n,capLevelController:a,errorController:o,fpsController:l}=s,d=new o(this),u=this.abrController=new r(this),c=new Hm(this),h=s.interstitialsController,f=h?this.interstitialsController=new h(this,i):null,m=this.bufferController=new n(this,c),p=this.capLevelController=new a(this),g=new l(this),v=new zp(this),T=s.contentSteeringController,y=T?new T(this):null,b=this.levelController=new qp(this,y),A=new Vp(this),R=new jp(this.config,this.logger),I=this.streamController=new Yp(this,c,R),x=this.gapController=new Gp(this,c);p.setStreamController(I),g.setStreamController(I);let D=[v,b,I];f&&D.splice(1,0,f),y&&D.splice(1,0,y),this.networkControllers=D;let S=[u,m,x,p,g,A,c];this.audioTrackController=this.createController(s.audioTrackController,D);let C=s.audioStreamController;C&&D.push(this.audioStreamController=new C(this,c,R)),this.subtitleTrackController=this.createController(s.subtitleTrackController,D);let P=s.subtitleStreamController;P&&D.push(this.subtititleStreamController=new P(this,c,R)),this.createController(s.timelineController,S),R.emeController=this.emeController=this.createController(s.emeController,S),this.cmcdController=this.createController(s.cmcdController,S),this.latencyController=this.createController(Wp,S),this.coreComponents=S,D.push(d);let N=d.onErrorOut;typeof N=="function"&&this.on(E.ERROR,N,d),this.on(E.MANIFEST_LOADED,v.onManifestLoaded,v)}createController(e,t){if(e){let s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,r){this._emitter.off(e,t,s,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(s){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;let r=e===E.ERROR;this.trigger(E.ERROR,{type:se.OTHER_ERROR,details:M.INTERNAL_EXCEPTION,fatal:r,event:e,error:s}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(E.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;let e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){let n=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(E.ERROR,{type:se.OTHER_ERROR,details:M.ATTACH_MEDIA_ERROR,fatal:!0,error:n});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());let t="media"in e,s=t?e.media:e,r=t?e:{media:s};this._media=s,this.trigger(E.MEDIA_ATTACHING,r)}detachMedia(){this.logger.log("detachMedia"),this.trigger(E.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;let e=this.bufferController.transferMedia();return this.trigger(E.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();let t=this.media,s=this._url,r=this._url=Qp.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),t&&s&&(s!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(E.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(e,t),!(!this.started||!this.networkControllers));s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){let e={[J.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[J.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[J.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");let e=this._media,t=e==null?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=$D()),e}get levels(){let e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){let e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){let t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){let{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){dx(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){let{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;let s=e.length;for(let r=0;r<s;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this,r;if(t===-1&&e!=null&&e.length?r=e.length-1:r=t,s)for(let n=r;n--;){let a=e[n].attrs["HDCP-LEVEL"];if(a&&a<=s)return n}return r}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){let e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){let e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){let e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){let t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){let e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){let e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){let e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){let t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){let e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){let t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){var e;return((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){let s=hT(t);return uT(e,s,navigator.mediaCapabilities)}};Xo.defaultConfig=void 0;var _e=Xo,Ue={VIDEO:"video",THUMBNAIL:"thumbnail",STORYBOARD:"storyboard",DRM:"drm"},ne={NOT_AN_ERROR:0,NETWORK_OFFLINE:2000002,NETWORK_UNKNOWN_ERROR:2e6,NETWORK_NO_STATUS:2000001,NETWORK_INVALID_URL:24e5,NETWORK_NOT_FOUND:2404e3,NETWORK_NOT_READY:2412e3,NETWORK_GENERIC_SERVER_FAIL:25e5,NETWORK_TOKEN_MISSING:2403201,NETWORK_TOKEN_MALFORMED:2412202,NETWORK_TOKEN_EXPIRED:2403210,NETWORK_TOKEN_AUD_MISSING:2403221,NETWORK_TOKEN_AUD_MISMATCH:2403222,NETWORK_TOKEN_SUB_MISMATCH:2403232,ENCRYPTED_ERROR:5e6,ENCRYPTED_UNSUPPORTED_KEY_SYSTEM:5000001,ENCRYPTED_GENERATE_REQUEST_FAILED:5000002,ENCRYPTED_UPDATE_LICENSE_FAILED:5000003,ENCRYPTED_UPDATE_SERVER_CERT_FAILED:5000004,ENCRYPTED_CDM_ERROR:5000005,ENCRYPTED_OUTPUT_RESTRICTED:5000006,ENCRYPTED_MISSING_TOKEN:5000002},tl=i=>i===Ue.VIDEO?"playback":i,or=class Zo extends Error{constructor(e,t=Zo.MEDIA_ERR_CUSTOM,s,r){var n;super(e),this.name="MediaError",this.code=t,this.context=r,this.fatal=s!=null?s:t>=Zo.MEDIA_ERR_NETWORK&&t<=Zo.MEDIA_ERR_ENCRYPTED,this.message||(this.message=(n=Zo.defaultMessages[this.code])!=null?n:"")}};or.MEDIA_ERR_ABORTED=1,or.MEDIA_ERR_NETWORK=2,or.MEDIA_ERR_DECODE=3,or.MEDIA_ERR_SRC_NOT_SUPPORTED=4,or.MEDIA_ERR_ENCRYPTED=5,or.MEDIA_ERR_CUSTOM=100,or.defaultMessages={1:"You aborted the media playback",2:"A network error caused the media download to fail.",3:"A media error caused playback to be aborted. The media could be corrupt or your browser does not support this format.",4:"An unsupported error occurred. The server or network failed, or your browser does not support this format.",5:"The media is encrypted and there are no keys to decrypt it."};var z=or,kC=i=>i==null,Sg=(i,e)=>kC(e)?!1:i in e,pg={ANY:"any",MUTED:"muted"},we={ON_DEMAND:"on-demand",LIVE:"live",UNKNOWN:"unknown"},gi={MSE:"mse",NATIVE:"native"},Jo={HEADER:"header",QUERY:"query",NONE:"none"},la=Object.values(Jo),Cs={M3U8:"application/vnd.apple.mpegurl",MP4:"video/mp4"},gg={HLS:Cs.M3U8},IN=Object.keys(gg),LN=[...Object.values(Cs),"hls","HLS"];var DC="en",vg={code:DC},mt=(i,e,t,s,r=i)=>{r.addEventListener(e,t,s),i.addEventListener("teardown",()=>{r.removeEventListener(e,t)},{once:!0})};function CC(i,e,t){e&&t>e&&(t=e);for(let s=0;s<i.length;s++)if(i.start(s)<=t&&i.end(s)>=t)return!0;return!1}var Gu=i=>{let e=i.indexOf("?");if(e<0)return[i];let t=i.slice(0,e),s=i.slice(e);return[t,s]},Ku=i=>{let{type:e}=i;if(e){let t=e.toUpperCase();return Sg(t,gg)?gg[t]:e}return wC(i)},xb=i=>i==="VOD"?we.ON_DEMAND:we.LIVE,kb=i=>i==="EVENT"?Number.POSITIVE_INFINITY:i==="VOD"?Number.NaN:0,wC=i=>{let{src:e}=i;if(!e)return"";let t="";try{t=Ig(e).pathname}catch{console.error("Invalid url when trying to infer mime type",e)}let s=t.lastIndexOf(".");if(s<0)return OC(i)?Cs.M3U8:"";let r=t.slice(s+1).toUpperCase();return Sg(r,Cs)?Cs[r]:""},Eg=i=>{try{return new URL(i),!1}catch{return!0}},MC=i=>i.split(`
56
- `).find((e,t,s)=>t>0&&s[t-1].startsWith("#EXT-X-STREAM-INF")),Ig=(i,e)=>{var t;if(!Eg(i))return new URL(i);let s=(t=window==null?void 0:window.location)==null?void 0:t.href,r=e!=null?e:s;return e&&Eg(e.toString())&&(r=new URL(e,s)),new URL(i,r)},PC="mux.com",OC=({src:i,customDomain:e=PC})=>{let t;try{t=new URL(`${i}`)}catch{return!1}let s=t.protocol==="https:",r=t.hostname===`stream.${e}`.toLowerCase(),n=t.pathname.split("/"),a=n.length===2,o=!(n!=null&&n[1].includes("."));return s&&r&&a&&o},dr=i=>{let e=(i!=null?i:"").split(".")[1];if(e)try{let t=e.replace(/-/g,"+").replace(/_/g,"/"),s=decodeURIComponent(atob(t).split("").map(function(r){return"%"+("00"+r.charCodeAt(0).toString(16)).slice(-2)}).join(""));return JSON.parse(s)}catch{return}},NC=({exp:i},e=Date.now())=>!i||i*1e3<e,UC=({sub:i},e)=>i!==e,FC=({aud:i},e)=>!i,BC=({aud:i},e)=>i!==e,Db="en";function te(i,e=!0){var t,s;let r=e&&(s=(t=vg)==null?void 0:t[i])!=null?s:i,n=e?vg.code:Db;return new $C(r,n)}var $C=class{constructor(i,e=(t=>(t=vg)!=null?t:Db)()){this.message=i,this.locale=e}format(i){return this.message.replace(/\{(\w+)\}/g,(e,t)=>{var s;return(s=i[t])!=null?s:""})}toString(){return this.message}},HC=Object.values(pg),yb=i=>typeof i=="boolean"||typeof i=="string"&&HC.includes(i),GC=(i,e,t)=>{let{autoplay:s}=i,r=!1,n=!1,a=yb(s)?s:!!s,o=()=>{r||mt(e,"playing",()=>{r=!0},{once:!0})};if(o(),mt(e,"loadstart",()=>{r=!1,o(),fg(e,a)},{once:!0}),mt(e,"loadstart",()=>{t||(i.streamType&&i.streamType!==we.UNKNOWN?n=i.streamType===we.LIVE:n=!Number.isFinite(e.duration)),fg(e,a)},{once:!0}),t&&t.once(_e.Events.LEVEL_LOADED,(l,d)=>{var u;i.streamType&&i.streamType!==we.UNKNOWN?n=i.streamType===we.LIVE:n=(u=d.details.live)!=null?u:!1}),!a){let l=()=>{!n||Number.isFinite(i.startTime)||(t!=null&&t.liveSyncPosition?e.currentTime=t.liveSyncPosition:Number.isFinite(e.seekable.end(0))&&(e.currentTime=e.seekable.end(0)))};t&&mt(e,"play",()=>{e.preload==="metadata"?t.once(_e.Events.LEVEL_UPDATED,l):l()},{once:!0})}return l=>{r||(a=yb(l)?l:!!l,fg(e,a))}},fg=(i,e)=>{if(!e)return;let t=i.muted,s=()=>i.muted=t;switch(e){case pg.ANY:i.play().catch(()=>{i.muted=!0,i.play().catch(s)});break;case pg.MUTED:i.muted=!0,i.play().catch(s);break;default:i.play().catch(()=>{});break}},KC=({preload:i,src:e},t,s)=>{let r=c=>{c!=null&&["","none","metadata","auto"].includes(c)?t.setAttribute("preload",c):t.removeAttribute("preload")};if(!s)return r(i),r;let n=!1,a=!1,o=s.config.maxBufferLength,l=s.config.maxBufferSize,d=c=>{r(c);let h=c!=null?c:t.preload;a||h==="none"||(h==="metadata"?(s.config.maxBufferLength=1,s.config.maxBufferSize=1):(s.config.maxBufferLength=o,s.config.maxBufferSize=l),u())},u=()=>{!n&&e&&(n=!0,s.loadSource(e))};return mt(t,"play",()=>{a=!0,s.config.maxBufferLength=o,s.config.maxBufferSize=l,u()},{once:!0}),d(i),d},VC=(i,e,t)=>{let{minPreloadSegments:s}=i;if(s==null||s<=0||!t)return;let r=0,n=!1,a=e.playbackRate||1,o=()=>{e.playbackRate!==0&&(a=e.playbackRate,e.playbackRate=0)};e.playbackRate=0,mt(e,"ratechange",o);let l=(d,{frag:u})=>{n||u.type!=="main"||(r++,r>=s&&(n=!0,e.removeEventListener("ratechange",o),e.playbackRate=a))};t.on(_e.Events.FRAG_BUFFERED,l),e.addEventListener("teardown",()=>{n||(n=!0,t.off(_e.Events.FRAG_BUFFERED,l),e.playbackRate=a)},{once:!0})},WC=(i,e,t)=>{let{initialEstimateSegments:s}=i;if(s==null||s<=0||!t)return;let r=0;t.on(_e.Events.FRAG_BUFFERED,(n,{frag:a})=>{a.type==="main"&&(r++,r<s&&t.abrController.resetEstimator(t.config.abrEwmaDefaultEstimate))})};function qC(i,e){var t;if(!("videoTracks"in i))return;let s=new WeakMap;e.on(_e.Events.MANIFEST_PARSED,function(d,u){l();let c=i.addVideoTrack("main");c.selected=!0;for(let[h,f]of u.levels.entries()){let m=c.addRendition(f.url[0],f.width,f.height,f.videoCodec,f.bitrate);s.set(f,`${h}`),m.id=`${h}`}}),e.on(_e.Events.AUDIO_TRACKS_UPDATED,function(d,u){o();for(let c of u.audioTracks){let h=c.default?"main":"alternative",f=i.addAudioTrack(h,c.name,c.lang);f.id=`${c.id}`,c.default&&(f.enabled=!0)}});let r=()=>{var d;let u=+((d=[...i.audioTracks].find(h=>h.enabled))==null?void 0:d.id),c=e.audioTracks.map(h=>h.id);u!=e.audioTrack&&c.includes(u)&&(e.audioTrack=u)};i.audioTracks.addEventListener("change",r),e.on(_e.Events.LEVELS_UPDATED,function(d,u){var c;let h=i.videoTracks[(c=i.videoTracks.selectedIndex)!=null?c:0];if(!h)return;let f=u.levels.map(m=>s.get(m));for(let m of i.videoRenditions)m.id&&!f.includes(m.id)&&h.removeRendition(m)});let n=d=>{let u=d.target.selectedIndex;u!=e.nextLevel&&(e.nextLevel=u)};(t=i.videoRenditions)==null||t.addEventListener("change",n);let a=()=>{for(let d of i.videoTracks)i.removeVideoTrack(d)},o=()=>{for(let d of i.audioTracks)i.removeAudioTrack(d)},l=()=>{a(),o()};e.once(_e.Events.DESTROYING,()=>{var d,u;l(),(d=i.audioTracks)==null||d.removeEventListener("change",r),(u=i.videoRenditions)==null||u.removeEventListener("change",n)})}var mg=i=>"time"in i?i.time:i.startTime;function YC(i,e){e.on(_e.Events.NON_NATIVE_TEXT_TRACKS_FOUND,(r,{tracks:n})=>{n.forEach(a=>{var o,l;let d=(o=a.subtitleTrack)!=null?o:a.closedCaptions,u=e.subtitleTracks.findIndex(({lang:h,name:f,type:m})=>h==(d==null?void 0:d.lang)&&f===a.label&&m.toLowerCase()===a.kind),c=((l=a._id)!=null?l:a.default)?"default":`${a.kind}${u}`;Vu(i,a.kind,a.label,d==null?void 0:d.lang,c,a.default)})});let t=()=>{if(!e.subtitleTracks.length)return;let r=Array.from(i.textTracks).find(o=>o.id&&o.mode==="showing"&&["subtitles","captions"].includes(o.kind));if(!r)return;let n=e.subtitleTracks[e.subtitleTrack],a=n?n.default?"default":`${e.subtitleTracks[e.subtitleTrack].type.toLowerCase()}${e.subtitleTrack}`:void 0;if(e.subtitleTrack<0||(r==null?void 0:r.id)!==a){let o=e.subtitleTracks.findIndex(({lang:l,name:d,type:u,default:c})=>r.id==="default"&&c||l==r.language&&d===r.label&&u.toLowerCase()===r.kind);e.subtitleTrack=o}(r==null?void 0:r.id)===a&&r.cues&&Array.from(r.cues).forEach(o=>{r.addCue(o)})};i.textTracks.addEventListener("change",t),e.on(_e.Events.CUES_PARSED,(r,{track:n,cues:a})=>{let o=i.textTracks.getTrackById(n);if(!o)return;let l=o.mode==="disabled";l&&(o.mode="hidden"),a.forEach(d=>{var u;(u=o.cues)!=null&&u.getCueById(d.id)||o.addCue(d)}),l&&(o.mode="disabled")}),e.once(_e.Events.DESTROYING,()=>{i.textTracks.removeEventListener("change",t),i.querySelectorAll("track[data-removeondestroy]").forEach(r=>{r.remove()})});let s=()=>{Array.from(i.textTracks).forEach(r=>{var n,a;if(!["subtitles","caption"].includes(r.kind)&&(r.label==="thumbnails"||r.kind==="chapters")){if(!((n=r.cues)!=null&&n.length)){let o="track";r.kind&&(o+=`[kind="${r.kind}"]`),r.label&&(o+=`[label="${r.label}"]`);let l=i.querySelector(o),d=(a=l==null?void 0:l.getAttribute("src"))!=null?a:"";l==null||l.removeAttribute("src"),setTimeout(()=>{l==null||l.setAttribute("src",d)},0)}r.mode!=="hidden"&&(r.mode="hidden")}})};e.once(_e.Events.MANIFEST_LOADED,s),e.once(_e.Events.MEDIA_ATTACHED,s)}function Vu(i,e,t,s,r,n){let a=document.createElement("track");return a.kind=e,a.label=t,s&&(a.srclang=s),r&&(a.id=r),n&&(a.default=!0),a.track.mode=["subtitles","captions"].includes(e)?"disabled":"hidden",a.setAttribute("data-removeondestroy",""),i.append(a),a.track}function Cb(i,e){let t=Array.prototype.find.call(i.querySelectorAll("track"),s=>s.track===e);t==null||t.remove()}function il(i,e,t){var s;return(s=Array.from(i.querySelectorAll("track")).find(r=>r.track.label===e&&r.track.kind===t))==null?void 0:s.track}async function wb(i,e,t,s){let r=il(i,t,s);return r||(r=Vu(i,s,t),r.mode="hidden",await new Promise(n=>setTimeout(()=>n(void 0),0))),r.mode!=="hidden"&&(r.mode="hidden"),[...e].sort((n,a)=>mg(a)-mg(n)).forEach(n=>{var a,o;let l=n.value,d=mg(n);if("endTime"in n&&n.endTime!=null)r==null||r.addCue(new VTTCue(d,n.endTime,s==="chapters"?l:JSON.stringify(l!=null?l:null)));else{let u=Array.prototype.findIndex.call(r==null?void 0:r.cues,m=>m.startTime>=d),c=(a=r==null?void 0:r.cues)==null?void 0:a[u],h=c?c.startTime:Number.isFinite(i.duration)?i.duration:Number.MAX_SAFE_INTEGER,f=(o=r==null?void 0:r.cues)==null?void 0:o[u-1];f&&(f.endTime=d),r==null||r.addCue(new VTTCue(d,h,s==="chapters"?l:JSON.stringify(l!=null?l:null)))}}),i.textTracks.dispatchEvent(new Event("change",{bubbles:!0,composed:!0})),r}var Lg="cuepoints",Mb=Object.freeze({label:Lg});async function Rg(i,e,t=Mb){return wb(i,e,t.label,"metadata")}var yg=i=>({time:i.startTime,value:JSON.parse(i.text)});function Pb(i,e={label:Lg}){let t=il(i,e.label,"metadata");return t!=null&&t.cues?Array.from(t.cues,s=>yg(s)):[]}function xg(i,e={label:Lg}){var t,s;let r=il(i,e.label,"metadata");if(!((t=r==null?void 0:r.activeCues)!=null&&t.length))return;if(r.activeCues.length===1)return yg(r.activeCues[0]);let{currentTime:n}=i,a=Array.prototype.find.call((s=r.activeCues)!=null?s:[],({startTime:o,endTime:l})=>o<=n&&l>n);return yg(a||r.activeCues[0])}async function jC(i,e=Mb){return new Promise(t=>{mt(i,"loadstart",async()=>{let s=await Rg(i,[],e);mt(i,"cuechange",()=>{let r=xg(i);if(r){let n=new CustomEvent("cuepointchange",{composed:!0,bubbles:!0,detail:r});i.dispatchEvent(n)}},{},s),t(s)})})}var kg="chapters",Ob=Object.freeze({label:kg}),Tg=i=>({startTime:i.startTime,endTime:i.endTime,value:i.text});async function Dg(i,e,t=Ob){return wb(i,e,t.label,"chapters")}function Nb(i,e={label:kg}){var t;let s=il(i,e.label,"chapters");return(t=s==null?void 0:s.cues)!=null&&t.length?Array.from(s.cues,r=>Tg(r)):[]}function Cg(i,e={label:kg}){var t,s;let r=il(i,e.label,"chapters");if(!((t=r==null?void 0:r.activeCues)!=null&&t.length))return;if(r.activeCues.length===1)return Tg(r.activeCues[0]);let{currentTime:n}=i,a=Array.prototype.find.call((s=r.activeCues)!=null?s:[],({startTime:o,endTime:l})=>o<=n&&l>n);return Tg(a||r.activeCues[0])}async function zC(i,e=Ob){return new Promise(t=>{mt(i,"loadstart",async()=>{let s=await Dg(i,[],e);mt(i,"cuechange",()=>{let r=Cg(i);if(r){let n=new CustomEvent("chapterchange",{composed:!0,bubbles:!0,detail:r});i.dispatchEvent(n)}},{},s),t(s)})})}function Ub(i,e){if(e){let t=e.playingDate;if(t!=null)return new Date(t.getTime()-i.currentTime*1e3)}return typeof i.getStartDate=="function"?i.getStartDate():new Date(NaN)}function Fb(i,e){if(e&&e.playingDate)return e.playingDate;if(typeof i.getStartDate=="function"){let t=i.getStartDate();return new Date(t.getTime()+i.currentTime*1e3)}return new Date(NaN)}var oa={VIDEO:"v",THUMBNAIL:"t",STORYBOARD:"s",DRM:"d"},QC=i=>{if(i===Ue.VIDEO)return oa.VIDEO;if(i===Ue.DRM)return oa.DRM},XC=(i,e)=>{var t,s;let r=tl(i),n=`${r}Token`;return(t=e.tokens)!=null&&t[r]?(s=e.tokens)==null?void 0:s[r]:Sg(n,e)?e[n]:void 0},$u=(i,e,t,s,r=!1,n=!(a=>(a=globalThis.navigator)==null?void 0:a.onLine)())=>{var a,o;if(n){let v=te("Your device appears to be offline",r),T,y=z.MEDIA_ERR_NETWORK,b=new z(v,y,!1,T);return b.errorCategory=e,b.muxCode=ne.NETWORK_OFFLINE,b.data=i,b}let l="status"in i?i.status:i.code,d=Date.now(),u=z.MEDIA_ERR_NETWORK;if(l===200)return;let c=tl(e),h=XC(e,t),f=QC(e),[m]=Gu((a=t.playbackId)!=null?a:"");if(!l||!m)return;let p=dr(h);if(h&&!p){let v=te("The {tokenNamePrefix}-token provided is invalid or malformed.",r).format({tokenNamePrefix:c}),T=te("Compact JWT string: {token}",r).format({token:h}),y=new z(v,u,!0,T);return y.errorCategory=e,y.muxCode=ne.NETWORK_TOKEN_MALFORMED,y.data=i,y}if(l>=500){let v=new z("",u,s!=null?s:!0);return v.errorCategory=e,v.muxCode=ne.NETWORK_UNKNOWN_ERROR,v}if(l===403)if(p){if(NC(p,d)){let v={timeStyle:"medium",dateStyle:"medium"},T=te("The video\u2019s secured {tokenNamePrefix}-token has expired.",r).format({tokenNamePrefix:c}),y=te("Expired at: {expiredDate}. Current time: {currentDate}.",r).format({expiredDate:new Intl.DateTimeFormat("en",v).format((o=p.exp)!=null?o:0*1e3),currentDate:new Intl.DateTimeFormat("en",v).format(d)}),b=new z(T,u,!0,y);return b.errorCategory=e,b.muxCode=ne.NETWORK_TOKEN_EXPIRED,b.data=i,b}if(UC(p,m)){let v=te("The video\u2019s playback ID does not match the one encoded in the {tokenNamePrefix}-token.",r).format({tokenNamePrefix:c}),T=te("Specified playback ID: {playbackId} and the playback ID encoded in the {tokenNamePrefix}-token: {tokenPlaybackId}",r).format({tokenNamePrefix:c,playbackId:m,tokenPlaybackId:p.sub}),y=new z(v,u,!0,T);return y.errorCategory=e,y.muxCode=ne.NETWORK_TOKEN_SUB_MISMATCH,y.data=i,y}if(FC(p,f)){let v=te("The {tokenNamePrefix}-token is formatted with incorrect information.",r).format({tokenNamePrefix:c}),T=te("The {tokenNamePrefix}-token has no aud value. aud value should be {expectedAud}.",r).format({tokenNamePrefix:c,expectedAud:f}),y=new z(v,u,!0,T);return y.errorCategory=e,y.muxCode=ne.NETWORK_TOKEN_AUD_MISSING,y.data=i,y}if(BC(p,f)){let v=te("The {tokenNamePrefix}-token is formatted with incorrect information.",r).format({tokenNamePrefix:c}),T=te("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.",r).format({tokenNamePrefix:c,expectedAud:f,aud:p.aud}),y=new z(v,u,!0,T);return y.errorCategory=e,y.muxCode=ne.NETWORK_TOKEN_AUD_MISMATCH,y.data=i,y}}else{let v=te("Authorization error trying to access this {category} URL. If this is a signed URL, you might need to provide a {tokenNamePrefix}-token.",r).format({tokenNamePrefix:c,category:e}),T=te("Specified playback ID: {playbackId}",r).format({playbackId:m}),y=new z(v,u,s!=null?s:!0,T);return y.errorCategory=e,y.muxCode=ne.NETWORK_TOKEN_MISSING,y.data=i,y}if(l===412){let v=te("This playback-id may belong to a live stream that is not currently active or an asset that is not ready.",r),T=te("Specified playback ID: {playbackId}",r).format({playbackId:m}),y=new z(v,u,s!=null?s:!0,T);return y.errorCategory=e,y.muxCode=ne.NETWORK_NOT_READY,y.streamType=t.streamType===we.LIVE?"live":t.streamType===we.ON_DEMAND?"on-demand":"unknown",y.data=i,y}if(l===404){let v=te("This URL or playback-id does not exist. You may have used an Asset ID or an ID from a different resource.",r),T=te("Specified playback ID: {playbackId}",r).format({playbackId:m}),y=new z(v,u,s!=null?s:!0,T);return y.errorCategory=e,y.muxCode=ne.NETWORK_NOT_FOUND,y.data=i,y}if(l===400){let v=te("The URL or playback-id was invalid. You may have used an invalid value as a playback-id."),T=te("Specified playback ID: {playbackId}",r).format({playbackId:m}),y=new z(v,u,s!=null?s:!0,T);return y.errorCategory=e,y.muxCode=ne.NETWORK_INVALID_URL,y.data=i,y}let g=new z("",u,s!=null?s:!0);return g.errorCategory=e,g.muxCode=ne.NETWORK_UNKNOWN_ERROR,g.data=i,g},Tb=_e.DefaultConfig.capLevelController,ZC={"720p":921600,"1080p":2073600,"1440p":4194304,"2160p":8294400};function JC(i){let e=i.toLowerCase().trim();return ZC[e]}var bg=class el extends Tb{constructor(e){super(e)}static setMaxAutoResolution(e,t){t?el.maxAutoResolution.set(e,t):el.maxAutoResolution.delete(e)}getMaxAutoResolution(){var e;let t=this.hls;return(e=el.maxAutoResolution.get(t))!=null?e:void 0}get levels(){var e;return(e=this.hls.levels)!=null?e:[]}getValidLevels(e){return this.levels.filter((t,s)=>this.isLevelAllowed(t)&&s<=e)}getMaxLevelCapped(e){let t=this.getValidLevels(e),s=this.getMaxAutoResolution();if(!s)return super.getMaxLevel(e);let r=JC(s);if(!r)return super.getMaxLevel(e);let n=t.filter(l=>l.width*l.height<=r),a=n.findIndex(l=>l.width*l.height===r);if(a!==-1){let l=n[a];return t.findIndex(d=>d===l)}if(n.length===0)return 0;let o=n[n.length-1];return t.findIndex(l=>l===o)}getMaxLevel(e){if(this.getMaxAutoResolution()!==void 0)return this.getMaxLevelCapped(e);let t=super.getMaxLevel(e),s=this.getValidLevels(e);if(!s[t])return t;let r=Math.min(s[t].width,s[t].height),n=el.minMaxResolution;return r>=n?t:Tb.getMaxLevelByMediaSize(s,n*(16/9),n)}};bg.minMaxResolution=720,bg.maxAutoResolution=new WeakMap;var ew=bg,_g=ew,tw="com.apple.fps.1_0",iw="application/vnd.apple.mpegurl",sw=({mediaEl:i,getAppCertificate:e,getLicenseKey:t,saveAndDispatchError:s,drmTypeCb:r})=>{if(!window.WebKitMediaKeys||!("onwebkitneedkey"in i)){console.error("No WebKitMediaKeys. FairPlay may not be supported");let h=te("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser."),f=new z(h,z.MEDIA_ERR_ENCRYPTED,!0);return f.errorCategory=Ue.DRM,f.muxCode=ne.ENCRYPTED_CDM_ERROR,s(i,f),()=>{}}let n=i,a=e(),o=null,l=h=>{(async()=>{try{n.webkitKeys||d();let f=await a;if(h.initData===null||f==null)return;let m=rw(h.initData,f);u(m)}catch(f){console.error("Could not start encrypted playback due to exception",f),s(n,f)}})()},d=()=>{try{let h=new WebKitMediaKeys(tw);n.webkitSetMediaKeys(h),r()}catch{let h="Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser.",f=new z(h,z.MEDIA_ERR_ENCRYPTED,!0);throw f.errorCategory=Ue.DRM,f.muxCode=ne.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM,f}},u=h=>{let f=n.webkitKeys.createSession(iw,h),m=async v=>{try{let T=v.message,y=await t(T);f.update(y)}catch(T){console.error("Error on FairPlay session message",T),s(i,T)}},p=v=>{let T=v.target.error;if(!T)return;console.error(`Internal Webkit Key Session Error - sysCode: ${T.systemCode} code: ${T.code}`);let y=te("The DRM Content Decryption Module system had an internal failure. Try reloading the page, updating your browser, or playing in another browser."),b=new z(y,z.MEDIA_ERR_ENCRYPTED,!0);b.errorCategory=Ue.DRM,b.muxCode=ne.ENCRYPTED_CDM_ERROR,s(i,b)},g=()=>{f.removeEventListener("webkitkeymessage",m),f.removeEventListener("webkitkeyerror",p),i.removeEventListener("teardown",g),"webkitCurrentPlaybackTargetIsWireless"in i&&i.removeEventListener("webkitcurrentplaybacktargetiswirelesschanged",g),o=null;try{f.close()}catch{}};"webkitCurrentPlaybackTargetIsWireless"in i&&i.addEventListener("webkitcurrentplaybacktargetiswirelesschanged",g,{once:!0}),f.addEventListener("webkitkeymessage",m),f.addEventListener("webkitkeyerror",p),i.addEventListener("teardown",g),o=g},c=()=>{i.removeEventListener("webkitneedkey",l),i.removeEventListener("teardown",c),o==null||o();try{n.webkitSetMediaKeys(null)}catch{}};return i.addEventListener("webkitneedkey",l),i.addEventListener("teardown",c,{once:!0}),c},rw=(i,e)=>{let t=aw(nw(i)),s=new Uint8Array(i),r=new Uint8Array(t),n=new Uint8Array(e),a=s.byteLength+4+n.byteLength+4+r.byteLength,o=new Uint8Array(a),l=0,d=c=>{o.set(c,l),l+=c.byteLength},u=c=>{let h=new DataView(o.buffer),f=c.byteLength;h.setUint32(l,f,!0),l+=4,d(c)};return d(s),u(r),u(n),o},nw=i=>new TextDecoder("utf-16le").decode(i).replace("skd://","").slice(1);function aw(i){let e=new ArrayBuffer(i.length*2),t=new DataView(e);for(let s=0;s<i.length;s++)t.setUint16(s*2,i.charCodeAt(s),!0);return e}var ow=({mediaEl:i,getAppCertificate:e,getLicenseKey:t,saveAndDispatchError:s,drmTypeCb:r,fallbackToWebkitFairplay:n})=>{let a=null,o=async c=>{try{let h=c.initDataType;if(h!=="skd"){console.error(`Received unexpected initialization data type "${h}"`);return}i.mediaKeys||await l(h);let f=c.initData;if(f==null){console.error(`Could not start encrypted playback due to missing initData in ${c.type} event`);return}await d(h,f)}catch(h){s(i,h);return}},l=async c=>{let h=await navigator.requestMediaKeySystemAccess("com.apple.fps",[{initDataTypes:[c],videoCapabilities:[{contentType:"application/vnd.apple.mpegurl",robustness:""}],distinctiveIdentifier:"not-allowed",persistentState:"not-allowed",sessionTypes:["temporary"]}]).then(m=>(r(),m)).catch(()=>{let m=te("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser."),p=new z(m,z.MEDIA_ERR_ENCRYPTED,!0);p.errorCategory=Ue.DRM,p.muxCode=ne.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM,s(i,p)});if(!h)return;let f=await h.createMediaKeys();try{let m=await e();await f.setServerCertificate(m).catch(()=>{let p=te("Your server certificate failed when attempting to set it. This may be an issue with a no longer valid certificate."),g=new z(p,z.MEDIA_ERR_ENCRYPTED,!0);return g.errorCategory=Ue.DRM,g.muxCode=ne.ENCRYPTED_UPDATE_SERVER_CERT_FAILED,Promise.reject(g)})}catch(m){s(i,m);return}await i.setMediaKeys(f)},d=async(c,h)=>{let f=i.mediaKeys.createSession(),m=async v=>{let T=v.message,y=await t(T);try{await f.update(y)}catch{let b=te("Failed to update DRM license. This may be an issue with the player or your protected content."),A=new z(b,z.MEDIA_ERR_ENCRYPTED,!0);A.errorCategory=Ue.DRM,A.muxCode=ne.ENCRYPTED_UPDATE_LICENSE_FAILED,s(i,A)}},p=()=>{let v=T=>{let y;if(T==="internal-error"){let b=te("The DRM Content Decryption Module system had an internal failure. Try reloading the page, updating your browser, or playing in another browser.");y=new z(b,z.MEDIA_ERR_ENCRYPTED,!0),y.errorCategory=Ue.DRM,y.muxCode=ne.ENCRYPTED_CDM_ERROR}else if(T==="output-restricted"||T==="output-downscaled"){let b=te("DRM playback is being attempted in an environment that is not sufficiently secure. User may see black screen.");y=new z(b,z.MEDIA_ERR_ENCRYPTED,!1),y.errorCategory=Ue.DRM,y.muxCode=ne.ENCRYPTED_OUTPUT_RESTRICTED}y&&s(i,y)};f.keyStatuses.forEach(T=>v(T))};f.addEventListener("keystatuseschange",p),f.addEventListener("message",m);let g=async()=>{f.removeEventListener("keystatuseschange",p),f.removeEventListener("message",m),"webkitCurrentPlaybackTargetIsWireless"in i&&i.removeEventListener("webkitcurrentplaybacktargetiswirelesschanged",g),i.removeEventListener("teardown",g),await f.close().catch(v=>{console.warn("There was an error when closing EME session",v)}),a=null};"webkitCurrentPlaybackTargetIsWireless"in i&&i.addEventListener("webkitcurrentplaybacktargetiswirelesschanged",g,{once:!0}),i.addEventListener("teardown",g,{once:!0}),a=g,await f.generateRequest(c,h).catch(async v=>{if(v.name==="NotSupportedError"&&"webkitCurrentPlaybackTargetIsWireless"in i&&i.webkitCurrentPlaybackTargetIsWireless)console.warn("Failed to generate a DRM license request. Attempting to fallback to Webkit DRM"),n==null||n();else{let T=te("Failed to generate a DRM license request. This may be an issue with the player or your protected content."),y=new z(T,z.MEDIA_ERR_ENCRYPTED,!0);return y.errorCategory=Ue.DRM,y.muxCode=ne.ENCRYPTED_GENERATE_REQUEST_FAILED,console.error("Failed to generate license request",v),Promise.reject(y)}})},u=async()=>{i.removeEventListener("encrypted",o),i.removeEventListener("teardown",u),a&&await a(),await i.setMediaKeys(null).catch(()=>{})};return i.addEventListener("encrypted",o),i.addEventListener("teardown",u,{once:!0}),u},Fu={FAIRPLAY:"fairplay",PLAYREADY:"playready",WIDEVINE:"widevine"},lw=i=>{if(i.includes("fps"))return Fu.FAIRPLAY;if(i.includes("playready"))return Fu.PLAYREADY;if(i.includes("widevine"))return Fu.WIDEVINE},dw=(i,e)=>{let t=MC(i);if(!t)return Promise.reject(new Error("No media playlist URL found in multivariant playlist"));if(Eg(t)&&!e)return Promise.reject(new Error("masterPlaylistUrl is required to resolve relative media playlist URL"));let s;try{s=Ig(t,e)}catch(r){return Promise.reject(r)}return fetch(s).then(r=>r.status!==200?Promise.reject(r):r.text())},uw=i=>{let e=i.split(`
53
+ `),d=[],u=e?wk(e.baseTime,e.timescale):0,c="00:00.000",h=0,f=0,m,p=!0;o.oncue=function(g){let v=t[s],b=t.ccOffset,y=(h-u)/9e4;if(v!=null&&v.new&&(f!==void 0?b=t.ccOffset=v.start:eC(t,s,y)),y){if(!e){m=new Error("Missing initPTS for VTT MPEGTS");return}b=y-t.presentationOffset}let T=g.endTime-g.startTime,A=ai((g.startTime+b-f)*9e4,r*9e4)/9e4;g.startTime=Math.max(A,0),g.endTime=Math.max(A+T,0);let R=g.text.trim();g.text=decodeURIComponent(encodeURIComponent(R)),g.id||(g.id=hg(g.startTime,g.endTime,R)),g.endTime>0&&d.push(g)},o.onparsingerror=function(g){m=g},o.onflush=function(){if(m){a(m);return}n(d)},l.forEach(g=>{if(p)if(Sm(g,"X-TIMESTAMP-MAP=")){p=!1,g.slice(16).split(",").forEach(v=>{Sm(v,"LOCAL:")?c=v.slice(6):Sm(v,"MPEGTS:")&&(h=parseInt(v.slice(7)))});try{f=JD(c)/1e3}catch(v){m=v}return}else g===""&&(p=!1);o.parse(g+`
54
+ `)}),o.flush()}var Im="stpp.ttml.im1t",fT=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,mT=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,iC={left:"start",center:"center",right:"end",start:"start",end:"end"};function Gy(i,e,t,s){let r=Te(new Uint8Array(i),["mdat"]);if(r.length===0){s(new Error("Could not parse IMSC1 mdat"));return}let n=r.map(o=>li(o)),a=Ck(e.baseTime,1,e.timescale);try{n.forEach(o=>t(sC(o,a)))}catch(o){s(o)}}function sC(i,e){let r=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");let n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(n).reduce((c,h)=>(c[h]=r.getAttribute(`ttp:${h}`)||n[h],c),{}),o=r.getAttribute("xml:space")!=="preserve",l=Ky(Lm(r,"styling","style")),d=Ky(Lm(r,"layout","region")),u=Lm(r,"body","[begin]");return[].map.call(u,c=>{let h=pT(c,o);if(!h||!c.hasAttribute("begin"))return null;let f=xm(c.getAttribute("begin"),a),m=xm(c.getAttribute("dur"),a),p=xm(c.getAttribute("end"),a);if(f===null)throw Vy(c);if(p===null){if(m===null)throw Vy(c);p=f+m}let g=new cg(f-e,p-e,h);g.id=hg(g.startTime,g.endTime,g.text);let v=d[c.getAttribute("region")],b=l[c.getAttribute("style")],y=rC(v,b,l),{textAlign:T}=y;if(T){let A=iC[T];A&&(g.lineAlign=A),g.align=T}return $e(g,y),g}).filter(c=>c!==null)}function Lm(i,e,t){let s=i.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(t)):[]}function Ky(i){return i.reduce((e,t)=>{let s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function pT(i,e){return[].slice.call(i.childNodes).reduce((t,s,r)=>{var n;return s.nodeName==="br"&&r?t+`
55
+ `:(n=s.childNodes)!=null&&n.length?pT(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function rC(i,e,t){let s="http://www.w3.org/ns/ttml#styling",r=null,n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=i!=null&&i.hasAttribute("style")?i.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(r=t[a]),n.reduce((o,l)=>{let d=Rm(e,s,l)||Rm(i,s,l)||Rm(r,s,l);return d&&(o[l]=d),o},{})}function Rm(i,e,t){return i&&i.hasAttributeNS(e,t)?i.getAttributeNS(e,t):null}function Vy(i){return new Error(`Could not parse ttml timestamp ${i}`)}function xm(i,e){if(!i)return null;let t=uT(i);return t===null&&(fT.test(i)?t=nC(i,e):mT.test(i)&&(t=aC(i,e))),t}function nC(i,e){let t=fT.exec(i),s=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+s/e.frameRate}function aC(i,e){let t=mT.exec(i),s=Number(t[1]);switch(t[2]){case"h":return s*3600;case"m":return s*60;case"ms":return s*1e3;case"f":return s/e.frameRate;case"t":return s/e.tickRate}return s}var Jn=class{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,s){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},Bp=class{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=qy(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(E.FRAG_LOADING,this.onFragLoading,this),e.on(E.FRAG_LOADED,this.onFragLoaded,this),e.on(E.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(E.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(E.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){let{hls:e}=this;e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(E.FRAG_LOADING,this.onFragLoading,this),e.off(E.FRAG_LOADED,this.onFragLoaded,this),e.off(E.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(E.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(E.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(E.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){let e=new Jn(this,"textTrack1"),t=new Jn(this,"textTrack2"),s=new Jn(this,"textTrack3"),r=new Jn(this,"textTrack4");this.cea608Parser1=new wu(1,e,t),this.cea608Parser2=new wu(3,s,r)}addCues(e,t,s,r,n){let a=!1;for(let o=n.length;o--;){let l=n[o],d=oC(l[0],l[1],t,s);if(d>=0&&(l[0]=Math.min(l[0],t),l[1]=Math.max(l[1],s),a=!0,d/(s-t)>.5))return}if(a||n.push([t,s]),this.config.renderTextTracksNatively){let o=this.captionsTracks[e];this.Cues.newCue(o,t,s,r)}else{let o=this.Cues.newCue(null,t,s,r);this.hls.trigger(E.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:s,initPTS:r,timescale:n,trackId:a}){let{unparsedVttFrags:o}=this;s===J.MAIN&&(this.initPTS[t.cc]={baseTime:r,timescale:n,trackId:a}),o.length&&(this.unparsedVttFrags=[],o.forEach(l=>{this.initPTS[l.frag.cc]?this.onFragLoaded(E.FRAG_LOADED,l):this.hls.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:l.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){let{media:s}=this;if(s)for(let r=0;r<s.textTracks.length;r++){let n=s.textTracks[r];if(Wy(n,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return n}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;let{captionsProperties:t,captionsTracks:s,media:r}=this,{label:n,languageCode:a}=t[e],o=this.getExistingTrack(n,a);if(o)s[e]=o,Zn(s[e]),aT(s[e],r);else{let l=this.createTextTrack("captions",n,a);l&&(l[e]=!0,s[e]=l)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let s=t.label,r={_id:e,label:s,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=r,this.hls.trigger(E.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[r]})}createTextTrack(e,t,s){let r=this.media;if(r)return r.addTextTrack(e,t,s)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){let s=!!t.transferMedia;if(this.media=null,s)return;let{captionsTracks:r}=this;Object.keys(r).forEach(n=>{Zn(r[n]),delete r[n]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=qy(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){let{media:e}=this;if(!e)return;let t=e.textTracks;if(t)for(let s=0;s<t.length;s++)Zn(t[s])}onSubtitleTracksUpdated(e,t){let s=t.subtitleTracks||[],r=s.some(n=>n.textCodec===Im);if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(jb(this.tracks,s)){this.tracks=s;return}if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){let a=this.media,o=a?ou(a.textTracks):null;if(this.tracks.forEach((l,d)=>{let u;if(o){let c=null;for(let h=0;h<o.length;h++)if(o[h]&&Wy(o[h],l)){c=o[h],o[h]=null;break}c&&(u=c)}if(u)Zn(u);else{let c=gT(l);u=this.createTextTrack(c,l.name,l.lang),u&&(u.mode="disabled")}u&&this.textTracks.push(u)}),o!=null&&o.length){let l=o.filter(d=>d!==null).map(d=>d.label);l.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${l.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){let a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(E.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(s=>{let r=/(?:CC|SERVICE)([1-4])/.exec(s.instreamId);if(!r)return;let n=`textTrack${r[1]}`,a=this.captionsProperties[n];a&&(a.label=s.name,s.lang&&(a.languageCode=s.lang),a.media=s)})}closedCaptionsForLevel(e){let t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===J.MAIN){var s,r;let{cea608Parser1:n,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:d}=t.frag,u=(s=(r=t.part)==null?void 0:r.index)!=null?s:-1;n&&a&&(d!==o+1||d===o&&u!==this.lastPartIndex+1||l!==this.lastCc)&&(n.reset(),a.reset()),this.lastCc=l,this.lastSn=d,this.lastPartIndex=u}}onFragLoaded(e,t){let{frag:s,payload:r}=t;if(s.type===J.SUBTITLE)if(r.byteLength){let n=s.decryptdata,a="stats"in t;if(n==null||!n.encrypted||a){let o=this.tracks[s.level],l=this.vttCCs;l[s.cc]||(l[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),o&&o.textCodec===Im?this._parseIMSC1(s,r):this._parseVTTs(t)}}else this.hls.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){let s=this.hls;Gy(t,this.initPTS[e.cc],r=>{this._appendCues(r,e.level),s.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},r=>{s.logger.log(`Failed to parse IMSC1: ${r}`),s.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:r})})}_parseVTTs(e){var t;let{frag:s,payload:r}=e,{initPTS:n,unparsedVttFrags:a}=this,o=n.length-1;if(!n[s.cc]&&o===-1){a.push(e);return}let l=this.hls,d=(t=s.initSegment)!=null&&t.data?pi(s.initSegment.data,new Uint8Array(r)).buffer:r;tC(d,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,u=>{this._appendCues(u,s.level),l.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})},u=>{let c=u.message==="Missing initPTS for VTT MPEGTS";c?a.push(e):this._fallbackToIMSC1(s,r),l.logger.log(`Failed to parse VTT cue: ${u}`),!(c&&o>s.cc)&&l.trigger(E.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:u})})}_fallbackToIMSC1(e,t){let s=this.tracks[e.level];s.textCodec||Gy(t,this.initPTS[e.cc],()=>{s.textCodec=Im,this._parseIMSC1(e,t)},()=>{s.textCodec="wvtt"})}_appendCues(e,t){let s=this.hls;if(this.config.renderTextTracksNatively){let r=this.textTracks[t];if(!r||r.mode==="disabled")return;e.forEach(n=>oT(r,n))}else{let r=this.tracks[t];if(!r)return;let n=r.default?"default":"subtitles"+t;s.trigger(E.CUES_PARSED,{type:"subtitles",cues:e,track:n})}}onFragDecrypted(e,t){let{frag:s}=t;s.type===J.SUBTITLE&&this.onFragLoaded(E.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;let{frag:s,samples:r}=t;if(!(s.type===J.MAIN&&this.closedCaptionsForLevel(s)==="NONE"))for(let n=0;n<r.length;n++){let a=r[n].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();let o=this.extractCea608Data(a);this.cea608Parser1.addData(r[n].pts,o[0]),this.cea608Parser2.addData(r[n].pts,o[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:s,endOffsetSubtitles:r,type:n}){let{media:a}=this;if(!(!a||a.currentTime<s)){if(!n||n==="video"){let{captionsTracks:o}=this;Object.keys(o).forEach(l=>Ap(o[l],t,s))}if(this.config.renderTextTracksNatively&&t===0&&r!==void 0){let{textTracks:o}=this;Object.keys(o).forEach(l=>Ap(o[l],t,r))}}}extractCea608Data(e){let t=[[],[]],s=e[0]&31,r=2;for(let n=0;n<s;n++){let a=e[r++],o=127&e[r++],l=127&e[r++];if(o===0&&l===0)continue;if((4&a)!==0){let u=3&a;(u===0||u===1)&&(t[u].push(o),t[u].push(l))}}return t}};function gT(i){return i.characteristics&&/transcribes-spoken-dialog/gi.test(i.characteristics)&&/describes-music-and-sound/gi.test(i.characteristics)?"captions":"subtitles"}function Wy(i,e){return!!i&&i.kind===gT(e)&&hp(e,i)}function oC(i,e,t,s){return Math.min(e,s)-Math.max(i,t)}function qy(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var lC=/\s/,dC={newCue(i,e,t,s){let r=[],n,a,o,l,d,u=self.VTTCue||self.TextTrackCue;for(let h=0;h<s.rows.length;h++)if(n=s.rows[h],o=!0,l=0,d="",!n.isEmpty()){var c;for(let p=0;p<n.chars.length;p++)lC.test(n.chars[p].uchar)&&o?l++:(d+=n.chars[p].uchar,o=!1);n.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;let f=hT(d.trim()),m=hg(e,t,f);i!=null&&(c=i.cues)!=null&&c.getCueById(m)||(a=new u(e,t,f),a.id=m,a.line=h+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),r.push(a))}return i&&r.length&&(r.sort((h,f)=>h.line==="auto"||f.line==="auto"?0:h.line>8&&f.line>8?f.line-h.line:h.line-f.line),r.forEach(h=>oT(i,h))),r}};function uC(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var cC=/(\d+)-(\d+)\/(\d+)/,Mu=class{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||pC,this.controller=new self.AbortController,this.stats=new Fo}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,s){let r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();let n=hC(e,this.controller.signal),a=e.responseType==="arraybuffer",o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:d}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=s,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=l&&Q(l)?l:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response))},t.timeout),(Yo(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(c=>{var h;this.response=this.loader=c;let f=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response))},d-(f-r.loading.start)),!c.ok){let{status:p,statusText:g}=c;throw new $p(g||"fetch, bad network response",p,c)}r.loading.first=f,r.total=mC(c.headers)||r.total;let m=(h=this.callbacks)==null?void 0:h.onProgress;return m&&Q(t.highWaterMark)?this.loadProgressively(c,r,e,t.highWaterMark,m):a?c.arrayBuffer():e.responseType==="json"?c.json():c.text()}).then(c=>{var h,f;let m=this.response;if(!m)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);let p=c[o];p&&(r.loaded=r.total=p);let g={url:m.url,data:c,code:m.status},v=(h=this.callbacks)==null?void 0:h.onProgress;v&&!Q(t.highWaterMark)&&v(r,e,c,m),(f=this.callbacks)==null||f.onSuccess(g,r,e,m)}).catch(c=>{var h;if(self.clearTimeout(this.requestTimeout),r.aborted)return;let f=c&&c.code||0,m=c?c.message:null;(h=this.callbacks)==null||h.onError({code:f,text:m},e,c?c.details:null,r)})}getCacheAge(){let e=null;if(this.response){let t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,s,r=0,n){let a=new _u,o=e.body.getReader(),l=()=>o.read().then(d=>{if(d.done)return a.dataLength&&n(t,s,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));let u=d.value,c=u.length;return t.loaded+=c,c<r||a.dataLength?(a.push(u),a.dataLength>=r&&n(t,s,a.flush().buffer,e)):n(t,s,u.buffer,e),l()}).catch(()=>Promise.reject());return l()}};function hC(i,e){let t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers($e({},i.headers))};return i.rangeEnd&&t.headers.set("Range","bytes="+i.rangeStart+"-"+String(i.rangeEnd-1)),t}function fC(i){let e=cC.exec(i);if(e)return parseInt(e[2])-parseInt(e[1])+1}function mC(i){let e=i.get("Content-Range");if(e){let s=fC(e);if(Q(s))return s}let t=i.get("Content-Length");if(t)return parseInt(t)}function pC(i,e){return new self.Request(i.url,e)}var $p=class extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}},gC=/^age:\s*[\d.]+\s*$/im,Pu=class{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new Fo,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){let e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}loadInternal(){let{config:e,context:t}=this;if(!e||!t)return;let s=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;let n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!(this.loader!==s||this.stats.aborted))return n(s,t.url)}).catch(a=>{if(!(this.loader!==s||this.stats.aborted))return s.open("GET",t.url,!0),n(s,t.url)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:s.status,text:a.message},t,s,r)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);let r=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=s.loadPolicy;if(r)for(let o in r)e.setRequestHeader(o,r[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),s.timeout=n&&Q(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:s}=this;if(!e||!t)return;let r=t.readyState,n=this.config;if(!s.aborted&&r>=2&&(s.loading.first===0&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),r===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let d=t.status,u=t.responseType==="text"?t.responseText:null;if(d>=200&&d<300){let m=u!=null?u:t.response;if(m!=null){var a,o;s.loading.end=Math.max(self.performance.now(),s.loading.first);let p=t.responseType==="arraybuffer"?m.byteLength:m.length;s.loaded=s.total=p,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first);let g=(a=this.callbacks)==null?void 0:a.onProgress;g&&g(s,e,m,t);let v={url:t.responseURL,data:m,code:d};(o=this.callbacks)==null||o.onSuccess(v,s,e,t);return}}let c=n.loadPolicy.errorRetry,h=s.retry,f={url:e.url,data:void 0,code:d};if(gu(c,h,!1,f))this.retry(c);else{var l;Be.error(`${d} while loading ${e.url}`),(l=this.callbacks)==null||l.onError({code:d,text:t.statusText},e,t,s)}}}loadtimeout(){if(!this.config)return;let e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(gu(e,t,!0))this.retry(e);else{var s;Be.warn(`timeout while loading ${(s=this.context)==null?void 0:s.url}`);let r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.loader))}}retry(e){let{context:t,stats:s}=this;this.retryDelay=eg(e,s.retry),s.retry++,Be.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&gC.test(this.loader.getAllResponseHeaders())){let t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}},vC={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},EC=Fe(Fe({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:Pu,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Fm,bufferController:gp,capLevelController:Qo,errorController:$m,fpsController:_p,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:bb,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:vC},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},yC()),{},{subtitleStreamController:Dp,subtitleTrackController:Sp,timelineController:Bp,audioStreamController:cp,audioTrackController:fp,emeController:xu,cmcdController:bp,contentSteeringController:Tp,interstitialsController:kp});function yC(){return{cueHandler:dC,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function bC(i,e,t){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');let s=Hp(i),r=["manifest","level","frag"],n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return r.forEach(a=>{let o=`${a==="level"?"playlist":a}LoadPolicy`,l=e[o]===void 0,d=[];n.forEach(u=>{let c=`${a}Loading${u}`,h=e[c];if(h!==void 0&&l){d.push(c);let f=s[o].default;switch(e[o]={default:f},u){case"TimeOut":f.maxLoadTimeMs=h,f.maxTimeToFirstByteMs=h;break;case"MaxRetry":f.errorRetry.maxNumRetry=h,f.timeoutRetry.maxNumRetry=h;break;case"RetryDelay":f.errorRetry.retryDelayMs=h,f.timeoutRetry.retryDelayMs=h;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=h,f.timeoutRetry.maxRetryDelayMs=h;break}}}),d.length&&t.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${o}": ${qe(e[o])}`)}),Fe(Fe({},s),e)}function Hp(i){return i&&typeof i=="object"?Array.isArray(i)?i.map(Hp):Object.keys(i).reduce((e,t)=>(e[t]=Hp(i[t]),e),{}):i}function TC(i,e){let t=i.loader;t!==Mu&&t!==Pu?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),i.progressive=!1):uC()&&(i.loader=Mu,i.progressive=!0,i.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}var lu=2,_C=.1,AC=.05,SC=100,Gp=class extends vu{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var s;(s=this.media)!=null&&s.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var s;this.ended=((s=this.media)==null?void 0:s.currentTime)||1,this.hls.trigger(E.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){let{hls:e}=this;e&&(e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(SC),this.mediaSource=t.mediaSource;let s=this.media=t.media;Ht(s,"playing",this.onMediaPlaying),Ht(s,"waiting",this.onMediaWaiting),Ht(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();let{media:s}=this;s&&(zt(s,"playing",this.onMediaPlaying),zt(s,"waiting",this.onMediaWaiting),zt(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;let t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var s,r;let n=(s=this.hls)==null?void 0:s.config;if(!n)return;let a=this.media;if(!a)return;let{seeking:o}=a,l=this.seeking&&!o,d=!this.seeking&&o,u=a.paused&&!o||a.ended||a.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,n.nudgeOnVideoHole&&!u&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(d||l){l&&this.stallResolved(e);return}if(u){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(E.MEDIA_ENDED,{stalled:!1}));return}if(!Ee.getBuffered(a).length){this.nudgeRetry=0;return}let c=Ee.bufferInfo(a,e,0),h=c.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){let R=Yy(this.hls.inFlightFragments,e),I=c.len>lu,x=!h||R||h-e>lu&&!f.getPartialFragment(e);if(I||x)return;this.moved=!1}let m=(r=this.hls)==null?void 0:r.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(c.len>0)&&!h)return;let I=Math.max(h,c.start||0)-e,D=!!(m!=null&&m.live)?m.targetduration*2:lu,S=eu(e,f);if(I>0&&(I<=D||S)){a.paused||this._trySkipBufferHole(S);return}}let p=n.detectStallWithCurrentTimeMs,g=self.performance.now(),v=this.waiting,b=this.stalled;if(b===null)if(v>0&&g-v<p)b=this.stalled=v;else{this.stalled=g;return}let y=g-b;if(!o&&(y>=p||v)&&this.hls){var T;if(((T=this.mediaSource)==null?void 0:T.readyState)==="ended"&&!(m!=null&&m.live)&&Math.abs(e-((m==null?void 0:m.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(E.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(c),!this.media||!this.hls)return}let A=Ee.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(A,y,e)}stallResolved(e){let t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){let s=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(E.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;let r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(s=this.buffered.audio)!=null&&s.length&&r&&r.length>1&&e>r.end(0)){let n=Ee.bufferedInfo(Ee.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){let a=Ee.timeRangesToArray(r),o=Ee.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&o<a.length-1){let l=Ee.bufferedInfo(a,e,0).bufferedIndex,d=a[o].end,u=a[o+1].start;if((l===-1||l>o)&&u-d<1&&e-d<2){let c=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${d} -> ${u} buffered index: ${l}`);this.warn(c.message),this.media.currentTime+=1e-6;let h=eu(e,this.fragmentTracker);h&&"fragment"in h?h=h.fragment:h||(h=void 0);let f=Ee.bufferInfo(this.media,e,0);this.hls.trigger(E.ERROR,{type:se.MEDIA_ERROR,details:M.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:c,reason:c.message,frag:h,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(e,t,s){var r,n;let{fragmentTracker:a,media:o}=this,l=(r=this.hls)==null?void 0:r.config;if(!o||!a||!l)return;let d=(n=this.hls)==null?void 0:n.latestLevelDetails,u=eu(s,a);if((u||d!=null&&d.live&&s<d.fragmentStart)&&(this._trySkipBufferHole(u)||!this.media))return;let c=e.buffered,h=this.adjacentTraversal(e,s);(c&&c.length>1&&e.len>l.maxBufferHole||e.nextStart&&(e.nextStart-s<l.maxBufferHole||h))&&(t>l.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){let s=this.fragmentTracker,r=e.nextStart;if(s&&r){let n=s.getFragAtPos(t,J.MAIN),a=s.getFragAtPos(r,J.MAIN);if(n&&a)return a.sn-n.sn<2}return!1}_reportStall(e){let{hls:t,media:s,stallReported:r,stalled:n}=this;if(!r&&n!==null&&s&&t){this.stallReported=!0;let a=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${qe(e)})`);this.warn(a.message),t.trigger(E.ERROR,{type:se.MEDIA_ERROR,details:M.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:n}})}}_trySkipBufferHole(e){var t;let{fragmentTracker:s,media:r}=this,n=(t=this.hls)==null?void 0:t.config;if(!r||!s||!n)return 0;let a=r.currentTime,o=Ee.bufferInfo(r,a,0),l=a<o.start?o.start:o.nextStart;if(l&&this.hls){let u=o.len<=n.maxBufferHole,c=o.len>0&&o.len<1&&r.readyState<3,h=l-a;if(h>0&&(u||c)){if(h>n.maxBufferHole){let m=!1;if(a===0){let p=s.getAppendedFrag(0,J.MAIN);p&&l<p.end&&(m=!0)}if(!m&&e){var d;if(!((d=this.hls.loadLevelObj)!=null&&d.details)||Yy(this.hls.inFlightFragments,l))return 0;let g=!1,v=e.end;for(;v<l;){let b=eu(v,s);if(b)v+=b.duration;else{g=!0;break}}if(g)return 0}}let f=Math.max(l+AC,a+_C);if(this.warn(`skipping hole, adjusting currentTime from ${a} to ${f}`),this.moved=!0,r.currentTime=f,!(e!=null&&e.gap)){let m=new Error(`fragment loaded with buffer holes, seeking from ${a} to ${f}`),p={type:se.MEDIA_ERROR,details:M.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:m,reason:m.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?p.part=e:p.frag=e),this.hls.trigger(E.ERROR,p)}return f}}return 0}_tryNudgeBuffer(e){let{hls:t,media:s,nudgeRetry:r}=this,n=t==null?void 0:t.config;if(!s||!n)return 0;let a=s.currentTime;if(this.nudgeRetry++,r<n.nudgeMaxRetry){let o=a+(r+1)*n.nudgeOffset,l=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(l.message),s.currentTime=o,t.trigger(E.ERROR,{type:se.MEDIA_ERROR,details:M.BUFFER_NUDGE_ON_STALL,error:l,fatal:!1,buffer:e.len,bufferInfo:e})}else{let o=new Error(`Playhead still not moving while enough data buffered @${a} after ${n.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(E.ERROR,{type:se.MEDIA_ERROR,details:M.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}};function Yy(i,e){let t=jy(i.main);if(t&&t.start<=e)return t;let s=jy(i.audio);return s&&s.start<=e?s:null}function jy(i){if(!i)return null;switch(i.state){case O.IDLE:case O.STOPPED:case O.ENDED:case O.ERROR:return null}return i.frag}function eu(i,e){return e.getAppendedFrag(i,J.MAIN)||e.getPartialFragment(i)}var IC=.25;function Kp(){if(typeof self!="undefined")return self.VTTCue||self.TextTrackCue}function km(i,e,t,s,r){let n=new i(e,t,"");try{n.value=s,r&&(n.type=r)}catch{n=new i(e,t,qe(r?Fe({type:r},s):s))}return n}var tu=(()=>{let i=Kp();try{i&&new i(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})(),Vp=class{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(E.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){let{hls:e}=this;e&&(e.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var s;this.media=t.media,((s=t.overrides)==null?void 0:s.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;let t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&Zn(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){let t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){let s=e[t];if(s.kind==="metadata"&&s.label==="id3")return aT(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;let{enableEmsgMetadataCues:s,enableID3MetadataCues:r}=this.hls.config;if(!s&&!r)return;let{samples:n}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));let a=Kp();if(a)for(let o=0;o<n.length;o++){let l=n[o].type;if(l===oi.emsg&&!s||!r)continue;let d=Ub(n[o].data),u=n[o].pts,c=u+n[o].duration;c>tu&&(c=tu),c-u<=0&&(c=u+IC);for(let f=0;f<d.length;f++){let m=d[f];if(!Fb(m)){this.updateId3CueEnds(u,l);let p=km(a,u,c,m,l);p&&this.id3Track.addCue(p)}}}}updateId3CueEnds(e,t){var s;let r=(s=this.id3Track)==null?void 0:s.cues;if(r)for(let n=r.length;n--;){let a=r[n];a.type===t&&a.startTime<e&&a.endTime===tu&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:r}){let{id3Track:n,hls:a}=this;if(!a)return;let{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=a;if(n&&(o||l)){let d;r==="audio"?d=u=>u.type===oi.audioId3&&l:r==="video"?d=u=>u.type===oi.emsg&&o:d=u=>u.type===oi.audioId3&&l||u.type===oi.emsg&&o,Ap(n,t,s,d)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;let{assetPlayerId:s,timelineOffset:r,enableDateRangeMetadataCues:n,interstitialsController:a}=this.hls.config;if(!n)return;let o=Kp();if(s&&r&&!a){let{fragmentStart:p,fragmentEnd:g}=e,v=this.assetCue;v?(v.startTime=p,v.endTime=g):o&&(v=this.assetCue=km(o,p,g,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),v&&(v.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(v),v.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;let{id3Track:l}=this,{dateRanges:d}=e,u=Object.keys(d),c=this.dateRangeCuesAppended;if(l&&t){var h;if((h=l.cues)!=null&&h.length){let p=Object.keys(c).filter(g=>!u.includes(g));for(let g=p.length;g--;){var f;let v=p[g],b=(f=c[v])==null?void 0:f.cues;delete c[v],b&&Object.keys(b).forEach(y=>{let T=b[y];if(T){T.removeEventListener("enter",this.onEventCueEnter);try{l.removeCue(T)}catch{}}})}}else c=this.dateRangeCuesAppended={}}let m=e.fragments[e.fragments.length-1];if(!(u.length===0||!Q(m==null?void 0:m.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let p=0;p<u.length;p++){let g=u[p],v=d[g],b=v.startTime,y=c[g],T=(y==null?void 0:y.cues)||{},A=(y==null?void 0:y.durationKnown)||!1,R=tu,{duration:I,endDate:x}=v;if(x&&I!==null)R=b+I,A=!0;else if(v.endOnNext&&!A){let S=u.reduce((C,P)=>{if(P!==v.id){let N=d[P];if(N.class===v.class&&N.startDate>v.startDate&&(!C||v.startDate<C.startDate))return N}return C},null);S&&(R=S.startTime,A=!0)}let D=Object.keys(v.attr);for(let S=0;S<D.length;S++){let C=D[S];if(!Dx(C))continue;let P=T[C];if(P)A&&!(y!=null&&y.durationKnown)?P.endTime=R:Math.abs(P.startTime-b)>.01&&(P.startTime=b,P.endTime=R);else if(o){let N=v.attr[C];Cx(C)&&(N=Zy(N));let H=km(o,b,R,{key:C,data:N},oi.dateRange);H&&(H.id=g,this.id3Track.addCue(H),T[C]=H,a&&(C==="X-ASSET-LIST"||C==="X-ASSET-URL")&&H.addEventListener("enter",this.onEventCueEnter))}}c[g]={cues:T,dateRange:v,durationKnown:A}}}}},Wp=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{let{media:t}=this,s=this.levelDetails;if(!t||!s)return;this.currentTime=t.currentTime;let r=this.computeLatency();if(r===null)return;this._latency=r;let{lowLatencyMode:n,maxLiveSyncPlaybackRate:a}=this.config;if(!n||a===1||!s.live)return;let o=this.targetLatency;if(o===null)return;let l=r-o,d=Math.min(this.maxLatency,o+s.targetduration);if(l<d&&l>.05&&this.forwardBufferLength>1){let c=Math.min(2,Math.max(1,a)),h=Math.round(2/(1+Math.exp(-.75*l-this.edgeStalled))*20)/20,f=Math.min(c,Math.max(1,h));this.changeMediaPlaybackRate(t,f)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){let{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;let t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){let e=this.levelDetails;if(e===null||this.hls===null)return null;let{holdBack:t,partHoldBack:s,targetduration:r}=e,{liveSyncDuration:n,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,l=this.hls.userConfig,d=o&&s||t;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||d===0)&&(d=n!==void 0?n:a*r);let u=r;return d+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,u)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){let e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;let s=this.levelDetails;if(s===null)return null;let r=s.edge,n=e-t-this.edgeStalled,a=r-s.totalduration,o=r-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(a,n),o)}get drift(){let e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){let e=this.levelDetails;if(e===null)return 0;let t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){let{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;let s=e.buffered.length;return(s?e.buffered.end(s-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){let{hls:e}=this;e&&(e.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(E.ERROR,this.onError,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(E.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var s;t.details===M.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(s=this.levelDetails)!=null&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var s,r;e.playbackRate!==t&&((s=this.hls)==null||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(r=this.targetLatency)==null?void 0:r.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){let e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){let e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}},qp=class extends jo{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){let{hls:e}=this;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this),e.on(E.ERROR,this.onError,this)}_unregisterListeners(){let{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this),e.off(E.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){let s=this.hls.config.preferManagedMediaSource,r=[],n={},a={},o=!1,l=!1,d=!1;t.levels.forEach(u=>{let c=u.attrs,{audioCodec:h,videoCodec:f}=u;h&&(u.audioCodec=h=cu(h,s)||void 0),f&&(f=u.videoCodec=ex(f));let{width:m,height:p,unknownCodecs:g}=u,v=(g==null?void 0:g.length)||0;if(o||(o=!!(m&&p)),l||(l=!!f),d||(d=!!h),v||h&&!this.isAudioSupported(h)||f&&!this.isVideoSupported(f)){this.log(`Some or all CODECS not supported "${c.CODECS}"`);return}let{CODECS:b,"FRAME-RATE":y,"HDCP-LEVEL":T,"PATHWAY-ID":A,RESOLUTION:R,"VIDEO-RANGE":I}=c,D=`${`${A||"."}-`}${u.bitrate}-${R}-${y}-${b}-${I}-${T}`;if(n[D])if(n[D].uri!==u.url&&!u.attrs["PATHWAY-ID"]){let S=a[D]+=1;u.attrs["PATHWAY-ID"]=new Array(S+1).join(".");let C=this.createLevel(u);n[D]=C,r.push(C)}else n[D].addGroupId("audio",c.AUDIO),n[D].addGroupId("text",c.SUBTITLES);else{let S=this.createLevel(u);n[D]=S,a[D]=1,r.push(S)}}),this.filterAndSortMediaOptions(r,t,o,l,d)}createLevel(e){let t=new tn(e),s=e.supplemental;if(s!=null&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){let r=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(r.message),t.supportedResult=db(r,[])}return t}isAudioSupported(e){return Bo(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Bo(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,s,r,n){var a;let o=[],l=[],d=e,u=((a=t.stats)==null?void 0:a.parsing)||{};if((s||r)&&n&&(d=d.filter(({videoCodec:b,videoRange:y,width:T,height:A})=>(!!b||!!(T&&A))&&ux(y))),d.length===0){Promise.resolve().then(()=>{if(this.hls){let b="no level with compatible codecs found in manifest",y=b;t.levels.length&&(y=`one or more CODECS in variant not supported: ${qe(t.levels.map(A=>A.attrs.CODECS).filter((A,R,I)=>I.indexOf(A)===R))}`,this.warn(y),b+=` (${y})`);let T=new Error(b);this.hls.trigger(E.ERROR,{type:se.MEDIA_ERROR,details:M.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:T,reason:y})}}),u.end=performance.now();return}t.audioTracks&&(o=t.audioTracks.filter(b=>!b.audioCodec||this.isAudioSupported(b.audioCodec)),zy(o)),t.subtitles&&(l=t.subtitles,zy(l));let c=d.slice(0);d.sort((b,y)=>{if(b.attrs["HDCP-LEVEL"]!==y.attrs["HDCP-LEVEL"])return(b.attrs["HDCP-LEVEL"]||"")>(y.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&b.height!==y.height)return b.height-y.height;if(b.frameRate!==y.frameRate)return b.frameRate-y.frameRate;if(b.videoRange!==y.videoRange)return hu.indexOf(b.videoRange)-hu.indexOf(y.videoRange);if(b.videoCodec!==y.videoCodec){let T=WE(b.videoCodec),A=WE(y.videoCodec);if(T!==A)return A-T}if(b.uri===y.uri&&b.codecSet!==y.codecSet){let T=uu(b.codecSet),A=uu(y.codecSet);if(T!==A)return A-T}return b.averageBitrate!==y.averageBitrate?b.averageBitrate-y.averageBitrate:0});let h=c[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==c.length)){for(let b=0;b<c.length;b++)if(c[b].pathwayId===d[0].pathwayId){h=c[b];break}}this._levels=d;for(let b=0;b<d.length;b++)if(d[b]===h){var f;this._firstLevel=b;let y=h.bitrate,T=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${d.length} level(s) found, first bitrate: ${y}`),((f=this.hls.userConfig)==null?void 0:f.abrEwmaDefaultEstimate)===void 0){let A=Math.min(y,this.hls.config.abrEwmaDefaultEstimateMax);A>T&&T===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=A)}break}let m=n&&!r,p=this.hls.config,g=!!(p.audioStreamController&&p.audioTrackController),v={levels:d,audioTracks:o,subtitleTracks:l,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:r,altAudio:g&&!m&&o.some(b=>!!b.url)};u.end=performance.now(),this.hls.trigger(E.MANIFEST_PARSED,v)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){let t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){let u=new Error("invalid level idx"),c=e<0;if(this.hls.trigger(E.ERROR,{type:se.OTHER_ERROR,details:M.LEVEL_SWITCH_ERROR,level:e,fatal:c,error:u,reason:u.message}),c)return;e=Math.min(e,t.length-1)}let s=this.currentLevelIndex,r=this.currentLevel,n=r?r.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,s===e&&r&&n===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${s}${n?" with Pathway "+n:""}`);let l={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(E.LEVEL_SWITCHING,l);let d=a.details;if(!d||d.live){let u=this.switchParams(a.uri,r==null?void 0:r.details,d);this.loadPlaylist(u)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){let e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){let t=this.steering.pathways(),s=e.filter(r=>t.indexOf(r)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=s}}onError(e,t){t.fatal||!t.context||t.context.type===Le.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===J.MAIN){let s=t.elementaryStreams;if(!Object.keys(s).some(n=>!!s[n]))return;let r=this._levels[t.level];r!=null&&r.loadError&&(this.log(`Resetting level error count of ${r.loadError} on frag buffered`),r.loadError=0)}}onLevelLoaded(e,t){var s;let{level:r,details:n}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${r}`),(o=t.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let l=a.details;l===t.details&&l.advanced&&(l=void 0),this.playlistLoaded(r,t,l)}else(s=t.deliveryDirectives)!=null&&s.skip&&(n.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let s=this.getUrlWithDirectives(e.uri,t),r=this.currentLevelIndex,n=e.attrs["PATHWAY-ID"],a=e.details,o=a==null?void 0:a.age;this.log(`Loading level index ${r}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${n?" Pathway "+n:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${s}`),this.hls.trigger(E.LEVEL_LOADING,{url:s,level:r,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;let s=this._levels.filter((n,a)=>a!==e?!0:(this.steering&&this.steering.removeLevel(n),n===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,n.details&&n.details.fragments.forEach(o=>o.level=-1)),!1));xb(s),this._levels=s,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);let r=s.length-1;this._firstLevel=Math.min(this._firstLevel,r),this._startLevel&&(this._startLevel=Math.min(this._startLevel,r)),this.hls.trigger(E.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(E.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}};function zy(i){let e={};i.forEach(t=>{let s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}function vT(){return self.SourceBuffer||self.WebKitSourceBuffer}function ET(){if(!nr())return!1;let e=vT();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function LC(){if(!ET())return!1;let i=nr();return typeof(i==null?void 0:i.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>i.isTypeSupported($o(e,"video")))||["mp4a.40.2","fLaC"].some(e=>i.isTypeSupported($o(e,"audio"))))}function RC(){var i;let e=vT();return typeof(e==null||(i=e.prototype)==null?void 0:i.changeType)=="function"}var xC=100,Yp=class extends Ko{constructor(e,t,s){super(e,t,s,"stream-controller",J.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{let r=this.media,n=r?r.currentTime:null;if(n===null||!Q(n)||(this.log(`Media seeked to ${n.toFixed(3)}`),!this.getBufferedFrag(n)))return;let a=this.getFwdBufferInfoAtPos(r,n,J.MAIN,0);if(a===null||a.len===0){this.warn(`Main forward buffer length at ${n} on "seeked" event ${a?a.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(E.MANIFEST_PARSED,this.onManifestParsed,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.LEVEL_LOADED,this.onLevelLoaded,this),e.on(E.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(E.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(E.BUFFER_CREATED,this.onBufferCreated,this),e.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(E.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(E.MANIFEST_PARSED,this.onManifestParsed,this),e.off(E.LEVEL_LOADED,this.onLevelLoaded,this),e.off(E.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(E.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(E.BUFFER_CREATED,this.onBufferCreated,this),e.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(E.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){let{lastCurrentTime:s,hls:r}=this;if(this.stopLoad(),this.setInterval(xC),this.level=-1,!this.startFragRequested){let n=r.startLevel;n===-1&&(r.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=!0):n=r.firstAutoLevel),r.nextLoadLevel=n,this.level=r.loadLevel,this._hasEnoughToStart=!!t}s>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=O.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=O.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case O.WAITING_LEVEL:{let{levels:e,level:t}=this,s=e==null?void 0:e[t],r=s==null?void 0:s.details;if(r&&(!r.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(r))break;this.state=O.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=O.IDLE;break}break}case O.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===O.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){let{hls:e,levelLastLoaded:t,levels:s,media:r}=this;if(t===null||!r&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;let n=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(s!=null&&s[n]))return;let a=s[n],o=this.getMainFwdBufferInfo();if(o===null)return;let l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){let p={};this.altAudio===2&&(p.type="video"),this.hls.trigger(E.BUFFER_EOS,p),this.state=O.ENDED;return}if(!this.buffering)return;e.loadLevel!==n&&e.manualLevel===-1&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=e.nextLoadLevel=n;let d=a.details;if(!d||this.state===O.WAITING_LEVEL||this.waitForLive(a)){this.level=n,this.state=O.WAITING_LEVEL,this.startFragRequested=!1;return}let u=o.len,c=this.getMaxBufferLength(a.maxBitrate);if(u>=c)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);let h=this.backtrackFragment?this.backtrackFragment.start:o.end,f=this.getNextFragment(h,d);if(this.couldBacktrack&&!this.fragPrevious&&f&&at(f)&&this.fragmentTracker.getState(f)!==Tt.OK){var m;let g=((m=this.backtrackFragment)!=null?m:f).sn-d.startSN,v=d.fragments[g-1];v&&f.cc===v.cc&&(f=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,h)){if(!f.gap){let g=this.audioOnly&&!this.altAudio?We.AUDIO:We.VIDEO,v=(g===We.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,g,J.MAIN)}f=this.getNextFragmentLoopLoading(f,d,o,J.MAIN,c)}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,h))}loadFragment(e,t,s){let r=this.fragmentTracker.getState(e);r===Tt.NOT_LOADED||r===Tt.PARTIAL?at(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,s):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,J.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){let{levels:e,media:t}=this;if(t!=null&&t.readyState){let s,r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);let n=this.getLevelDetails();if(n!=null&&n.live){let o=this.getMainFwdBufferInfo();if(!o||o.len<n.targetduration*2)return}if(!t.paused&&e){let o=this.hls.nextLoadLevel,l=e[o],d=this.fragLastKbps;d&&this.fragCurrent?s=this.fragCurrent.duration*l.maxBitrate/(1e3*d)+1:s=0}else s=0;let a=this.getBufferedFrag(t.currentTime+s);if(a){let o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();let l=o.maxStartPTS?o.maxStartPTS:o.start,d=o.duration,u=Math.max(a.end,l+Math.min(Math.max(d-this.config.maxFragLookUpTolerance,d*(this.couldBacktrack?.5:.125)),d*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(u,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){let e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case O.KEY_LOADING:case O.FRAG_LOADING:case O.FRAG_LOADING_WAITING_RETRY:case O.PARSING:case O.PARSED:this.state=O.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);let s=t.media;Ht(s,"playing",this.onMediaPlaying),Ht(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){let{media:s}=this;s&&(zt(s,"playing",this.onMediaPlaying),zt(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(E.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let s=!1,r=!1;for(let n=0;n<t.levels.length;n++){let a=t.levels[n].audioCodec;a&&(s=s||a.indexOf("mp4a.40.2")!==-1,r=r||a.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=s&&r&&!RC(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){let{levels:s}=this;if(!s||this.state!==O.IDLE)return;let r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=O.WAITING_LEVEL)}onLevelLoaded(e,t){var s;let{levels:r,startFragRequested:n}=this,a=t.level,o=t.details,l=o.totalduration;if(!r){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${l}`);let d=t.levelInfo,u=this.fragCurrent;u&&(this.state===O.FRAG_LOADING||this.state===O.FRAG_LOADING_WAITING_RETRY)&&u.level!==t.level&&u.loader&&this.abortCurrentFrag();let c=0;if(o.live||(s=d.details)!=null&&s.live){var h;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;c=this.alignPlaylists(o,d.details,(h=this.levelLastLoaded)==null?void 0:h.details)}if(d.details=o,this.levelLastLoaded=d,n||this.setStartPosition(o,c),this.hls.trigger(E.LEVEL_UPDATED,{details:o,level:a}),this.state===O.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=O.IDLE}n&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(e){let{config:t,media:s}=this;if(!s)return;let r=this.hls.liveSyncPosition,n=this.getLoadPosition(),a=e.fragmentStart,o=e.edge,l=n>=a-t.maxFragLookUpTolerance&&n<=o;if(r!==null&&s.duration>r&&(n<r||!l)){let u=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!l&&s.readyState<4||n<o-u)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),s.readyState))if(this.warn(`Playback: ${n.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${r.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var d;let c=Ee.bufferInfo(s,r,0);if(!((d=c.buffered)!=null&&d.length)){s.currentTime=r;return}if(c.start<=n){s.currentTime=r;return}let{nextStart:f}=Ee.bufferedInfo(c.buffered,n,0);f&&(s.currentTime=f)}else s.currentTime=r}}_handleFragmentLoadProgress(e){var t;let s=e.frag,{part:r,payload:n}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}let o=a[s.level];if(!o){this.warn(`Level ${s.level} not found on progress`);return}let l=o.details;if(!l){this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),this.fragmentTracker.removeFragment(s);return}let d=o.videoCodec,u=l.PTSKnown||!l.live,c=(t=s.initSegment)==null?void 0:t.data,h=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new Lu(this.hls,J.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),m=r?r.index:-1,p=m!==-1,g=new Go(s.level,s.sn,s.stats.chunkCount,n.byteLength,m,p),v=this.initPTS[s.cc];f.push(n,c,h,d,s,r,l.totalduration,u,g,v)}onAudioTrackSwitching(e,t){let s=this.hls,r=this.altAudio!==0;if(mu(t.url,s))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;let a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(r){this.altAudio=0,this.fragmentTracker.removeAllFragments(),s.once(E.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(E.AUDIO_TRACK_SWITCHED,t)}),s.trigger(E.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}s.trigger(E.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){let s=mu(t.url,this.hls);if(s){let r=this.videoBuffer;r&&this.mediaBuffer!==r&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=r)}this.altAudio=s?2:0,this.tick()}onBufferCreated(e,t){let s=t.tracks,r,n,a=!1;for(let o in s){let l=s[o];if(l.id==="main"){if(n=o,r=l,o==="video"){let d=s[o];d&&(this.videoBuffer=d.buffer)}}else a=!0}a&&r?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){let{frag:s,part:r}=t,n=s.type===J.MAIN;if(n){if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${r?" p: "+r.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),this.state===O.PARSED&&(this.state=O.IDLE);return}let o=r?r.stats:s.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),at(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,r)}let a=this.media;a&&(!this._hasEnoughToStart&&Ee.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal){this.state=O.ERROR;return}switch(t.details){case M.FRAG_GAP:case M.FRAG_PARSING_ERROR:case M.FRAG_DECRYPT_ERROR:case M.FRAG_LOAD_ERROR:case M.FRAG_LOAD_TIMEOUT:case M.KEY_LOAD_ERROR:case M.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(J.MAIN,t);break;case M.LEVEL_LOAD_ERROR:case M.LEVEL_LOAD_TIMEOUT:case M.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===O.WAITING_LEVEL&&((s=t.context)==null?void 0:s.type)===Le.LEVEL&&(this.state=O.IDLE);break;case M.BUFFER_ADD_CODEC_ERROR:case M.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case M.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case M.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=O.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==We.AUDIO||!this.altAudio){let s=(t===We.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;s&&(this.afterBufferFlushed(s,t,J.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){let{media:e}=this;if(!e)return;let t=e.currentTime,s=this.startPosition;if(s>=0&&t<s){if(e.seeking){this.log(`could not seek to ${s}, already seeking at ${t}`);return}let r=this.timelineOffset;r&&s&&(s+=r);let n=this.getLevelDetails(),a=Ee.getBuffered(e),o=a.length?a.start(0):0,l=o-s,d=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||l>0&&(l<d||this.loadingParts&&l<2*((n==null?void 0:n.partTarget)||0)))&&(this.log(`adjusting start position by ${l} to match buffer start`),s+=l,this.startPosition=s),t<s&&(this.log(`seek to target start position ${s} from current time ${t} buffer start ${o}`),e.currentTime=s)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(s=>{let{hls:r}=this,n=s==null?void 0:s.frag;if(!n||this.fragContextChanged(n))return;t.fragmentError=0,this.state=O.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;let a=n.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),r.trigger(E.FRAG_LOADED,s),n.bitrateTest=!1}).catch(s=>{this.state===O.STOPPED||this.state===O.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){let t=this.playlistType,{hls:s}=this,{remuxResult:r,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a){this.resetWhenMissingContext(n);return}let{frag:o,part:l,level:d}=a,{video:u,text:c,id3:h,initSegment:f}=r,{details:m}=d,p=this.altAudio?void 0:r.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=O.PARSING,f){let g=f.tracks;if(g){let T=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(d,g,T,n),s.trigger(E.FRAG_PARSING_INIT_SEGMENT,{frag:T,id:t,tracks:g})}let v=f.initPTS,b=f.timescale,y=this.initPTS[o.cc];if(Q(v)&&(!y||y.baseTime!==v||y.timescale!==b)){let T=f.trackId;this.initPTS[o.cc]={baseTime:v,timescale:b,trackId:T},s.trigger(E.INIT_PTS_FOUND,{frag:o,id:t,initPTS:v,timescale:b,trackId:T})}}if(u&&m){p&&u.type==="audiovideo"&&this.logMuxedErr(o);let g=m.fragments[o.sn-1-m.startSN],v=o.sn===m.startSN,b=!g||o.cc>g.cc;if(r.independent!==!1){let{startPTS:y,endPTS:T,startDTS:A,endDTS:R}=u;if(l)l.elementaryStreams[u.type]={startPTS:y,endPTS:T,startDTS:A,endDTS:R};else if(u.firstKeyFrame&&u.independent&&n.id===1&&!b&&(this.couldBacktrack=!0),u.dropped&&u.independent){let I=this.getMainFwdBufferInfo(),x=(I?I.end:this.getLoadPosition())+this.config.maxBufferHole,D=u.firstKeyFramePTS?u.firstKeyFramePTS:y;if(!v&&x<D-this.config.maxBufferHole&&!b){this.backtrack(o);return}else b&&(o.gap=!0);o.setElementaryStreamInfo(u.type,o.start,T,o.start,R,!0)}else v&&y-(m.appliedTimelineOffset||0)>lu&&(o.gap=!0);o.setElementaryStreamInfo(u.type,y,T,A,R),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,o,l,n,v||b)}else if(v||b)o.gap=!0;else{this.backtrack(o);return}}if(p){let{startPTS:g,endPTS:v,startDTS:b,endDTS:y}=p;l&&(l.elementaryStreams[We.AUDIO]={startPTS:g,endPTS:v,startDTS:b,endDTS:y}),o.setElementaryStreamInfo(We.AUDIO,g,v,b,y),this.bufferFragmentData(p,o,l,n)}if(m&&h!=null&&h.samples.length){let g={id:t,frag:o,details:m,samples:h.samples};s.trigger(E.FRAG_PARSING_METADATA,g)}if(m&&c){let g={id:t,frag:o,details:m,samples:c.samples};s.trigger(E.FRAG_PARSING_USERDATA,g)}}logMuxedErr(e){this.warn(`${at(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,r){if(this.state!==O.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));let{audio:n,video:a,audiovideo:o}=t;if(n){let d=e.audioCodec,u=iu(n.codec,d);u==="mp4a"&&(u="mp4a.40.5");let c=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){u&&(u.indexOf("mp4a.40.5")!==-1?u="mp4a.40.2":u="mp4a.40.5");let h=n.metadata;h&&"channelCount"in h&&(h.channelCount||1)!==1&&c.indexOf("firefox")===-1&&(u="mp4a.40.5")}u&&u.indexOf("mp4a.40.5")!==-1&&c.indexOf("android")!==-1&&n.container!=="audio/mpeg"&&(u="mp4a.40.2",this.log(`Android: force audio codec to ${u}`)),d&&d!==u&&this.log(`Swapping manifest audio codec "${d}" for "${u}"`),n.levelCodec=u,n.id=J.MAIN,this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${u||""}/${d||""}/${n.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=J.MAIN;let d=a.codec;if((d==null?void 0:d.length)===4)switch(d){case"hvc1":case"hev1":a.codec="hvc1.1.6.L120.90";break;case"av01":a.codec="av01.0.04M.08";break;case"avc1":a.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${d}]${a.codec!==d?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete t.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);let l=Object.keys(t);if(l.length){if(this.hls.trigger(E.BUFFER_CODECS,t),!this.hls)return;l.forEach(d=>{let c=t[d].initSegment;c!=null&&c.byteLength&&this.hls.trigger(E.BUFFER_APPENDING,{type:d,data:c,frag:s,part:null,chunkMeta:r,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){let e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,J.MAIN)}get maxBufferLength(){let{levels:e,level:t}=this,s=e==null?void 0:e[t];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=O.IDLE}checkFragmentChanged(){let e=this.media,t=null;if(e&&e.readyState>1&&e.seeking===!1){let s=e.currentTime;if(Ee.isBuffered(e,s)?t=this.getAppendedFrag(s):Ee.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;let r=this.fragPlaying,n=t.level;(!r||t.sn!==r.sn||r.level!==n)&&(this.fragPlaying=t,this.hls.trigger(E.FRAG_CHANGED,{frag:t}),(!r||r.level!==n)&&this.hls.trigger(E.LEVEL_SWITCHED,{level:n}))}}}get nextLevel(){let e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;let t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return Q(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;let t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(Q(t)){let s=this.getLevelDetails(),r=this.currentFrag||(s?sn(null,s.fragments,t):null);if(r){let n=r.programDateTime;if(n!==null){let a=n+(t-r.start)*1e3;return new Date(a)}}}return null}get currentLevel(){let e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){let e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}},jp=class extends Qt{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(let s in this.keyIdToKeyInfo){let r=this.keyIdToKeyInfo[s].loader;if(r){var t;if(e&&e!==((t=r.context)==null?void 0:t.frag.type))return;r.abort()}}}detach(){for(let e in this.keyIdToKeyInfo){let t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(let e in this.keyIdToKeyInfo){let t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=M.KEY_LOAD_ERROR,s,r,n){return new Mi({type:se.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:s,networkDetails:r})}loadClear(e,t,s){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let r=0,n=t.length;r<n;r++){let a=t[r];if(e.cc<=a.cc&&(!at(e)||!at(a)||e.sn<a.sn)||!s&&r==n-1)return this.emeController.selectKeySystemFormat(a).then(o=>{if(!this.emeController)return;a.setKeyFormat(o);let l=ru(o);if(l)return this.emeController.getKeySystemAccess([l])})}if(this.config.requireKeySystemAccessOnStart){let r=Mo(this.config);if(r.length)return this.emeController.getKeySystemAccess(r)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var s,r;t&&e.setKeyFormat(t);let n=e.decryptdata;if(!n){let d=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,M.KEY_LOAD_ERROR,d))}let a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,M.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));let o=Dm(n),l=this.keyIdToKeyInfo[o];if((s=l)!=null&&s.decryptdata.key)return n.key=l.decryptdata.key,Promise.resolve({frag:e,keyInfo:l});if(this.emeController&&(r=l)!=null&&r.keyLoadPromise)switch(this.emeController.getKeyStatus(l.decryptdata)){case"usable":case"usable-in-future":return l.keyLoadPromise.then(u=>{let{keyInfo:c}=u;return n.key=c.decryptdata.key,{frag:e,keyInfo:c}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${n.keyId?" keyId: "+Dt(n.keyId):""} URI: ${n.uri} from ${e.type} ${e.level}`),l=this.keyIdToKeyInfo[o]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return n.keyFormat==="identity"?this.loadKeyHTTP(l,e):this.loadKeyEME(l,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(l,e);default:return Promise.reject(this.createKeyLoadError(e,M.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(e,t){let s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var r;if(!e.decryptdata.keyId&&(r=t.initSegment)!=null&&r.data){let a=GR(t.initSegment.data);if(a.length){let o=a[0];o.some(l=>l!==0)?(this.log(`Using keyId found in init segment ${Dt(o)}`),na.setKeyIdForUri(e.decryptdata.uri,o)):(o=na.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${Dt(o)}`)),e.decryptdata.keyId=o}}if(!e.decryptdata.keyId&&!at(t))return Promise.resolve(s);let n=this.emeController.loadKey(s);return(e.keyLoadPromise=n.then(a=>(e.mediaKeySessionContext=a,s))).catch(a=>{throw e.keyLoadPromise=null,"data"in a&&(a.data.frag=t),a})}return Promise.resolve(s)}loadKeyHTTP(e,t){let s=this.config,r=s.loader,n=new r(s);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise((a,o)=>{let l={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},d=s.keyLoadPolicy.default,u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(h,f,m,p)=>{let{frag:g,keyInfo:v}=m,b=Dm(v.decryptdata);if(!g.decryptdata||v!==this.keyIdToKeyInfo[b])return o(this.createKeyLoadError(g,M.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),p));v.decryptdata.key=g.decryptdata.key=new Uint8Array(h.data),g.keyLoader=null,v.loader=null,a({frag:g,keyInfo:v})},onError:(h,f,m,p)=>{this.resetLoader(f),o(this.createKeyLoadError(t,M.KEY_LOAD_ERROR,new Error(`HTTP Error ${h.code} loading key ${h.text}`),m,Fe({url:l.url,data:void 0},h)))},onTimeout:(h,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,M.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),m))},onAbort:(h,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,M.INTERNAL_ABORTED,new Error("key loading aborted"),m))}};n.load(l,u,c)})}resetLoader(e){let{frag:t,keyInfo:s,url:r}=e,n=s.loader;t.keyLoader===n&&(t.keyLoader=null,s.loader=null);let a=Dm(s.decryptdata)||r;delete this.keyIdToKeyInfo[a],n&&n.destroy()}};function Dm(i){if(i.keyFormat!==Ct.FAIRPLAY){let e=i.keyId;if(e)return Dt(e)}return i.uri}function Qy(i){let{type:e}=i;switch(e){case Le.AUDIO_TRACK:return J.AUDIO;case Le.SUBTITLE_TRACK:return J.SUBTITLE;default:return J.MAIN}}function Cm(i,e){let t=i.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}var zp=class{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){let{hls:e}=this;e.on(E.MANIFEST_LOADING,this.onManifestLoading,this),e.on(E.LEVEL_LOADING,this.onLevelLoading,this),e.on(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){let{hls:e}=this;e.off(E.MANIFEST_LOADING,this.onManifestLoading,this),e.off(E.LEVEL_LOADING,this.onLevelLoading,this),e.off(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){let t=this.hls.config,s=t.pLoader,r=t.loader,n=s||r,a=new n(t);return this.loaders[e.type]=a,a}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(let e in this.loaders){let t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){let{url:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Le.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){let{id:s,level:r,pathwayId:n,url:a,deliveryDirectives:o,levelInfo:l}=t;this.load({id:s,level:r,pathwayId:n,responseType:"text",type:Le.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:l})}onAudioTrackLoading(e,t){let{id:s,groupId:r,url:n,deliveryDirectives:a,track:o}=t;this.load({id:s,groupId:r,level:null,responseType:"text",type:Le.AUDIO_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){let{id:s,groupId:r,url:n,deliveryDirectives:a,track:o}=t;this.load({id:s,groupId:r,level:null,responseType:"text",type:Le.SUBTITLE_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){let s=this.loaders[Le.LEVEL];if(s){let r=s.context;r&&!t.levels.some(n=>n===r.levelOrTrack)&&(s.abort(),delete this.loaders[Le.LEVEL])}}load(e){var t;let s=this.hls.config,r=this.getInternalLoader(e);if(r){let d=this.hls.logger,u=r.context;if(u&&u.levelOrTrack===e.levelOrTrack&&(u.url===e.url||u.deliveryDirectives&&!e.deliveryDirectives)){u.url===e.url?d.log(`[playlist-loader]: ignore ${e.url} ongoing request`):d.log(`[playlist-loader]: ignore ${e.url} in favor of ${u.url}`);return}d.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),r.abort()}let n;if(e.type===Le.MANIFEST?n=s.manifestLoadPolicy.default:n=$e({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(e),Q((t=e.deliveryDirectives)==null?void 0:t.part)){let d;if(e.type===Le.LEVEL&&e.level!==null?d=this.hls.levels[e.level].details:e.type===Le.AUDIO_TRACK&&e.id!==null?d=this.hls.audioTracks[e.id].details:e.type===Le.SUBTITLE_TRACK&&e.id!==null&&(d=this.hls.subtitleTracks[e.id].details),d){let u=d.partTarget,c=d.targetduration;if(u&&c){let h=Math.max(u*3,c*.8)*1e3;n=$e({},n,{maxTimeToFirstByteMs:Math.min(h,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(h,n.maxTimeToFirstByteMs)})}}}let a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(d,u,c,h)=>{let f=this.getInternalLoader(c);this.resetInternalLoader(c.type);let m=d.data;u.parsing.start=performance.now(),Zr.isMediaPlaylist(m)||c.type!==Le.MANIFEST?this.handleTrackOrLevelPlaylist(d,u,c,h||null,f):this.handleMasterPlaylist(d,u,c,h)},onError:(d,u,c,h)=>{this.handleNetworkError(u,c,!1,d,h)},onTimeout:(d,u,c)=>{this.handleNetworkError(u,c,!0,void 0,d)}};r.load(e,o,l)}checkAutostartLoad(){if(!this.hls)return;let{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,r){let n=this.hls,a=e.data,o=Cm(e,s),l=Zr.parseMasterPlaylist(a,o);if(l.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,s,l.playlistParsingError,r,t);return}let{contentSteering:d,levels:u,sessionData:c,sessionKeys:h,startTimeOffset:f,variableList:m}=l;this.variableList=m,u.forEach(b=>{let{unknownCodecs:y}=b;if(y){let{preferManagedMediaSource:T}=this.hls.config,{audioCodec:A,videoCodec:R}=b;for(let I=y.length;I--;){let x=y[I];Bo(x,"audio",T)?(b.audioCodec=A=A?`${A},${x}`:x,ra.audio[A.substring(0,4)]=2,y.splice(I,1)):Bo(x,"video",T)&&(b.videoCodec=R=R?`${R},${x}`:x,ra.video[R.substring(0,4)]=2,y.splice(I,1))}}});let{AUDIO:p=[],SUBTITLES:g,"CLOSED-CAPTIONS":v}=Zr.parseMasterPlaylistMedia(a,o,l);p.length&&!p.some(y=>!y.url)&&u[0].audioCodec&&!u[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new tt({}),bitrate:0,url:""})),n.trigger(E.MANIFEST_LOADED,{levels:u,audioTracks:p,subtitles:g,captions:v,contentSteering:d,url:o,stats:t,networkDetails:r,sessionData:c,sessionKeys:h,startTimeOffset:f,variableList:m})}handleTrackOrLevelPlaylist(e,t,s,r,n){let a=this.hls,{id:o,level:l,type:d}=s,u=Cm(e,s),c=Q(l)?l:Q(o)?o:0,h=Qy(s),f=Zr.parseLevelPlaylist(e.data,u,c,h,0,this.variableList);if(d===Le.MANIFEST){let m={attrs:new tt({}),bitrate:0,details:f,name:"",url:u};f.requestScheduled=t.loading.start+Ib(f,0),a.trigger(E.MANIFEST_LOADED,{levels:[m],audioTracks:[],url:u,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=f,this.handlePlaylistLoaded(f,e,t,s,r,n)}handleManifestParsingError(e,t,s,r,n){this.hls.trigger(E.ERROR,{type:se.NETWORK_ERROR,details:M.MANIFEST_PARSING_ERROR,fatal:t.type===Le.MANIFEST,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:r,stats:n})}handleNetworkError(e,t,s=!1,r,n){let a=`A network ${s?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${e.type}`;e.type===Le.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===Le.AUDIO_TRACK||e.type===Le.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);let o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let l=M.UNKNOWN,d=!1,u=this.getInternalLoader(e);switch(e.type){case Le.MANIFEST:l=s?M.MANIFEST_LOAD_TIMEOUT:M.MANIFEST_LOAD_ERROR,d=!0;break;case Le.LEVEL:l=s?M.LEVEL_LOAD_TIMEOUT:M.LEVEL_LOAD_ERROR,d=!1;break;case Le.AUDIO_TRACK:l=s?M.AUDIO_TRACK_LOAD_TIMEOUT:M.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case Le.SUBTITLE_TRACK:l=s?M.SUBTITLE_TRACK_LOAD_TIMEOUT:M.SUBTITLE_LOAD_ERROR,d=!1;break}u&&this.resetInternalLoader(e.type);let c={type:se.NETWORK_ERROR,details:l,fatal:d,url:e.url,loader:u,context:e,error:o,networkDetails:t,stats:n};if(r){let h=(t==null?void 0:t.url)||e.url;c.response=Fe({url:h,data:void 0},r)}this.hls.trigger(E.ERROR,c)}handlePlaylistLoaded(e,t,s,r,n,a){let o=this.hls,{type:l,level:d,levelOrTrack:u,id:c,groupId:h,deliveryDirectives:f}=r,m=Cm(t,r),p=Qy(r),g=typeof r.level=="number"&&p===J.MAIN?d:void 0,v=e.playlistParsingError;if(v){if(this.hls.logger.warn(`${v} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(E.ERROR,{type:se.NETWORK_ERROR,details:M.LEVEL_PARSING_ERROR,fatal:!1,url:m,error:v,reason:v.message,response:t,context:r,level:g,parent:p,networkDetails:n,stats:s});return}e.playlistParsingError=null}if(!e.fragments.length){let b=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(E.ERROR,{type:se.NETWORK_ERROR,details:M.LEVEL_EMPTY_ERROR,fatal:!1,url:m,error:b,reason:b.message,response:t,context:r,level:g,parent:p,networkDetails:n,stats:s});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case Le.MANIFEST:case Le.LEVEL:if(g){if(!u)g=0;else if(u!==o.levels[g]){let b=o.levels.indexOf(u);b>-1&&(g=b)}}o.trigger(E.LEVEL_LOADED,{details:e,levelInfo:u||o.levels[0],level:g||0,id:c||0,stats:s,networkDetails:n,deliveryDirectives:f,withoutMultiVariant:l===Le.MANIFEST});break;case Le.AUDIO_TRACK:o.trigger(E.AUDIO_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:h||"",stats:s,networkDetails:n,deliveryDirectives:f});break;case Le.SUBTITLE_TRACK:o.trigger(E.SUBTITLE_TRACK_LOADED,{details:e,track:u,id:c||0,groupId:h||"",stats:s,networkDetails:n,deliveryDirectives:f});break}}},Xo=class i{static get version(){return Vo}static isMSESupported(){return ET()}static isSupported(){return LC()}static getMediaSource(){return nr()}static get Events(){return E}static get MetadataSchema(){return oi}static get ErrorTypes(){return se}static get ErrorDetails(){return M}static get DefaultConfig(){return i.defaultConfig?i.defaultConfig:EC}static set DefaultConfig(e){i.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new sg,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;let t=this.logger=CR(e.debug||!1,"Hls instance",e.assetPlayerId),s=this.config=bC(i.DefaultConfig,e,t);this.userConfig=e,s.progressive&&TC(s,t);let{abrController:r,bufferController:n,capLevelController:a,errorController:o,fpsController:l}=s,d=new o(this),u=this.abrController=new r(this),c=new Hm(this),h=s.interstitialsController,f=h?this.interstitialsController=new h(this,i):null,m=this.bufferController=new n(this,c),p=this.capLevelController=new a(this),g=new l(this),v=new zp(this),b=s.contentSteeringController,y=b?new b(this):null,T=this.levelController=new qp(this,y),A=new Vp(this),R=new jp(this.config,this.logger),I=this.streamController=new Yp(this,c,R),x=this.gapController=new Gp(this,c);p.setStreamController(I),g.setStreamController(I);let D=[v,T,I];f&&D.splice(1,0,f),y&&D.splice(1,0,y),this.networkControllers=D;let S=[u,m,x,p,g,A,c];this.audioTrackController=this.createController(s.audioTrackController,D);let C=s.audioStreamController;C&&D.push(this.audioStreamController=new C(this,c,R)),this.subtitleTrackController=this.createController(s.subtitleTrackController,D);let P=s.subtitleStreamController;P&&D.push(this.subtititleStreamController=new P(this,c,R)),this.createController(s.timelineController,S),R.emeController=this.emeController=this.createController(s.emeController,S),this.cmcdController=this.createController(s.cmcdController,S),this.latencyController=this.createController(Wp,S),this.coreComponents=S,D.push(d);let N=d.onErrorOut;typeof N=="function"&&this.on(E.ERROR,N,d),this.on(E.MANIFEST_LOADED,v.onManifestLoaded,v)}createController(e,t){if(e){let s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,r){this._emitter.off(e,t,s,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(s){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;let r=e===E.ERROR;this.trigger(E.ERROR,{type:se.OTHER_ERROR,details:M.INTERNAL_EXCEPTION,fatal:r,event:e,error:s}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(E.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;let e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){let n=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(E.ERROR,{type:se.OTHER_ERROR,details:M.ATTACH_MEDIA_ERROR,fatal:!0,error:n});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());let t="media"in e,s=t?e.media:e,r=t?e:{media:s};this._media=s,this.trigger(E.MEDIA_ATTACHING,r)}detachMedia(){this.logger.log("detachMedia"),this.trigger(E.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;let e=this.bufferController.transferMedia();return this.trigger(E.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();let t=this.media,s=this._url,r=this._url=Qp.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),t&&s&&(s!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(E.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(e,t),!(!this.started||!this.networkControllers));s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){let e={[J.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[J.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[J.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");let e=this._media,t=e==null?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=$D()),e}get levels(){let e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){let e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){let t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){let{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){dx(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){let{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;let s=e.length;for(let r=0;r<s;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this,r;if(t===-1&&e!=null&&e.length?r=e.length-1:r=t,s)for(let n=r;n--;){let a=e[n].attrs["HDCP-LEVEL"];if(a&&a<=s)return n}return r}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){let e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){let e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){let e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){let t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){let e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){let e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){let e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){let t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){let e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){let t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){var e;return((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){let s=hb(t);return ub(e,s,navigator.mediaCapabilities)}};Xo.defaultConfig=void 0;var _e=Xo,Ue={VIDEO:"video",THUMBNAIL:"thumbnail",STORYBOARD:"storyboard",DRM:"drm"},ne={NOT_AN_ERROR:0,NETWORK_OFFLINE:2000002,NETWORK_UNKNOWN_ERROR:2e6,NETWORK_NO_STATUS:2000001,NETWORK_INVALID_URL:24e5,NETWORK_NOT_FOUND:2404e3,NETWORK_NOT_READY:2412e3,NETWORK_GENERIC_SERVER_FAIL:25e5,NETWORK_TOKEN_MISSING:2403201,NETWORK_TOKEN_MALFORMED:2412202,NETWORK_TOKEN_EXPIRED:2403210,NETWORK_TOKEN_AUD_MISSING:2403221,NETWORK_TOKEN_AUD_MISMATCH:2403222,NETWORK_TOKEN_SUB_MISMATCH:2403232,ENCRYPTED_ERROR:5e6,ENCRYPTED_UNSUPPORTED_KEY_SYSTEM:5000001,ENCRYPTED_GENERATE_REQUEST_FAILED:5000002,ENCRYPTED_UPDATE_LICENSE_FAILED:5000003,ENCRYPTED_UPDATE_SERVER_CERT_FAILED:5000004,ENCRYPTED_CDM_ERROR:5000005,ENCRYPTED_OUTPUT_RESTRICTED:5000006,ENCRYPTED_MISSING_TOKEN:5000002},tl=i=>i===Ue.VIDEO?"playback":i,or=class Zo extends Error{constructor(e,t=Zo.MEDIA_ERR_CUSTOM,s,r){var n;super(e),this.name="MediaError",this.code=t,this.context=r,this.fatal=s!=null?s:t>=Zo.MEDIA_ERR_NETWORK&&t<=Zo.MEDIA_ERR_ENCRYPTED,this.message||(this.message=(n=Zo.defaultMessages[this.code])!=null?n:"")}};or.MEDIA_ERR_ABORTED=1,or.MEDIA_ERR_NETWORK=2,or.MEDIA_ERR_DECODE=3,or.MEDIA_ERR_SRC_NOT_SUPPORTED=4,or.MEDIA_ERR_ENCRYPTED=5,or.MEDIA_ERR_CUSTOM=100,or.defaultMessages={1:"You aborted the media playback",2:"A network error caused the media download to fail.",3:"A media error caused playback to be aborted. The media could be corrupt or your browser does not support this format.",4:"An unsupported error occurred. The server or network failed, or your browser does not support this format.",5:"The media is encrypted and there are no keys to decrypt it."};var z=or,kC=i=>i==null,Sg=(i,e)=>kC(e)?!1:i in e,pg={ANY:"any",MUTED:"muted"},we={ON_DEMAND:"on-demand",LIVE:"live",UNKNOWN:"unknown"},gi={MSE:"mse",NATIVE:"native"},Jo={HEADER:"header",QUERY:"query",NONE:"none"},la=Object.values(Jo),Cs={M3U8:"application/vnd.apple.mpegurl",MP4:"video/mp4"},gg={HLS:Cs.M3U8},IN=Object.keys(gg),LN=[...Object.values(Cs),"hls","HLS"];var DC="en",vg={code:DC},mt=(i,e,t,s,r=i)=>{r.addEventListener(e,t,s),i.addEventListener("teardown",()=>{r.removeEventListener(e,t)},{once:!0})};function CC(i,e,t){e&&t>e&&(t=e);for(let s=0;s<i.length;s++)if(i.start(s)<=t&&i.end(s)>=t)return!0;return!1}var Gu=i=>{let e=i.indexOf("?");if(e<0)return[i];let t=i.slice(0,e),s=i.slice(e);return[t,s]},Ku=i=>{let{type:e}=i;if(e){let t=e.toUpperCase();return Sg(t,gg)?gg[t]:e}return wC(i)},xT=i=>i==="VOD"?we.ON_DEMAND:we.LIVE,kT=i=>i==="EVENT"?Number.POSITIVE_INFINITY:i==="VOD"?Number.NaN:0,wC=i=>{let{src:e}=i;if(!e)return"";let t="";try{t=Ig(e).pathname}catch{console.error("Invalid url when trying to infer mime type",e)}let s=t.lastIndexOf(".");if(s<0)return OC(i)?Cs.M3U8:"";let r=t.slice(s+1).toUpperCase();return Sg(r,Cs)?Cs[r]:""},Eg=i=>{try{return new URL(i),!1}catch{return!0}},MC=i=>i.split(`
56
+ `).find((e,t,s)=>t>0&&s[t-1].startsWith("#EXT-X-STREAM-INF")),Ig=(i,e)=>{var t;if(!Eg(i))return new URL(i);let s=(t=window==null?void 0:window.location)==null?void 0:t.href,r=e!=null?e:s;return e&&Eg(e.toString())&&(r=new URL(e,s)),new URL(i,r)},PC="mux.com",OC=({src:i,customDomain:e=PC})=>{let t;try{t=new URL(`${i}`)}catch{return!1}let s=t.protocol==="https:",r=t.hostname===`stream.${e}`.toLowerCase(),n=t.pathname.split("/"),a=n.length===2,o=!(n!=null&&n[1].includes("."));return s&&r&&a&&o},dr=i=>{let e=(i!=null?i:"").split(".")[1];if(e)try{let t=e.replace(/-/g,"+").replace(/_/g,"/"),s=decodeURIComponent(atob(t).split("").map(function(r){return"%"+("00"+r.charCodeAt(0).toString(16)).slice(-2)}).join(""));return JSON.parse(s)}catch{return}},NC=({exp:i},e=Date.now())=>!i||i*1e3<e,UC=({sub:i},e)=>i!==e,FC=({aud:i},e)=>!i,BC=({aud:i},e)=>i!==e,DT="en";function te(i,e=!0){var t,s;let r=e&&(s=(t=vg)==null?void 0:t[i])!=null?s:i,n=e?vg.code:DT;return new $C(r,n)}var $C=class{constructor(i,e=(t=>(t=vg)!=null?t:DT)()){this.message=i,this.locale=e}format(i){return this.message.replace(/\{(\w+)\}/g,(e,t)=>{var s;return(s=i[t])!=null?s:""})}toString(){return this.message}},HC=Object.values(pg),yT=i=>typeof i=="boolean"||typeof i=="string"&&HC.includes(i),GC=(i,e,t)=>{let{autoplay:s}=i,r=!1,n=!1,a=yT(s)?s:!!s,o=()=>{r||mt(e,"playing",()=>{r=!0},{once:!0})};if(o(),mt(e,"loadstart",()=>{r=!1,o(),fg(e,a)},{once:!0}),mt(e,"loadstart",()=>{t||(i.streamType&&i.streamType!==we.UNKNOWN?n=i.streamType===we.LIVE:n=!Number.isFinite(e.duration)),fg(e,a)},{once:!0}),t&&t.once(_e.Events.LEVEL_LOADED,(l,d)=>{var u;i.streamType&&i.streamType!==we.UNKNOWN?n=i.streamType===we.LIVE:n=(u=d.details.live)!=null?u:!1}),!a){let l=()=>{!n||Number.isFinite(i.startTime)||(t!=null&&t.liveSyncPosition?e.currentTime=t.liveSyncPosition:Number.isFinite(e.seekable.end(0))&&(e.currentTime=e.seekable.end(0)))};t&&mt(e,"play",()=>{e.preload==="metadata"?t.once(_e.Events.LEVEL_UPDATED,l):l()},{once:!0})}return l=>{r||(a=yT(l)?l:!!l,fg(e,a))}},fg=(i,e)=>{if(!e)return;let t=i.muted,s=()=>i.muted=t;switch(e){case pg.ANY:i.play().catch(()=>{i.muted=!0,i.play().catch(s)});break;case pg.MUTED:i.muted=!0,i.play().catch(s);break;default:i.play().catch(()=>{});break}},KC=({preload:i,src:e},t,s)=>{let r=c=>{c!=null&&["","none","metadata","auto"].includes(c)?t.setAttribute("preload",c):t.removeAttribute("preload")};if(!s)return r(i),r;let n=!1,a=!1,o=s.config.maxBufferLength,l=s.config.maxBufferSize,d=c=>{r(c);let h=c!=null?c:t.preload;a||h==="none"||(h==="metadata"?(s.config.maxBufferLength=1,s.config.maxBufferSize=1):(s.config.maxBufferLength=o,s.config.maxBufferSize=l),u())},u=()=>{!n&&e&&(n=!0,s.loadSource(e))};return mt(t,"play",()=>{a=!0,s.config.maxBufferLength=o,s.config.maxBufferSize=l,u()},{once:!0}),d(i),d},VC=(i,e,t)=>{let{minPreloadSegments:s}=i;if(s==null||s<=0||!t)return;let r=0,n=!1,a=e.playbackRate||1,o=()=>{e.playbackRate!==0&&(a=e.playbackRate,e.playbackRate=0)};e.playbackRate=0,mt(e,"ratechange",o);let l=(d,{frag:u})=>{n||u.type!=="main"||(r++,r>=s&&(n=!0,e.removeEventListener("ratechange",o),e.playbackRate=a))};t.on(_e.Events.FRAG_BUFFERED,l),e.addEventListener("teardown",()=>{n||(n=!0,t.off(_e.Events.FRAG_BUFFERED,l),e.playbackRate=a)},{once:!0})},WC=(i,e,t)=>{let{initialEstimateSegments:s}=i;if(s==null||s<=0||!t)return;let r=0;t.on(_e.Events.FRAG_BUFFERED,(n,{frag:a})=>{a.type==="main"&&(r++,r<s&&t.abrController.resetEstimator(t.config.abrEwmaDefaultEstimate))})};function qC(i,e){var t;if(!("videoTracks"in i))return;let s=new WeakMap;e.on(_e.Events.MANIFEST_PARSED,function(d,u){l();let c=i.addVideoTrack("main");c.selected=!0;for(let[h,f]of u.levels.entries()){let m=c.addRendition(f.url[0],f.width,f.height,f.videoCodec,f.bitrate);s.set(f,`${h}`),m.id=`${h}`}}),e.on(_e.Events.AUDIO_TRACKS_UPDATED,function(d,u){o();for(let c of u.audioTracks){let h=c.default?"main":"alternative",f=i.addAudioTrack(h,c.name,c.lang);f.id=`${c.id}`,c.default&&(f.enabled=!0)}});let r=()=>{var d;let u=+((d=[...i.audioTracks].find(h=>h.enabled))==null?void 0:d.id),c=e.audioTracks.map(h=>h.id);u!=e.audioTrack&&c.includes(u)&&(e.audioTrack=u)};i.audioTracks.addEventListener("change",r),e.on(_e.Events.LEVELS_UPDATED,function(d,u){var c;let h=i.videoTracks[(c=i.videoTracks.selectedIndex)!=null?c:0];if(!h)return;let f=u.levels.map(m=>s.get(m));for(let m of i.videoRenditions)m.id&&!f.includes(m.id)&&h.removeRendition(m)});let n=d=>{let u=d.target.selectedIndex;u!=e.nextLevel&&(e.nextLevel=u)};(t=i.videoRenditions)==null||t.addEventListener("change",n);let a=()=>{for(let d of i.videoTracks)i.removeVideoTrack(d)},o=()=>{for(let d of i.audioTracks)i.removeAudioTrack(d)},l=()=>{a(),o()};e.once(_e.Events.DESTROYING,()=>{var d,u;l(),(d=i.audioTracks)==null||d.removeEventListener("change",r),(u=i.videoRenditions)==null||u.removeEventListener("change",n)})}var mg=i=>"time"in i?i.time:i.startTime;function YC(i,e){e.on(_e.Events.NON_NATIVE_TEXT_TRACKS_FOUND,(r,{tracks:n})=>{n.forEach(a=>{var o,l;let d=(o=a.subtitleTrack)!=null?o:a.closedCaptions,u=e.subtitleTracks.findIndex(({lang:h,name:f,type:m})=>h==(d==null?void 0:d.lang)&&f===a.label&&m.toLowerCase()===a.kind),c=((l=a._id)!=null?l:a.default)?"default":`${a.kind}${u}`;Vu(i,a.kind,a.label,d==null?void 0:d.lang,c,a.default)})});let t=()=>{if(!e.subtitleTracks.length)return;let r=Array.from(i.textTracks).find(o=>o.id&&o.mode==="showing"&&["subtitles","captions"].includes(o.kind));if(!r)return;let n=e.subtitleTracks[e.subtitleTrack],a=n?n.default?"default":`${e.subtitleTracks[e.subtitleTrack].type.toLowerCase()}${e.subtitleTrack}`:void 0;if(e.subtitleTrack<0||(r==null?void 0:r.id)!==a){let o=e.subtitleTracks.findIndex(({lang:l,name:d,type:u,default:c})=>r.id==="default"&&c||l==r.language&&d===r.label&&u.toLowerCase()===r.kind);e.subtitleTrack=o}(r==null?void 0:r.id)===a&&r.cues&&Array.from(r.cues).forEach(o=>{r.addCue(o)})};i.textTracks.addEventListener("change",t),e.on(_e.Events.CUES_PARSED,(r,{track:n,cues:a})=>{let o=i.textTracks.getTrackById(n);if(!o)return;let l=o.mode==="disabled";l&&(o.mode="hidden"),a.forEach(d=>{var u;(u=o.cues)!=null&&u.getCueById(d.id)||o.addCue(d)}),l&&(o.mode="disabled")}),e.once(_e.Events.DESTROYING,()=>{i.textTracks.removeEventListener("change",t),i.querySelectorAll("track[data-removeondestroy]").forEach(r=>{r.remove()})});let s=()=>{Array.from(i.textTracks).forEach(r=>{var n,a;if(!["subtitles","caption"].includes(r.kind)&&(r.label==="thumbnails"||r.kind==="chapters")){if(!((n=r.cues)!=null&&n.length)){let o="track";r.kind&&(o+=`[kind="${r.kind}"]`),r.label&&(o+=`[label="${r.label}"]`);let l=i.querySelector(o),d=(a=l==null?void 0:l.getAttribute("src"))!=null?a:"";l==null||l.removeAttribute("src"),setTimeout(()=>{l==null||l.setAttribute("src",d)},0)}r.mode!=="hidden"&&(r.mode="hidden")}})};e.once(_e.Events.MANIFEST_LOADED,s),e.once(_e.Events.MEDIA_ATTACHED,s)}function Vu(i,e,t,s,r,n){let a=document.createElement("track");return a.kind=e,a.label=t,s&&(a.srclang=s),r&&(a.id=r),n&&(a.default=!0),a.track.mode=["subtitles","captions"].includes(e)?"disabled":"hidden",a.setAttribute("data-removeondestroy",""),i.append(a),a.track}function CT(i,e){let t=Array.prototype.find.call(i.querySelectorAll("track"),s=>s.track===e);t==null||t.remove()}function il(i,e,t){var s;return(s=Array.from(i.querySelectorAll("track")).find(r=>r.track.label===e&&r.track.kind===t))==null?void 0:s.track}async function wT(i,e,t,s){let r=il(i,t,s);return r||(r=Vu(i,s,t),r.mode="hidden",await new Promise(n=>setTimeout(()=>n(void 0),0))),r.mode!=="hidden"&&(r.mode="hidden"),[...e].sort((n,a)=>mg(a)-mg(n)).forEach(n=>{var a,o;let l=n.value,d=mg(n);if("endTime"in n&&n.endTime!=null)r==null||r.addCue(new VTTCue(d,n.endTime,s==="chapters"?l:JSON.stringify(l!=null?l:null)));else{let u=Array.prototype.findIndex.call(r==null?void 0:r.cues,m=>m.startTime>=d),c=(a=r==null?void 0:r.cues)==null?void 0:a[u],h=c?c.startTime:Number.isFinite(i.duration)?i.duration:Number.MAX_SAFE_INTEGER,f=(o=r==null?void 0:r.cues)==null?void 0:o[u-1];f&&(f.endTime=d),r==null||r.addCue(new VTTCue(d,h,s==="chapters"?l:JSON.stringify(l!=null?l:null)))}}),i.textTracks.dispatchEvent(new Event("change",{bubbles:!0,composed:!0})),r}var Lg="cuepoints",MT=Object.freeze({label:Lg});async function Rg(i,e,t=MT){return wT(i,e,t.label,"metadata")}var yg=i=>({time:i.startTime,value:JSON.parse(i.text)});function PT(i,e={label:Lg}){let t=il(i,e.label,"metadata");return t!=null&&t.cues?Array.from(t.cues,s=>yg(s)):[]}function xg(i,e={label:Lg}){var t,s;let r=il(i,e.label,"metadata");if(!((t=r==null?void 0:r.activeCues)!=null&&t.length))return;if(r.activeCues.length===1)return yg(r.activeCues[0]);let{currentTime:n}=i,a=Array.prototype.find.call((s=r.activeCues)!=null?s:[],({startTime:o,endTime:l})=>o<=n&&l>n);return yg(a||r.activeCues[0])}async function jC(i,e=MT){return new Promise(t=>{mt(i,"loadstart",async()=>{let s=await Rg(i,[],e);mt(i,"cuechange",()=>{let r=xg(i);if(r){let n=new CustomEvent("cuepointchange",{composed:!0,bubbles:!0,detail:r});i.dispatchEvent(n)}},{},s),t(s)})})}var kg="chapters",OT=Object.freeze({label:kg}),bg=i=>({startTime:i.startTime,endTime:i.endTime,value:i.text});async function Dg(i,e,t=OT){return wT(i,e,t.label,"chapters")}function NT(i,e={label:kg}){var t;let s=il(i,e.label,"chapters");return(t=s==null?void 0:s.cues)!=null&&t.length?Array.from(s.cues,r=>bg(r)):[]}function Cg(i,e={label:kg}){var t,s;let r=il(i,e.label,"chapters");if(!((t=r==null?void 0:r.activeCues)!=null&&t.length))return;if(r.activeCues.length===1)return bg(r.activeCues[0]);let{currentTime:n}=i,a=Array.prototype.find.call((s=r.activeCues)!=null?s:[],({startTime:o,endTime:l})=>o<=n&&l>n);return bg(a||r.activeCues[0])}async function zC(i,e=OT){return new Promise(t=>{mt(i,"loadstart",async()=>{let s=await Dg(i,[],e);mt(i,"cuechange",()=>{let r=Cg(i);if(r){let n=new CustomEvent("chapterchange",{composed:!0,bubbles:!0,detail:r});i.dispatchEvent(n)}},{},s),t(s)})})}function UT(i,e){if(e){let t=e.playingDate;if(t!=null)return new Date(t.getTime()-i.currentTime*1e3)}return typeof i.getStartDate=="function"?i.getStartDate():new Date(NaN)}function FT(i,e){if(e&&e.playingDate)return e.playingDate;if(typeof i.getStartDate=="function"){let t=i.getStartDate();return new Date(t.getTime()+i.currentTime*1e3)}return new Date(NaN)}var oa={VIDEO:"v",THUMBNAIL:"t",STORYBOARD:"s",DRM:"d"},QC=i=>{if(i===Ue.VIDEO)return oa.VIDEO;if(i===Ue.DRM)return oa.DRM},XC=(i,e)=>{var t,s;let r=tl(i),n=`${r}Token`;return(t=e.tokens)!=null&&t[r]?(s=e.tokens)==null?void 0:s[r]:Sg(n,e)?e[n]:void 0},$u=(i,e,t,s,r=!1,n=!(a=>(a=globalThis.navigator)==null?void 0:a.onLine)())=>{var a,o;if(n){let v=te("Your device appears to be offline",r),b,y=z.MEDIA_ERR_NETWORK,T=new z(v,y,!1,b);return T.errorCategory=e,T.muxCode=ne.NETWORK_OFFLINE,T.data=i,T}let l="status"in i?i.status:i.code,d=Date.now(),u=z.MEDIA_ERR_NETWORK;if(l===200)return;let c=tl(e),h=XC(e,t),f=QC(e),[m]=Gu((a=t.playbackId)!=null?a:"");if(!l||!m)return;let p=dr(h);if(h&&!p){let v=te("The {tokenNamePrefix}-token provided is invalid or malformed.",r).format({tokenNamePrefix:c}),b=te("Compact JWT string: {token}",r).format({token:h}),y=new z(v,u,!0,b);return y.errorCategory=e,y.muxCode=ne.NETWORK_TOKEN_MALFORMED,y.data=i,y}if(l>=500){let v=new z("",u,s!=null?s:!0);return v.errorCategory=e,v.muxCode=ne.NETWORK_UNKNOWN_ERROR,v}if(l===403)if(p){if(NC(p,d)){let v={timeStyle:"medium",dateStyle:"medium"},b=te("The video\u2019s secured {tokenNamePrefix}-token has expired.",r).format({tokenNamePrefix:c}),y=te("Expired at: {expiredDate}. Current time: {currentDate}.",r).format({expiredDate:new Intl.DateTimeFormat("en",v).format((o=p.exp)!=null?o:0*1e3),currentDate:new Intl.DateTimeFormat("en",v).format(d)}),T=new z(b,u,!0,y);return T.errorCategory=e,T.muxCode=ne.NETWORK_TOKEN_EXPIRED,T.data=i,T}if(UC(p,m)){let v=te("The video\u2019s playback ID does not match the one encoded in the {tokenNamePrefix}-token.",r).format({tokenNamePrefix:c}),b=te("Specified playback ID: {playbackId} and the playback ID encoded in the {tokenNamePrefix}-token: {tokenPlaybackId}",r).format({tokenNamePrefix:c,playbackId:m,tokenPlaybackId:p.sub}),y=new z(v,u,!0,b);return y.errorCategory=e,y.muxCode=ne.NETWORK_TOKEN_SUB_MISMATCH,y.data=i,y}if(FC(p,f)){let v=te("The {tokenNamePrefix}-token is formatted with incorrect information.",r).format({tokenNamePrefix:c}),b=te("The {tokenNamePrefix}-token has no aud value. aud value should be {expectedAud}.",r).format({tokenNamePrefix:c,expectedAud:f}),y=new z(v,u,!0,b);return y.errorCategory=e,y.muxCode=ne.NETWORK_TOKEN_AUD_MISSING,y.data=i,y}if(BC(p,f)){let v=te("The {tokenNamePrefix}-token is formatted with incorrect information.",r).format({tokenNamePrefix:c}),b=te("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.",r).format({tokenNamePrefix:c,expectedAud:f,aud:p.aud}),y=new z(v,u,!0,b);return y.errorCategory=e,y.muxCode=ne.NETWORK_TOKEN_AUD_MISMATCH,y.data=i,y}}else{let v=te("Authorization error trying to access this {category} URL. If this is a signed URL, you might need to provide a {tokenNamePrefix}-token.",r).format({tokenNamePrefix:c,category:e}),b=te("Specified playback ID: {playbackId}",r).format({playbackId:m}),y=new z(v,u,s!=null?s:!0,b);return y.errorCategory=e,y.muxCode=ne.NETWORK_TOKEN_MISSING,y.data=i,y}if(l===412){let v=te("This playback-id may belong to a live stream that is not currently active or an asset that is not ready.",r),b=te("Specified playback ID: {playbackId}",r).format({playbackId:m}),y=new z(v,u,s!=null?s:!0,b);return y.errorCategory=e,y.muxCode=ne.NETWORK_NOT_READY,y.streamType=t.streamType===we.LIVE?"live":t.streamType===we.ON_DEMAND?"on-demand":"unknown",y.data=i,y}if(l===404){let v=te("This URL or playback-id does not exist. You may have used an Asset ID or an ID from a different resource.",r),b=te("Specified playback ID: {playbackId}",r).format({playbackId:m}),y=new z(v,u,s!=null?s:!0,b);return y.errorCategory=e,y.muxCode=ne.NETWORK_NOT_FOUND,y.data=i,y}if(l===400){let v=te("The URL or playback-id was invalid. You may have used an invalid value as a playback-id."),b=te("Specified playback ID: {playbackId}",r).format({playbackId:m}),y=new z(v,u,s!=null?s:!0,b);return y.errorCategory=e,y.muxCode=ne.NETWORK_INVALID_URL,y.data=i,y}let g=new z("",u,s!=null?s:!0);return g.errorCategory=e,g.muxCode=ne.NETWORK_UNKNOWN_ERROR,g.data=i,g},bT=_e.DefaultConfig.capLevelController,ZC={"720p":921600,"1080p":2073600,"1440p":4194304,"2160p":8294400};function JC(i){let e=i.toLowerCase().trim();return ZC[e]}var Tg=class el extends bT{constructor(e){super(e)}static setMaxAutoResolution(e,t){t?el.maxAutoResolution.set(e,t):el.maxAutoResolution.delete(e)}getMaxAutoResolution(){var e;let t=this.hls;return(e=el.maxAutoResolution.get(t))!=null?e:void 0}get levels(){var e;return(e=this.hls.levels)!=null?e:[]}getValidLevels(e){return this.levels.filter((t,s)=>this.isLevelAllowed(t)&&s<=e)}getMaxLevelCapped(e){let t=this.getValidLevels(e),s=this.getMaxAutoResolution();if(!s)return super.getMaxLevel(e);let r=JC(s);if(!r)return super.getMaxLevel(e);let n=t.filter(l=>l.width*l.height<=r),a=n.findIndex(l=>l.width*l.height===r);if(a!==-1){let l=n[a];return t.findIndex(d=>d===l)}if(n.length===0)return 0;let o=n[n.length-1];return t.findIndex(l=>l===o)}getMaxLevel(e){if(this.getMaxAutoResolution()!==void 0)return this.getMaxLevelCapped(e);let t=super.getMaxLevel(e),s=this.getValidLevels(e);if(!s[t])return t;let r=Math.min(s[t].width,s[t].height),n=el.minMaxResolution;return r>=n?t:bT.getMaxLevelByMediaSize(s,n*(16/9),n)}};Tg.minMaxResolution=720,Tg.maxAutoResolution=new WeakMap;var ew=Tg,_g=ew,tw="com.apple.fps.1_0",iw="application/vnd.apple.mpegurl",sw=({mediaEl:i,getAppCertificate:e,getLicenseKey:t,saveAndDispatchError:s,drmTypeCb:r})=>{if(!window.WebKitMediaKeys||!("onwebkitneedkey"in i)){console.error("No WebKitMediaKeys. FairPlay may not be supported");let h=te("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser."),f=new z(h,z.MEDIA_ERR_ENCRYPTED,!0);return f.errorCategory=Ue.DRM,f.muxCode=ne.ENCRYPTED_CDM_ERROR,s(i,f),()=>{}}let n=i,a=e(),o=null,l=h=>{(async()=>{try{n.webkitKeys||d();let f=await a;if(h.initData===null||f==null)return;let m=rw(h.initData,f);u(m)}catch(f){console.error("Could not start encrypted playback due to exception",f),s(n,f)}})()},d=()=>{try{let h=new WebKitMediaKeys(tw);n.webkitSetMediaKeys(h),r()}catch{let h="Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser.",f=new z(h,z.MEDIA_ERR_ENCRYPTED,!0);throw f.errorCategory=Ue.DRM,f.muxCode=ne.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM,f}},u=h=>{let f=n.webkitKeys.createSession(iw,h),m=async v=>{try{let b=v.message,y=await t(b);f.update(y)}catch(b){console.error("Error on FairPlay session message",b),s(i,b)}},p=v=>{let b=v.target.error;if(!b)return;console.error(`Internal Webkit Key Session Error - sysCode: ${b.systemCode} code: ${b.code}`);let y=te("The DRM Content Decryption Module system had an internal failure. Try reloading the page, updating your browser, or playing in another browser."),T=new z(y,z.MEDIA_ERR_ENCRYPTED,!0);T.errorCategory=Ue.DRM,T.muxCode=ne.ENCRYPTED_CDM_ERROR,s(i,T)},g=()=>{f.removeEventListener("webkitkeymessage",m),f.removeEventListener("webkitkeyerror",p),i.removeEventListener("teardown",g),"webkitCurrentPlaybackTargetIsWireless"in i&&i.removeEventListener("webkitcurrentplaybacktargetiswirelesschanged",g),o=null;try{f.close()}catch{}};"webkitCurrentPlaybackTargetIsWireless"in i&&i.addEventListener("webkitcurrentplaybacktargetiswirelesschanged",g,{once:!0}),f.addEventListener("webkitkeymessage",m),f.addEventListener("webkitkeyerror",p),i.addEventListener("teardown",g),o=g},c=()=>{i.removeEventListener("webkitneedkey",l),i.removeEventListener("teardown",c),o==null||o();try{n.webkitSetMediaKeys(null)}catch{}};return i.addEventListener("webkitneedkey",l),i.addEventListener("teardown",c,{once:!0}),c},rw=(i,e)=>{let t=aw(nw(i)),s=new Uint8Array(i),r=new Uint8Array(t),n=new Uint8Array(e),a=s.byteLength+4+n.byteLength+4+r.byteLength,o=new Uint8Array(a),l=0,d=c=>{o.set(c,l),l+=c.byteLength},u=c=>{let h=new DataView(o.buffer),f=c.byteLength;h.setUint32(l,f,!0),l+=4,d(c)};return d(s),u(r),u(n),o},nw=i=>new TextDecoder("utf-16le").decode(i).replace("skd://","").slice(1);function aw(i){let e=new ArrayBuffer(i.length*2),t=new DataView(e);for(let s=0;s<i.length;s++)t.setUint16(s*2,i.charCodeAt(s),!0);return e}var ow=({mediaEl:i,getAppCertificate:e,getLicenseKey:t,saveAndDispatchError:s,drmTypeCb:r,fallbackToWebkitFairplay:n})=>{let a=null,o=async c=>{try{let h=c.initDataType;if(h!=="skd"){console.error(`Received unexpected initialization data type "${h}"`);return}i.mediaKeys||await l(h);let f=c.initData;if(f==null){console.error(`Could not start encrypted playback due to missing initData in ${c.type} event`);return}await d(h,f)}catch(h){s(i,h);return}},l=async c=>{let h=await navigator.requestMediaKeySystemAccess("com.apple.fps",[{initDataTypes:[c],videoCapabilities:[{contentType:"application/vnd.apple.mpegurl",robustness:""}],distinctiveIdentifier:"not-allowed",persistentState:"not-allowed",sessionTypes:["temporary"]}]).then(m=>(r(),m)).catch(()=>{let m=te("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser."),p=new z(m,z.MEDIA_ERR_ENCRYPTED,!0);p.errorCategory=Ue.DRM,p.muxCode=ne.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM,s(i,p)});if(!h)return;let f=await h.createMediaKeys();try{let m=await e();await f.setServerCertificate(m).catch(()=>{let p=te("Your server certificate failed when attempting to set it. This may be an issue with a no longer valid certificate."),g=new z(p,z.MEDIA_ERR_ENCRYPTED,!0);return g.errorCategory=Ue.DRM,g.muxCode=ne.ENCRYPTED_UPDATE_SERVER_CERT_FAILED,Promise.reject(g)})}catch(m){s(i,m);return}await i.setMediaKeys(f)},d=async(c,h)=>{let f=i.mediaKeys.createSession(),m=async v=>{let b=v.message,y=await t(b);try{await f.update(y)}catch{let T=te("Failed to update DRM license. This may be an issue with the player or your protected content."),A=new z(T,z.MEDIA_ERR_ENCRYPTED,!0);A.errorCategory=Ue.DRM,A.muxCode=ne.ENCRYPTED_UPDATE_LICENSE_FAILED,s(i,A)}},p=()=>{let v=b=>{let y;if(b==="internal-error"){let T=te("The DRM Content Decryption Module system had an internal failure. Try reloading the page, updating your browser, or playing in another browser.");y=new z(T,z.MEDIA_ERR_ENCRYPTED,!0),y.errorCategory=Ue.DRM,y.muxCode=ne.ENCRYPTED_CDM_ERROR}else if(b==="output-restricted"||b==="output-downscaled"){let T=te("DRM playback is being attempted in an environment that is not sufficiently secure. User may see black screen.");y=new z(T,z.MEDIA_ERR_ENCRYPTED,!1),y.errorCategory=Ue.DRM,y.muxCode=ne.ENCRYPTED_OUTPUT_RESTRICTED}y&&s(i,y)};f.keyStatuses.forEach(b=>v(b))};f.addEventListener("keystatuseschange",p),f.addEventListener("message",m);let g=async()=>{f.removeEventListener("keystatuseschange",p),f.removeEventListener("message",m),"webkitCurrentPlaybackTargetIsWireless"in i&&i.removeEventListener("webkitcurrentplaybacktargetiswirelesschanged",g),i.removeEventListener("teardown",g),await f.close().catch(v=>{console.warn("There was an error when closing EME session",v)}),a=null};"webkitCurrentPlaybackTargetIsWireless"in i&&i.addEventListener("webkitcurrentplaybacktargetiswirelesschanged",g,{once:!0}),i.addEventListener("teardown",g,{once:!0}),a=g,await f.generateRequest(c,h).catch(async v=>{if(v.name==="NotSupportedError"&&"webkitCurrentPlaybackTargetIsWireless"in i&&i.webkitCurrentPlaybackTargetIsWireless)console.warn("Failed to generate a DRM license request. Attempting to fallback to Webkit DRM"),n==null||n();else{let b=te("Failed to generate a DRM license request. This may be an issue with the player or your protected content."),y=new z(b,z.MEDIA_ERR_ENCRYPTED,!0);return y.errorCategory=Ue.DRM,y.muxCode=ne.ENCRYPTED_GENERATE_REQUEST_FAILED,console.error("Failed to generate license request",v),Promise.reject(y)}})},u=async()=>{i.removeEventListener("encrypted",o),i.removeEventListener("teardown",u),a&&await a(),await i.setMediaKeys(null).catch(()=>{})};return i.addEventListener("encrypted",o),i.addEventListener("teardown",u,{once:!0}),u},Fu={FAIRPLAY:"fairplay",PLAYREADY:"playready",WIDEVINE:"widevine"},lw=i=>{if(i.includes("fps"))return Fu.FAIRPLAY;if(i.includes("playready"))return Fu.PLAYREADY;if(i.includes("widevine"))return Fu.WIDEVINE},dw=(i,e)=>{let t=MC(i);if(!t)return Promise.reject(new Error("No media playlist URL found in multivariant playlist"));if(Eg(t)&&!e)return Promise.reject(new Error("masterPlaylistUrl is required to resolve relative media playlist URL"));let s;try{s=Ig(t,e)}catch(r){return Promise.reject(r)}return fetch(s).then(r=>r.status!==200?Promise.reject(r):r.text())},uw=i=>{let e=i.split(`
57
57
  `).filter(s=>s.startsWith("#EXT-X-SESSION-DATA"));if(!e.length)return{};let t={};for(let s of e){let r=hw(s),n=r["DATA-ID"];n&&(t[n]={...r})}return{sessionData:t}},cw=/([A-Z0-9-]+)="?(.*?)"?(?:,|$)/g;function hw(i){let e=[...i.matchAll(cw)];return Object.fromEntries(e.map(([,t,s])=>[t,s]))}var fw=i=>{var e,t,s;let r=i.split(`
58
- `),n=(t=((e=r.find(d=>d.startsWith("#EXT-X-PLAYLIST-TYPE")))!=null?e:"").split(":")[1])==null?void 0:t.trim(),a=xb(n),o=kb(n),l;if(a===we.LIVE){let d=r.find(u=>u.startsWith("#EXT-X-PART-INF"));if(d)l=+d.split(":")[1].split("=")[1]*2;else{let u=r.find(h=>h.startsWith("#EXT-X-TARGETDURATION")),c=(s=u==null?void 0:u.split(":"))==null?void 0:s[1];l=+(c!=null?c:6)*3}}return{streamType:a,targetLiveWindow:o,liveEdgeStartOffset:l}},mw=async(i,e)=>{if(e===Cs.MP4)return{streamType:we.ON_DEMAND,targetLiveWindow:Number.NaN,liveEdgeStartOffset:void 0,sessionData:void 0};if(e===Cs.M3U8){let t=await fetch(i);if(!t.ok)return Promise.reject(t);let s=await t.text(),r=await dw(s,t.url);return{...uw(s),...fw(r)}}return console.error(`Media type ${e} is an unrecognized or unsupported type for src ${i}.`),{streamType:void 0,targetLiveWindow:void 0,liveEdgeStartOffset:void 0,sessionData:void 0}},pw=async(i,e,t=Ku({src:i}))=>{var s,r,n,a;let{streamType:o,targetLiveWindow:l,liveEdgeStartOffset:d,sessionData:u}=await mw(i,t),c=u==null?void 0:u["com.apple.hls.chapters"];(c!=null&&c.URI||c!=null&&c.VALUE.toLocaleLowerCase().startsWith("http"))&&wg((s=c.URI)!=null?s:c.VALUE,e),((r=Xe.get(e))!=null?r:{}).liveEdgeStartOffset=d,((n=Xe.get(e))!=null?n:{}).targetLiveWindow=l,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((a=Xe.get(e))!=null?a:{}).streamType=o,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},wg=async(i,e)=>{var t,s;try{let r=await fetch(i);if(!r.ok)throw new Error(`Failed to fetch Mux metadata: ${r.status} ${r.statusText}`);let n=await r.json(),a={};if(!((t=n==null?void 0:n[0])!=null&&t.metadata))return;for(let l of n[0].metadata)l.key&&l.value&&(a[l.key]=l.value);((s=Xe.get(e))!=null?s:{}).metadata=a;let o=new CustomEvent("muxmetadata");e.dispatchEvent(o)}catch(r){console.error(r)}},gw=i=>{var e;let t=i.type,s=xb(t),r=kb(t),n,a=!!((e=i.partList)!=null&&e.length);return s===we.LIVE&&(n=a?i.partTarget*2:i.targetduration*3),{streamType:s,targetLiveWindow:r,liveEdgeStartOffset:n,lowLatency:a}},vw=(i,e,t)=>{var s,r,n,a,o,l,d,u;let{streamType:c,targetLiveWindow:h,liveEdgeStartOffset:f,lowLatency:m}=gw(i);if(c===we.LIVE){m?(t.config.backBufferLength=(s=t.userConfig.backBufferLength)!=null?s:4,t.config.maxFragLookUpTolerance=(r=t.userConfig.maxFragLookUpTolerance)!=null?r:.001,t.config.abrBandWidthUpFactor=(n=t.userConfig.abrBandWidthUpFactor)!=null?n:t.config.abrBandWidthFactor):t.config.backBufferLength=(a=t.userConfig.backBufferLength)!=null?a:8;let p=Object.freeze({get length(){return e.seekable.length},start(g){return e.seekable.start(g)},end(g){var v;return g>this.length||g<0||Number.isFinite(e.duration)?e.seekable.end(g):(v=t.liveSyncPosition)!=null?v:e.seekable.end(g)}});((o=Xe.get(e))!=null?o:{}).seekable=p}((l=Xe.get(e))!=null?l:{}).liveEdgeStartOffset=f,((d=Xe.get(e))!=null?d:{}).targetLiveWindow=h,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((u=Xe.get(e))!=null?u:{}).streamType=c,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},bb,_b,Bb=(_b=(bb=globalThis==null?void 0:globalThis.navigator)==null?void 0:bb.userAgent)!=null?_b:"",Ab,Sb,Ib,Ew=(Ib=(Sb=(Ab=globalThis==null?void 0:globalThis.navigator)==null?void 0:Ab.userAgentData)==null?void 0:Sb.platform)!=null?Ib:"",yw=Bb.toLowerCase().includes("android")||["x11","android"].some(i=>Ew.toLowerCase().includes(i)),Tw=i=>/^((?!chrome|android).)*safari/i.test(Bb)&&!!i.canPlayType("application/vnd.apple.mpegurl"),Xe=new WeakMap,ws="mux.com",Lb,Rb,$b=(Rb=(Lb=_e).isSupported)==null?void 0:Rb.call(Lb),bw=i=>yw||!Tw(i),Wu=()=>{if(typeof window!="undefined")return Hd.utils.now()},_w=Hd.utils.generateUUID,sl=({playbackId:i,customDomain:e=ws,maxResolution:t,minResolution:s,renditionOrder:r,programStartTime:n,programEndTime:a,assetStartTime:o,assetEndTime:l,playbackToken:d,tokens:{playback:u=d}={},extraSourceParams:c={}}={})=>{if(!i)return;let[h,f=""]=Gu(i),m=new URL(`https://stream.${e}/${h}.m3u8${f}`);return u||m.searchParams.has("token")?(m.searchParams.forEach((p,g)=>{g!="token"&&m.searchParams.delete(g)}),u&&m.searchParams.set("token",u)):(t&&m.searchParams.set("max_resolution",t),s&&(m.searchParams.set("min_resolution",s),t&&+t.slice(0,-1)<+s.slice(0,-1)&&console.error("minResolution must be <= maxResolution","minResolution",s,"maxResolution",t)),r&&m.searchParams.set("rendition_order",r),n&&m.searchParams.set("program_start_time",`${n}`),a&&m.searchParams.set("program_end_time",`${a}`),o&&m.searchParams.set("asset_start_time",`${o}`),l&&m.searchParams.set("asset_end_time",`${l}`),Object.entries(c).forEach(([p,g])=>{g!=null&&m.searchParams.set(p,g)})),m.toString()},qu=i=>{if(!i)return;let[e]=i.split("?");return e||void 0},Yu=i=>{if(!i||!i.startsWith("https://stream."))return;let[e]=new URL(i).pathname.slice(1).split(/\.m3u8|\//);return e||void 0},Aw=i=>{var e,t,s;return(e=i==null?void 0:i.metadata)!=null&&e.video_id?i.metadata.video_id:zb(i)&&(s=(t=qu(i.playbackId))!=null?t:Yu(i.src))!=null?s:i.src},Mg=i=>{var e;return(e=Xe.get(i))==null?void 0:e.error},Hb=i=>{var e;return(e=Xe.get(i))==null?void 0:e.metadata},Hu=i=>{var e,t;return(t=(e=Xe.get(i))==null?void 0:e.streamType)!=null?t:we.UNKNOWN},Gb=i=>{var e,t;return(t=(e=Xe.get(i))==null?void 0:e.targetLiveWindow)!=null?t:Number.NaN},ju=i=>{var e,t;return(t=(e=Xe.get(i))==null?void 0:e.seekable)!=null?t:i.seekable},Kb=i=>{var e;let t=(e=Xe.get(i))==null?void 0:e.liveEdgeStartOffset;if(typeof t!="number")return Number.NaN;let s=ju(i);return s.length?s.end(s.length-1)-t:Number.NaN},Vb=i=>{var e;return(e=Xe.get(i))==null?void 0:e.coreReference},Pg=.034,Sw=(i,e,t=Pg)=>Math.abs(i-e)<=t,Wb=(i,e,t=Pg)=>i>e||Sw(i,e,t),Iw=(i,e=Pg)=>i.paused&&Wb(i.currentTime,i.duration,e),qb=(i,e)=>{var t,s,r;if(!e||!i.buffered.length)return;if(i.readyState>2)return!1;let n=e.currentLevel>=0?(s=(t=e.levels)==null?void 0:t[e.currentLevel])==null?void 0:s.details:(r=e.levels.find(c=>!!c.details))==null?void 0:r.details;if(!n||n.live)return;let{fragments:a}=n;if(!(a!=null&&a.length))return;if(i.currentTime<i.duration-(n.targetduration+.5))return!1;let o=a[a.length-1];if(i.currentTime<=o.start)return!1;let l=o.start+o.duration/2,d=i.buffered.start(i.buffered.length-1),u=i.buffered.end(i.buffered.length-1);return l>d&&l<u},Og=(i,e)=>i.ended||i.loop?i.ended:e&&qb(i,e)?!0:Iw(i),Ng=(i,e,t)=>{Ug(e,t,i);let{metadata:s={}}=i,{view_session_id:r=_w()}=s,n=Aw(i);s.view_session_id=r,s.video_id=n,i.metadata=s;let a=h=>{var f;(f=e.mux)==null||f.emit("hb",{view_drm_type:h})};i.drmTypeCb=a,i.fallbackToWebkitFairplay=async()=>{var h;let f=!e.paused,m=e.currentTime;i.useWebkitFairplay=!0;let p=i.muxDataKeepSession;i.muxDataKeepSession=!0;let g=(h=Xe.get(e))==null?void 0:h.coreReference;Ng(i,e,g),i.muxDataKeepSession=p,i.useWebkitFairplay=!1,f&&await e.play().then(()=>{e.currentTime=m}).catch(()=>{}),e.currentTime=m},Xe.set(e,{retryCount:0});let o=Lw(i,e),l=KC(i,e,o);i!=null&&i.muxDataKeepSession&&e!=null&&e.mux&&!e.mux.deleted?o&&e.mux.addHLSJS({hlsjs:o,Hls:o?_e:void 0}):Mw(i,e,o),Pw(i,e,o),jC(e),zC(e);let d=GC(i,e,o);VC(i,e,o),WC(i,e,o);let u={engine:o,setAutoplay:d,setPreload:l},c=Xe.get(e);return c&&(c.coreReference=u),u},Ug=(i,e,t)=>{let s=e==null?void 0:e.engine;i!=null&&i.mux&&!i.mux.deleted&&(t!=null&&t.muxDataKeepSession?s&&i.mux.removeHLSJS():(i.mux.destroy(),delete i.mux)),s&&(s.detachMedia(),s.destroy()),i&&(i.hasAttribute("src")&&(i.removeAttribute("src"),i.load()),i.removeEventListener("error",Xb),i.removeEventListener("error",Ag),i.removeEventListener("durationchange",Qb),Xe.delete(i),i.dispatchEvent(new Event("teardown")))};function Yb(i,e){var t;let s=Ku(i);if(s!==Cs.M3U8)return!0;let r=!s||((t=e.canPlayType(s))!=null?t:!0),{preferPlayback:n}=i,a=n===gi.MSE,o=n===gi.NATIVE,l=$b&&(a||bw(e));return r&&(o||!l)}var Lw=(i,e)=>{let{debug:t,streamType:s,startTime:r=-1,metadata:n,preferCmcd:a,_hlsConfig:o={},maxAutoResolution:l,initialBandwidthEstimateKbps:d}=i,u=Ku(i)===Cs.M3U8,c=Yb(i,e);if(u&&!c&&$b){let h={backBufferLength:30,renderTextTracksNatively:!1,liveDurationInfinity:!0,capLevelOnFPSDrop:!0,...d!=null?{abrEwmaDefaultEstimate:d*1e3}:{}},f=Rw(s),m=xw(i),p=[Jo.QUERY,Jo.HEADER].includes(a)?{useHeaders:a===Jo.HEADER,sessionId:n==null?void 0:n.view_session_id,contentId:n==null?void 0:n.video_id}:void 0,g=ww(i,o),v=new _e({debug:t,startPosition:r,cmcd:p,xhrSetup:(T,y)=>{var b,A;if(a&&a!==Jo.QUERY)return;let R=Ig(y);if(!R.searchParams.has("CMCD"))return;let I=((A=(b=R.searchParams.get("CMCD"))==null?void 0:b.split(","))!=null?A:[]).filter(x=>x.startsWith("sid")||x.startsWith("cid")).join(",");R.searchParams.set("CMCD",I),T.open("GET",R)},...h,...g,...f,...m,...o});return g.capLevelController===_g&&l!==void 0&&_g.setMaxAutoResolution(v,l),v.on(_e.Events.MANIFEST_PARSED,async function(T,y){var b,A;let R=(b=y.sessionData)==null?void 0:b["com.apple.hls.chapters"];(R!=null&&R.URI||R!=null&&R.VALUE.toLocaleLowerCase().startsWith("http"))&&wg((A=R==null?void 0:R.URI)!=null?A:R==null?void 0:R.VALUE,e)}),v}},Rw=i=>i===we.LIVE?{backBufferLength:8}:{},xw=i=>{let{tokens:{drm:e}={},playbackId:t,drmTypeCb:s}=i,r=qu(t);return!e||!r?{}:{emeEnabled:!0,drmSystems:{"com.apple.fps":{licenseUrl:Bu(i,"fairplay"),serverCertificateUrl:jb(i,"fairplay")},"com.widevine.alpha":{licenseUrl:Bu(i,"widevine")},"com.microsoft.playready":{licenseUrl:Bu(i,"playready")}},requestMediaKeySystemAccessFunc:(n,a)=>(n==="com.widevine.alpha"&&(a=[...a.map(o=>{var l;let d=(l=o.videoCapabilities)==null?void 0:l.map(u=>({...u,robustness:"HW_SECURE_ALL"}));return{...o,videoCapabilities:d}}),...a]),navigator.requestMediaKeySystemAccess(n,a).then(o=>{let l=lw(n);return s==null||s(l),o}))}},kw=async i=>{let e=await fetch(i);return e.status!==200?Promise.reject(e):await e.arrayBuffer()},Dw=async(i,e)=>{let t=await fetch(e,{method:"POST",headers:{"Content-type":"application/octet-stream"},body:i});if(t.status!==200)return Promise.reject(t);let s=await t.arrayBuffer();return new Uint8Array(s)},Cw=(i,e)=>{let t={mediaEl:e,getAppCertificate:()=>kw(jb(i,"fairplay")).catch(s=>{if(s instanceof Response){let r=$u(s,Ue.DRM,i);return console.error("mediaError",r==null?void 0:r.message,r==null?void 0:r.context),r?Promise.reject(r):Promise.reject(new Error("Unexpected error in app cert request"))}return Promise.reject(s)}),getLicenseKey:s=>Dw(s,Bu(i,"fairplay")).catch(r=>{if(r instanceof Response){let n=$u(r,Ue.DRM,i);return console.error("mediaError",n==null?void 0:n.message,n==null?void 0:n.context),n?Promise.reject(n):Promise.reject(new Error("Unexpected error in license key request"))}return Promise.reject(r)}),saveAndDispatchError:lr,drmTypeCb:()=>{var s;(s=i.drmTypeCb)==null||s.call(i,Fu.FAIRPLAY)}};if(i.useWebkitFairplay)sw(t);else{let s={fallbackToWebkitFairplay:async()=>{var n;await r(),(n=i.fallbackToWebkitFairplay)==null||n.call(i)},...t},r=ow(s)}},Bu=({playbackId:i,tokens:{drm:e}={},customDomain:t=ws},s)=>{let r=qu(i);return`https://license.${t.toLocaleLowerCase().endsWith(ws)?t:ws}/license/${s}/${r}?token=${e}`},jb=({playbackId:i,tokens:{drm:e}={},customDomain:t=ws},s)=>{let r=qu(i);return`https://license.${t.toLocaleLowerCase().endsWith(ws)?t:ws}/appcert/${s}/${r}?token=${e}`},zb=({playbackId:i,src:e,customDomain:t})=>{if(i)return!0;if(typeof e!="string")return!1;let s=window==null?void 0:window.location.href,r=new URL(e,s).hostname.toLocaleLowerCase();return r.includes(ws)||!!t&&r.includes(t.toLocaleLowerCase())},ww=(i,e)=>{let t={};return t.capLevelToPlayerSize=i.capRenditionToPlayerSize,t.capLevelToPlayerSize==null?(t.capLevelController=_g,t.capLevelToPlayerSize=!0):t.capLevelController=Qo,t},Mw=(i,e,t)=>{var s;let{envKey:r,disableTracking:n,muxDataSDK:a=Hd,muxDataSDKOptions:o={}}=i,l=zb(i);if(!n&&(r||l)){let{playerInitTime:d,playerSoftwareName:u,playerSoftwareVersion:c,beaconCollectionDomain:h,debug:f,disableCookies:m}=i,p={...i.metadata,video_title:((s=i==null?void 0:i.metadata)==null?void 0:s.video_title)||void 0},g=v=>typeof v.player_error_code=="string"?!1:typeof i.errorTranslator=="function"?i.errorTranslator(v):v;a.monitor(e,{debug:f,beaconCollectionDomain:h,hlsjs:t,Hls:t?_e:void 0,automaticErrorTracking:!1,errorTranslator:g,disableCookies:m,...o,data:{...r?{env_key:r}:{},player_software_name:u,player_software:u,player_software_version:c,player_init_time:d,...p}})}},Pw=(i,e,t)=>{var s,r;let n=Yb(i,e),{src:a,customDomain:o=ws}=i,l=()=>{e.ended||i.disablePseudoEnded||!Og(e,t)||(qb(e,t)?e.currentTime=e.buffered.end(e.buffered.length-1):e.dispatchEvent(new Event("ended")))},d,u,c=()=>{let h=ju(e),f,m;h.length>0&&(f=h.start(0),m=h.end(0)),(u!==m||d!==f)&&e.dispatchEvent(new CustomEvent("seekablechange",{composed:!0})),d=f,u=m};if(mt(e,"durationchange",c),e&&n){let h=Ku(i);if(typeof a=="string"){if(a.endsWith(".mp4")&&a.includes(o)){let p=Yu(a),g=new URL(`https://stream.${o}/${p}/metadata.json`);wg(g.toString(),e)}let f=()=>{if(Hu(e)!==we.LIVE||Number.isFinite(e.duration))return;let p=setInterval(c,1e3);e.addEventListener("teardown",()=>{clearInterval(p)},{once:!0}),mt(e,"durationchange",()=>{Number.isFinite(e.duration)&&clearInterval(p)})},m=async()=>pw(a,e,h).then(f).catch(p=>{if(p instanceof Response){let g=$u(p,Ue.VIDEO,i);if(g){lr(e,g);return}}else p instanceof Error});if(e.preload==="none"){let p=()=>{m(),e.removeEventListener("loadedmetadata",g)},g=()=>{m(),e.removeEventListener("play",p)};mt(e,"play",p,{once:!0}),mt(e,"loadedmetadata",g,{once:!0})}else m();(s=i.tokens)!=null&&s.drm?Cw(i,e):mt(e,"encrypted",()=>{let p=te("Attempting to play DRM-protected content without providing a DRM token."),g=new z(p,z.MEDIA_ERR_ENCRYPTED,!0);g.errorCategory=Ue.DRM,g.muxCode=ne.ENCRYPTED_MISSING_TOKEN,lr(e,g)},{once:!0}),e.setAttribute("src",a),i.startTime&&(((r=Xe.get(e))!=null?r:{}).startTime=i.startTime,e.addEventListener("durationchange",Qb,{once:!0}))}else e.removeAttribute("src");e.addEventListener("error",Xb),e.addEventListener("error",Ag),e.addEventListener("emptied",()=>{e.querySelectorAll("track[data-removeondestroy]").forEach(f=>{f.remove()})},{once:!0}),mt(e,"pause",l),mt(e,"seeked",l),mt(e,"play",()=>{e.ended||Wb(e.currentTime,e.duration)&&(e.currentTime=e.seekable.length?e.seekable.start(0):0)})}else t&&a?(t.once(_e.Events.LEVEL_LOADED,(h,f)=>{vw(f.details,e,t),c(),Hu(e)===we.LIVE&&!Number.isFinite(e.duration)&&(t.on(_e.Events.LEVEL_UPDATED,c),mt(e,"durationchange",()=>{Number.isFinite(e.duration)&&t.off(_e.Events.LEVELS_UPDATED,c)}))}),t.on(_e.Events.ERROR,(h,f)=>{var m,p;let g=Ow(f,i);if(g.muxCode===ne.NETWORK_NOT_READY){let v=(m=Xe.get(e))!=null?m:{},T=(p=v.retryCount)!=null?p:0;if(T<6){let y=T===0?5e3:6e4,b=new z(`Retrying in ${y/1e3} seconds...`,g.code,g.fatal);Object.assign(b,g),lr(e,b);let A=setTimeout(()=>{v.retryCount=T+1,f.details==="manifestLoadError"&&f.url&&t.loadSource(f.url)},y);e.addEventListener("teardown",()=>clearTimeout(A),{once:!0});return}else{v.retryCount=0;let y=new z('Try again later or <a href="#" onclick="window.location.reload(); return false;" style="color: #4a90e2;">click here to retry</a>',g.code,g.fatal);Object.assign(y,g),lr(e,y);return}}lr(e,g)}),t.on(_e.Events.MANIFEST_LOADED,()=>{let h=Xe.get(e);h&&h.error&&(h.error=null,h.retryCount=0,e.dispatchEvent(new Event("emptied")),e.dispatchEvent(new Event("loadstart")))}),e.addEventListener("error",Ag),mt(e,"waiting",l),qC(i,t),YC(e,t),t.attachMedia(e)):console.error("It looks like the video you're trying to play will not work on this system! If possible, try upgrading to the newest versions of your browser or software.")};function Qb(i){var e;let t=i.target,s=(e=Xe.get(t))==null?void 0:e.startTime;if(s&&CC(t.seekable,t.duration,s)){let r=t.preload==="auto";r&&(t.preload="none"),t.currentTime=s,r&&(t.preload="auto")}}async function Xb(i){if(!i.isTrusted)return;i.stopImmediatePropagation();let e=i.target;if(!(e!=null&&e.error))return;let{message:t,code:s}=e.error,r=new z(t,s);if(e.src&&s===z.MEDIA_ERR_SRC_NOT_SUPPORTED&&e.readyState===HTMLMediaElement.HAVE_NOTHING){setTimeout(()=>{var n;let a=(n=Mg(e))!=null?n:e.error;(a==null?void 0:a.code)===z.MEDIA_ERR_SRC_NOT_SUPPORTED&&lr(e,r)},500);return}if(e.src&&(s!==z.MEDIA_ERR_DECODE||s!==void 0))try{let{status:n}=await fetch(e.src);r.data={response:{code:n}}}catch{}lr(e,r)}function lr(i,e){var t;e.fatal&&(((t=Xe.get(i))!=null?t:{}).error=e,i.dispatchEvent(new CustomEvent("error",{detail:e})))}function Ag(i){var e,t;if(!(i instanceof CustomEvent)||!(i.detail instanceof z))return;let s=i.target,r=i.detail;!r||!r.fatal||(((e=Xe.get(s))!=null?e:{}).error=r,(t=s.mux)==null||t.emit("error",{player_error_code:r.code,player_error_message:r.message,player_error_context:r.context}))}var Ow=(i,e)=>{var t,s,r;i.fatal?console.error("getErrorFromHlsErrorData()",i):e.debug&&console.warn("getErrorFromHlsErrorData() (non-fatal)",i);let n={[_e.ErrorTypes.NETWORK_ERROR]:z.MEDIA_ERR_NETWORK,[_e.ErrorTypes.MEDIA_ERROR]:z.MEDIA_ERR_DECODE,[_e.ErrorTypes.KEY_SYSTEM_ERROR]:z.MEDIA_ERR_ENCRYPTED},a=u=>[_e.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,_e.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED].includes(u.details)?z.MEDIA_ERR_NETWORK:n[u.type],o=u=>{if(u.type===_e.ErrorTypes.KEY_SYSTEM_ERROR)return Ue.DRM;if(u.type===_e.ErrorTypes.NETWORK_ERROR)return Ue.VIDEO},l,d=a(i);if(d===z.MEDIA_ERR_NETWORK&&i.response){let u=(t=o(i))!=null?t:Ue.VIDEO;l=(s=$u(i.response,u,e,i.fatal))!=null?s:new z("",d,i.fatal)}else if(d===z.MEDIA_ERR_ENCRYPTED)if(i.details===_e.ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE){let u=te("Attempting to play DRM-protected content without providing a DRM token.");l=new z(u,z.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Ue.DRM,l.muxCode=ne.ENCRYPTED_MISSING_TOKEN}else if(i.details===_e.ErrorDetails.KEY_SYSTEM_NO_ACCESS){let u=te("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser.");l=new z(u,z.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Ue.DRM,l.muxCode=ne.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM}else if(i.details===_e.ErrorDetails.KEY_SYSTEM_NO_SESSION){let u=te("Failed to generate a DRM license request. This may be an issue with the player or your protected content.");l=new z(u,z.MEDIA_ERR_ENCRYPTED,!0),l.errorCategory=Ue.DRM,l.muxCode=ne.ENCRYPTED_GENERATE_REQUEST_FAILED}else if(i.details===_e.ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED){let u=te("Failed to update DRM license. This may be an issue with the player or your protected content.");l=new z(u,z.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Ue.DRM,l.muxCode=ne.ENCRYPTED_UPDATE_LICENSE_FAILED}else if(i.details===_e.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED){let u=te("Your server certificate failed when attempting to set it. This may be an issue with a no longer valid certificate.");l=new z(u,z.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Ue.DRM,l.muxCode=ne.ENCRYPTED_UPDATE_SERVER_CERT_FAILED}else if(i.details===_e.ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR){let u=te("The DRM Content Decryption Module system had an internal failure. Try reloading the page, updating your browser, or playing in another browser.");l=new z(u,z.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Ue.DRM,l.muxCode=ne.ENCRYPTED_CDM_ERROR}else if(i.details===_e.ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED){let u=te("DRM playback is being attempted in an environment that is not sufficiently secure. User may see black screen.");l=new z(u,z.MEDIA_ERR_ENCRYPTED,!1),l.errorCategory=Ue.DRM,l.muxCode=ne.ENCRYPTED_OUTPUT_RESTRICTED}else l=new z(i.error.message,z.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Ue.DRM,l.muxCode=ne.ENCRYPTED_ERROR;else l=new z("",d,i.fatal);return l.context||(l.context=`${i.url?`url: ${i.url}
58
+ `),n=(t=((e=r.find(d=>d.startsWith("#EXT-X-PLAYLIST-TYPE")))!=null?e:"").split(":")[1])==null?void 0:t.trim(),a=xT(n),o=kT(n),l;if(a===we.LIVE){let d=r.find(u=>u.startsWith("#EXT-X-PART-INF"));if(d)l=+d.split(":")[1].split("=")[1]*2;else{let u=r.find(h=>h.startsWith("#EXT-X-TARGETDURATION")),c=(s=u==null?void 0:u.split(":"))==null?void 0:s[1];l=+(c!=null?c:6)*3}}return{streamType:a,targetLiveWindow:o,liveEdgeStartOffset:l}},mw=async(i,e)=>{if(e===Cs.MP4)return{streamType:we.ON_DEMAND,targetLiveWindow:Number.NaN,liveEdgeStartOffset:void 0,sessionData:void 0};if(e===Cs.M3U8){let t=await fetch(i);if(!t.ok)return Promise.reject(t);let s=await t.text(),r=await dw(s,t.url);return{...uw(s),...fw(r)}}return console.error(`Media type ${e} is an unrecognized or unsupported type for src ${i}.`),{streamType:void 0,targetLiveWindow:void 0,liveEdgeStartOffset:void 0,sessionData:void 0}},pw=async(i,e,t=Ku({src:i}))=>{var s,r,n,a;let{streamType:o,targetLiveWindow:l,liveEdgeStartOffset:d,sessionData:u}=await mw(i,t),c=u==null?void 0:u["com.apple.hls.chapters"];(c!=null&&c.URI||c!=null&&c.VALUE.toLocaleLowerCase().startsWith("http"))&&wg((s=c.URI)!=null?s:c.VALUE,e),((r=Xe.get(e))!=null?r:{}).liveEdgeStartOffset=d,((n=Xe.get(e))!=null?n:{}).targetLiveWindow=l,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((a=Xe.get(e))!=null?a:{}).streamType=o,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},wg=async(i,e)=>{var t,s;try{let r=await fetch(i);if(!r.ok)throw new Error(`Failed to fetch Mux metadata: ${r.status} ${r.statusText}`);let n=await r.json(),a={};if(!((t=n==null?void 0:n[0])!=null&&t.metadata))return;for(let l of n[0].metadata)l.key&&l.value&&(a[l.key]=l.value);((s=Xe.get(e))!=null?s:{}).metadata=a;let o=new CustomEvent("muxmetadata");e.dispatchEvent(o)}catch(r){console.error(r)}},gw=i=>{var e;let t=i.type,s=xT(t),r=kT(t),n,a=!!((e=i.partList)!=null&&e.length);return s===we.LIVE&&(n=a?i.partTarget*2:i.targetduration*3),{streamType:s,targetLiveWindow:r,liveEdgeStartOffset:n,lowLatency:a}},vw=(i,e,t)=>{var s,r,n,a,o,l,d,u;let{streamType:c,targetLiveWindow:h,liveEdgeStartOffset:f,lowLatency:m}=gw(i);if(c===we.LIVE){m?(t.config.backBufferLength=(s=t.userConfig.backBufferLength)!=null?s:4,t.config.maxFragLookUpTolerance=(r=t.userConfig.maxFragLookUpTolerance)!=null?r:.001,t.config.abrBandWidthUpFactor=(n=t.userConfig.abrBandWidthUpFactor)!=null?n:t.config.abrBandWidthFactor):t.config.backBufferLength=(a=t.userConfig.backBufferLength)!=null?a:8;let p=Object.freeze({get length(){return e.seekable.length},start(g){return e.seekable.start(g)},end(g){var v;return g>this.length||g<0||Number.isFinite(e.duration)?e.seekable.end(g):(v=t.liveSyncPosition)!=null?v:e.seekable.end(g)}});((o=Xe.get(e))!=null?o:{}).seekable=p}((l=Xe.get(e))!=null?l:{}).liveEdgeStartOffset=f,((d=Xe.get(e))!=null?d:{}).targetLiveWindow=h,e.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0})),((u=Xe.get(e))!=null?u:{}).streamType=c,e.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}))},TT,_T,BT=(_T=(TT=globalThis==null?void 0:globalThis.navigator)==null?void 0:TT.userAgent)!=null?_T:"",AT,ST,IT,Ew=(IT=(ST=(AT=globalThis==null?void 0:globalThis.navigator)==null?void 0:AT.userAgentData)==null?void 0:ST.platform)!=null?IT:"",yw=BT.toLowerCase().includes("android")||["x11","android"].some(i=>Ew.toLowerCase().includes(i)),bw=i=>/^((?!chrome|android).)*safari/i.test(BT)&&!!i.canPlayType("application/vnd.apple.mpegurl"),Xe=new WeakMap,ws="mux.com",LT,RT,$T=(RT=(LT=_e).isSupported)==null?void 0:RT.call(LT),Tw=i=>yw||!bw(i),Wu=()=>{if(typeof window!="undefined")return Hd.utils.now()},_w=Hd.utils.generateUUID,sl=({playbackId:i,customDomain:e=ws,maxResolution:t,minResolution:s,renditionOrder:r,programStartTime:n,programEndTime:a,assetStartTime:o,assetEndTime:l,playbackToken:d,tokens:{playback:u=d}={},extraSourceParams:c={}}={})=>{if(!i)return;let[h,f=""]=Gu(i),m=new URL(`https://stream.${e}/${h}.m3u8${f}`);return u||m.searchParams.has("token")?(m.searchParams.forEach((p,g)=>{g!="token"&&m.searchParams.delete(g)}),u&&m.searchParams.set("token",u)):(t&&m.searchParams.set("max_resolution",t),s&&(m.searchParams.set("min_resolution",s),t&&+t.slice(0,-1)<+s.slice(0,-1)&&console.error("minResolution must be <= maxResolution","minResolution",s,"maxResolution",t)),r&&m.searchParams.set("rendition_order",r),n&&m.searchParams.set("program_start_time",`${n}`),a&&m.searchParams.set("program_end_time",`${a}`),o&&m.searchParams.set("asset_start_time",`${o}`),l&&m.searchParams.set("asset_end_time",`${l}`),Object.entries(c).forEach(([p,g])=>{g!=null&&m.searchParams.set(p,g)})),m.toString()},qu=i=>{if(!i)return;let[e]=i.split("?");return e||void 0},Yu=i=>{if(!i||!i.startsWith("https://stream."))return;let[e]=new URL(i).pathname.slice(1).split(/\.m3u8|\//);return e||void 0},Aw=i=>{var e,t,s;return(e=i==null?void 0:i.metadata)!=null&&e.video_id?i.metadata.video_id:zT(i)&&(s=(t=qu(i.playbackId))!=null?t:Yu(i.src))!=null?s:i.src},Mg=i=>{var e;return(e=Xe.get(i))==null?void 0:e.error},HT=i=>{var e;return(e=Xe.get(i))==null?void 0:e.metadata},Hu=i=>{var e,t;return(t=(e=Xe.get(i))==null?void 0:e.streamType)!=null?t:we.UNKNOWN},GT=i=>{var e,t;return(t=(e=Xe.get(i))==null?void 0:e.targetLiveWindow)!=null?t:Number.NaN},ju=i=>{var e,t;return(t=(e=Xe.get(i))==null?void 0:e.seekable)!=null?t:i.seekable},KT=i=>{var e;let t=(e=Xe.get(i))==null?void 0:e.liveEdgeStartOffset;if(typeof t!="number")return Number.NaN;let s=ju(i);return s.length?s.end(s.length-1)-t:Number.NaN},VT=i=>{var e;return(e=Xe.get(i))==null?void 0:e.coreReference},Pg=.034,Sw=(i,e,t=Pg)=>Math.abs(i-e)<=t,WT=(i,e,t=Pg)=>i>e||Sw(i,e,t),Iw=(i,e=Pg)=>i.paused&&WT(i.currentTime,i.duration,e),qT=(i,e)=>{var t,s,r;if(!e||!i.buffered.length)return;if(i.readyState>2)return!1;let n=e.currentLevel>=0?(s=(t=e.levels)==null?void 0:t[e.currentLevel])==null?void 0:s.details:(r=e.levels.find(c=>!!c.details))==null?void 0:r.details;if(!n||n.live)return;let{fragments:a}=n;if(!(a!=null&&a.length))return;if(i.currentTime<i.duration-(n.targetduration+.5))return!1;let o=a[a.length-1];if(i.currentTime<=o.start)return!1;let l=o.start+o.duration/2,d=i.buffered.start(i.buffered.length-1),u=i.buffered.end(i.buffered.length-1);return l>d&&l<u},Og=(i,e)=>i.ended||i.loop?i.ended:e&&qT(i,e)?!0:Iw(i),Ng=(i,e,t)=>{Ug(e,t,i);let{metadata:s={}}=i,{view_session_id:r=_w()}=s,n=Aw(i);s.view_session_id=r,s.video_id=n,i.metadata=s;let a=h=>{var f;(f=e.mux)==null||f.emit("hb",{view_drm_type:h})};i.drmTypeCb=a,i.fallbackToWebkitFairplay=async()=>{var h;let f=!e.paused,m=e.currentTime;i.useWebkitFairplay=!0;let p=i.muxDataKeepSession;i.muxDataKeepSession=!0;let g=(h=Xe.get(e))==null?void 0:h.coreReference;Ng(i,e,g),i.muxDataKeepSession=p,i.useWebkitFairplay=!1,f&&await e.play().then(()=>{e.currentTime=m}).catch(()=>{}),e.currentTime=m},Xe.set(e,{retryCount:0});let o=Lw(i,e),l=KC(i,e,o);i!=null&&i.muxDataKeepSession&&e!=null&&e.mux&&!e.mux.deleted?o&&e.mux.addHLSJS({hlsjs:o,Hls:o?_e:void 0}):Mw(i,e,o),Pw(i,e,o),jC(e),zC(e);let d=GC(i,e,o);VC(i,e,o),WC(i,e,o);let u={engine:o,setAutoplay:d,setPreload:l},c=Xe.get(e);return c&&(c.coreReference=u),u},Ug=(i,e,t)=>{let s=e==null?void 0:e.engine;i!=null&&i.mux&&!i.mux.deleted&&(t!=null&&t.muxDataKeepSession?s&&i.mux.removeHLSJS():(i.mux.destroy(),delete i.mux)),s&&(s.detachMedia(),s.destroy()),i&&(i.hasAttribute("src")&&(i.removeAttribute("src"),i.load()),i.removeEventListener("error",XT),i.removeEventListener("error",Ag),i.removeEventListener("durationchange",QT),Xe.delete(i),i.dispatchEvent(new Event("teardown")))};function YT(i,e){var t;let s=Ku(i);if(s!==Cs.M3U8)return!0;let r=!s||((t=e.canPlayType(s))!=null?t:!0),{preferPlayback:n}=i,a=n===gi.MSE,o=n===gi.NATIVE,l=$T&&(a||Tw(e));return r&&(o||!l)}var Lw=(i,e)=>{let{debug:t,streamType:s,startTime:r=-1,metadata:n,preferCmcd:a,_hlsConfig:o={},maxAutoResolution:l,initialBandwidthEstimateKbps:d}=i,u=Ku(i)===Cs.M3U8,c=YT(i,e);if(u&&!c&&$T){let h={backBufferLength:30,renderTextTracksNatively:!1,liveDurationInfinity:!0,capLevelOnFPSDrop:!0,...d!=null?{abrEwmaDefaultEstimate:d*1e3}:{}},f=Rw(s),m=xw(i),p=[Jo.QUERY,Jo.HEADER].includes(a)?{useHeaders:a===Jo.HEADER,sessionId:n==null?void 0:n.view_session_id,contentId:n==null?void 0:n.video_id}:void 0,g=ww(i,o),v=new _e({debug:t,startPosition:r,cmcd:p,xhrSetup:(b,y)=>{var T,A;if(a&&a!==Jo.QUERY)return;let R=Ig(y);if(!R.searchParams.has("CMCD"))return;let I=((A=(T=R.searchParams.get("CMCD"))==null?void 0:T.split(","))!=null?A:[]).filter(x=>x.startsWith("sid")||x.startsWith("cid")).join(",");R.searchParams.set("CMCD",I),b.open("GET",R)},...h,...g,...f,...m,...o});return g.capLevelController===_g&&l!==void 0&&_g.setMaxAutoResolution(v,l),v.on(_e.Events.MANIFEST_PARSED,async function(b,y){var T,A;let R=(T=y.sessionData)==null?void 0:T["com.apple.hls.chapters"];(R!=null&&R.URI||R!=null&&R.VALUE.toLocaleLowerCase().startsWith("http"))&&wg((A=R==null?void 0:R.URI)!=null?A:R==null?void 0:R.VALUE,e)}),v}},Rw=i=>i===we.LIVE?{backBufferLength:8}:{},xw=i=>{let{tokens:{drm:e}={},playbackId:t,drmTypeCb:s}=i,r=qu(t);return!e||!r?{}:{emeEnabled:!0,drmSystems:{"com.apple.fps":{licenseUrl:Bu(i,"fairplay"),serverCertificateUrl:jT(i,"fairplay")},"com.widevine.alpha":{licenseUrl:Bu(i,"widevine")},"com.microsoft.playready":{licenseUrl:Bu(i,"playready")}},requestMediaKeySystemAccessFunc:(n,a)=>(n==="com.widevine.alpha"&&(a=[...a.map(o=>{var l;let d=(l=o.videoCapabilities)==null?void 0:l.map(u=>({...u,robustness:"HW_SECURE_ALL"}));return{...o,videoCapabilities:d}}),...a]),navigator.requestMediaKeySystemAccess(n,a).then(o=>{let l=lw(n);return s==null||s(l),o}))}},kw=async i=>{let e=await fetch(i);return e.status!==200?Promise.reject(e):await e.arrayBuffer()},Dw=async(i,e)=>{let t=await fetch(e,{method:"POST",headers:{"Content-type":"application/octet-stream"},body:i});if(t.status!==200)return Promise.reject(t);let s=await t.arrayBuffer();return new Uint8Array(s)},Cw=(i,e)=>{let t={mediaEl:e,getAppCertificate:()=>kw(jT(i,"fairplay")).catch(s=>{if(s instanceof Response){let r=$u(s,Ue.DRM,i);return console.error("mediaError",r==null?void 0:r.message,r==null?void 0:r.context),r?Promise.reject(r):Promise.reject(new Error("Unexpected error in app cert request"))}return Promise.reject(s)}),getLicenseKey:s=>Dw(s,Bu(i,"fairplay")).catch(r=>{if(r instanceof Response){let n=$u(r,Ue.DRM,i);return console.error("mediaError",n==null?void 0:n.message,n==null?void 0:n.context),n?Promise.reject(n):Promise.reject(new Error("Unexpected error in license key request"))}return Promise.reject(r)}),saveAndDispatchError:lr,drmTypeCb:()=>{var s;(s=i.drmTypeCb)==null||s.call(i,Fu.FAIRPLAY)}};if(i.useWebkitFairplay)sw(t);else{let s={fallbackToWebkitFairplay:async()=>{var n;await r(),(n=i.fallbackToWebkitFairplay)==null||n.call(i)},...t},r=ow(s)}},Bu=({playbackId:i,tokens:{drm:e}={},customDomain:t=ws},s)=>{let r=qu(i);return`https://license.${t.toLocaleLowerCase().endsWith(ws)?t:ws}/license/${s}/${r}?token=${e}`},jT=({playbackId:i,tokens:{drm:e}={},customDomain:t=ws},s)=>{let r=qu(i);return`https://license.${t.toLocaleLowerCase().endsWith(ws)?t:ws}/appcert/${s}/${r}?token=${e}`},zT=({playbackId:i,src:e,customDomain:t})=>{if(i)return!0;if(typeof e!="string")return!1;let s=window==null?void 0:window.location.href,r=new URL(e,s).hostname.toLocaleLowerCase();return r.includes(ws)||!!t&&r.includes(t.toLocaleLowerCase())},ww=(i,e)=>{let t={};return t.capLevelToPlayerSize=i.capRenditionToPlayerSize,t.capLevelToPlayerSize==null?(t.capLevelController=_g,t.capLevelToPlayerSize=!0):t.capLevelController=Qo,t},Mw=(i,e,t)=>{var s;let{envKey:r,disableTracking:n,muxDataSDK:a=Hd,muxDataSDKOptions:o={}}=i,l=zT(i);if(!n&&(r||l)){let{playerInitTime:d,playerSoftwareName:u,playerSoftwareVersion:c,beaconCollectionDomain:h,debug:f,disableCookies:m}=i,p={...i.metadata,video_title:((s=i==null?void 0:i.metadata)==null?void 0:s.video_title)||void 0},g=v=>typeof v.player_error_code=="string"?!1:typeof i.errorTranslator=="function"?i.errorTranslator(v):v;a.monitor(e,{debug:f,beaconCollectionDomain:h,hlsjs:t,Hls:t?_e:void 0,automaticErrorTracking:!1,errorTranslator:g,disableCookies:m,...o,data:{...r?{env_key:r}:{},player_software_name:u,player_software:u,player_software_version:c,player_init_time:d,...p}})}},Pw=(i,e,t)=>{var s,r;let n=YT(i,e),{src:a,customDomain:o=ws}=i,l=()=>{e.ended||i.disablePseudoEnded||!Og(e,t)||(qT(e,t)?e.currentTime=e.buffered.end(e.buffered.length-1):e.dispatchEvent(new Event("ended")))},d,u,c=()=>{let h=ju(e),f,m;h.length>0&&(f=h.start(0),m=h.end(0)),(u!==m||d!==f)&&e.dispatchEvent(new CustomEvent("seekablechange",{composed:!0})),d=f,u=m};if(mt(e,"durationchange",c),e&&n){let h=Ku(i);if(typeof a=="string"){if(a.endsWith(".mp4")&&a.includes(o)){let p=Yu(a),g=new URL(`https://stream.${o}/${p}/metadata.json`);wg(g.toString(),e)}let f=()=>{if(Hu(e)!==we.LIVE||Number.isFinite(e.duration))return;let p=setInterval(c,1e3);e.addEventListener("teardown",()=>{clearInterval(p)},{once:!0}),mt(e,"durationchange",()=>{Number.isFinite(e.duration)&&clearInterval(p)})},m=async()=>pw(a,e,h).then(f).catch(p=>{if(p instanceof Response){let g=$u(p,Ue.VIDEO,i);if(g){lr(e,g);return}}else p instanceof Error});if(e.preload==="none"){let p=()=>{m(),e.removeEventListener("loadedmetadata",g)},g=()=>{m(),e.removeEventListener("play",p)};mt(e,"play",p,{once:!0}),mt(e,"loadedmetadata",g,{once:!0})}else m();(s=i.tokens)!=null&&s.drm?Cw(i,e):mt(e,"encrypted",()=>{let p=te("Attempting to play DRM-protected content without providing a DRM token."),g=new z(p,z.MEDIA_ERR_ENCRYPTED,!0);g.errorCategory=Ue.DRM,g.muxCode=ne.ENCRYPTED_MISSING_TOKEN,lr(e,g)},{once:!0}),e.setAttribute("src",a),i.startTime&&(((r=Xe.get(e))!=null?r:{}).startTime=i.startTime,e.addEventListener("durationchange",QT,{once:!0}))}else e.removeAttribute("src");e.addEventListener("error",XT),e.addEventListener("error",Ag),e.addEventListener("emptied",()=>{e.querySelectorAll("track[data-removeondestroy]").forEach(f=>{f.remove()})},{once:!0}),mt(e,"pause",l),mt(e,"seeked",l),mt(e,"play",()=>{e.ended||WT(e.currentTime,e.duration)&&(e.currentTime=e.seekable.length?e.seekable.start(0):0)})}else t&&a?(t.once(_e.Events.LEVEL_LOADED,(h,f)=>{vw(f.details,e,t),c(),Hu(e)===we.LIVE&&!Number.isFinite(e.duration)&&(t.on(_e.Events.LEVEL_UPDATED,c),mt(e,"durationchange",()=>{Number.isFinite(e.duration)&&t.off(_e.Events.LEVELS_UPDATED,c)}))}),t.on(_e.Events.ERROR,(h,f)=>{var m,p;let g=Ow(f,i);if(g.muxCode===ne.NETWORK_NOT_READY){let v=(m=Xe.get(e))!=null?m:{},b=(p=v.retryCount)!=null?p:0;if(b<6){let y=b===0?5e3:6e4,T=new z(`Retrying in ${y/1e3} seconds...`,g.code,g.fatal);Object.assign(T,g),lr(e,T);let A=setTimeout(()=>{v.retryCount=b+1,f.details==="manifestLoadError"&&f.url&&t.loadSource(f.url)},y);e.addEventListener("teardown",()=>clearTimeout(A),{once:!0});return}else{v.retryCount=0;let y=new z('Try again later or <a href="#" onclick="window.location.reload(); return false;" style="color: #4a90e2;">click here to retry</a>',g.code,g.fatal);Object.assign(y,g),lr(e,y);return}}lr(e,g)}),t.on(_e.Events.MANIFEST_LOADED,()=>{let h=Xe.get(e);h&&h.error&&(h.error=null,h.retryCount=0,e.dispatchEvent(new Event("emptied")),e.dispatchEvent(new Event("loadstart")))}),e.addEventListener("error",Ag),mt(e,"waiting",l),qC(i,t),YC(e,t),t.attachMedia(e)):console.error("It looks like the video you're trying to play will not work on this system! If possible, try upgrading to the newest versions of your browser or software.")};function QT(i){var e;let t=i.target,s=(e=Xe.get(t))==null?void 0:e.startTime;if(s&&CC(t.seekable,t.duration,s)){let r=t.preload==="auto";r&&(t.preload="none"),t.currentTime=s,r&&(t.preload="auto")}}async function XT(i){if(!i.isTrusted)return;i.stopImmediatePropagation();let e=i.target;if(!(e!=null&&e.error))return;let{message:t,code:s}=e.error,r=new z(t,s);if(e.src&&s===z.MEDIA_ERR_SRC_NOT_SUPPORTED&&e.readyState===HTMLMediaElement.HAVE_NOTHING){setTimeout(()=>{var n;let a=(n=Mg(e))!=null?n:e.error;(a==null?void 0:a.code)===z.MEDIA_ERR_SRC_NOT_SUPPORTED&&lr(e,r)},500);return}if(e.src&&(s!==z.MEDIA_ERR_DECODE||s!==void 0))try{let{status:n}=await fetch(e.src);r.data={response:{code:n}}}catch{}lr(e,r)}function lr(i,e){var t;e.fatal&&(((t=Xe.get(i))!=null?t:{}).error=e,i.dispatchEvent(new CustomEvent("error",{detail:e})))}function Ag(i){var e,t;if(!(i instanceof CustomEvent)||!(i.detail instanceof z))return;let s=i.target,r=i.detail;!r||!r.fatal||(((e=Xe.get(s))!=null?e:{}).error=r,(t=s.mux)==null||t.emit("error",{player_error_code:r.code,player_error_message:r.message,player_error_context:r.context}))}var Ow=(i,e)=>{var t,s,r;i.fatal?console.error("getErrorFromHlsErrorData()",i):e.debug&&console.warn("getErrorFromHlsErrorData() (non-fatal)",i);let n={[_e.ErrorTypes.NETWORK_ERROR]:z.MEDIA_ERR_NETWORK,[_e.ErrorTypes.MEDIA_ERROR]:z.MEDIA_ERR_DECODE,[_e.ErrorTypes.KEY_SYSTEM_ERROR]:z.MEDIA_ERR_ENCRYPTED},a=u=>[_e.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,_e.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED].includes(u.details)?z.MEDIA_ERR_NETWORK:n[u.type],o=u=>{if(u.type===_e.ErrorTypes.KEY_SYSTEM_ERROR)return Ue.DRM;if(u.type===_e.ErrorTypes.NETWORK_ERROR)return Ue.VIDEO},l,d=a(i);if(d===z.MEDIA_ERR_NETWORK&&i.response){let u=(t=o(i))!=null?t:Ue.VIDEO;l=(s=$u(i.response,u,e,i.fatal))!=null?s:new z("",d,i.fatal)}else if(d===z.MEDIA_ERR_ENCRYPTED)if(i.details===_e.ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE){let u=te("Attempting to play DRM-protected content without providing a DRM token.");l=new z(u,z.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Ue.DRM,l.muxCode=ne.ENCRYPTED_MISSING_TOKEN}else if(i.details===_e.ErrorDetails.KEY_SYSTEM_NO_ACCESS){let u=te("Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser.");l=new z(u,z.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Ue.DRM,l.muxCode=ne.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM}else if(i.details===_e.ErrorDetails.KEY_SYSTEM_NO_SESSION){let u=te("Failed to generate a DRM license request. This may be an issue with the player or your protected content.");l=new z(u,z.MEDIA_ERR_ENCRYPTED,!0),l.errorCategory=Ue.DRM,l.muxCode=ne.ENCRYPTED_GENERATE_REQUEST_FAILED}else if(i.details===_e.ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED){let u=te("Failed to update DRM license. This may be an issue with the player or your protected content.");l=new z(u,z.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Ue.DRM,l.muxCode=ne.ENCRYPTED_UPDATE_LICENSE_FAILED}else if(i.details===_e.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED){let u=te("Your server certificate failed when attempting to set it. This may be an issue with a no longer valid certificate.");l=new z(u,z.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Ue.DRM,l.muxCode=ne.ENCRYPTED_UPDATE_SERVER_CERT_FAILED}else if(i.details===_e.ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR){let u=te("The DRM Content Decryption Module system had an internal failure. Try reloading the page, updating your browser, or playing in another browser.");l=new z(u,z.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Ue.DRM,l.muxCode=ne.ENCRYPTED_CDM_ERROR}else if(i.details===_e.ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED){let u=te("DRM playback is being attempted in an environment that is not sufficiently secure. User may see black screen.");l=new z(u,z.MEDIA_ERR_ENCRYPTED,!1),l.errorCategory=Ue.DRM,l.muxCode=ne.ENCRYPTED_OUTPUT_RESTRICTED}else l=new z(i.error.message,z.MEDIA_ERR_ENCRYPTED,i.fatal),l.errorCategory=Ue.DRM,l.muxCode=ne.ENCRYPTED_ERROR;else l=new z("",d,i.fatal);return l.context||(l.context=`${i.url?`url: ${i.url}
59
59
  `:""}${i.response&&(i.response.code||i.response.text)?`response: ${i.response.code}, ${i.response.text}
60
60
  `:""}${i.reason?`failure reason: ${i.reason}
61
61
  `:""}${i.level?`level: ${i.level}
@@ -106,8 +106,8 @@ Schedule: ${l.map(p=>Ci(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Remo
106
106
  <video${o_(i)}></video>
107
107
  </slot>
108
108
  <slot></slot>
109
- `}function a_(i,{tag:e,is:t}){var n,a,o,l,d,i_,c,h,f,m,p,g,rn,Fg,Bg,s_,$g,r_,n_;let s=(a=(n=globalThis.document)==null?void 0:n.createElement)==null?void 0:a.call(n,e,{is:t}),r=s?Fw(s):[];return o=class extends i{constructor(){super(...arguments);oe(this,g);oe(this,c,!1);oe(this,h,null);oe(this,f,new Map);oe(this,m);oe(this,p);Ie(this,"get");Ie(this,"set");Ie(this,"call")}static get observedAttributes(){var C,P,N;return Ne(C=o,d,i_).call(C),[...(N=(P=s==null?void 0:s.constructor)==null?void 0:P.observedAttributes)!=null?N:[],...t_]}get nativeEl(){var S,C,P,N,$;return Ne(this,g,rn).call(this),($=(N=(C=(S=w(this,h))!=null?S:this.querySelector(":scope > [slot=media]"))!=null?C:this.querySelector(e))!=null?N:(P=this.shadowRoot)==null?void 0:P.querySelector(e))!=null?$:null}set nativeEl(S){ee(this,h,S)}get defaultMuted(){return this.hasAttribute("muted")}set defaultMuted(S){this.toggleAttribute("muted",S)}get src(){return this.getAttribute("src")}set src(S){this.setAttribute("src",`${S}`)}get preload(){var S,C;return(C=this.getAttribute("preload"))!=null?C:(S=this.nativeEl)==null?void 0:S.preload}set preload(S){this.setAttribute("preload",`${S}`)}init(){if(!this.shadowRoot){this.attachShadow({mode:"open"});let S=Bw(this.attributes);t&&(S.is=t),e&&(S.part=e),this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(S)}this.nativeEl.muted=this.hasAttribute("muted");for(let S of r)Ne(this,g,r_).call(this,S);Ne(this,g,Fg).call(this)}handleEvent(S){S.target===this.nativeEl&&this.dispatchEvent(new CustomEvent(S.type,{detail:S.detail}))}attributeChangedCallback(S,C,P){Ne(this,g,rn).call(this),Ne(this,g,n_).call(this,S,C,P)}connectedCallback(){Ne(this,g,rn).call(this),w(this,p)||Ne(this,g,Fg).call(this)}disconnectedCallback(){var S,C,P;(S=w(this,m))==null||S.disconnect(),ee(this,m,void 0),w(this,p)&&((C=this.shadowRoot)==null||C.removeEventListener("slotchange",w(this,p)),ee(this,p,void 0));for(let N of this.constructor.Events)(P=this.shadowRoot)==null||P.removeEventListener(N,this,!0);w(this,f).forEach(N=>N.remove()),w(this,f).clear(),ee(this,h,null)}},l=new WeakMap,d=new WeakSet,i_=function(){if(w(this,l))return;ee(this,l,!0);let S=new Set(this.observedAttributes);S.delete("muted");for(let C of r)if(!(C in this.prototype))if(typeof s[C]=="function")this.prototype[C]=function(...P){return Ne(this,g,rn).call(this),(()=>{var H;if(this.call)return this.call(C,...P);let $=(H=this.nativeEl)==null?void 0:H[C];return $==null?void 0:$.apply(this.nativeEl,P)})()};else{let P={get(){var $,H,U;Ne(this,g,rn).call(this);let N=C.toLowerCase();if(S.has(N)){let j=this.getAttribute(N);return j===null?!1:j===""?!0:j}return(U=($=this.get)==null?void 0:$.call(this,C))!=null?U:(H=this.nativeEl)==null?void 0:H[C]}};C!==C.toUpperCase()&&(P.set=function(N){Ne(this,g,rn).call(this);let $=C.toLowerCase();if(S.has($)){N===!0||N===!1||N==null?this.toggleAttribute($,!!N):this.setAttribute($,N);return}if(this.set){this.set(C,N);return}this.nativeEl&&(this.nativeEl[C]=N)}),Object.defineProperty(this.prototype,C,P)}},c=new WeakMap,h=new WeakMap,f=new WeakMap,m=new WeakMap,p=new WeakMap,g=new WeakSet,rn=function(){w(this,c)||(ee(this,c,!0),this.init())},Fg=function(){var S,C;ee(this,m,new MutationObserver(Ne(this,g,s_).bind(this))),ee(this,p,()=>Ne(this,g,Bg).call(this)),(S=this.shadowRoot)==null||S.addEventListener("slotchange",w(this,p)),Ne(this,g,Bg).call(this);for(let P of this.constructor.Events)(C=this.shadowRoot)==null||C.addEventListener(P,this,!0)},Bg=function(){var N;let S=new Map(w(this,f)),C=(N=this.shadowRoot)==null?void 0:N.querySelector("slot:not([name])");(C==null?void 0:C.assignedElements({flatten:!0}).filter($=>["track","source"].includes($.localName))).forEach($=>{var U,j;S.delete($);let H=w(this,f).get($);H||(H=$.cloneNode(),w(this,f).set($,H),(U=w(this,m))==null||U.observe($,{attributes:!0})),(j=this.nativeEl)==null||j.append(H),Ne(this,g,$g).call(this,H)}),S.forEach(($,H)=>{$.remove(),w(this,f).delete(H)})},s_=function(S){var C;for(let P of S)if(P.type==="attributes"){let{target:N,attributeName:$}=P,H=w(this,f).get(N);H&&$&&(H.setAttribute($,(C=N.getAttribute($))!=null?C:""),Ne(this,g,$g).call(this,H))}},$g=function(S){S&&S.localName==="track"&&S.default&&(S.kind==="chapters"||S.kind==="metadata")&&S.track.mode==="disabled"&&(S.track.mode="hidden")},r_=function(S){if(Object.prototype.hasOwnProperty.call(this,S)){let C=this[S];delete this[S],this[S]=C}},n_=function(S,C,P){var N,$,H;["id","class"].includes(S)||!o.observedAttributes.includes(S)&&this.constructor.observedAttributes.includes(S)||(P===null?(N=this.nativeEl)==null||N.removeAttribute(S):(($=this.nativeEl)==null?void 0:$.getAttribute(S))!==P&&((H=this.nativeEl)==null||H.setAttribute(S,P)))},oe(o,d),Ie(o,"getTemplateHTML",e.endsWith("audio")?Nw:Uw),Ie(o,"shadowRootOptions",{mode:"open"}),Ie(o,"Events",e_),oe(o,l,!1),o}function Fw(i){let e=[];for(let t=Object.getPrototypeOf(i);t&&t!==HTMLElement.prototype;t=Object.getPrototypeOf(t)){let s=Object.getOwnPropertyNames(t);e.push(...s)}return e}function o_(i){let e="";for(let t in i){if(!t_.includes(t))continue;let s=i[t];s===""?e+=` ${t}`:e+=` ${t}="${s}"`}return e}function Bw(i){let e={};for(let t of i)e[t.name]=t.value;return e}var Zb,rl=a_((Zb=globalThis.HTMLElement)!=null?Zb:class{},{tag:"video"}),Jb,kN=a_((Jb=globalThis.HTMLElement)!=null?Jb:class{},{tag:"audio"});var u_=i=>{throw TypeError(i)},Hg=(i,e,t)=>e.has(i)||u_("Cannot "+t),pt=(i,e,t)=>(Hg(i,e,"read from private field"),t?t.call(i):e.get(i)),vi=(i,e,t)=>e.has(i)?u_("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),Pi=(i,e,t,s)=>(Hg(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),zu=(i,e,t)=>(Hg(i,e,"access private method"),t),$w=()=>{try{return"0.31.0"}catch{}return"UNKNOWN"},Hw=$w(),Gw=()=>Hw,Kw=`
110
- <svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" part="logo" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2" viewBox="0 0 1600 500"><g fill="#fff"><path d="M994.287 93.486c-17.121 0-31-13.879-31-31 0-17.121 13.879-31 31-31 17.121 0 31 13.879 31 31 0 17.121-13.879 31-31 31m0-93.486c-34.509 0-62.484 27.976-62.484 62.486v187.511c0 68.943-56.09 125.033-125.032 125.033s-125.03-56.09-125.03-125.033V62.486C681.741 27.976 653.765 0 619.256 0s-62.484 27.976-62.484 62.486v187.511C556.772 387.85 668.921 500 806.771 500c137.851 0 250.001-112.15 250.001-250.003V62.486c0-34.51-27.976-62.486-62.485-62.486M1537.51 468.511c-17.121 0-31-13.879-31-31 0-17.121 13.879-31 31-31 17.121 0 31 13.879 31 31 0 17.121-13.879 31-31 31m-275.883-218.509-143.33 143.329c-24.402 24.402-24.402 63.966 0 88.368 24.402 24.402 63.967 24.402 88.369 0l143.33-143.329 143.328 143.329c24.402 24.4 63.967 24.402 88.369 0 24.403-24.402 24.403-63.966.001-88.368l-143.33-143.329.001-.004 143.329-143.329c24.402-24.402 24.402-63.965 0-88.367s-63.967-24.402-88.369 0L1349.996 161.63 1206.667 18.302c-24.402-24.401-63.967-24.402-88.369 0s-24.402 63.965 0 88.367l143.329 143.329v.004ZM437.511 468.521c-17.121 0-31-13.879-31-31 0-17.121 13.879-31 31-31 17.121 0 31 13.879 31 31 0 17.121-13.879 31-31 31M461.426 4.759C438.078-4.913 411.2.432 393.33 18.303L249.999 161.632 106.669 18.303C88.798.432 61.922-4.913 38.573 4.759 15.224 14.43-.001 37.214-.001 62.488v375.026c0 34.51 27.977 62.486 62.487 62.486 34.51 0 62.486-27.976 62.486-62.486V213.341l80.843 80.844c24.404 24.402 63.965 24.402 88.369 0l80.843-80.844v224.173c0 34.51 27.976 62.486 62.486 62.486s62.486-27.976 62.486-62.486V62.488c0-25.274-15.224-48.058-38.573-57.729" style="fill-rule:nonzero"/></g></svg>`,k={BEACON_COLLECTION_DOMAIN:"beacon-collection-domain",CUSTOM_DOMAIN:"custom-domain",DEBUG:"debug",DISABLE_TRACKING:"disable-tracking",DISABLE_COOKIES:"disable-cookies",DISABLE_PSEUDO_ENDED:"disable-pseudo-ended",DRM_TOKEN:"drm-token",PLAYBACK_TOKEN:"playback-token",ENV_KEY:"env-key",MAX_RESOLUTION:"max-resolution",MIN_RESOLUTION:"min-resolution",MAX_AUTO_RESOLUTION:"max-auto-resolution",RENDITION_ORDER:"rendition-order",PROGRAM_START_TIME:"program-start-time",PROGRAM_END_TIME:"program-end-time",ASSET_START_TIME:"asset-start-time",ASSET_END_TIME:"asset-end-time",METADATA_URL:"metadata-url",PLAYBACK_ID:"playback-id",PLAYER_SOFTWARE_NAME:"player-software-name",PLAYER_SOFTWARE_VERSION:"player-software-version",PLAYER_INIT_TIME:"player-init-time",PREFER_CMCD:"prefer-cmcd",PREFER_PLAYBACK:"prefer-playback",START_TIME:"start-time",STREAM_TYPE:"stream-type",TARGET_LIVE_WINDOW:"target-live-window",LIVE_EDGE_OFFSET:"live-edge-offset",TYPE:"type",LOGO:"logo",CAP_RENDITION_TO_PLAYER_SIZE:"cap-rendition-to-player-size",INITIAL_BANDWIDTH_ESTIMATE_KBPS:"initial-bandwidth-estimate-kbps",INITIAL_ESTIMATE_SEGMENTS:"initial-estimate-segments",MIN_PRELOAD_SEGMENTS:"min-preload-segments"},Vw=Object.values(k),l_=Gw(),d_="mux-video",nl,Qu,al,Xu,Zu,Ju,ec,tc,ol,ic,Ei,nn,sc,ll,c_=class extends rl{constructor(){super(),vi(this,Ei),vi(this,nl),vi(this,Qu),vi(this,al,{}),vi(this,Xu,{}),vi(this,Zu),vi(this,Ju),vi(this,ec),vi(this,tc),vi(this,ol,""),vi(this,ic,i=>{var e;let t=Hb(this.nativeEl),s=(e=this.metadata)!=null?e:{};this.metadata={...t,...s},(t==null?void 0:t["com.mux.video.branding"])==="mux-free-plan"&&(Pi(this,ol,"default"),this.updateLogo())}),vi(this,sc),Pi(this,Qu,Wu())}static get NAME(){return d_}static get VERSION(){return l_}static get observedAttributes(){var i;return[...Vw,...(i=rl.observedAttributes)!=null?i:[]]}static getLogoHTML(i){return!i||i==="false"?"":i==="default"?Kw:`<img part="logo" src="${i}" />`}static getTemplateHTML(i={}){var e;return`
109
+ `}function a_(i,{tag:e,is:t}){var n,a,o,l,d,i_,c,h,f,m,p,g,rn,Fg,Bg,s_,$g,r_,n_;let s=(a=(n=globalThis.document)==null?void 0:n.createElement)==null?void 0:a.call(n,e,{is:t}),r=s?Fw(s):[];return o=class extends i{constructor(){super(...arguments);oe(this,g);oe(this,c,!1);oe(this,h,null);oe(this,f,new Map);oe(this,m);oe(this,p);Ie(this,"get");Ie(this,"set");Ie(this,"call")}static get observedAttributes(){var C,P,N;return Ne(C=o,d,i_).call(C),[...(N=(P=s==null?void 0:s.constructor)==null?void 0:P.observedAttributes)!=null?N:[],...t_]}get nativeEl(){var S,C,P,N,$;return Ne(this,g,rn).call(this),($=(N=(C=(S=w(this,h))!=null?S:this.querySelector(":scope > [slot=media]"))!=null?C:this.querySelector(e))!=null?N:(P=this.shadowRoot)==null?void 0:P.querySelector(e))!=null?$:null}set nativeEl(S){ee(this,h,S)}get defaultMuted(){return this.hasAttribute("muted")}set defaultMuted(S){this.toggleAttribute("muted",S)}get src(){return this.getAttribute("src")}set src(S){this.setAttribute("src",`${S}`)}get preload(){var S,C;return(C=this.getAttribute("preload"))!=null?C:(S=this.nativeEl)==null?void 0:S.preload}set preload(S){this.setAttribute("preload",`${S}`)}init(){if(!this.shadowRoot){this.attachShadow({mode:"open"});let S=Bw(this.attributes);t&&(S.is=t),e&&(S.part=e),this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(S)}this.nativeEl.muted=this.hasAttribute("muted");for(let S of r)Ne(this,g,r_).call(this,S);Ne(this,g,Fg).call(this)}handleEvent(S){S.target===this.nativeEl&&this.dispatchEvent(new CustomEvent(S.type,{detail:S.detail}))}attributeChangedCallback(S,C,P){Ne(this,g,rn).call(this),Ne(this,g,n_).call(this,S,C,P)}connectedCallback(){Ne(this,g,rn).call(this),w(this,p)||Ne(this,g,Fg).call(this)}disconnectedCallback(){var S,C,P;(S=w(this,m))==null||S.disconnect(),ee(this,m,void 0),w(this,p)&&((C=this.shadowRoot)==null||C.removeEventListener("slotchange",w(this,p)),ee(this,p,void 0));for(let N of this.constructor.Events)(P=this.shadowRoot)==null||P.removeEventListener(N,this,!0);w(this,f).forEach(N=>N.remove()),w(this,f).clear(),ee(this,h,null)}},l=new WeakMap,d=new WeakSet,i_=function(){if(w(this,l))return;ee(this,l,!0);let S=new Set(this.observedAttributes);S.delete("muted");for(let C of r)if(!(C in this.prototype))if(typeof s[C]=="function")this.prototype[C]=function(...P){return Ne(this,g,rn).call(this),(()=>{var H;if(this.call)return this.call(C,...P);let $=(H=this.nativeEl)==null?void 0:H[C];return $==null?void 0:$.apply(this.nativeEl,P)})()};else{let P={get(){var $,H,U;Ne(this,g,rn).call(this);let N=C.toLowerCase();if(S.has(N)){let j=this.getAttribute(N);return j===null?!1:j===""?!0:j}return(U=($=this.get)==null?void 0:$.call(this,C))!=null?U:(H=this.nativeEl)==null?void 0:H[C]}};C!==C.toUpperCase()&&(P.set=function(N){Ne(this,g,rn).call(this);let $=C.toLowerCase();if(S.has($)){N===!0||N===!1||N==null?this.toggleAttribute($,!!N):this.setAttribute($,N);return}if(this.set){this.set(C,N);return}this.nativeEl&&(this.nativeEl[C]=N)}),Object.defineProperty(this.prototype,C,P)}},c=new WeakMap,h=new WeakMap,f=new WeakMap,m=new WeakMap,p=new WeakMap,g=new WeakSet,rn=function(){w(this,c)||(ee(this,c,!0),this.init())},Fg=function(){var S,C;ee(this,m,new MutationObserver(Ne(this,g,s_).bind(this))),ee(this,p,()=>Ne(this,g,Bg).call(this)),(S=this.shadowRoot)==null||S.addEventListener("slotchange",w(this,p)),Ne(this,g,Bg).call(this);for(let P of this.constructor.Events)(C=this.shadowRoot)==null||C.addEventListener(P,this,!0)},Bg=function(){var N;let S=new Map(w(this,f)),C=(N=this.shadowRoot)==null?void 0:N.querySelector("slot:not([name])");(C==null?void 0:C.assignedElements({flatten:!0}).filter($=>["track","source"].includes($.localName))).forEach($=>{var U,j;S.delete($);let H=w(this,f).get($);H||(H=$.cloneNode(),w(this,f).set($,H),(U=w(this,m))==null||U.observe($,{attributes:!0})),(j=this.nativeEl)==null||j.append(H),Ne(this,g,$g).call(this,H)}),S.forEach(($,H)=>{$.remove(),w(this,f).delete(H)})},s_=function(S){var C;for(let P of S)if(P.type==="attributes"){let{target:N,attributeName:$}=P,H=w(this,f).get(N);H&&$&&(H.setAttribute($,(C=N.getAttribute($))!=null?C:""),Ne(this,g,$g).call(this,H))}},$g=function(S){S&&S.localName==="track"&&S.default&&(S.kind==="chapters"||S.kind==="metadata")&&S.track.mode==="disabled"&&(S.track.mode="hidden")},r_=function(S){if(Object.prototype.hasOwnProperty.call(this,S)){let C=this[S];delete this[S],this[S]=C}},n_=function(S,C,P){var N,$,H;["id","class"].includes(S)||!o.observedAttributes.includes(S)&&this.constructor.observedAttributes.includes(S)||(P===null?(N=this.nativeEl)==null||N.removeAttribute(S):(($=this.nativeEl)==null?void 0:$.getAttribute(S))!==P&&((H=this.nativeEl)==null||H.setAttribute(S,P)))},oe(o,d),Ie(o,"getTemplateHTML",e.endsWith("audio")?Nw:Uw),Ie(o,"shadowRootOptions",{mode:"open"}),Ie(o,"Events",e_),oe(o,l,!1),o}function Fw(i){let e=[];for(let t=Object.getPrototypeOf(i);t&&t!==HTMLElement.prototype;t=Object.getPrototypeOf(t)){let s=Object.getOwnPropertyNames(t);e.push(...s)}return e}function o_(i){let e="";for(let t in i){if(!t_.includes(t))continue;let s=i[t];s===""?e+=` ${t}`:e+=` ${t}="${s}"`}return e}function Bw(i){let e={};for(let t of i)e[t.name]=t.value;return e}var ZT,rl=a_((ZT=globalThis.HTMLElement)!=null?ZT:class{},{tag:"video"}),JT,kN=a_((JT=globalThis.HTMLElement)!=null?JT:class{},{tag:"audio"});var u_=i=>{throw TypeError(i)},Hg=(i,e,t)=>e.has(i)||u_("Cannot "+t),pt=(i,e,t)=>(Hg(i,e,"read from private field"),t?t.call(i):e.get(i)),vi=(i,e,t)=>e.has(i)?u_("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),Pi=(i,e,t,s)=>(Hg(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),zu=(i,e,t)=>(Hg(i,e,"access private method"),t),$w=()=>{try{return"0.31.0"}catch{}return"UNKNOWN"},Hw=$w(),Gw=()=>Hw,Kw=`
110
+ <svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" part="logo" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2" viewBox="0 0 1600 500"><g fill="#fff"><path d="M994.287 93.486c-17.121 0-31-13.879-31-31 0-17.121 13.879-31 31-31 17.121 0 31 13.879 31 31 0 17.121-13.879 31-31 31m0-93.486c-34.509 0-62.484 27.976-62.484 62.486v187.511c0 68.943-56.09 125.033-125.032 125.033s-125.03-56.09-125.03-125.033V62.486C681.741 27.976 653.765 0 619.256 0s-62.484 27.976-62.484 62.486v187.511C556.772 387.85 668.921 500 806.771 500c137.851 0 250.001-112.15 250.001-250.003V62.486c0-34.51-27.976-62.486-62.485-62.486M1537.51 468.511c-17.121 0-31-13.879-31-31 0-17.121 13.879-31 31-31 17.121 0 31 13.879 31 31 0 17.121-13.879 31-31 31m-275.883-218.509-143.33 143.329c-24.402 24.402-24.402 63.966 0 88.368 24.402 24.402 63.967 24.402 88.369 0l143.33-143.329 143.328 143.329c24.402 24.4 63.967 24.402 88.369 0 24.403-24.402 24.403-63.966.001-88.368l-143.33-143.329.001-.004 143.329-143.329c24.402-24.402 24.402-63.965 0-88.367s-63.967-24.402-88.369 0L1349.996 161.63 1206.667 18.302c-24.402-24.401-63.967-24.402-88.369 0s-24.402 63.965 0 88.367l143.329 143.329v.004ZM437.511 468.521c-17.121 0-31-13.879-31-31 0-17.121 13.879-31 31-31 17.121 0 31 13.879 31 31 0 17.121-13.879 31-31 31M461.426 4.759C438.078-4.913 411.2.432 393.33 18.303L249.999 161.632 106.669 18.303C88.798.432 61.922-4.913 38.573 4.759 15.224 14.43-.001 37.214-.001 62.488v375.026c0 34.51 27.977 62.486 62.487 62.486 34.51 0 62.486-27.976 62.486-62.486V213.341l80.843 80.844c24.404 24.402 63.965 24.402 88.369 0l80.843-80.844v224.173c0 34.51 27.976 62.486 62.486 62.486s62.486-27.976 62.486-62.486V62.488c0-25.274-15.224-48.058-38.573-57.729" style="fill-rule:nonzero"/></g></svg>`,k={BEACON_COLLECTION_DOMAIN:"beacon-collection-domain",CUSTOM_DOMAIN:"custom-domain",DEBUG:"debug",DISABLE_TRACKING:"disable-tracking",DISABLE_COOKIES:"disable-cookies",DISABLE_PSEUDO_ENDED:"disable-pseudo-ended",DRM_TOKEN:"drm-token",PLAYBACK_TOKEN:"playback-token",ENV_KEY:"env-key",MAX_RESOLUTION:"max-resolution",MIN_RESOLUTION:"min-resolution",MAX_AUTO_RESOLUTION:"max-auto-resolution",RENDITION_ORDER:"rendition-order",PROGRAM_START_TIME:"program-start-time",PROGRAM_END_TIME:"program-end-time",ASSET_START_TIME:"asset-start-time",ASSET_END_TIME:"asset-end-time",METADATA_URL:"metadata-url",PLAYBACK_ID:"playback-id",PLAYER_SOFTWARE_NAME:"player-software-name",PLAYER_SOFTWARE_VERSION:"player-software-version",PLAYER_INIT_TIME:"player-init-time",PREFER_CMCD:"prefer-cmcd",PREFER_PLAYBACK:"prefer-playback",START_TIME:"start-time",STREAM_TYPE:"stream-type",TARGET_LIVE_WINDOW:"target-live-window",LIVE_EDGE_OFFSET:"live-edge-offset",TYPE:"type",LOGO:"logo",CAP_RENDITION_TO_PLAYER_SIZE:"cap-rendition-to-player-size",INITIAL_BANDWIDTH_ESTIMATE_KBPS:"initial-bandwidth-estimate-kbps",INITIAL_ESTIMATE_SEGMENTS:"initial-estimate-segments",MIN_PRELOAD_SEGMENTS:"min-preload-segments"},Vw=Object.values(k),l_=Gw(),d_="mux-video",nl,Qu,al,Xu,Zu,Ju,ec,tc,ol,ic,Ei,nn,sc,ll,c_=class extends rl{constructor(){super(),vi(this,Ei),vi(this,nl),vi(this,Qu),vi(this,al,{}),vi(this,Xu,{}),vi(this,Zu),vi(this,Ju),vi(this,ec),vi(this,tc),vi(this,ol,""),vi(this,ic,i=>{var e;let t=HT(this.nativeEl),s=(e=this.metadata)!=null?e:{};this.metadata={...t,...s},(t==null?void 0:t["com.mux.video.branding"])==="mux-free-plan"&&(Pi(this,ol,"default"),this.updateLogo())}),vi(this,sc),Pi(this,Qu,Wu())}static get NAME(){return d_}static get VERSION(){return l_}static get observedAttributes(){var i;return[...Vw,...(i=rl.observedAttributes)!=null?i:[]]}static getLogoHTML(i){return!i||i==="false"?"":i==="default"?Kw:`<img part="logo" src="${i}" />`}static getTemplateHTML(i={}){var e;return`
111
111
  ${rl.getTemplateHTML(i)}
112
112
  <style>
113
113
  :host {
@@ -135,16 +135,16 @@ Schedule: ${l.map(p=>Ci(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Remo
135
135
  <slot name="logo">
136
136
  ${this.getLogoHTML((e=i[k.LOGO])!=null?e:"")}
137
137
  </slot>
138
- `}get preferCmcd(){var i;return(i=this.getAttribute(k.PREFER_CMCD))!=null?i:void 0}set preferCmcd(i){i!==this.preferCmcd&&(i?la.includes(i)?this.setAttribute(k.PREFER_CMCD,i):console.warn(`Invalid value for preferCmcd. Must be one of ${la.join()}`):this.removeAttribute(k.PREFER_CMCD))}get playerInitTime(){return this.hasAttribute(k.PLAYER_INIT_TIME)?+this.getAttribute(k.PLAYER_INIT_TIME):pt(this,Qu)}set playerInitTime(i){i!=this.playerInitTime&&(i==null?this.removeAttribute(k.PLAYER_INIT_TIME):this.setAttribute(k.PLAYER_INIT_TIME,`${+i}`))}get playerSoftwareName(){var i;return(i=pt(this,ec))!=null?i:d_}set playerSoftwareName(i){Pi(this,ec,i)}get playerSoftwareVersion(){var i;return(i=pt(this,Ju))!=null?i:l_}set playerSoftwareVersion(i){Pi(this,Ju,i)}get _hls(){var i;return(i=pt(this,Ei,nn))==null?void 0:i.engine}get mux(){var i;return(i=this.nativeEl)==null?void 0:i.mux}get error(){var i;return(i=Mg(this.nativeEl))!=null?i:null}get errorTranslator(){return pt(this,tc)}set errorTranslator(i){Pi(this,tc,i)}get src(){return this.getAttribute("src")}set src(i){i!==this.src&&(i==null?this.removeAttribute("src"):this.setAttribute("src",i))}get type(){var i;return(i=this.getAttribute(k.TYPE))!=null?i:void 0}set type(i){i!==this.type&&(i?this.setAttribute(k.TYPE,i):this.removeAttribute(k.TYPE))}get preload(){let i=this.getAttribute("preload");return i===""?"auto":["none","metadata","auto"].includes(i)?i:super.preload}set preload(i){i!=this.getAttribute("preload")&&(["","none","metadata","auto"].includes(i)?this.setAttribute("preload",i):this.removeAttribute("preload"))}get debug(){return this.getAttribute(k.DEBUG)!=null}set debug(i){i!==this.debug&&(i?this.setAttribute(k.DEBUG,""):this.removeAttribute(k.DEBUG))}get disableTracking(){return this.hasAttribute(k.DISABLE_TRACKING)}set disableTracking(i){i!==this.disableTracking&&this.toggleAttribute(k.DISABLE_TRACKING,!!i)}get disableCookies(){return this.hasAttribute(k.DISABLE_COOKIES)}set disableCookies(i){i!==this.disableCookies&&(i?this.setAttribute(k.DISABLE_COOKIES,""):this.removeAttribute(k.DISABLE_COOKIES))}get disablePseudoEnded(){return this.hasAttribute(k.DISABLE_PSEUDO_ENDED)}set disablePseudoEnded(i){i!==this.disablePseudoEnded&&(i?this.setAttribute(k.DISABLE_PSEUDO_ENDED,""):this.removeAttribute(k.DISABLE_PSEUDO_ENDED))}get startTime(){let i=this.getAttribute(k.START_TIME);if(i==null)return;let e=+i;return Number.isNaN(e)?void 0:e}set startTime(i){i!==this.startTime&&(i==null?this.removeAttribute(k.START_TIME):this.setAttribute(k.START_TIME,`${i}`))}get initialBandwidthEstimateKbps(){let i=this.getAttribute(k.INITIAL_BANDWIDTH_ESTIMATE_KBPS);if(i==null)return;let e=+i;return Number.isNaN(e)?void 0:e}set initialBandwidthEstimateKbps(i){i!==this.initialBandwidthEstimateKbps&&(i==null?this.removeAttribute(k.INITIAL_BANDWIDTH_ESTIMATE_KBPS):this.setAttribute(k.INITIAL_BANDWIDTH_ESTIMATE_KBPS,`${i}`))}get initialEstimateSegments(){let i=this.getAttribute(k.INITIAL_ESTIMATE_SEGMENTS);if(i==null)return;let e=+i;return Number.isNaN(e)?void 0:e}set initialEstimateSegments(i){i!==this.initialEstimateSegments&&(i==null?this.removeAttribute(k.INITIAL_ESTIMATE_SEGMENTS):this.setAttribute(k.INITIAL_ESTIMATE_SEGMENTS,`${i}`))}get minPreloadSegments(){let i=this.getAttribute(k.MIN_PRELOAD_SEGMENTS);if(i==null)return;let e=+i;return Number.isNaN(e)?void 0:e}set minPreloadSegments(i){i!==this.minPreloadSegments&&(i==null?this.removeAttribute(k.MIN_PRELOAD_SEGMENTS):this.setAttribute(k.MIN_PRELOAD_SEGMENTS,`${i}`))}get playbackId(){var i;return this.hasAttribute(k.PLAYBACK_ID)?this.getAttribute(k.PLAYBACK_ID):(i=Yu(this.src))!=null?i:void 0}set playbackId(i){i!==this.playbackId&&(i?this.setAttribute(k.PLAYBACK_ID,i):this.removeAttribute(k.PLAYBACK_ID))}get maxResolution(){var i;return(i=this.getAttribute(k.MAX_RESOLUTION))!=null?i:void 0}set maxResolution(i){i!==this.maxResolution&&(i?this.setAttribute(k.MAX_RESOLUTION,i):this.removeAttribute(k.MAX_RESOLUTION))}get minResolution(){var i;return(i=this.getAttribute(k.MIN_RESOLUTION))!=null?i:void 0}set minResolution(i){i!==this.minResolution&&(i?this.setAttribute(k.MIN_RESOLUTION,i):this.removeAttribute(k.MIN_RESOLUTION))}get maxAutoResolution(){var i;return(i=this.getAttribute(k.MAX_AUTO_RESOLUTION))!=null?i:void 0}set maxAutoResolution(i){i==null?this.removeAttribute(k.MAX_AUTO_RESOLUTION):this.setAttribute(k.MAX_AUTO_RESOLUTION,i)}get renditionOrder(){var i;return(i=this.getAttribute(k.RENDITION_ORDER))!=null?i:void 0}set renditionOrder(i){i!==this.renditionOrder&&(i?this.setAttribute(k.RENDITION_ORDER,i):this.removeAttribute(k.RENDITION_ORDER))}get programStartTime(){let i=this.getAttribute(k.PROGRAM_START_TIME);if(i==null)return;let e=+i;return Number.isNaN(e)?void 0:e}set programStartTime(i){i==null?this.removeAttribute(k.PROGRAM_START_TIME):this.setAttribute(k.PROGRAM_START_TIME,`${i}`)}get programEndTime(){let i=this.getAttribute(k.PROGRAM_END_TIME);if(i==null)return;let e=+i;return Number.isNaN(e)?void 0:e}set programEndTime(i){i==null?this.removeAttribute(k.PROGRAM_END_TIME):this.setAttribute(k.PROGRAM_END_TIME,`${i}`)}get assetStartTime(){let i=this.getAttribute(k.ASSET_START_TIME);if(i==null)return;let e=+i;return Number.isNaN(e)?void 0:e}set assetStartTime(i){i==null?this.removeAttribute(k.ASSET_START_TIME):this.setAttribute(k.ASSET_START_TIME,`${i}`)}get assetEndTime(){let i=this.getAttribute(k.ASSET_END_TIME);if(i==null)return;let e=+i;return Number.isNaN(e)?void 0:e}set assetEndTime(i){i==null?this.removeAttribute(k.ASSET_END_TIME):this.setAttribute(k.ASSET_END_TIME,`${i}`)}get customDomain(){var i;return(i=this.getAttribute(k.CUSTOM_DOMAIN))!=null?i:void 0}set customDomain(i){i!==this.customDomain&&(i?this.setAttribute(k.CUSTOM_DOMAIN,i):this.removeAttribute(k.CUSTOM_DOMAIN))}get capRenditionToPlayerSize(){var i;return((i=this._hlsConfig)==null?void 0:i.capLevelToPlayerSize)!=null?this._hlsConfig.capLevelToPlayerSize:pt(this,sc)}set capRenditionToPlayerSize(i){Pi(this,sc,i)}get drmToken(){var i;return(i=this.getAttribute(k.DRM_TOKEN))!=null?i:void 0}set drmToken(i){i!==this.drmToken&&(i?this.setAttribute(k.DRM_TOKEN,i):this.removeAttribute(k.DRM_TOKEN))}get playbackToken(){var i,e,t,s;if(this.hasAttribute(k.PLAYBACK_TOKEN))return(i=this.getAttribute(k.PLAYBACK_TOKEN))!=null?i:void 0;if(this.hasAttribute(k.PLAYBACK_ID)){let[,r]=Gu((e=this.playbackId)!=null?e:"");return(t=new URLSearchParams(r).get("token"))!=null?t:void 0}if(this.src)return(s=new URLSearchParams(this.src).get("token"))!=null?s:void 0}set playbackToken(i){i!==this.playbackToken&&(i?this.setAttribute(k.PLAYBACK_TOKEN,i):this.removeAttribute(k.PLAYBACK_TOKEN))}get tokens(){let i=this.getAttribute(k.PLAYBACK_TOKEN),e=this.getAttribute(k.DRM_TOKEN);return{...pt(this,Xu),...i!=null?{playback:i}:{},...e!=null?{drm:e}:{}}}set tokens(i){Pi(this,Xu,i!=null?i:{})}get ended(){return Og(this.nativeEl,this._hls)}get envKey(){var i;return(i=this.getAttribute(k.ENV_KEY))!=null?i:void 0}set envKey(i){i!==this.envKey&&(i?this.setAttribute(k.ENV_KEY,i):this.removeAttribute(k.ENV_KEY))}get beaconCollectionDomain(){var i;return(i=this.getAttribute(k.BEACON_COLLECTION_DOMAIN))!=null?i:void 0}set beaconCollectionDomain(i){i!==this.beaconCollectionDomain&&(i?this.setAttribute(k.BEACON_COLLECTION_DOMAIN,i):this.removeAttribute(k.BEACON_COLLECTION_DOMAIN))}get streamType(){var i;return(i=this.getAttribute(k.STREAM_TYPE))!=null?i:Hu(this.nativeEl)}set streamType(i){i!==this.streamType&&(i?this.setAttribute(k.STREAM_TYPE,i):this.removeAttribute(k.STREAM_TYPE))}get targetLiveWindow(){return this.hasAttribute(k.TARGET_LIVE_WINDOW)?+this.getAttribute(k.TARGET_LIVE_WINDOW):Gb(this.nativeEl)}set targetLiveWindow(i){i!=this.targetLiveWindow&&(i==null?this.removeAttribute(k.TARGET_LIVE_WINDOW):this.setAttribute(k.TARGET_LIVE_WINDOW,`${+i}`))}get liveEdgeStart(){var i,e;if(this.hasAttribute(k.LIVE_EDGE_OFFSET)){let{liveEdgeOffset:t}=this,s=(i=this.nativeEl.seekable.end(0))!=null?i:0,r=(e=this.nativeEl.seekable.start(0))!=null?e:0;return Math.max(r,s-t)}return Kb(this.nativeEl)}get liveEdgeOffset(){if(this.hasAttribute(k.LIVE_EDGE_OFFSET))return+this.getAttribute(k.LIVE_EDGE_OFFSET)}set liveEdgeOffset(i){i!=this.liveEdgeOffset&&(i==null?this.removeAttribute(k.LIVE_EDGE_OFFSET):this.setAttribute(k.LIVE_EDGE_OFFSET,`${+i}`))}get seekable(){return ju(this.nativeEl)}async addCuePoints(i){return Rg(this.nativeEl,i)}get activeCuePoint(){return xg(this.nativeEl)}get cuePoints(){return Pb(this.nativeEl)}async addChapters(i){return Dg(this.nativeEl,i)}get activeChapter(){return Cg(this.nativeEl)}get chapters(){return Nb(this.nativeEl)}getStartDate(){return Ub(this.nativeEl,this._hls)}get currentPdt(){return Fb(this.nativeEl,this._hls)}get preferPlayback(){let i=this.getAttribute(k.PREFER_PLAYBACK);if(i===gi.MSE||i===gi.NATIVE)return i}set preferPlayback(i){i!==this.preferPlayback&&(i===gi.MSE||i===gi.NATIVE?this.setAttribute(k.PREFER_PLAYBACK,i):this.removeAttribute(k.PREFER_PLAYBACK))}get metadata(){return{...this.getAttributeNames().filter(i=>i.startsWith("metadata-")&&![k.METADATA_URL].includes(i)).reduce((i,e)=>{let t=this.getAttribute(e);return t!=null&&(i[e.replace(/^metadata-/,"").replace(/-/g,"_")]=t),i},{}),...pt(this,al)}}set metadata(i){Pi(this,al,i!=null?i:{}),this.mux&&this.mux.emit("hb",pt(this,al))}get _hlsConfig(){return pt(this,Zu)}set _hlsConfig(i){Pi(this,Zu,i)}get logo(){var i;return(i=this.getAttribute(k.LOGO))!=null?i:pt(this,ol)}set logo(i){i?this.setAttribute(k.LOGO,i):this.removeAttribute(k.LOGO)}load(){Ng(this,this.nativeEl,pt(this,Ei,nn))}unload(){Ug(this.nativeEl,pt(this,Ei,nn),this)}attributeChangedCallback(i,e,t){var s,r;switch(rl.observedAttributes.includes(i)&&!["src","autoplay","preload"].includes(i)&&super.attributeChangedCallback(i,e,t),i){case k.PLAYER_SOFTWARE_NAME:this.playerSoftwareName=t!=null?t:void 0;break;case k.PLAYER_SOFTWARE_VERSION:this.playerSoftwareVersion=t!=null?t:void 0;break;case"src":{let n=!!e,a=!!t;!n&&a?zu(this,Ei,ll).call(this):n&&!a?this.unload():n&&a&&(this.unload(),zu(this,Ei,ll).call(this));break}case"autoplay":if(t===e)break;(s=pt(this,Ei,nn))==null||s.setAutoplay(this.autoplay);break;case"preload":if(t===e)break;(r=pt(this,Ei,nn))==null||r.setPreload(t);break;case k.PLAYBACK_ID:case k.CUSTOM_DOMAIN:case k.MAX_RESOLUTION:case k.MIN_RESOLUTION:case k.RENDITION_ORDER:case k.PROGRAM_START_TIME:case k.PROGRAM_END_TIME:case k.ASSET_START_TIME:case k.ASSET_END_TIME:case k.PLAYBACK_TOKEN:this.src=sl(this);break;case k.DEBUG:{let n=this.debug;this.mux&&console.info("Cannot toggle debug mode of mux data after initialization. Make sure you set all metadata to override before setting the src."),this._hls&&(this._hls.config.debug=n);break}case k.METADATA_URL:t&&fetch(t).then(n=>n.json()).then(n=>this.metadata=n).catch(()=>console.error(`Unable to load or parse metadata JSON from metadata-url ${t}!`));break;case k.STREAM_TYPE:(t==null||t!==e)&&this.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}));break;case k.TARGET_LIVE_WINDOW:(t==null||t!==e)&&this.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0,detail:this.targetLiveWindow}));break;case k.LOGO:(t==null||t!==e)&&this.updateLogo();break;case k.DISABLE_TRACKING:{if(t==null||t!==e){let n=this.currentTime,a=this.paused;this.unload(),zu(this,Ei,ll).call(this).then(()=>{this.currentTime=n,a||this.play()})}break}case k.DISABLE_COOKIES:{(t==null||t!==e)&&this.disableCookies&&document.cookie.split(";").forEach(n=>{n.trim().startsWith("muxData")&&(document.cookie=n.replace(/^ +/,"").replace(/=.*/,"=;expires="+new Date().toUTCString()+";path=/"))});break}case k.CAP_RENDITION_TO_PLAYER_SIZE:(t==null||t!==e)&&(this.capRenditionToPlayerSize=t!=null?!0:void 0)}}updateLogo(){if(!this.shadowRoot)return;let i=this.shadowRoot.querySelector('slot[name="logo"]');if(!i)return;let e=this.constructor.getLogoHTML(pt(this,ol)||this.logo);i.innerHTML=e}connectedCallback(){var i,e;(i=super.connectedCallback)==null||i.call(this),(e=this.nativeEl)==null||e.addEventListener("muxmetadata",pt(this,ic)),this.nativeEl&&this.src&&!pt(this,Ei,nn)&&zu(this,Ei,ll).call(this)}disconnectedCallback(){var i,e;(i=this.nativeEl)==null||i.removeEventListener("muxmetadata",pt(this,ic)),this.unload(),(e=super.disconnectedCallback)==null||e.call(this)}handleEvent(i){i.target===this.nativeEl&&this.dispatchEvent(new CustomEvent(i.type,{composed:!0,detail:i.detail}))}};nl=new WeakMap,Qu=new WeakMap,al=new WeakMap,Xu=new WeakMap,Zu=new WeakMap,Ju=new WeakMap,ec=new WeakMap,tc=new WeakMap,ol=new WeakMap,ic=new WeakMap,Ei=new WeakSet,nn=function(){return Vb(this.nativeEl)},sc=new WeakMap,ll=async function(){pt(this,nl)||(await Pi(this,nl,Promise.resolve()),Pi(this,nl,null),this.load())};var ts=new WeakMap,da=class extends Error{},rc=class extends Error{};var Ww=["application/x-mpegURL","application/vnd.apple.mpegurl","audio/mpegurl"],h_=globalThis.WeakRef?class extends Set{add(i){super.add(new WeakRef(i))}forEach(i){super.forEach(e=>{let t=e.deref();t&&i(t)})}}:Set;function f_(i){var e,t,s;(t=(e=globalThis.chrome)==null?void 0:e.cast)!=null&&t.isAvailable?(s=globalThis.cast)!=null&&s.framework?i():customElements.whenDefined("google-cast-button").then(i):globalThis.__onGCastApiAvailable=()=>{customElements.whenDefined("google-cast-button").then(i)}}function m_(){return globalThis.chrome}function p_(){var t;let i="https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1";if((t=globalThis.chrome)!=null&&t.cast||document.querySelector(`script[src="${i}"]`))return;let e=document.createElement("script");e.src=i,document.head.append(e)}function Ms(){var i,e;return(e=(i=globalThis.cast)==null?void 0:i.framework)==null?void 0:e.CastContext.getInstance()}function dl(){var i;return(i=Ms())==null?void 0:i.getCurrentSession()}function nc(){var i;return(i=dl())==null?void 0:i.getSessionObj().media[0]}function g_(i){return new Promise((e,t)=>{nc().editTracksInfo(i,e,t)})}function v_(i){return new Promise((e,t)=>{nc().getStatus(i,e,t)})}function Gg(i){return Ms().setOptions({...Kg(),...i})}function Kg(){return{receiverApplicationId:"CC1AD845",autoJoinPolicy:"origin_scoped",androidReceiverCompatible:!1,language:"en-US",resumeSavedSession:!0}}function qw(i){if(!i)return;let e=/\.([a-zA-Z0-9]+)(?:\?.*)?$/,t=i.match(e);return t?t[1]:null}function Yw(i){let e=i.split(`
138
+ `}get preferCmcd(){var i;return(i=this.getAttribute(k.PREFER_CMCD))!=null?i:void 0}set preferCmcd(i){i!==this.preferCmcd&&(i?la.includes(i)?this.setAttribute(k.PREFER_CMCD,i):console.warn(`Invalid value for preferCmcd. Must be one of ${la.join()}`):this.removeAttribute(k.PREFER_CMCD))}get playerInitTime(){return this.hasAttribute(k.PLAYER_INIT_TIME)?+this.getAttribute(k.PLAYER_INIT_TIME):pt(this,Qu)}set playerInitTime(i){i!=this.playerInitTime&&(i==null?this.removeAttribute(k.PLAYER_INIT_TIME):this.setAttribute(k.PLAYER_INIT_TIME,`${+i}`))}get playerSoftwareName(){var i;return(i=pt(this,ec))!=null?i:d_}set playerSoftwareName(i){Pi(this,ec,i)}get playerSoftwareVersion(){var i;return(i=pt(this,Ju))!=null?i:l_}set playerSoftwareVersion(i){Pi(this,Ju,i)}get _hls(){var i;return(i=pt(this,Ei,nn))==null?void 0:i.engine}get mux(){var i;return(i=this.nativeEl)==null?void 0:i.mux}get error(){var i;return(i=Mg(this.nativeEl))!=null?i:null}get errorTranslator(){return pt(this,tc)}set errorTranslator(i){Pi(this,tc,i)}get src(){return this.getAttribute("src")}set src(i){i!==this.src&&(i==null?this.removeAttribute("src"):this.setAttribute("src",i))}get type(){var i;return(i=this.getAttribute(k.TYPE))!=null?i:void 0}set type(i){i!==this.type&&(i?this.setAttribute(k.TYPE,i):this.removeAttribute(k.TYPE))}get preload(){let i=this.getAttribute("preload");return i===""?"auto":["none","metadata","auto"].includes(i)?i:super.preload}set preload(i){i!=this.getAttribute("preload")&&(["","none","metadata","auto"].includes(i)?this.setAttribute("preload",i):this.removeAttribute("preload"))}get debug(){return this.getAttribute(k.DEBUG)!=null}set debug(i){i!==this.debug&&(i?this.setAttribute(k.DEBUG,""):this.removeAttribute(k.DEBUG))}get disableTracking(){return this.hasAttribute(k.DISABLE_TRACKING)}set disableTracking(i){i!==this.disableTracking&&this.toggleAttribute(k.DISABLE_TRACKING,!!i)}get disableCookies(){return this.hasAttribute(k.DISABLE_COOKIES)}set disableCookies(i){i!==this.disableCookies&&(i?this.setAttribute(k.DISABLE_COOKIES,""):this.removeAttribute(k.DISABLE_COOKIES))}get disablePseudoEnded(){return this.hasAttribute(k.DISABLE_PSEUDO_ENDED)}set disablePseudoEnded(i){i!==this.disablePseudoEnded&&(i?this.setAttribute(k.DISABLE_PSEUDO_ENDED,""):this.removeAttribute(k.DISABLE_PSEUDO_ENDED))}get startTime(){let i=this.getAttribute(k.START_TIME);if(i==null)return;let e=+i;return Number.isNaN(e)?void 0:e}set startTime(i){i!==this.startTime&&(i==null?this.removeAttribute(k.START_TIME):this.setAttribute(k.START_TIME,`${i}`))}get initialBandwidthEstimateKbps(){let i=this.getAttribute(k.INITIAL_BANDWIDTH_ESTIMATE_KBPS);if(i==null)return;let e=+i;return Number.isNaN(e)?void 0:e}set initialBandwidthEstimateKbps(i){i!==this.initialBandwidthEstimateKbps&&(i==null?this.removeAttribute(k.INITIAL_BANDWIDTH_ESTIMATE_KBPS):this.setAttribute(k.INITIAL_BANDWIDTH_ESTIMATE_KBPS,`${i}`))}get initialEstimateSegments(){let i=this.getAttribute(k.INITIAL_ESTIMATE_SEGMENTS);if(i==null)return;let e=+i;return Number.isNaN(e)?void 0:e}set initialEstimateSegments(i){i!==this.initialEstimateSegments&&(i==null?this.removeAttribute(k.INITIAL_ESTIMATE_SEGMENTS):this.setAttribute(k.INITIAL_ESTIMATE_SEGMENTS,`${i}`))}get minPreloadSegments(){let i=this.getAttribute(k.MIN_PRELOAD_SEGMENTS);if(i==null)return;let e=+i;return Number.isNaN(e)?void 0:e}set minPreloadSegments(i){i!==this.minPreloadSegments&&(i==null?this.removeAttribute(k.MIN_PRELOAD_SEGMENTS):this.setAttribute(k.MIN_PRELOAD_SEGMENTS,`${i}`))}get playbackId(){var i;return this.hasAttribute(k.PLAYBACK_ID)?this.getAttribute(k.PLAYBACK_ID):(i=Yu(this.src))!=null?i:void 0}set playbackId(i){i!==this.playbackId&&(i?this.setAttribute(k.PLAYBACK_ID,i):this.removeAttribute(k.PLAYBACK_ID))}get maxResolution(){var i;return(i=this.getAttribute(k.MAX_RESOLUTION))!=null?i:void 0}set maxResolution(i){i!==this.maxResolution&&(i?this.setAttribute(k.MAX_RESOLUTION,i):this.removeAttribute(k.MAX_RESOLUTION))}get minResolution(){var i;return(i=this.getAttribute(k.MIN_RESOLUTION))!=null?i:void 0}set minResolution(i){i!==this.minResolution&&(i?this.setAttribute(k.MIN_RESOLUTION,i):this.removeAttribute(k.MIN_RESOLUTION))}get maxAutoResolution(){var i;return(i=this.getAttribute(k.MAX_AUTO_RESOLUTION))!=null?i:void 0}set maxAutoResolution(i){i==null?this.removeAttribute(k.MAX_AUTO_RESOLUTION):this.setAttribute(k.MAX_AUTO_RESOLUTION,i)}get renditionOrder(){var i;return(i=this.getAttribute(k.RENDITION_ORDER))!=null?i:void 0}set renditionOrder(i){i!==this.renditionOrder&&(i?this.setAttribute(k.RENDITION_ORDER,i):this.removeAttribute(k.RENDITION_ORDER))}get programStartTime(){let i=this.getAttribute(k.PROGRAM_START_TIME);if(i==null)return;let e=+i;return Number.isNaN(e)?void 0:e}set programStartTime(i){i==null?this.removeAttribute(k.PROGRAM_START_TIME):this.setAttribute(k.PROGRAM_START_TIME,`${i}`)}get programEndTime(){let i=this.getAttribute(k.PROGRAM_END_TIME);if(i==null)return;let e=+i;return Number.isNaN(e)?void 0:e}set programEndTime(i){i==null?this.removeAttribute(k.PROGRAM_END_TIME):this.setAttribute(k.PROGRAM_END_TIME,`${i}`)}get assetStartTime(){let i=this.getAttribute(k.ASSET_START_TIME);if(i==null)return;let e=+i;return Number.isNaN(e)?void 0:e}set assetStartTime(i){i==null?this.removeAttribute(k.ASSET_START_TIME):this.setAttribute(k.ASSET_START_TIME,`${i}`)}get assetEndTime(){let i=this.getAttribute(k.ASSET_END_TIME);if(i==null)return;let e=+i;return Number.isNaN(e)?void 0:e}set assetEndTime(i){i==null?this.removeAttribute(k.ASSET_END_TIME):this.setAttribute(k.ASSET_END_TIME,`${i}`)}get customDomain(){var i;return(i=this.getAttribute(k.CUSTOM_DOMAIN))!=null?i:void 0}set customDomain(i){i!==this.customDomain&&(i?this.setAttribute(k.CUSTOM_DOMAIN,i):this.removeAttribute(k.CUSTOM_DOMAIN))}get capRenditionToPlayerSize(){var i;return((i=this._hlsConfig)==null?void 0:i.capLevelToPlayerSize)!=null?this._hlsConfig.capLevelToPlayerSize:pt(this,sc)}set capRenditionToPlayerSize(i){Pi(this,sc,i)}get drmToken(){var i;return(i=this.getAttribute(k.DRM_TOKEN))!=null?i:void 0}set drmToken(i){i!==this.drmToken&&(i?this.setAttribute(k.DRM_TOKEN,i):this.removeAttribute(k.DRM_TOKEN))}get playbackToken(){var i,e,t,s;if(this.hasAttribute(k.PLAYBACK_TOKEN))return(i=this.getAttribute(k.PLAYBACK_TOKEN))!=null?i:void 0;if(this.hasAttribute(k.PLAYBACK_ID)){let[,r]=Gu((e=this.playbackId)!=null?e:"");return(t=new URLSearchParams(r).get("token"))!=null?t:void 0}if(this.src)return(s=new URLSearchParams(this.src).get("token"))!=null?s:void 0}set playbackToken(i){i!==this.playbackToken&&(i?this.setAttribute(k.PLAYBACK_TOKEN,i):this.removeAttribute(k.PLAYBACK_TOKEN))}get tokens(){let i=this.getAttribute(k.PLAYBACK_TOKEN),e=this.getAttribute(k.DRM_TOKEN);return{...pt(this,Xu),...i!=null?{playback:i}:{},...e!=null?{drm:e}:{}}}set tokens(i){Pi(this,Xu,i!=null?i:{})}get ended(){return Og(this.nativeEl,this._hls)}get envKey(){var i;return(i=this.getAttribute(k.ENV_KEY))!=null?i:void 0}set envKey(i){i!==this.envKey&&(i?this.setAttribute(k.ENV_KEY,i):this.removeAttribute(k.ENV_KEY))}get beaconCollectionDomain(){var i;return(i=this.getAttribute(k.BEACON_COLLECTION_DOMAIN))!=null?i:void 0}set beaconCollectionDomain(i){i!==this.beaconCollectionDomain&&(i?this.setAttribute(k.BEACON_COLLECTION_DOMAIN,i):this.removeAttribute(k.BEACON_COLLECTION_DOMAIN))}get streamType(){var i;return(i=this.getAttribute(k.STREAM_TYPE))!=null?i:Hu(this.nativeEl)}set streamType(i){i!==this.streamType&&(i?this.setAttribute(k.STREAM_TYPE,i):this.removeAttribute(k.STREAM_TYPE))}get targetLiveWindow(){return this.hasAttribute(k.TARGET_LIVE_WINDOW)?+this.getAttribute(k.TARGET_LIVE_WINDOW):GT(this.nativeEl)}set targetLiveWindow(i){i!=this.targetLiveWindow&&(i==null?this.removeAttribute(k.TARGET_LIVE_WINDOW):this.setAttribute(k.TARGET_LIVE_WINDOW,`${+i}`))}get liveEdgeStart(){var i,e;if(this.hasAttribute(k.LIVE_EDGE_OFFSET)){let{liveEdgeOffset:t}=this,s=(i=this.nativeEl.seekable.end(0))!=null?i:0,r=(e=this.nativeEl.seekable.start(0))!=null?e:0;return Math.max(r,s-t)}return KT(this.nativeEl)}get liveEdgeOffset(){if(this.hasAttribute(k.LIVE_EDGE_OFFSET))return+this.getAttribute(k.LIVE_EDGE_OFFSET)}set liveEdgeOffset(i){i!=this.liveEdgeOffset&&(i==null?this.removeAttribute(k.LIVE_EDGE_OFFSET):this.setAttribute(k.LIVE_EDGE_OFFSET,`${+i}`))}get seekable(){return ju(this.nativeEl)}async addCuePoints(i){return this.nativeEl.currentSrc||console.warn("addCuePoints() was called before the media element has loaded. Wait for the loadstart event before calling addCuePoints()."),Rg(this.nativeEl,i)}get activeCuePoint(){return xg(this.nativeEl)}get cuePoints(){return PT(this.nativeEl)}async addChapters(i){return this.nativeEl.currentSrc||console.warn("addChapters() was called before the media element has loaded. Wait for the loadstart event before calling addChapters()."),Dg(this.nativeEl,i)}get activeChapter(){return Cg(this.nativeEl)}get chapters(){return NT(this.nativeEl)}getStartDate(){return UT(this.nativeEl,this._hls)}get currentPdt(){return FT(this.nativeEl,this._hls)}get preferPlayback(){let i=this.getAttribute(k.PREFER_PLAYBACK);if(i===gi.MSE||i===gi.NATIVE)return i}set preferPlayback(i){i!==this.preferPlayback&&(i===gi.MSE||i===gi.NATIVE?this.setAttribute(k.PREFER_PLAYBACK,i):this.removeAttribute(k.PREFER_PLAYBACK))}get metadata(){return{...this.getAttributeNames().filter(i=>i.startsWith("metadata-")&&![k.METADATA_URL].includes(i)).reduce((i,e)=>{let t=this.getAttribute(e);return t!=null&&(i[e.replace(/^metadata-/,"").replace(/-/g,"_")]=t),i},{}),...pt(this,al)}}set metadata(i){Pi(this,al,i!=null?i:{}),this.mux&&this.mux.emit("hb",pt(this,al))}get _hlsConfig(){return pt(this,Zu)}set _hlsConfig(i){Pi(this,Zu,i)}get logo(){var i;return(i=this.getAttribute(k.LOGO))!=null?i:pt(this,ol)}set logo(i){i?this.setAttribute(k.LOGO,i):this.removeAttribute(k.LOGO)}load(){Ng(this,this.nativeEl,pt(this,Ei,nn))}unload(){Ug(this.nativeEl,pt(this,Ei,nn),this)}attributeChangedCallback(i,e,t){var s,r;switch(rl.observedAttributes.includes(i)&&!["src","autoplay","preload"].includes(i)&&super.attributeChangedCallback(i,e,t),i){case k.PLAYER_SOFTWARE_NAME:this.playerSoftwareName=t!=null?t:void 0;break;case k.PLAYER_SOFTWARE_VERSION:this.playerSoftwareVersion=t!=null?t:void 0;break;case"src":{let n=!!e,a=!!t;!n&&a?zu(this,Ei,ll).call(this):n&&!a?this.unload():n&&a&&(this.unload(),zu(this,Ei,ll).call(this));break}case"autoplay":if(t===e)break;(s=pt(this,Ei,nn))==null||s.setAutoplay(this.autoplay);break;case"preload":if(t===e)break;(r=pt(this,Ei,nn))==null||r.setPreload(t);break;case k.PLAYBACK_ID:case k.CUSTOM_DOMAIN:case k.MAX_RESOLUTION:case k.MIN_RESOLUTION:case k.RENDITION_ORDER:case k.PROGRAM_START_TIME:case k.PROGRAM_END_TIME:case k.ASSET_START_TIME:case k.ASSET_END_TIME:case k.PLAYBACK_TOKEN:this.src=sl(this);break;case k.DEBUG:{let n=this.debug;this.mux&&console.info("Cannot toggle debug mode of mux data after initialization. Make sure you set all metadata to override before setting the src."),this._hls&&(this._hls.config.debug=n);break}case k.METADATA_URL:t&&fetch(t).then(n=>n.json()).then(n=>this.metadata=n).catch(()=>console.error(`Unable to load or parse metadata JSON from metadata-url ${t}!`));break;case k.STREAM_TYPE:(t==null||t!==e)&&this.dispatchEvent(new CustomEvent("streamtypechange",{composed:!0,bubbles:!0}));break;case k.TARGET_LIVE_WINDOW:(t==null||t!==e)&&this.dispatchEvent(new CustomEvent("targetlivewindowchange",{composed:!0,bubbles:!0,detail:this.targetLiveWindow}));break;case k.LOGO:(t==null||t!==e)&&this.updateLogo();break;case k.DISABLE_TRACKING:{if(t==null||t!==e){let n=this.currentTime,a=this.paused;this.unload(),zu(this,Ei,ll).call(this).then(()=>{this.currentTime=n,a||this.play()})}break}case k.DISABLE_COOKIES:{(t==null||t!==e)&&this.disableCookies&&document.cookie.split(";").forEach(n=>{n.trim().startsWith("muxData")&&(document.cookie=n.replace(/^ +/,"").replace(/=.*/,"=;expires="+new Date().toUTCString()+";path=/"))});break}case k.CAP_RENDITION_TO_PLAYER_SIZE:(t==null||t!==e)&&(this.capRenditionToPlayerSize=t!=null?!0:void 0)}}updateLogo(){if(!this.shadowRoot)return;let i=this.shadowRoot.querySelector('slot[name="logo"]');if(!i)return;let e=this.constructor.getLogoHTML(pt(this,ol)||this.logo);i.innerHTML=e}connectedCallback(){var i,e;(i=super.connectedCallback)==null||i.call(this),(e=this.nativeEl)==null||e.addEventListener("muxmetadata",pt(this,ic)),this.nativeEl&&this.src&&!pt(this,Ei,nn)&&zu(this,Ei,ll).call(this)}disconnectedCallback(){var i,e;(i=this.nativeEl)==null||i.removeEventListener("muxmetadata",pt(this,ic)),this.unload(),(e=super.disconnectedCallback)==null||e.call(this)}handleEvent(i){i.target===this.nativeEl&&this.dispatchEvent(new CustomEvent(i.type,{composed:!0,detail:i.detail}))}};nl=new WeakMap,Qu=new WeakMap,al=new WeakMap,Xu=new WeakMap,Zu=new WeakMap,Ju=new WeakMap,ec=new WeakMap,tc=new WeakMap,ol=new WeakMap,ic=new WeakMap,Ei=new WeakSet,nn=function(){return VT(this.nativeEl)},sc=new WeakMap,ll=async function(){pt(this,nl)||(await Pi(this,nl,Promise.resolve()),Pi(this,nl,null),this.load())};var ts=new WeakMap,da=class extends Error{},rc=class extends Error{};var Ww=["application/x-mpegURL","application/vnd.apple.mpegurl","audio/mpegurl"],h_=globalThis.WeakRef?class extends Set{add(i){super.add(new WeakRef(i))}forEach(i){super.forEach(e=>{let t=e.deref();t&&i(t)})}}:Set;function f_(i){var e,t,s;(t=(e=globalThis.chrome)==null?void 0:e.cast)!=null&&t.isAvailable?(s=globalThis.cast)!=null&&s.framework?i():customElements.whenDefined("google-cast-button").then(i):globalThis.__onGCastApiAvailable=()=>{customElements.whenDefined("google-cast-button").then(i)}}function m_(){return globalThis.chrome}function p_(){var t;let i="https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1";if((t=globalThis.chrome)!=null&&t.cast||document.querySelector(`script[src="${i}"]`))return;let e=document.createElement("script");e.src=i,document.head.append(e)}function Ms(){var i,e;return(e=(i=globalThis.cast)==null?void 0:i.framework)==null?void 0:e.CastContext.getInstance()}function dl(){var i;return(i=Ms())==null?void 0:i.getCurrentSession()}function nc(){var i;return(i=dl())==null?void 0:i.getSessionObj().media[0]}function g_(i){return new Promise((e,t)=>{nc().editTracksInfo(i,e,t)})}function v_(i){return new Promise((e,t)=>{nc().getStatus(i,e,t)})}function Gg(i){return Ms().setOptions({...Kg(),...i})}function Kg(){return{receiverApplicationId:"CC1AD845",autoJoinPolicy:"origin_scoped",androidReceiverCompatible:!1,language:"en-US",resumeSavedSession:!0}}function qw(i){if(!i)return;let e=/\.([a-zA-Z0-9]+)(?:\?.*)?$/,t=i.match(e);return t?t[1]:null}function Yw(i){let e=i.split(`
139
139
  `),t=[];for(let s=0;s<e.length;s++)if(e[s].trim().startsWith("#EXT-X-STREAM-INF")){let n=e[s+1]?e[s+1].trim():"";n&&!n.startsWith("#")&&t.push(n)}return t}function jw(i){return i.split(`
140
- `).find(s=>!s.trim().startsWith("#")&&s.trim()!=="")}async function E_(i){if(!i)return!1;if(/\.m3u8?(\?.*)?$/i.test(i))return!0;if(i.startsWith("blob:"))return!1;try{let t=(await fetch(i,{method:"HEAD"})).headers.get("Content-Type");return Ww.some(s=>t===s)}catch(e){return console.error("Error while trying to get the Content-Type of the manifest",e),!1}}async function y_(i){if(!(!i||i.startsWith("blob:")))try{let e=await(await fetch(i)).text(),t=e,s=Yw(e);if(s.length>0){let a=new URL(s[0],i).toString();t=await(await fetch(a)).text()}let r=jw(t);return qw(r)}catch(e){console.error("Error while trying to parse the manifest playlist",e);return}}var ac=new h_,Ps=new WeakSet,At;f_(()=>{var i,e,t,s;if(!((e=(i=globalThis.chrome)==null?void 0:i.cast)!=null&&e.isAvailable)){console.debug("chrome.cast.isAvailable",(s=(t=globalThis.chrome)==null?void 0:t.cast)==null?void 0:s.isAvailable);return}At||(At=cast.framework,Ms().addEventListener(At.CastContextEventType.CAST_STATE_CHANGED,r=>{ac.forEach(n=>{var a,o;return(o=(a=ts.get(n)).onCastStateChanged)==null?void 0:o.call(a,r)})}),Ms().addEventListener(At.CastContextEventType.SESSION_STATE_CHANGED,r=>{ac.forEach(n=>{var a,o;return(o=(a=ts.get(n)).onSessionStateChanged)==null?void 0:o.call(a,r)})}),ac.forEach(r=>{var n,a;return(a=(n=ts.get(r)).init)==null?void 0:a.call(n)}))});var T_=0,Ce,ua,Gt,Oi,on,ln,ur,lc,ul,ze,an,b_,__,Vg,A_,Wg,S_,qg,oc=class extends EventTarget{constructor(t){super();oe(this,ze);oe(this,Ce);oe(this,ua);oe(this,Gt);oe(this,Oi);oe(this,on,"disconnected");oe(this,ln,!1);oe(this,ur,new Set);oe(this,lc,new WeakMap);oe(this,ul,()=>Ne(this,ze,qg).call(this));ee(this,Ce,t),ac.add(this),ts.set(this,{init:()=>Ne(this,ze,Wg).call(this),onCastStateChanged:()=>Ne(this,ze,Vg).call(this),onSessionStateChanged:()=>Ne(this,ze,A_).call(this),getCastPlayer:()=>w(this,ze,an)}),Ne(this,ze,Wg).call(this)}destroy(){var t,s,r;(s=(t=w(this,Ce))==null?void 0:t.textTracks)==null||s.removeEventListener("change",w(this,ul)),w(this,Oi)&&((r=w(this,Gt))!=null&&r.controller)&&Object.entries(w(this,Oi)).forEach(([n,a])=>{w(this,Gt).controller.removeEventListener(n,a)}),w(this,Ce)&&Ps.delete(w(this,Ce)),ee(this,ua,!1)}get state(){return w(this,on)}async watchAvailability(t){if(w(this,Ce).disableRemotePlayback)throw new da("disableRemotePlayback attribute is present.");return w(this,lc).set(t,++T_),w(this,ur).add(t),queueMicrotask(()=>t(Ne(this,ze,__).call(this))),T_}async cancelWatchAvailability(t){if(w(this,Ce).disableRemotePlayback)throw new da("disableRemotePlayback attribute is present.");t?w(this,ur).delete(t):w(this,ur).clear()}async prompt(){var s,r,n,a;if(w(this,Ce).disableRemotePlayback)throw new da("disableRemotePlayback attribute is present.");if(!((r=(s=globalThis.chrome)==null?void 0:s.cast)!=null&&r.isAvailable))throw new rc("The RemotePlayback API is disabled on this platform.");let t=Ps.has(w(this,Ce));Ps.add(w(this,Ce)),Gg(w(this,Ce).castOptions),Object.entries(w(this,Oi)).forEach(([o,l])=>{w(this,Gt).controller.addEventListener(o,l)});try{await Ms().requestSession()}catch(o){if(t||Ps.delete(w(this,Ce)),o==="cancel")return;throw new Error(o)}(a=(n=ts.get(w(this,Ce)))==null?void 0:n.loadOnPrompt)==null||a.call(n)}};Ce=new WeakMap,ua=new WeakMap,Gt=new WeakMap,Oi=new WeakMap,on=new WeakMap,ln=new WeakMap,ur=new WeakMap,lc=new WeakMap,ul=new WeakMap,ze=new WeakSet,an=function(){if(Ps.has(w(this,Ce)))return w(this,Gt)},b_=function(){Ps.has(w(this,Ce))&&(Object.entries(w(this,Oi)).forEach(([t,s])=>{w(this,Gt).controller.removeEventListener(t,s)}),Ps.delete(w(this,Ce)),w(this,Ce).muted=w(this,Gt).isMuted,w(this,Ce).currentTime=w(this,Gt).savedPlayerState.currentTime,w(this,Gt).savedPlayerState.isPaused===!1&&w(this,Ce).play())},__=function(){var s;let t=(s=Ms())==null?void 0:s.getCastState();return t&&t!=="NO_DEVICES_AVAILABLE"},Vg=function(){let t=Ms().getCastState();if(Ps.has(w(this,Ce))&&t==="CONNECTING"&&(ee(this,on,"connecting"),this.dispatchEvent(new Event("connecting"))),!w(this,ln)&&(t!=null&&t.includes("CONNECT"))){ee(this,ln,!0);for(let s of w(this,ur))s(!0)}else if(w(this,ln)&&(!t||t==="NO_DEVICES_AVAILABLE")){ee(this,ln,!1);for(let s of w(this,ur))s(!1)}},A_=async function(){var s;let{SESSION_RESUMED:t}=At.SessionState;if(Ms().getSessionState()===t&&w(this,Ce).castSrc===((s=nc())==null?void 0:s.media.contentId)){Ps.add(w(this,Ce)),Object.entries(w(this,Oi)).forEach(([r,n])=>{w(this,Gt).controller.addEventListener(r,n)});try{await v_(new chrome.cast.media.GetStatusRequest)}catch(r){console.error(r)}w(this,Oi)[At.RemotePlayerEventType.IS_PAUSED_CHANGED](),w(this,Oi)[At.RemotePlayerEventType.PLAYER_STATE_CHANGED]()}},Wg=function(){!At||w(this,ua)||(ee(this,ua,!0),Gg(w(this,Ce).castOptions),w(this,Ce).textTracks.addEventListener("change",w(this,ul)),Ne(this,ze,Vg).call(this),ee(this,Gt,new At.RemotePlayer),new At.RemotePlayerController(w(this,Gt)),ee(this,Oi,{[At.RemotePlayerEventType.IS_CONNECTED_CHANGED]:({value:t})=>{t===!0?(ee(this,on,"connected"),this.dispatchEvent(new Event("connect"))):(Ne(this,ze,b_).call(this),ee(this,on,"disconnected"),this.dispatchEvent(new Event("disconnect")))},[At.RemotePlayerEventType.DURATION_CHANGED]:()=>{w(this,Ce).dispatchEvent(new Event("durationchange"))},[At.RemotePlayerEventType.VOLUME_LEVEL_CHANGED]:()=>{w(this,Ce).dispatchEvent(new Event("volumechange"))},[At.RemotePlayerEventType.IS_MUTED_CHANGED]:()=>{w(this,Ce).dispatchEvent(new Event("volumechange"))},[At.RemotePlayerEventType.CURRENT_TIME_CHANGED]:()=>{var t;(t=w(this,ze,an))!=null&&t.isMediaLoaded&&w(this,Ce).dispatchEvent(new Event("timeupdate"))},[At.RemotePlayerEventType.VIDEO_INFO_CHANGED]:()=>{w(this,Ce).dispatchEvent(new Event("resize"))},[At.RemotePlayerEventType.IS_PAUSED_CHANGED]:()=>{w(this,Ce).dispatchEvent(new Event(this.paused?"pause":"play"))},[At.RemotePlayerEventType.PLAYER_STATE_CHANGED]:()=>{var t,s;((t=w(this,ze,an))==null?void 0:t.playerState)!==chrome.cast.media.PlayerState.PAUSED&&w(this,Ce).dispatchEvent(new Event({[chrome.cast.media.PlayerState.PLAYING]:"playing",[chrome.cast.media.PlayerState.BUFFERING]:"waiting",[chrome.cast.media.PlayerState.IDLE]:"emptied"}[(s=w(this,ze,an))==null?void 0:s.playerState]))},[At.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED]:async()=>{var t;(t=w(this,ze,an))!=null&&t.isMediaLoaded&&(await Promise.resolve(),Ne(this,ze,S_).call(this))}}))},S_=function(){Ne(this,ze,qg).call(this)},qg=async function(){var h,f,m,p,g;if(!w(this,ze,an))return;let s=((f=(h=w(this,Gt).mediaInfo)==null?void 0:h.tracks)!=null?f:[]).filter(({type:v})=>v===chrome.cast.media.TrackType.TEXT),r=[...w(this,Ce).textTracks].filter(({kind:v})=>v==="subtitles"||v==="captions"),n=s.map(({language:v,name:T,trackId:y})=>{var A;let{mode:b}=(A=r.find(R=>R.language===v&&R.label===T))!=null?A:{};return b?{mode:b,trackId:y}:!1}).filter(Boolean),o=n.filter(({mode:v})=>v!=="showing").map(({trackId:v})=>v),l=n.find(({mode:v})=>v==="showing"),d=(g=(p=(m=dl())==null?void 0:m.getSessionObj().media[0])==null?void 0:p.activeTrackIds)!=null?g:[],u=d;if(d.length&&(u=u.filter(v=>!o.includes(v))),l!=null&&l.trackId&&(u=[...u,l.trackId]),u=[...new Set(u)],!((v,T)=>v.length===T.length&&v.every(y=>T.includes(y)))(d,u))try{let v=new chrome.cast.media.EditTracksInfoRequest(u);await g_(v)}catch(v){console.error(v)}};var I_=i=>{var e,t,s,r,n,a,o,Me,L_;return t=class extends i{constructor(){super(...arguments);oe(this,o);oe(this,s,{paused:!1});oe(this,r,Kg());oe(this,n);oe(this,a)}get remote(){return w(this,a)?w(this,a):m_()?this.isConnected?(this.disableRemotePlayback||p_(),ts.set(this,{loadOnPrompt:()=>Ne(this,o,L_).call(this)}),ee(this,a,new oc(this))):void 0:super.remote}disconnectedCallback(){var h,f;(h=w(this,a))==null||h.destroy(),ee(this,a,null),ts.delete(this),(f=super.disconnectedCallback)==null||f.call(this)}attributeChangedCallback(h,f,m){if(super.attributeChangedCallback(h,f,m),h==="cast-receiver"&&m){w(this,r).receiverApplicationId=m;return}if(w(this,o,Me))switch(h){case"cast-stream-type":case"cast-src":this.load();break}}async load(){var T,y;if(!w(this,o,Me))return super.load();let h=new chrome.cast.media.MediaInfo(this.castSrc,this.castContentType);h.customData=this.castCustomData;let f=[...this.querySelectorAll("track")].filter(({kind:b,src:A})=>A&&(b==="subtitles"||b==="captions")),m=[],p=0;if(f.length&&(h.tracks=f.map(b=>{let A=++p;m.length===0&&b.track.mode==="showing"&&m.push(A);let R=new chrome.cast.media.Track(A,chrome.cast.media.TrackType.TEXT);return R.trackContentId=b.src,R.trackContentType="text/vtt",R.subtype=b.kind==="captions"?chrome.cast.media.TextTrackType.CAPTIONS:chrome.cast.media.TextTrackType.SUBTITLES,R.name=b.label,R.language=b.srclang,R})),this.castStreamType==="live"?h.streamType=chrome.cast.media.StreamType.LIVE:h.streamType=chrome.cast.media.StreamType.BUFFERED,h.metadata=new chrome.cast.media.GenericMediaMetadata,h.metadata.title=this.title,h.metadata.images=[{url:this.poster}],await E_(this.castSrc)){h.contentType||(h.contentType="application/x-mpegURL");let b=await y_(this.castSrc);(b==null?void 0:b.includes("m4s"))||(b==null?void 0:b.includes("mp4"))?(h.hlsSegmentFormat=chrome.cast.media.HlsSegmentFormat.FMP4,h.hlsVideoSegmentFormat=chrome.cast.media.HlsVideoSegmentFormat.FMP4):b!=null&&b.includes("ts")&&(h.hlsSegmentFormat=chrome.cast.media.HlsSegmentFormat.TS,h.hlsVideoSegmentFormat=chrome.cast.media.HlsVideoSegmentFormat.TS)}let v=new chrome.cast.media.LoadRequest(h);v.currentTime=(T=super.currentTime)!=null?T:0,v.autoplay=!w(this,s).paused,v.activeTrackIds=m,await((y=dl())==null?void 0:y.loadMedia(v)),this.dispatchEvent(new Event("volumechange"))}play(){var h;if(w(this,o,Me)){w(this,o,Me).isPaused&&((h=w(this,o,Me).controller)==null||h.playOrPause());return}return super.play()}pause(){var h;if(w(this,o,Me)){w(this,o,Me).isPaused||(h=w(this,o,Me).controller)==null||h.playOrPause();return}super.pause()}get castOptions(){return w(this,r)}get castReceiver(){var h;return(h=this.getAttribute("cast-receiver"))!=null?h:void 0}set castReceiver(h){this.castReceiver!=h&&this.setAttribute("cast-receiver",`${h}`)}get castSrc(){var m,p,g,v,T;let h=this.currentSrc,f=h!=null&&h.startsWith("blob:")?void 0:h;return(T=(v=(g=(p=this.getAttribute("cast-src"))!=null?p:(m=this.querySelector("source"))==null?void 0:m.src)!=null?g:f)!=null?v:this.getAttribute("src"))!=null?T:void 0}set castSrc(h){this.castSrc!=h&&this.setAttribute("cast-src",`${h}`)}get castContentType(){var h;return(h=this.getAttribute("cast-content-type"))!=null?h:void 0}set castContentType(h){this.setAttribute("cast-content-type",`${h}`)}get castStreamType(){var h,f;return(f=(h=this.getAttribute("cast-stream-type"))!=null?h:this.streamType)!=null?f:void 0}set castStreamType(h){this.setAttribute("cast-stream-type",`${h}`)}get castCustomData(){return w(this,n)}set castCustomData(h){let f=typeof h;if(!["object","undefined"].includes(f)){console.error(`castCustomData must be nullish or an object but value was of type ${f}`);return}ee(this,n,h)}get readyState(){if(w(this,o,Me))switch(w(this,o,Me).playerState){case chrome.cast.media.PlayerState.IDLE:return 0;case chrome.cast.media.PlayerState.BUFFERING:return 2;default:return 3}return super.readyState}get paused(){return w(this,o,Me)?w(this,o,Me).isPaused:super.paused}get muted(){var h;return w(this,o,Me)?(h=w(this,o,Me))==null?void 0:h.isMuted:super.muted}set muted(h){var f;if(w(this,o,Me)){(h&&!w(this,o,Me).isMuted||!h&&w(this,o,Me).isMuted)&&((f=w(this,o,Me).controller)==null||f.muteOrUnmute());return}super.muted=h}get volume(){var h,f;return w(this,o,Me)?(f=(h=w(this,o,Me))==null?void 0:h.volumeLevel)!=null?f:1:super.volume}set volume(h){var f;if(w(this,o,Me)){w(this,o,Me).volumeLevel=+h,(f=w(this,o,Me).controller)==null||f.setVolumeLevel();return}super.volume=h}get duration(){var h,f,m;return w(this,o,Me)&&((h=w(this,o,Me))!=null&&h.isMediaLoaded)?(m=(f=w(this,o,Me))==null?void 0:f.duration)!=null?m:NaN:super.duration}get currentTime(){var h,f,m;return w(this,o,Me)&&((h=w(this,o,Me))!=null&&h.isMediaLoaded)?(m=(f=w(this,o,Me))==null?void 0:f.currentTime)!=null?m:0:super.currentTime}set currentTime(h){var f;if(w(this,o,Me)){w(this,o,Me).currentTime=h,(f=w(this,o,Me).controller)==null||f.seek();return}super.currentTime=h}},s=new WeakMap,r=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakSet,Me=function(){var h,f;return(f=(h=ts.get(this.remote))==null?void 0:h.getCastPlayer)==null?void 0:f.call(h)},L_=async function(){w(this,s).paused=wd(t.prototype,this,"paused"),wd(t.prototype,this,"pause").call(this),this.muted=wd(t.prototype,this,"muted");try{await this.load()}catch(h){console.error(h)}},Ie(t,"observedAttributes",[...(e=i.observedAttributes)!=null?e:[],"cast-src","cast-content-type","cast-stream-type","cast-receiver"]),t};var Os=class extends Event{constructor(t,s){super(t);Ie(this,"track");this.track=s.track}};var Yg=new WeakMap;function X(i){var e;return(e=Yg.get(i))!=null?e:zw(i,{})}function zw(i,e){let t=Yg.get(i);return t||Yg.set(i,t={}),Object.assign(t,e)}function dc(i,e){let t=i.videoTracks;X(e).media=new WeakRef(i),X(e).renditionSet||(X(e).renditionSet=new Set);let s=X(t).trackSet;s.add(e);let r=s.size-1;r in un.prototype||Object.defineProperty(un.prototype,r,{get(){return[...X(this).trackSet][r]}}),queueMicrotask(()=>{t.dispatchEvent(new Os("addtrack",{track:e}))})}function uc(i){var s,r;let e=(r=(s=X(i).media)==null?void 0:s.deref())==null?void 0:r.videoTracks;if(!e)return;X(e).trackSet.delete(i),queueMicrotask(()=>{e.dispatchEvent(new Os("removetrack",{track:i}))})}function R_(i){var s,r,n;let e=(n=(r=(s=X(i).media)==null?void 0:s.deref())==null?void 0:r.videoTracks)!=null?n:[],t=!1;for(let a of e)a!==i&&(a.selected=!1,t=!0);if(t){if(X(e).changeRequested)return;X(e).changeRequested=!0,queueMicrotask(()=>{delete X(e).changeRequested,e.dispatchEvent(new Event("change"))})}}var cr,hr,fr,dn,cl,un=class extends EventTarget{constructor(){super();oe(this,dn);oe(this,cr);oe(this,hr);oe(this,fr);X(this).trackSet=new Set}[Symbol.iterator](){return w(this,dn,cl).values()}get length(){return w(this,dn,cl).size}getTrackById(t){var s;return(s=[...w(this,dn,cl)].find(r=>r.id===t))!=null?s:null}get selectedIndex(){return[...w(this,dn,cl)].findIndex(t=>t.selected)}get onaddtrack(){return w(this,cr)}set onaddtrack(t){w(this,cr)&&(this.removeEventListener("addtrack",w(this,cr)),ee(this,cr,void 0)),typeof t=="function"&&(ee(this,cr,t),this.addEventListener("addtrack",t))}get onremovetrack(){return w(this,hr)}set onremovetrack(t){w(this,hr)&&(this.removeEventListener("removetrack",w(this,hr)),ee(this,hr,void 0)),typeof t=="function"&&(ee(this,hr,t),this.addEventListener("removetrack",t))}get onchange(){return w(this,fr)}set onchange(t){w(this,fr)&&(this.removeEventListener("change",w(this,fr)),ee(this,fr,void 0)),typeof t=="function"&&(ee(this,fr,t),this.addEventListener("change",t))}};cr=new WeakMap,hr=new WeakMap,fr=new WeakMap,dn=new WeakSet,cl=function(){return X(this).trackSet};var Ns=class extends Event{constructor(t,s){super(t);Ie(this,"rendition");this.rendition=s.rendition}};function x_(i,e){var n,a;let t=(a=(n=X(i).media)==null?void 0:n.deref())==null?void 0:a.videoRenditions;X(e).media=X(i).media,X(e).track=i;let s=X(i).renditionSet;s.add(e);let r=s.size-1;r in cn.prototype||Object.defineProperty(cn.prototype,r,{get(){return ca(this)[r]}}),queueMicrotask(()=>{!t||!i.selected||t.dispatchEvent(new Ns("addrendition",{rendition:e}))})}function k_(i){var r,n;let e=(n=(r=X(i).media)==null?void 0:r.deref())==null?void 0:n.videoRenditions,t=X(i).track;X(t).renditionSet.delete(i),queueMicrotask(()=>{let a=X(i).track;!e||!a.selected||e.dispatchEvent(new Ns("removerendition",{rendition:i}))})}function D_(i){var t,s;let e=(s=(t=X(i).media)==null?void 0:t.deref())==null?void 0:s.videoRenditions;!e||X(e).changeRequested||(X(e).changeRequested=!0,queueMicrotask(()=>{delete X(e).changeRequested,X(i).track.selected&&e.dispatchEvent(new Event("change"))}))}function ca(i){var t;let e=(t=X(i).media)==null?void 0:t.deref();return e?[...e.videoTracks].filter(s=>s.selected).flatMap(s=>[...X(s).renditionSet]):[]}var mr,pr,gr,cn=class extends EventTarget{constructor(){super(...arguments);oe(this,mr);oe(this,pr);oe(this,gr)}[Symbol.iterator](){return ca(this).values()}get length(){return ca(this).length}getRenditionById(t){var s;return(s=ca(this).find(r=>`${r.id}`==`${t}`))!=null?s:null}get selectedIndex(){return ca(this).findIndex(t=>t.selected)}set selectedIndex(t){for(let[s,r]of ca(this).entries())r.selected=s===t}get onaddrendition(){return w(this,mr)}set onaddrendition(t){w(this,mr)&&(this.removeEventListener("addrendition",w(this,mr)),ee(this,mr,void 0)),typeof t=="function"&&(ee(this,mr,t),this.addEventListener("addrendition",t))}get onremoverendition(){return w(this,pr)}set onremoverendition(t){w(this,pr)&&(this.removeEventListener("removerendition",w(this,pr)),ee(this,pr,void 0)),typeof t=="function"&&(ee(this,pr,t),this.addEventListener("removerendition",t))}get onchange(){return w(this,gr)}set onchange(t){w(this,gr)&&(this.removeEventListener("change",w(this,gr)),ee(this,gr,void 0)),typeof t=="function"&&(ee(this,gr,t),this.addEventListener("change",t))}};mr=new WeakMap,pr=new WeakMap,gr=new WeakMap;var ha,hl=class{constructor(){Ie(this,"src");Ie(this,"id");Ie(this,"width");Ie(this,"height");Ie(this,"bitrate");Ie(this,"frameRate");Ie(this,"codec");oe(this,ha,!1)}get selected(){return w(this,ha)}set selected(e){w(this,ha)!==e&&(ee(this,ha,e),D_(this))}};ha=new WeakMap;var fa,ma=class{constructor(){Ie(this,"id");Ie(this,"kind");Ie(this,"label","");Ie(this,"language","");Ie(this,"sourceBuffer");oe(this,fa,!1)}addRendition(e,t,s,r,n,a){let o=new hl;return o.src=e,o.width=t,o.height=s,o.frameRate=a,o.bitrate=n,o.codec=r,x_(this,o),o}removeRendition(e){k_(e)}get selected(){return w(this,fa)}set selected(e){w(this,fa)!==e&&(ee(this,fa,e),e===!0&&R_(this))}};fa=new WeakMap;function C_(i,e){var n,a;let t=(a=(n=X(i).media)==null?void 0:n.deref())==null?void 0:a.audioRenditions;X(e).media=X(i).media,X(e).track=i;let s=X(i).renditionSet;s.add(e);let r=s.size-1;r in hn.prototype||Object.defineProperty(hn.prototype,r,{get(){return pa(this)[r]}}),queueMicrotask(()=>{!t||!i.enabled||t.dispatchEvent(new Ns("addrendition",{rendition:e}))})}function w_(i){var r,n;let e=(n=(r=X(i).media)==null?void 0:r.deref())==null?void 0:n.audioRenditions,t=X(i).track;X(t).renditionSet.delete(i),queueMicrotask(()=>{let a=X(i).track;!e||!a.enabled||e.dispatchEvent(new Ns("removerendition",{rendition:i}))})}function M_(i){var t,s;let e=(s=(t=X(i).media)==null?void 0:t.deref())==null?void 0:s.audioRenditions;!e||X(e).changeRequested||(X(e).changeRequested=!0,queueMicrotask(()=>{delete X(e).changeRequested,X(i).track.enabled&&e.dispatchEvent(new Event("change"))}))}function pa(i){var t;let e=(t=X(i).media)==null?void 0:t.deref();return e?[...e.audioTracks].filter(s=>s.enabled).flatMap(s=>[...X(s).renditionSet]):[]}var vr,Er,yr,hn=class extends EventTarget{constructor(){super(...arguments);oe(this,vr);oe(this,Er);oe(this,yr)}[Symbol.iterator](){return pa(this).values()}get length(){return pa(this).length}getRenditionById(t){var s;return(s=pa(this).find(r=>`${r.id}`==`${t}`))!=null?s:null}get selectedIndex(){return pa(this).findIndex(t=>t.selected)}set selectedIndex(t){for(let[s,r]of pa(this).entries())r.selected=s===t}get onaddrendition(){return w(this,vr)}set onaddrendition(t){w(this,vr)&&(this.removeEventListener("addrendition",w(this,vr)),ee(this,vr,void 0)),typeof t=="function"&&(ee(this,vr,t),this.addEventListener("addrendition",t))}get onremoverendition(){return w(this,Er)}set onremoverendition(t){w(this,Er)&&(this.removeEventListener("removerendition",w(this,Er)),ee(this,Er,void 0)),typeof t=="function"&&(ee(this,Er,t),this.addEventListener("removerendition",t))}get onchange(){return w(this,yr)}set onchange(t){w(this,yr)&&(this.removeEventListener("change",w(this,yr)),ee(this,yr,void 0)),typeof t=="function"&&(ee(this,yr,t),this.addEventListener("change",t))}};vr=new WeakMap,Er=new WeakMap,yr=new WeakMap;var ga,fl=class{constructor(){Ie(this,"src");Ie(this,"id");Ie(this,"bitrate");Ie(this,"codec");oe(this,ga,!1)}get selected(){return w(this,ga)}set selected(e){w(this,ga)!==e&&(ee(this,ga,e),M_(this))}};ga=new WeakMap;function hc(i,e){let t=i.audioTracks;X(e).media=new WeakRef(i),X(e).renditionSet||(X(e).renditionSet=new Set);let s=X(t).trackSet;s.add(e);let r=s.size-1;r in fn.prototype||Object.defineProperty(fn.prototype,r,{get(){return[...X(this).trackSet][r]}}),queueMicrotask(()=>{t.dispatchEvent(new Os("addtrack",{track:e}))})}function fc(i){var s,r;let e=(r=(s=X(i).media)==null?void 0:s.deref())==null?void 0:r.audioTracks;if(!e)return;X(e).trackSet.delete(i),queueMicrotask(()=>{e.dispatchEvent(new Os("removetrack",{track:i}))})}function P_(i){var t,s;let e=(s=(t=X(i).media)==null?void 0:t.deref())==null?void 0:s.audioTracks;!e||X(e).changeRequested||(X(e).changeRequested=!0,queueMicrotask(()=>{delete X(e).changeRequested,e.dispatchEvent(new Event("change"))}))}var Tr,br,_r,va,cc,fn=class extends EventTarget{constructor(){super();oe(this,va);oe(this,Tr);oe(this,br);oe(this,_r);X(this).trackSet=new Set}[Symbol.iterator](){return w(this,va,cc).values()}get length(){return w(this,va,cc).size}getTrackById(t){var s;return(s=[...w(this,va,cc)].find(r=>r.id===t))!=null?s:null}get onaddtrack(){return w(this,Tr)}set onaddtrack(t){w(this,Tr)&&(this.removeEventListener("addtrack",w(this,Tr)),ee(this,Tr,void 0)),typeof t=="function"&&(ee(this,Tr,t),this.addEventListener("addtrack",t))}get onremovetrack(){return w(this,br)}set onremovetrack(t){w(this,br)&&(this.removeEventListener("removetrack",w(this,br)),ee(this,br,void 0)),typeof t=="function"&&(ee(this,br,t),this.addEventListener("removetrack",t))}get onchange(){return w(this,_r)}set onchange(t){w(this,_r)&&(this.removeEventListener("change",w(this,_r)),ee(this,_r,void 0)),typeof t=="function"&&(ee(this,_r,t),this.addEventListener("change",t))}};Tr=new WeakMap,br=new WeakMap,_r=new WeakMap,va=new WeakSet,cc=function(){return X(this).trackSet};var Ea,ya=class{constructor(){Ie(this,"id");Ie(this,"kind");Ie(this,"label","");Ie(this,"language","");Ie(this,"sourceBuffer");oe(this,Ea,!1)}addRendition(e,t,s){let r=new fl;return r.src=e,r.codec=t,r.bitrate=s,C_(this,r),r}removeRendition(e){w_(e)}get enabled(){return w(this,Ea)}set enabled(e){w(this,Ea)!==e&&(ee(this,Ea,e),P_(this))}};Ea=new WeakMap;var O_=mc(globalThis.HTMLMediaElement,"video"),N_=mc(globalThis.HTMLMediaElement,"audio");function U_(i){if(!(i!=null&&i.prototype))return i;let e=mc(i,"video");(!e||`${e}`.includes("[native code]"))&&Object.defineProperty(i.prototype,"videoTracks",{get(){return Qw(this)}});let t=mc(i,"audio");(!t||`${t}`.includes("[native code]"))&&Object.defineProperty(i.prototype,"audioTracks",{get(){return Xw(this)}}),"addVideoTrack"in i.prototype||(i.prototype.addVideoTrack=function(n,a="",o=""){let l=new ma;return l.kind=n,l.label=a,l.language=o,dc(this,l),l}),"removeVideoTrack"in i.prototype||(i.prototype.removeVideoTrack=uc),"addAudioTrack"in i.prototype||(i.prototype.addAudioTrack=function(n,a="",o=""){let l=new ya;return l.kind=n,l.label=a,l.language=o,hc(this,l),l}),"removeAudioTrack"in i.prototype||(i.prototype.removeAudioTrack=fc),"videoRenditions"in i.prototype||Object.defineProperty(i.prototype,"videoRenditions",{get(){return s(this)}});let s=n=>{let a=X(n).videoRenditions;return a||(a=new cn,X(a).media=new WeakRef(n),X(n).videoRenditions=a),a};"audioRenditions"in i.prototype||Object.defineProperty(i.prototype,"audioRenditions",{get(){return r(this)}});let r=n=>{let a=X(n).audioRenditions;return a||(a=new hn,X(a).media=new WeakRef(n),X(n).audioRenditions=a),a};return i}function mc(i,e){var t;if(i!=null&&i.prototype)return(t=Object.getOwnPropertyDescriptor(i.prototype,`${e}Tracks`))==null?void 0:t.get}function Qw(i){var t;let e=X(i).videoTracks;if(!e&&(e=new un,X(i).videoTracks=e,O_)){let s=O_.call((t=i.nativeEl)!=null?t:i);for(let o of s)dc(i,o);let r=()=>{e.dispatchEvent(new Event("change"))},n=o=>{if([...e].some(l=>l instanceof ma)){for(let l of s)uc(l);return}dc(i,o.track)},a=o=>{uc(o.track)};s.addEventListener("change",r),s.addEventListener("addtrack",n),s.addEventListener("removetrack",a)}return e}function Xw(i){var t;let e=X(i).audioTracks;if(!e&&(e=new fn,X(i).audioTracks=e,N_)){let s=N_.call((t=i.nativeEl)!=null?t:i);for(let o of s)hc(i,o);let r=()=>{e.dispatchEvent(new Event("change"))},n=o=>{if([...e].some(l=>l instanceof ya)){for(let l of s)fc(l);return}hc(i,o.track)},a=o=>{fc(o.track)};s.addEventListener("change",r),s.addEventListener("addtrack",n),s.addEventListener("removetrack",a)}return e}var B_=i=>{throw TypeError(i)},$_=(i,e,t)=>e.has(i)||B_("Cannot "+t),H_=(i,e,t)=>($_(i,e,"read from private field"),t?t.call(i):e.get(i)),G_=(i,e,t)=>e.has(i)?B_("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),K_=(i,e,t,s)=>($_(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),vc=class{addEventListener(){}removeEventListener(){}dispatchEvent(i){return!0}};if(typeof DocumentFragment=="undefined"){class i extends vc{}globalThis.DocumentFragment=i}var zg=class extends vc{},Zw=class extends vc{},Jw={get(i){},define(i,e,t){},getName(i){return null},upgrade(i){},whenDefined(i){return Promise.resolve(zg)}},pc,eM=class{constructor(i,e={}){G_(this,pc),K_(this,pc,e==null?void 0:e.detail)}get detail(){return H_(this,pc)}initCustomEvent(){}};pc=new WeakMap;function tM(i,e){return new zg}var V_={document:{createElement:tM},DocumentFragment,customElements:Jw,CustomEvent:eM,EventTarget:vc,HTMLElement:zg,HTMLVideoElement:Zw},W_=typeof window=="undefined"||typeof globalThis.customElements=="undefined",jg=W_?V_:globalThis,Q3=W_?V_.document:globalThis.document,gc,F_=class extends I_(U_(c_)){constructor(){super(...arguments),G_(this,gc)}get autoplay(){let i=this.getAttribute("autoplay");return i===null?!1:i===""?!0:i}set autoplay(i){let e=this.autoplay;i!==e&&(i?this.setAttribute("autoplay",typeof i=="string"?i:""):this.removeAttribute("autoplay"))}get muxCastCustomData(){return{mux:{playbackId:this.playbackId,minResolution:this.minResolution,maxResolution:this.maxResolution,renditionOrder:this.renditionOrder,customDomain:this.customDomain,tokens:{drm:this.drmToken},envKey:this.envKey,metadata:this.metadata,disableCookies:this.disableCookies,disableTracking:this.disableTracking,beaconCollectionDomain:this.beaconCollectionDomain,startTime:this.startTime,preferCmcd:this.preferCmcd}}}get castCustomData(){var i;return(i=H_(this,gc))!=null?i:this.muxCastCustomData}set castCustomData(i){K_(this,gc,i)}};gc=new WeakMap;jg.customElements.get("mux-video")||(jg.customElements.define("mux-video",F_),jg.MuxVideoElement=F_);var K={MEDIA_PLAY_REQUEST:"mediaplayrequest",MEDIA_PAUSE_REQUEST:"mediapauserequest",MEDIA_MUTE_REQUEST:"mediamuterequest",MEDIA_UNMUTE_REQUEST:"mediaunmuterequest",MEDIA_LOOP_REQUEST:"medialooprequest",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"},ge={MEDIA_CHROME_ATTRIBUTES:"mediachromeattributes",MEDIA_CONTROLLER:"mediacontroller"},Qg={MEDIA_AIRPLAY_UNAVAILABLE:"mediaAirplayUnavailable",MEDIA_AUDIO_TRACK_ENABLED:"mediaAudioTrackEnabled",MEDIA_AUDIO_TRACK_LIST:"mediaAudioTrackList",MEDIA_AUDIO_TRACK_UNAVAILABLE:"mediaAudioTrackUnavailable",MEDIA_BUFFERED:"mediaBuffered",MEDIA_CAST_UNAVAILABLE:"mediaCastUnavailable",MEDIA_CHAPTERS_CUES:"mediaChaptersCues",MEDIA_CURRENT_TIME:"mediaCurrentTime",MEDIA_DURATION:"mediaDuration",MEDIA_ENDED:"mediaEnded",MEDIA_ERROR:"mediaError",MEDIA_ERROR_CODE:"mediaErrorCode",MEDIA_ERROR_MESSAGE:"mediaErrorMessage",MEDIA_FULLSCREEN_UNAVAILABLE:"mediaFullscreenUnavailable",MEDIA_HAS_PLAYED:"mediaHasPlayed",MEDIA_HEIGHT:"mediaHeight",MEDIA_IS_AIRPLAYING:"mediaIsAirplaying",MEDIA_IS_CASTING:"mediaIsCasting",MEDIA_IS_FULLSCREEN:"mediaIsFullscreen",MEDIA_IS_PIP:"mediaIsPip",MEDIA_LOADING:"mediaLoading",MEDIA_MUTED:"mediaMuted",MEDIA_LOOP:"mediaLoop",MEDIA_PAUSED:"mediaPaused",MEDIA_PIP_UNAVAILABLE:"mediaPipUnavailable",MEDIA_PLAYBACK_RATE:"mediaPlaybackRate",MEDIA_PREVIEW_CHAPTER:"mediaPreviewChapter",MEDIA_PREVIEW_COORDS:"mediaPreviewCoords",MEDIA_PREVIEW_IMAGE:"mediaPreviewImage",MEDIA_PREVIEW_TIME:"mediaPreviewTime",MEDIA_RENDITION_LIST:"mediaRenditionList",MEDIA_RENDITION_SELECTED:"mediaRenditionSelected",MEDIA_RENDITION_UNAVAILABLE:"mediaRenditionUnavailable",MEDIA_SEEKABLE:"mediaSeekable",MEDIA_STREAM_TYPE:"mediaStreamType",MEDIA_SUBTITLES_LIST:"mediaSubtitlesList",MEDIA_SUBTITLES_SHOWING:"mediaSubtitlesShowing",MEDIA_TARGET_LIVE_WINDOW:"mediaTargetLiveWindow",MEDIA_TIME_IS_LIVE:"mediaTimeIsLive",MEDIA_VOLUME:"mediaVolume",MEDIA_VOLUME_LEVEL:"mediaVolumeLevel",MEDIA_VOLUME_UNAVAILABLE:"mediaVolumeUnavailable",MEDIA_LANG:"mediaLang",MEDIA_WIDTH:"mediaWidth"},q_=Object.entries(Qg),_=q_.reduce((i,[e,t])=>(i[e]=t.toLowerCase(),i),{}),iM={USER_INACTIVE_CHANGE:"userinactivechange",BREAKPOINTS_CHANGE:"breakpointchange",BREAKPOINTS_COMPUTED:"breakpointscomputed"},di=q_.reduce((i,[e,t])=>(i[e]=t.toLowerCase(),i),{...iM}),oU=Object.entries(di).reduce((i,[e,t])=>{let s=_[e];return s&&(i[t]=s),i},{userinactivechange:"userinactive"}),Y_=Object.entries(_).reduce((i,[e,t])=>{let s=di[e];return s&&(i[t]=s),i},{userinactive:"userinactivechange"}),Xt={SUBTITLES:"subtitles",CAPTIONS:"captions",DESCRIPTIONS:"descriptions",CHAPTERS:"chapters",METADATA:"metadata"},Ar={DISABLED:"disabled",HIDDEN:"hidden",SHOWING:"showing"};var Ec={MOUSE:"mouse",PEN:"pen",TOUCH:"touch"},Zt={UNAVAILABLE:"unavailable",UNSUPPORTED:"unsupported"},Ni={LIVE:"live",ON_DEMAND:"on-demand",UNKNOWN:"unknown"};var j_={INLINE:"inline",FULLSCREEN:"fullscreen",PICTURE_IN_PICTURE:"picture-in-picture"};function z_(i){return i==null?void 0:i.map(rM).join(" ")}function Q_(i){return i==null?void 0:i.split(/\s+/).map(nM)}function rM(i){if(i){let{id:e,width:t,height:s}=i;return[e,t,s].filter(r=>r!=null).join(":")}}function nM(i){if(i){let[e,t,s]=i.split(":");return{id:e,width:+t,height:+s}}}function X_(i){return i==null?void 0:i.map(aM).join(" ")}function Z_(i){return i==null?void 0:i.split(/\s+/).map(oM)}function aM(i){if(i){let{id:e,kind:t,language:s,label:r}=i;return[e,t,s,r].filter(n=>n!=null).join(":")}}function oM(i){if(i){let[e,t,s,r]=i.split(":");return{id:e,kind:t,language:s,label:r}}}function J_(i){return i.replace(/[-_]([a-z])/g,(e,t)=>t.toUpperCase())}function Ta(i){return typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i)}function yc(i){return typeof i!="string"?!1:!isNaN(i)&&!isNaN(parseFloat(i))}var Tc=i=>new Promise(e=>setTimeout(e,i));var eA={"Start airplay":"Start airplay","Stop airplay":"Stop airplay",Audio:"Audio",Captions:"Captions","Enable captions":"Enable captions","Disable captions":"Disable captions","Start casting":"Start casting","Stop casting":"Stop casting","Enter fullscreen mode":"Enter fullscreen mode","Exit fullscreen mode":"Exit fullscreen mode",Mute:"Mute",Unmute:"Unmute",Loop:"Loop","Enter picture in picture mode":"Enter picture in picture mode","Exit picture in picture mode":"Exit picture in picture mode",Play:"Play",Pause:"Pause","Playback rate":"Playback rate","Playback rate {playbackRate}":"Playback rate {playbackRate}",Quality:"Quality","Seek backward":"Seek backward","Seek forward":"Seek forward",Settings:"Settings",Auto:"Auto","audio player":"audio player","video player":"video player",volume:"volume",seek:"seek","closed captions":"closed captions","current playback rate":"current playback rate","playback time":"playback time","media loading":"media loading",settings:"settings","audio tracks":"audio tracks",quality:"quality",play:"play",pause:"pause",mute:"mute",unmute:"unmute","chapter: {chapterName}":"chapter: {chapterName}",live:"live",Off:"Off","start airplay":"start airplay","stop airplay":"stop airplay","start casting":"start casting","stop casting":"stop casting","enter fullscreen mode":"enter fullscreen mode","exit fullscreen mode":"exit fullscreen mode","enter picture in picture mode":"enter picture in picture mode","exit picture in picture mode":"exit picture in picture mode","seek to live":"seek to live","playing live":"playing live","seek back {seekOffset} seconds":"seek back {seekOffset} seconds","seek forward {seekOffset} seconds":"seek forward {seekOffset} seconds","Network Error":"Network Error","Decode Error":"Decode Error","Source Not Supported":"Source Not Supported","Encryption Error":"Encryption Error","A network error caused the media download to fail.":"A network error caused the media download to fail.","A media error caused playback to be aborted. The media could be corrupt or your browser does not support this format.":"A media error caused playback to be aborted. The media could be corrupt or your browser does not support this format.","An unsupported error occurred. The server or network failed, or your browser does not support this format.":"An unsupported error occurred. The server or network failed, or your browser does not support this format.","The media is encrypted and there are no keys to decrypt it.":"The media is encrypted and there are no keys to decrypt it.",hour:"hour",hours:"hours",minute:"minute",minutes:"minutes",second:"second",seconds:"seconds","{time} remaining":"{time} remaining","{currentTime} of {totalTime}":"{currentTime} of {totalTime}","video not loaded, unknown time.":"video not loaded, unknown time."};var tA,Xg={en:eA},Zg=((tA=globalThis.navigator)==null?void 0:tA.language)||"en",iA=i=>{Zg=i};var lM=i=>{var e,t,s;let[r]=Zg.split("-");return((e=Xg[Zg])==null?void 0:e[i])||((t=Xg[r])==null?void 0:t[i])||((s=Xg.en)==null?void 0:s[i])||i},F=(i,e={})=>lM(i).replace(/\{(\w+)\}/g,(t,s)=>s in e?String(e[s]):`{${s}}`);var sA=[{singular:"hour",plural:"hours"},{singular:"minute",plural:"minutes"},{singular:"second",plural:"seconds"}],dM=(i,e)=>{let t=i===1?F(sA[e].singular):F(sA[e].plural);return`${i} ${t}`},mn=i=>{if(!Ta(i))return"";let e=Math.abs(i),t=e!==i,s=new Date(0,0,0,0,0,e,0),n=[s.getHours(),s.getMinutes(),s.getSeconds()].map((a,o)=>a&&dM(a,o)).filter(a=>a).join(", ");return t?F("{time} remaining",{time:n}):n};function Ui(i,e){let t=!1;i<0&&(t=!0,i=0-i),i=i<0?0:i;let s=Math.floor(i%60),r=Math.floor(i/60%60),n=Math.floor(i/3600),a=Math.floor(e/60%60),o=Math.floor(e/3600);return(isNaN(i)||i===1/0)&&(n=r=s="0"),n=n>0||o>0?n+":":"",r=((n||a>=10)&&r<10?"0"+r:r)+":",s=s<10?"0"+s:s,(t?"-":"")+n+r+s}var mU=Object.freeze({length:0,start(i){let e=i>>>0;if(e>=this.length)throw new DOMException(`Failed to execute 'start' on 'TimeRanges': The index provided (${e}) is greater than or equal to the maximum bound (${this.length}).`);return 0},end(i){let e=i>>>0;if(e>=this.length)throw new DOMException(`Failed to execute 'end' on 'TimeRanges': The index provided (${e}) is greater than or equal to the maximum bound (${this.length}).`);return 0}});var bc=class{addEventListener(){}removeEventListener(){}dispatchEvent(){return!0}},_c=class extends bc{},Ac=class extends _c{constructor(){super(...arguments),this.role=null}},Jg=class{observe(){}unobserve(){}disconnect(){}},rA={createElement:function(){return new ml.HTMLElement},createElementNS:function(){return new ml.HTMLElement},addEventListener(){},removeEventListener(){},dispatchEvent(i){return!1}},ml={ResizeObserver:Jg,document:rA,Node:_c,Element:Ac,HTMLElement:class extends Ac{constructor(){super(...arguments),this.innerHTML=""}get content(){return new ml.DocumentFragment}},DocumentFragment:class extends bc{},customElements:{get:function(){},define:function(){},whenDefined:function(){}},localStorage:{getItem(i){return null},setItem(i,e){},removeItem(i){}},CustomEvent:function(){},getComputedStyle:function(){},navigator:{languages:[],get userAgent(){return""}},matchMedia(i){return{matches:!1,media:i}},DOMParser:class{parseFromString(e,t){return{body:{textContent:e}}}}},nA="global"in globalThis&&(globalThis==null?void 0:globalThis.global)===globalThis||typeof window=="undefined"||typeof window.customElements=="undefined",aA=Object.keys(ml).every(i=>i in globalThis),L=nA&&!aA?ml:globalThis,He=nA&&!aA?rA:globalThis.document;var oA=new WeakMap,e0=i=>{let e=oA.get(i);return e||oA.set(i,e=new Set),e},lA=new L.ResizeObserver(i=>{for(let e of i)for(let t of e0(e.target))t(e)});function Us(i,e){e0(i).add(e),lA.observe(i)}function Fs(i,e){let t=e0(i);t.delete(e),t.size||lA.unobserve(i)}function Qe(i){let e={};for(let t of i)e[t.name]=t.value;return e}function Ye(i){var e;return(e=Sc(i))!=null?e:is(i,"media-controller")}function Sc(i){var e;let{MEDIA_CONTROLLER:t}=ge,s=i.getAttribute(t);if(s)return(e=pn(i))==null?void 0:e.getElementById(s)}var Ic=(i,e,t=".value")=>{let s=i.querySelector(t);s&&(s.textContent=e)},cM=(i,e)=>{let t=`slot[name="${e}"]`,s=i.shadowRoot.querySelector(t);return s?s.children:[]},Lc=(i,e)=>cM(i,e)[0],Kt=(i,e)=>!i||!e?!1:i!=null&&i.contains(e)?!0:Kt(i,e.getRootNode().host),is=(i,e)=>{if(!i)return null;let t=i.closest(e);return t||is(i.getRootNode().host,e)};function pl(i=document){var e;let t=i==null?void 0:i.activeElement;return t?(e=pl(t.shadowRoot))!=null?e:t:null}function pn(i){var e;let t=(e=i==null?void 0:i.getRootNode)==null?void 0:e.call(i);return t instanceof ShadowRoot||t instanceof Document?t:null}function Rc(i,{depth:e=3,checkOpacity:t=!0,checkVisibilityCSS:s=!0}={}){if(i.checkVisibility)return i.checkVisibility({checkOpacity:t,checkVisibilityCSS:s});let r=i;for(;r&&e>0;){let n=getComputedStyle(r);if(t&&n.opacity==="0"||s&&n.visibility==="hidden"||n.display==="none")return!1;r=r.parentElement,e--}return!0}function dA(i,e,t,s){let r=s.x-t.x,n=s.y-t.y,a=r*r+n*n;if(a===0)return 0;let o=((i-t.x)*r+(e-t.y)*n)/a;return Math.max(0,Math.min(1,o))}function je(i,e){let t=hM(i,s=>s===e);return t||gl(i,e)}function hM(i,e){var t,s;let r;for(r of(t=i.querySelectorAll("style:not([media])"))!=null?t:[]){let n;try{n=(s=r.sheet)==null?void 0:s.cssRules}catch{continue}for(let a of n!=null?n:[])if(e(a.selectorText))return a}}function gl(i,e){var t,s;let r=(t=i.querySelectorAll("style:not([media])"))!=null?t:[],n=r==null?void 0:r[r.length-1];if(!(n!=null&&n.sheet))return console.warn("Media Chrome: No style sheet found on style tag of",i),{style:{setProperty:()=>{},removeProperty:()=>"",getPropertyValue:()=>""}};let a=n==null?void 0:n.sheet.insertRule(`${e}{}`,n.sheet.cssRules.length);return(s=n.sheet.cssRules)==null?void 0:s[a]}function ye(i,e,t=Number.NaN){let s=i.getAttribute(e);return s!=null?+s:t}function Re(i,e,t){let s=+t;if(t==null||Number.isNaN(s)){i.hasAttribute(e)&&i.removeAttribute(e);return}ye(i,e,void 0)!==s&&i.setAttribute(e,`${s}`)}function le(i,e){return i.hasAttribute(e)}function de(i,e,t){if(t==null){i.hasAttribute(e)&&i.removeAttribute(e);return}le(i,e)!=t&&i.toggleAttribute(e,t)}function pe(i,e,t=null){var s;return(s=i.getAttribute(e))!=null?s:t}function me(i,e,t){if(t==null){i.hasAttribute(e)&&i.removeAttribute(e);return}let s=`${t}`;pe(i,e,void 0)!==s&&i.setAttribute(e,s)}var uA=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},Fi=(i,e,t)=>(uA(i,e,"read from private field"),t?t.call(i):e.get(i)),fM=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},xc=(i,e,t,s)=>(uA(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),wt;function mM(i){return`
140
+ `).find(s=>!s.trim().startsWith("#")&&s.trim()!=="")}async function E_(i){if(!i)return!1;if(/\.m3u8?(\?.*)?$/i.test(i))return!0;if(i.startsWith("blob:"))return!1;try{let t=(await fetch(i,{method:"HEAD"})).headers.get("Content-Type");return Ww.some(s=>t===s)}catch(e){return console.error("Error while trying to get the Content-Type of the manifest",e),!1}}async function y_(i){if(!(!i||i.startsWith("blob:")))try{let e=await(await fetch(i)).text(),t=e,s=Yw(e);if(s.length>0){let a=new URL(s[0],i).toString();t=await(await fetch(a)).text()}let r=jw(t);return qw(r)}catch(e){console.error("Error while trying to parse the manifest playlist",e);return}}var ac=new h_,Ps=new WeakSet,At;f_(()=>{var i,e,t,s;if(!((e=(i=globalThis.chrome)==null?void 0:i.cast)!=null&&e.isAvailable)){console.debug("chrome.cast.isAvailable",(s=(t=globalThis.chrome)==null?void 0:t.cast)==null?void 0:s.isAvailable);return}At||(At=cast.framework,Ms().addEventListener(At.CastContextEventType.CAST_STATE_CHANGED,r=>{ac.forEach(n=>{var a,o;return(o=(a=ts.get(n)).onCastStateChanged)==null?void 0:o.call(a,r)})}),Ms().addEventListener(At.CastContextEventType.SESSION_STATE_CHANGED,r=>{ac.forEach(n=>{var a,o;return(o=(a=ts.get(n)).onSessionStateChanged)==null?void 0:o.call(a,r)})}),ac.forEach(r=>{var n,a;return(a=(n=ts.get(r)).init)==null?void 0:a.call(n)}))});var b_=0,Ce,ua,Gt,Oi,on,ln,ur,lc,ul,ze,an,T_,__,Vg,A_,Wg,S_,qg,oc=class extends EventTarget{constructor(t){super();oe(this,ze);oe(this,Ce);oe(this,ua);oe(this,Gt);oe(this,Oi);oe(this,on,"disconnected");oe(this,ln,!1);oe(this,ur,new Set);oe(this,lc,new WeakMap);oe(this,ul,()=>Ne(this,ze,qg).call(this));ee(this,Ce,t),ac.add(this),ts.set(this,{init:()=>Ne(this,ze,Wg).call(this),onCastStateChanged:()=>Ne(this,ze,Vg).call(this),onSessionStateChanged:()=>Ne(this,ze,A_).call(this),getCastPlayer:()=>w(this,ze,an)}),Ne(this,ze,Wg).call(this)}destroy(){var t,s,r;(s=(t=w(this,Ce))==null?void 0:t.textTracks)==null||s.removeEventListener("change",w(this,ul)),w(this,Oi)&&((r=w(this,Gt))!=null&&r.controller)&&Object.entries(w(this,Oi)).forEach(([n,a])=>{w(this,Gt).controller.removeEventListener(n,a)}),w(this,Ce)&&Ps.delete(w(this,Ce)),ee(this,ua,!1)}get state(){return w(this,on)}async watchAvailability(t){if(w(this,Ce).disableRemotePlayback)throw new da("disableRemotePlayback attribute is present.");return w(this,lc).set(t,++b_),w(this,ur).add(t),queueMicrotask(()=>t(Ne(this,ze,__).call(this))),b_}async cancelWatchAvailability(t){if(w(this,Ce).disableRemotePlayback)throw new da("disableRemotePlayback attribute is present.");t?w(this,ur).delete(t):w(this,ur).clear()}async prompt(){var s,r,n,a;if(w(this,Ce).disableRemotePlayback)throw new da("disableRemotePlayback attribute is present.");if(!((r=(s=globalThis.chrome)==null?void 0:s.cast)!=null&&r.isAvailable))throw new rc("The RemotePlayback API is disabled on this platform.");let t=Ps.has(w(this,Ce));Ps.add(w(this,Ce)),Gg(w(this,Ce).castOptions),Object.entries(w(this,Oi)).forEach(([o,l])=>{w(this,Gt).controller.addEventListener(o,l)});try{await Ms().requestSession()}catch(o){if(t||Ps.delete(w(this,Ce)),o==="cancel")return;throw new Error(o)}(a=(n=ts.get(w(this,Ce)))==null?void 0:n.loadOnPrompt)==null||a.call(n)}};Ce=new WeakMap,ua=new WeakMap,Gt=new WeakMap,Oi=new WeakMap,on=new WeakMap,ln=new WeakMap,ur=new WeakMap,lc=new WeakMap,ul=new WeakMap,ze=new WeakSet,an=function(){if(Ps.has(w(this,Ce)))return w(this,Gt)},T_=function(){Ps.has(w(this,Ce))&&(Object.entries(w(this,Oi)).forEach(([t,s])=>{w(this,Gt).controller.removeEventListener(t,s)}),Ps.delete(w(this,Ce)),w(this,Ce).muted=w(this,Gt).isMuted,w(this,Ce).currentTime=w(this,Gt).savedPlayerState.currentTime,w(this,Gt).savedPlayerState.isPaused===!1&&w(this,Ce).play())},__=function(){var s;let t=(s=Ms())==null?void 0:s.getCastState();return t&&t!=="NO_DEVICES_AVAILABLE"},Vg=function(){let t=Ms().getCastState();if(Ps.has(w(this,Ce))&&t==="CONNECTING"&&(ee(this,on,"connecting"),this.dispatchEvent(new Event("connecting"))),!w(this,ln)&&(t!=null&&t.includes("CONNECT"))){ee(this,ln,!0);for(let s of w(this,ur))s(!0)}else if(w(this,ln)&&(!t||t==="NO_DEVICES_AVAILABLE")){ee(this,ln,!1);for(let s of w(this,ur))s(!1)}},A_=async function(){var s;let{SESSION_RESUMED:t}=At.SessionState;if(Ms().getSessionState()===t&&w(this,Ce).castSrc===((s=nc())==null?void 0:s.media.contentId)){Ps.add(w(this,Ce)),Object.entries(w(this,Oi)).forEach(([r,n])=>{w(this,Gt).controller.addEventListener(r,n)});try{await v_(new chrome.cast.media.GetStatusRequest)}catch(r){console.error(r)}w(this,Oi)[At.RemotePlayerEventType.IS_PAUSED_CHANGED](),w(this,Oi)[At.RemotePlayerEventType.PLAYER_STATE_CHANGED]()}},Wg=function(){!At||w(this,ua)||(ee(this,ua,!0),Gg(w(this,Ce).castOptions),w(this,Ce).textTracks.addEventListener("change",w(this,ul)),Ne(this,ze,Vg).call(this),ee(this,Gt,new At.RemotePlayer),new At.RemotePlayerController(w(this,Gt)),ee(this,Oi,{[At.RemotePlayerEventType.IS_CONNECTED_CHANGED]:({value:t})=>{t===!0?(ee(this,on,"connected"),this.dispatchEvent(new Event("connect"))):(Ne(this,ze,T_).call(this),ee(this,on,"disconnected"),this.dispatchEvent(new Event("disconnect")))},[At.RemotePlayerEventType.DURATION_CHANGED]:()=>{w(this,Ce).dispatchEvent(new Event("durationchange"))},[At.RemotePlayerEventType.VOLUME_LEVEL_CHANGED]:()=>{w(this,Ce).dispatchEvent(new Event("volumechange"))},[At.RemotePlayerEventType.IS_MUTED_CHANGED]:()=>{w(this,Ce).dispatchEvent(new Event("volumechange"))},[At.RemotePlayerEventType.CURRENT_TIME_CHANGED]:()=>{var t;(t=w(this,ze,an))!=null&&t.isMediaLoaded&&w(this,Ce).dispatchEvent(new Event("timeupdate"))},[At.RemotePlayerEventType.VIDEO_INFO_CHANGED]:()=>{w(this,Ce).dispatchEvent(new Event("resize"))},[At.RemotePlayerEventType.IS_PAUSED_CHANGED]:()=>{w(this,Ce).dispatchEvent(new Event(this.paused?"pause":"play"))},[At.RemotePlayerEventType.PLAYER_STATE_CHANGED]:()=>{var t,s;((t=w(this,ze,an))==null?void 0:t.playerState)!==chrome.cast.media.PlayerState.PAUSED&&w(this,Ce).dispatchEvent(new Event({[chrome.cast.media.PlayerState.PLAYING]:"playing",[chrome.cast.media.PlayerState.BUFFERING]:"waiting",[chrome.cast.media.PlayerState.IDLE]:"emptied"}[(s=w(this,ze,an))==null?void 0:s.playerState]))},[At.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED]:async()=>{var t;(t=w(this,ze,an))!=null&&t.isMediaLoaded&&(await Promise.resolve(),Ne(this,ze,S_).call(this))}}))},S_=function(){Ne(this,ze,qg).call(this)},qg=async function(){var h,f,m,p,g;if(!w(this,ze,an))return;let s=((f=(h=w(this,Gt).mediaInfo)==null?void 0:h.tracks)!=null?f:[]).filter(({type:v})=>v===chrome.cast.media.TrackType.TEXT),r=[...w(this,Ce).textTracks].filter(({kind:v})=>v==="subtitles"||v==="captions"),n=s.map(({language:v,name:b,trackId:y})=>{var A;let{mode:T}=(A=r.find(R=>R.language===v&&R.label===b))!=null?A:{};return T?{mode:T,trackId:y}:!1}).filter(Boolean),o=n.filter(({mode:v})=>v!=="showing").map(({trackId:v})=>v),l=n.find(({mode:v})=>v==="showing"),d=(g=(p=(m=dl())==null?void 0:m.getSessionObj().media[0])==null?void 0:p.activeTrackIds)!=null?g:[],u=d;if(d.length&&(u=u.filter(v=>!o.includes(v))),l!=null&&l.trackId&&(u=[...u,l.trackId]),u=[...new Set(u)],!((v,b)=>v.length===b.length&&v.every(y=>b.includes(y)))(d,u))try{let v=new chrome.cast.media.EditTracksInfoRequest(u);await g_(v)}catch(v){console.error(v)}};var I_=i=>{var e,t,s,r,n,a,o,Me,L_;return t=class extends i{constructor(){super(...arguments);oe(this,o);oe(this,s,{paused:!1});oe(this,r,Kg());oe(this,n);oe(this,a)}get remote(){return w(this,a)?w(this,a):m_()?this.isConnected?(this.disableRemotePlayback||p_(),ts.set(this,{loadOnPrompt:()=>Ne(this,o,L_).call(this)}),ee(this,a,new oc(this))):void 0:super.remote}disconnectedCallback(){var h,f;(h=w(this,a))==null||h.destroy(),ee(this,a,null),ts.delete(this),(f=super.disconnectedCallback)==null||f.call(this)}attributeChangedCallback(h,f,m){if(super.attributeChangedCallback(h,f,m),h==="cast-receiver"&&m){w(this,r).receiverApplicationId=m;return}if(w(this,o,Me))switch(h){case"cast-stream-type":case"cast-src":this.load();break}}async load(){var b,y;if(!w(this,o,Me))return super.load();let h=new chrome.cast.media.MediaInfo(this.castSrc,this.castContentType);h.customData=this.castCustomData;let f=[...this.querySelectorAll("track")].filter(({kind:T,src:A})=>A&&(T==="subtitles"||T==="captions")),m=[],p=0;if(f.length&&(h.tracks=f.map(T=>{let A=++p;m.length===0&&T.track.mode==="showing"&&m.push(A);let R=new chrome.cast.media.Track(A,chrome.cast.media.TrackType.TEXT);return R.trackContentId=T.src,R.trackContentType="text/vtt",R.subtype=T.kind==="captions"?chrome.cast.media.TextTrackType.CAPTIONS:chrome.cast.media.TextTrackType.SUBTITLES,R.name=T.label,R.language=T.srclang,R})),this.castStreamType==="live"?h.streamType=chrome.cast.media.StreamType.LIVE:h.streamType=chrome.cast.media.StreamType.BUFFERED,h.metadata=new chrome.cast.media.GenericMediaMetadata,h.metadata.title=this.title,h.metadata.images=[{url:this.poster}],await E_(this.castSrc)){h.contentType||(h.contentType="application/x-mpegURL");let T=await y_(this.castSrc);(T==null?void 0:T.includes("m4s"))||(T==null?void 0:T.includes("mp4"))?(h.hlsSegmentFormat=chrome.cast.media.HlsSegmentFormat.FMP4,h.hlsVideoSegmentFormat=chrome.cast.media.HlsVideoSegmentFormat.FMP4):T!=null&&T.includes("ts")&&(h.hlsSegmentFormat=chrome.cast.media.HlsSegmentFormat.TS,h.hlsVideoSegmentFormat=chrome.cast.media.HlsVideoSegmentFormat.TS)}let v=new chrome.cast.media.LoadRequest(h);v.currentTime=(b=super.currentTime)!=null?b:0,v.autoplay=!w(this,s).paused,v.activeTrackIds=m,await((y=dl())==null?void 0:y.loadMedia(v)),this.dispatchEvent(new Event("volumechange"))}play(){var h;if(w(this,o,Me)){w(this,o,Me).isPaused&&((h=w(this,o,Me).controller)==null||h.playOrPause());return}return super.play()}pause(){var h;if(w(this,o,Me)){w(this,o,Me).isPaused||(h=w(this,o,Me).controller)==null||h.playOrPause();return}super.pause()}get castOptions(){return w(this,r)}get castReceiver(){var h;return(h=this.getAttribute("cast-receiver"))!=null?h:void 0}set castReceiver(h){this.castReceiver!=h&&this.setAttribute("cast-receiver",`${h}`)}get castSrc(){var m,p,g,v,b;let h=this.currentSrc,f=h!=null&&h.startsWith("blob:")?void 0:h;return(b=(v=(g=(p=this.getAttribute("cast-src"))!=null?p:(m=this.querySelector("source"))==null?void 0:m.src)!=null?g:f)!=null?v:this.getAttribute("src"))!=null?b:void 0}set castSrc(h){this.castSrc!=h&&this.setAttribute("cast-src",`${h}`)}get castContentType(){var h;return(h=this.getAttribute("cast-content-type"))!=null?h:void 0}set castContentType(h){this.setAttribute("cast-content-type",`${h}`)}get castStreamType(){var h,f;return(f=(h=this.getAttribute("cast-stream-type"))!=null?h:this.streamType)!=null?f:void 0}set castStreamType(h){this.setAttribute("cast-stream-type",`${h}`)}get castCustomData(){return w(this,n)}set castCustomData(h){let f=typeof h;if(!["object","undefined"].includes(f)){console.error(`castCustomData must be nullish or an object but value was of type ${f}`);return}ee(this,n,h)}get readyState(){if(w(this,o,Me))switch(w(this,o,Me).playerState){case chrome.cast.media.PlayerState.IDLE:return 0;case chrome.cast.media.PlayerState.BUFFERING:return 2;default:return 3}return super.readyState}get paused(){return w(this,o,Me)?w(this,o,Me).isPaused:super.paused}get muted(){var h;return w(this,o,Me)?(h=w(this,o,Me))==null?void 0:h.isMuted:super.muted}set muted(h){var f;if(w(this,o,Me)){(h&&!w(this,o,Me).isMuted||!h&&w(this,o,Me).isMuted)&&((f=w(this,o,Me).controller)==null||f.muteOrUnmute());return}super.muted=h}get volume(){var h,f;return w(this,o,Me)?(f=(h=w(this,o,Me))==null?void 0:h.volumeLevel)!=null?f:1:super.volume}set volume(h){var f;if(w(this,o,Me)){w(this,o,Me).volumeLevel=+h,(f=w(this,o,Me).controller)==null||f.setVolumeLevel();return}super.volume=h}get duration(){var h,f,m;return w(this,o,Me)&&((h=w(this,o,Me))!=null&&h.isMediaLoaded)?(m=(f=w(this,o,Me))==null?void 0:f.duration)!=null?m:NaN:super.duration}get currentTime(){var h,f,m;return w(this,o,Me)&&((h=w(this,o,Me))!=null&&h.isMediaLoaded)?(m=(f=w(this,o,Me))==null?void 0:f.currentTime)!=null?m:0:super.currentTime}set currentTime(h){var f;if(w(this,o,Me)){w(this,o,Me).currentTime=h,(f=w(this,o,Me).controller)==null||f.seek();return}super.currentTime=h}},s=new WeakMap,r=new WeakMap,n=new WeakMap,a=new WeakMap,o=new WeakSet,Me=function(){var h,f;return(f=(h=ts.get(this.remote))==null?void 0:h.getCastPlayer)==null?void 0:f.call(h)},L_=async function(){w(this,s).paused=wd(t.prototype,this,"paused"),wd(t.prototype,this,"pause").call(this),this.muted=wd(t.prototype,this,"muted");try{await this.load()}catch(h){console.error(h)}},Ie(t,"observedAttributes",[...(e=i.observedAttributes)!=null?e:[],"cast-src","cast-content-type","cast-stream-type","cast-receiver"]),t};var Os=class extends Event{constructor(t,s){super(t);Ie(this,"track");this.track=s.track}};var Yg=new WeakMap;function X(i){var e;return(e=Yg.get(i))!=null?e:zw(i,{})}function zw(i,e){let t=Yg.get(i);return t||Yg.set(i,t={}),Object.assign(t,e)}function dc(i,e){let t=i.videoTracks;X(e).media=new WeakRef(i),X(e).renditionSet||(X(e).renditionSet=new Set);let s=X(t).trackSet;s.add(e);let r=s.size-1;r in un.prototype||Object.defineProperty(un.prototype,r,{get(){return[...X(this).trackSet][r]}}),queueMicrotask(()=>{t.dispatchEvent(new Os("addtrack",{track:e}))})}function uc(i){var s,r;let e=(r=(s=X(i).media)==null?void 0:s.deref())==null?void 0:r.videoTracks;if(!e)return;X(e).trackSet.delete(i),queueMicrotask(()=>{e.dispatchEvent(new Os("removetrack",{track:i}))})}function R_(i){var s,r,n;let e=(n=(r=(s=X(i).media)==null?void 0:s.deref())==null?void 0:r.videoTracks)!=null?n:[],t=!1;for(let a of e)a!==i&&(a.selected=!1,t=!0);if(t){if(X(e).changeRequested)return;X(e).changeRequested=!0,queueMicrotask(()=>{delete X(e).changeRequested,e.dispatchEvent(new Event("change"))})}}var cr,hr,fr,dn,cl,un=class extends EventTarget{constructor(){super();oe(this,dn);oe(this,cr);oe(this,hr);oe(this,fr);X(this).trackSet=new Set}[Symbol.iterator](){return w(this,dn,cl).values()}get length(){return w(this,dn,cl).size}getTrackById(t){var s;return(s=[...w(this,dn,cl)].find(r=>r.id===t))!=null?s:null}get selectedIndex(){return[...w(this,dn,cl)].findIndex(t=>t.selected)}get onaddtrack(){return w(this,cr)}set onaddtrack(t){w(this,cr)&&(this.removeEventListener("addtrack",w(this,cr)),ee(this,cr,void 0)),typeof t=="function"&&(ee(this,cr,t),this.addEventListener("addtrack",t))}get onremovetrack(){return w(this,hr)}set onremovetrack(t){w(this,hr)&&(this.removeEventListener("removetrack",w(this,hr)),ee(this,hr,void 0)),typeof t=="function"&&(ee(this,hr,t),this.addEventListener("removetrack",t))}get onchange(){return w(this,fr)}set onchange(t){w(this,fr)&&(this.removeEventListener("change",w(this,fr)),ee(this,fr,void 0)),typeof t=="function"&&(ee(this,fr,t),this.addEventListener("change",t))}};cr=new WeakMap,hr=new WeakMap,fr=new WeakMap,dn=new WeakSet,cl=function(){return X(this).trackSet};var Ns=class extends Event{constructor(t,s){super(t);Ie(this,"rendition");this.rendition=s.rendition}};function x_(i,e){var n,a;let t=(a=(n=X(i).media)==null?void 0:n.deref())==null?void 0:a.videoRenditions;X(e).media=X(i).media,X(e).track=i;let s=X(i).renditionSet;s.add(e);let r=s.size-1;r in cn.prototype||Object.defineProperty(cn.prototype,r,{get(){return ca(this)[r]}}),queueMicrotask(()=>{!t||!i.selected||t.dispatchEvent(new Ns("addrendition",{rendition:e}))})}function k_(i){var r,n;let e=(n=(r=X(i).media)==null?void 0:r.deref())==null?void 0:n.videoRenditions,t=X(i).track;X(t).renditionSet.delete(i),queueMicrotask(()=>{let a=X(i).track;!e||!a.selected||e.dispatchEvent(new Ns("removerendition",{rendition:i}))})}function D_(i){var t,s;let e=(s=(t=X(i).media)==null?void 0:t.deref())==null?void 0:s.videoRenditions;!e||X(e).changeRequested||(X(e).changeRequested=!0,queueMicrotask(()=>{delete X(e).changeRequested,X(i).track.selected&&e.dispatchEvent(new Event("change"))}))}function ca(i){var t;let e=(t=X(i).media)==null?void 0:t.deref();return e?[...e.videoTracks].filter(s=>s.selected).flatMap(s=>[...X(s).renditionSet]):[]}var mr,pr,gr,cn=class extends EventTarget{constructor(){super(...arguments);oe(this,mr);oe(this,pr);oe(this,gr)}[Symbol.iterator](){return ca(this).values()}get length(){return ca(this).length}getRenditionById(t){var s;return(s=ca(this).find(r=>`${r.id}`==`${t}`))!=null?s:null}get selectedIndex(){return ca(this).findIndex(t=>t.selected)}set selectedIndex(t){for(let[s,r]of ca(this).entries())r.selected=s===t}get onaddrendition(){return w(this,mr)}set onaddrendition(t){w(this,mr)&&(this.removeEventListener("addrendition",w(this,mr)),ee(this,mr,void 0)),typeof t=="function"&&(ee(this,mr,t),this.addEventListener("addrendition",t))}get onremoverendition(){return w(this,pr)}set onremoverendition(t){w(this,pr)&&(this.removeEventListener("removerendition",w(this,pr)),ee(this,pr,void 0)),typeof t=="function"&&(ee(this,pr,t),this.addEventListener("removerendition",t))}get onchange(){return w(this,gr)}set onchange(t){w(this,gr)&&(this.removeEventListener("change",w(this,gr)),ee(this,gr,void 0)),typeof t=="function"&&(ee(this,gr,t),this.addEventListener("change",t))}};mr=new WeakMap,pr=new WeakMap,gr=new WeakMap;var ha,hl=class{constructor(){Ie(this,"src");Ie(this,"id");Ie(this,"width");Ie(this,"height");Ie(this,"bitrate");Ie(this,"frameRate");Ie(this,"codec");oe(this,ha,!1)}get selected(){return w(this,ha)}set selected(e){w(this,ha)!==e&&(ee(this,ha,e),D_(this))}};ha=new WeakMap;var fa,ma=class{constructor(){Ie(this,"id");Ie(this,"kind");Ie(this,"label","");Ie(this,"language","");Ie(this,"sourceBuffer");oe(this,fa,!1)}addRendition(e,t,s,r,n,a){let o=new hl;return o.src=e,o.width=t,o.height=s,o.frameRate=a,o.bitrate=n,o.codec=r,x_(this,o),o}removeRendition(e){k_(e)}get selected(){return w(this,fa)}set selected(e){w(this,fa)!==e&&(ee(this,fa,e),e===!0&&R_(this))}};fa=new WeakMap;function C_(i,e){var n,a;let t=(a=(n=X(i).media)==null?void 0:n.deref())==null?void 0:a.audioRenditions;X(e).media=X(i).media,X(e).track=i;let s=X(i).renditionSet;s.add(e);let r=s.size-1;r in hn.prototype||Object.defineProperty(hn.prototype,r,{get(){return pa(this)[r]}}),queueMicrotask(()=>{!t||!i.enabled||t.dispatchEvent(new Ns("addrendition",{rendition:e}))})}function w_(i){var r,n;let e=(n=(r=X(i).media)==null?void 0:r.deref())==null?void 0:n.audioRenditions,t=X(i).track;X(t).renditionSet.delete(i),queueMicrotask(()=>{let a=X(i).track;!e||!a.enabled||e.dispatchEvent(new Ns("removerendition",{rendition:i}))})}function M_(i){var t,s;let e=(s=(t=X(i).media)==null?void 0:t.deref())==null?void 0:s.audioRenditions;!e||X(e).changeRequested||(X(e).changeRequested=!0,queueMicrotask(()=>{delete X(e).changeRequested,X(i).track.enabled&&e.dispatchEvent(new Event("change"))}))}function pa(i){var t;let e=(t=X(i).media)==null?void 0:t.deref();return e?[...e.audioTracks].filter(s=>s.enabled).flatMap(s=>[...X(s).renditionSet]):[]}var vr,Er,yr,hn=class extends EventTarget{constructor(){super(...arguments);oe(this,vr);oe(this,Er);oe(this,yr)}[Symbol.iterator](){return pa(this).values()}get length(){return pa(this).length}getRenditionById(t){var s;return(s=pa(this).find(r=>`${r.id}`==`${t}`))!=null?s:null}get selectedIndex(){return pa(this).findIndex(t=>t.selected)}set selectedIndex(t){for(let[s,r]of pa(this).entries())r.selected=s===t}get onaddrendition(){return w(this,vr)}set onaddrendition(t){w(this,vr)&&(this.removeEventListener("addrendition",w(this,vr)),ee(this,vr,void 0)),typeof t=="function"&&(ee(this,vr,t),this.addEventListener("addrendition",t))}get onremoverendition(){return w(this,Er)}set onremoverendition(t){w(this,Er)&&(this.removeEventListener("removerendition",w(this,Er)),ee(this,Er,void 0)),typeof t=="function"&&(ee(this,Er,t),this.addEventListener("removerendition",t))}get onchange(){return w(this,yr)}set onchange(t){w(this,yr)&&(this.removeEventListener("change",w(this,yr)),ee(this,yr,void 0)),typeof t=="function"&&(ee(this,yr,t),this.addEventListener("change",t))}};vr=new WeakMap,Er=new WeakMap,yr=new WeakMap;var ga,fl=class{constructor(){Ie(this,"src");Ie(this,"id");Ie(this,"bitrate");Ie(this,"codec");oe(this,ga,!1)}get selected(){return w(this,ga)}set selected(e){w(this,ga)!==e&&(ee(this,ga,e),M_(this))}};ga=new WeakMap;function hc(i,e){let t=i.audioTracks;X(e).media=new WeakRef(i),X(e).renditionSet||(X(e).renditionSet=new Set);let s=X(t).trackSet;s.add(e);let r=s.size-1;r in fn.prototype||Object.defineProperty(fn.prototype,r,{get(){return[...X(this).trackSet][r]}}),queueMicrotask(()=>{t.dispatchEvent(new Os("addtrack",{track:e}))})}function fc(i){var s,r;let e=(r=(s=X(i).media)==null?void 0:s.deref())==null?void 0:r.audioTracks;if(!e)return;X(e).trackSet.delete(i),queueMicrotask(()=>{e.dispatchEvent(new Os("removetrack",{track:i}))})}function P_(i){var t,s;let e=(s=(t=X(i).media)==null?void 0:t.deref())==null?void 0:s.audioTracks;!e||X(e).changeRequested||(X(e).changeRequested=!0,queueMicrotask(()=>{delete X(e).changeRequested,e.dispatchEvent(new Event("change"))}))}var br,Tr,_r,va,cc,fn=class extends EventTarget{constructor(){super();oe(this,va);oe(this,br);oe(this,Tr);oe(this,_r);X(this).trackSet=new Set}[Symbol.iterator](){return w(this,va,cc).values()}get length(){return w(this,va,cc).size}getTrackById(t){var s;return(s=[...w(this,va,cc)].find(r=>r.id===t))!=null?s:null}get onaddtrack(){return w(this,br)}set onaddtrack(t){w(this,br)&&(this.removeEventListener("addtrack",w(this,br)),ee(this,br,void 0)),typeof t=="function"&&(ee(this,br,t),this.addEventListener("addtrack",t))}get onremovetrack(){return w(this,Tr)}set onremovetrack(t){w(this,Tr)&&(this.removeEventListener("removetrack",w(this,Tr)),ee(this,Tr,void 0)),typeof t=="function"&&(ee(this,Tr,t),this.addEventListener("removetrack",t))}get onchange(){return w(this,_r)}set onchange(t){w(this,_r)&&(this.removeEventListener("change",w(this,_r)),ee(this,_r,void 0)),typeof t=="function"&&(ee(this,_r,t),this.addEventListener("change",t))}};br=new WeakMap,Tr=new WeakMap,_r=new WeakMap,va=new WeakSet,cc=function(){return X(this).trackSet};var Ea,ya=class{constructor(){Ie(this,"id");Ie(this,"kind");Ie(this,"label","");Ie(this,"language","");Ie(this,"sourceBuffer");oe(this,Ea,!1)}addRendition(e,t,s){let r=new fl;return r.src=e,r.codec=t,r.bitrate=s,C_(this,r),r}removeRendition(e){w_(e)}get enabled(){return w(this,Ea)}set enabled(e){w(this,Ea)!==e&&(ee(this,Ea,e),P_(this))}};Ea=new WeakMap;var O_=mc(globalThis.HTMLMediaElement,"video"),N_=mc(globalThis.HTMLMediaElement,"audio");function U_(i){if(!(i!=null&&i.prototype))return i;let e=mc(i,"video");(!e||`${e}`.includes("[native code]"))&&Object.defineProperty(i.prototype,"videoTracks",{get(){return Qw(this)}});let t=mc(i,"audio");(!t||`${t}`.includes("[native code]"))&&Object.defineProperty(i.prototype,"audioTracks",{get(){return Xw(this)}}),"addVideoTrack"in i.prototype||(i.prototype.addVideoTrack=function(n,a="",o=""){let l=new ma;return l.kind=n,l.label=a,l.language=o,dc(this,l),l}),"removeVideoTrack"in i.prototype||(i.prototype.removeVideoTrack=uc),"addAudioTrack"in i.prototype||(i.prototype.addAudioTrack=function(n,a="",o=""){let l=new ya;return l.kind=n,l.label=a,l.language=o,hc(this,l),l}),"removeAudioTrack"in i.prototype||(i.prototype.removeAudioTrack=fc),"videoRenditions"in i.prototype||Object.defineProperty(i.prototype,"videoRenditions",{get(){return s(this)}});let s=n=>{let a=X(n).videoRenditions;return a||(a=new cn,X(a).media=new WeakRef(n),X(n).videoRenditions=a),a};"audioRenditions"in i.prototype||Object.defineProperty(i.prototype,"audioRenditions",{get(){return r(this)}});let r=n=>{let a=X(n).audioRenditions;return a||(a=new hn,X(a).media=new WeakRef(n),X(n).audioRenditions=a),a};return i}function mc(i,e){var t;if(i!=null&&i.prototype)return(t=Object.getOwnPropertyDescriptor(i.prototype,`${e}Tracks`))==null?void 0:t.get}function Qw(i){var t;let e=X(i).videoTracks;if(!e&&(e=new un,X(i).videoTracks=e,O_)){let s=O_.call((t=i.nativeEl)!=null?t:i);for(let o of s)dc(i,o);let r=()=>{e.dispatchEvent(new Event("change"))},n=o=>{if([...e].some(l=>l instanceof ma)){for(let l of s)uc(l);return}dc(i,o.track)},a=o=>{uc(o.track)};s.addEventListener("change",r),s.addEventListener("addtrack",n),s.addEventListener("removetrack",a)}return e}function Xw(i){var t;let e=X(i).audioTracks;if(!e&&(e=new fn,X(i).audioTracks=e,N_)){let s=N_.call((t=i.nativeEl)!=null?t:i);for(let o of s)hc(i,o);let r=()=>{e.dispatchEvent(new Event("change"))},n=o=>{if([...e].some(l=>l instanceof ya)){for(let l of s)fc(l);return}hc(i,o.track)},a=o=>{fc(o.track)};s.addEventListener("change",r),s.addEventListener("addtrack",n),s.addEventListener("removetrack",a)}return e}var B_=i=>{throw TypeError(i)},$_=(i,e,t)=>e.has(i)||B_("Cannot "+t),H_=(i,e,t)=>($_(i,e,"read from private field"),t?t.call(i):e.get(i)),G_=(i,e,t)=>e.has(i)?B_("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),K_=(i,e,t,s)=>($_(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),vc=class{addEventListener(){}removeEventListener(){}dispatchEvent(i){return!0}};if(typeof DocumentFragment=="undefined"){class i extends vc{}globalThis.DocumentFragment=i}var zg=class extends vc{},Zw=class extends vc{},Jw={get(i){},define(i,e,t){},getName(i){return null},upgrade(i){},whenDefined(i){return Promise.resolve(zg)}},pc,eM=class{constructor(i,e={}){G_(this,pc),K_(this,pc,e==null?void 0:e.detail)}get detail(){return H_(this,pc)}initCustomEvent(){}};pc=new WeakMap;function tM(i,e){return new zg}var V_={document:{createElement:tM},DocumentFragment,customElements:Jw,CustomEvent:eM,EventTarget:vc,HTMLElement:zg,HTMLVideoElement:Zw},W_=typeof window=="undefined"||typeof globalThis.customElements=="undefined",jg=W_?V_:globalThis,Q3=W_?V_.document:globalThis.document,gc,F_=class extends I_(U_(c_)){constructor(){super(...arguments),G_(this,gc)}get autoplay(){let i=this.getAttribute("autoplay");return i===null?!1:i===""?!0:i}set autoplay(i){let e=this.autoplay;i!==e&&(i?this.setAttribute("autoplay",typeof i=="string"?i:""):this.removeAttribute("autoplay"))}get muxCastCustomData(){return{mux:{playbackId:this.playbackId,minResolution:this.minResolution,maxResolution:this.maxResolution,renditionOrder:this.renditionOrder,customDomain:this.customDomain,tokens:{drm:this.drmToken},envKey:this.envKey,metadata:this.metadata,disableCookies:this.disableCookies,disableTracking:this.disableTracking,beaconCollectionDomain:this.beaconCollectionDomain,startTime:this.startTime,preferCmcd:this.preferCmcd}}}get castCustomData(){var i;return(i=H_(this,gc))!=null?i:this.muxCastCustomData}set castCustomData(i){K_(this,gc,i)}};gc=new WeakMap;jg.customElements.get("mux-video")||(jg.customElements.define("mux-video",F_),jg.MuxVideoElement=F_);var K={MEDIA_PLAY_REQUEST:"mediaplayrequest",MEDIA_PAUSE_REQUEST:"mediapauserequest",MEDIA_MUTE_REQUEST:"mediamuterequest",MEDIA_UNMUTE_REQUEST:"mediaunmuterequest",MEDIA_LOOP_REQUEST:"medialooprequest",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"},ge={MEDIA_CHROME_ATTRIBUTES:"mediachromeattributes",MEDIA_CONTROLLER:"mediacontroller"},Qg={MEDIA_AIRPLAY_UNAVAILABLE:"mediaAirplayUnavailable",MEDIA_AUDIO_TRACK_ENABLED:"mediaAudioTrackEnabled",MEDIA_AUDIO_TRACK_LIST:"mediaAudioTrackList",MEDIA_AUDIO_TRACK_UNAVAILABLE:"mediaAudioTrackUnavailable",MEDIA_BUFFERED:"mediaBuffered",MEDIA_CAST_UNAVAILABLE:"mediaCastUnavailable",MEDIA_CHAPTERS_CUES:"mediaChaptersCues",MEDIA_CURRENT_TIME:"mediaCurrentTime",MEDIA_DURATION:"mediaDuration",MEDIA_ENDED:"mediaEnded",MEDIA_ERROR:"mediaError",MEDIA_ERROR_CODE:"mediaErrorCode",MEDIA_ERROR_MESSAGE:"mediaErrorMessage",MEDIA_FULLSCREEN_UNAVAILABLE:"mediaFullscreenUnavailable",MEDIA_HAS_PLAYED:"mediaHasPlayed",MEDIA_HEIGHT:"mediaHeight",MEDIA_IS_AIRPLAYING:"mediaIsAirplaying",MEDIA_IS_CASTING:"mediaIsCasting",MEDIA_IS_FULLSCREEN:"mediaIsFullscreen",MEDIA_IS_PIP:"mediaIsPip",MEDIA_LOADING:"mediaLoading",MEDIA_MUTED:"mediaMuted",MEDIA_LOOP:"mediaLoop",MEDIA_PAUSED:"mediaPaused",MEDIA_PIP_UNAVAILABLE:"mediaPipUnavailable",MEDIA_PLAYBACK_RATE:"mediaPlaybackRate",MEDIA_PREVIEW_CHAPTER:"mediaPreviewChapter",MEDIA_PREVIEW_COORDS:"mediaPreviewCoords",MEDIA_PREVIEW_IMAGE:"mediaPreviewImage",MEDIA_PREVIEW_TIME:"mediaPreviewTime",MEDIA_RENDITION_LIST:"mediaRenditionList",MEDIA_RENDITION_SELECTED:"mediaRenditionSelected",MEDIA_RENDITION_UNAVAILABLE:"mediaRenditionUnavailable",MEDIA_SEEKABLE:"mediaSeekable",MEDIA_STREAM_TYPE:"mediaStreamType",MEDIA_SUBTITLES_LIST:"mediaSubtitlesList",MEDIA_SUBTITLES_SHOWING:"mediaSubtitlesShowing",MEDIA_TARGET_LIVE_WINDOW:"mediaTargetLiveWindow",MEDIA_TIME_IS_LIVE:"mediaTimeIsLive",MEDIA_VOLUME:"mediaVolume",MEDIA_VOLUME_LEVEL:"mediaVolumeLevel",MEDIA_VOLUME_UNAVAILABLE:"mediaVolumeUnavailable",MEDIA_LANG:"mediaLang",MEDIA_WIDTH:"mediaWidth"},q_=Object.entries(Qg),_=q_.reduce((i,[e,t])=>(i[e]=t.toLowerCase(),i),{}),iM={USER_INACTIVE_CHANGE:"userinactivechange",BREAKPOINTS_CHANGE:"breakpointchange",BREAKPOINTS_COMPUTED:"breakpointscomputed"},di=q_.reduce((i,[e,t])=>(i[e]=t.toLowerCase(),i),{...iM}),oU=Object.entries(di).reduce((i,[e,t])=>{let s=_[e];return s&&(i[t]=s),i},{userinactivechange:"userinactive"}),Y_=Object.entries(_).reduce((i,[e,t])=>{let s=di[e];return s&&(i[t]=s),i},{userinactive:"userinactivechange"}),Xt={SUBTITLES:"subtitles",CAPTIONS:"captions",DESCRIPTIONS:"descriptions",CHAPTERS:"chapters",METADATA:"metadata"},Ar={DISABLED:"disabled",HIDDEN:"hidden",SHOWING:"showing"};var Ec={MOUSE:"mouse",PEN:"pen",TOUCH:"touch"},Zt={UNAVAILABLE:"unavailable",UNSUPPORTED:"unsupported"},Ni={LIVE:"live",ON_DEMAND:"on-demand",UNKNOWN:"unknown"};var j_={INLINE:"inline",FULLSCREEN:"fullscreen",PICTURE_IN_PICTURE:"picture-in-picture"};function z_(i){return i==null?void 0:i.map(rM).join(" ")}function Q_(i){return i==null?void 0:i.split(/\s+/).map(nM)}function rM(i){if(i){let{id:e,width:t,height:s}=i;return[e,t,s].filter(r=>r!=null).join(":")}}function nM(i){if(i){let[e,t,s]=i.split(":");return{id:e,width:+t,height:+s}}}function X_(i){return i==null?void 0:i.map(aM).join(" ")}function Z_(i){return i==null?void 0:i.split(/\s+/).map(oM)}function aM(i){if(i){let{id:e,kind:t,language:s,label:r}=i;return[e,t,s,r].filter(n=>n!=null).join(":")}}function oM(i){if(i){let[e,t,s,r]=i.split(":");return{id:e,kind:t,language:s,label:r}}}function J_(i){return i.replace(/[-_]([a-z])/g,(e,t)=>t.toUpperCase())}function ba(i){return typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i)}function yc(i){return typeof i!="string"?!1:!isNaN(i)&&!isNaN(parseFloat(i))}var bc=i=>new Promise(e=>setTimeout(e,i));var eA={"Start airplay":"Start airplay","Stop airplay":"Stop airplay",Audio:"Audio",Captions:"Captions","Enable captions":"Enable captions","Disable captions":"Disable captions","Start casting":"Start casting","Stop casting":"Stop casting","Enter fullscreen mode":"Enter fullscreen mode","Exit fullscreen mode":"Exit fullscreen mode",Mute:"Mute",Unmute:"Unmute",Loop:"Loop","Enter picture in picture mode":"Enter picture in picture mode","Exit picture in picture mode":"Exit picture in picture mode",Play:"Play",Pause:"Pause","Playback rate":"Playback rate","Playback rate {playbackRate}":"Playback rate {playbackRate}",Quality:"Quality","Seek backward":"Seek backward","Seek forward":"Seek forward",Settings:"Settings",Auto:"Auto","audio player":"audio player","video player":"video player",volume:"volume",seek:"seek","closed captions":"closed captions","current playback rate":"current playback rate","playback time":"playback time","media loading":"media loading",settings:"settings","audio tracks":"audio tracks",quality:"quality",play:"play",pause:"pause",mute:"mute",unmute:"unmute","chapter: {chapterName}":"chapter: {chapterName}",live:"live",Off:"Off","start airplay":"start airplay","stop airplay":"stop airplay","start casting":"start casting","stop casting":"stop casting","enter fullscreen mode":"enter fullscreen mode","exit fullscreen mode":"exit fullscreen mode","enter picture in picture mode":"enter picture in picture mode","exit picture in picture mode":"exit picture in picture mode","seek to live":"seek to live","playing live":"playing live","seek back {seekOffset} seconds":"seek back {seekOffset} seconds","seek forward {seekOffset} seconds":"seek forward {seekOffset} seconds","Network Error":"Network Error","Decode Error":"Decode Error","Source Not Supported":"Source Not Supported","Encryption Error":"Encryption Error","A network error caused the media download to fail.":"A network error caused the media download to fail.","A media error caused playback to be aborted. The media could be corrupt or your browser does not support this format.":"A media error caused playback to be aborted. The media could be corrupt or your browser does not support this format.","An unsupported error occurred. The server or network failed, or your browser does not support this format.":"An unsupported error occurred. The server or network failed, or your browser does not support this format.","The media is encrypted and there are no keys to decrypt it.":"The media is encrypted and there are no keys to decrypt it.",hour:"hour",hours:"hours",minute:"minute",minutes:"minutes",second:"second",seconds:"seconds","{time} remaining":"{time} remaining","{currentTime} of {totalTime}":"{currentTime} of {totalTime}","video not loaded, unknown time.":"video not loaded, unknown time."};var tA,Xg={en:eA},Zg=((tA=globalThis.navigator)==null?void 0:tA.language)||"en",iA=i=>{Zg=i};var lM=i=>{var e,t,s;let[r]=Zg.split("-");return((e=Xg[Zg])==null?void 0:e[i])||((t=Xg[r])==null?void 0:t[i])||((s=Xg.en)==null?void 0:s[i])||i},F=(i,e={})=>lM(i).replace(/\{(\w+)\}/g,(t,s)=>s in e?String(e[s]):`{${s}}`);var sA=[{singular:"hour",plural:"hours"},{singular:"minute",plural:"minutes"},{singular:"second",plural:"seconds"}],dM=(i,e)=>{let t=i===1?F(sA[e].singular):F(sA[e].plural);return`${i} ${t}`},mn=i=>{if(!ba(i))return"";let e=Math.abs(i),t=e!==i,s=new Date(0,0,0,0,0,e,0),n=[s.getHours(),s.getMinutes(),s.getSeconds()].map((a,o)=>a&&dM(a,o)).filter(a=>a).join(", ");return t?F("{time} remaining",{time:n}):n};function Ui(i,e){let t=!1;i<0&&(t=!0,i=0-i),i=i<0?0:i;let s=Math.floor(i%60),r=Math.floor(i/60%60),n=Math.floor(i/3600),a=Math.floor(e/60%60),o=Math.floor(e/3600);return(isNaN(i)||i===1/0)&&(n=r=s="0"),n=n>0||o>0?n+":":"",r=((n||a>=10)&&r<10?"0"+r:r)+":",s=s<10?"0"+s:s,(t?"-":"")+n+r+s}var mU=Object.freeze({length:0,start(i){let e=i>>>0;if(e>=this.length)throw new DOMException(`Failed to execute 'start' on 'TimeRanges': The index provided (${e}) is greater than or equal to the maximum bound (${this.length}).`);return 0},end(i){let e=i>>>0;if(e>=this.length)throw new DOMException(`Failed to execute 'end' on 'TimeRanges': The index provided (${e}) is greater than or equal to the maximum bound (${this.length}).`);return 0}});var Tc=class{addEventListener(){}removeEventListener(){}dispatchEvent(){return!0}},_c=class extends Tc{},Ac=class extends _c{constructor(){super(...arguments),this.role=null}},Jg=class{observe(){}unobserve(){}disconnect(){}},rA={createElement:function(){return new ml.HTMLElement},createElementNS:function(){return new ml.HTMLElement},addEventListener(){},removeEventListener(){},dispatchEvent(i){return!1}},ml={ResizeObserver:Jg,document:rA,Node:_c,Element:Ac,HTMLElement:class extends Ac{constructor(){super(...arguments),this.innerHTML=""}get content(){return new ml.DocumentFragment}},DocumentFragment:class extends Tc{},customElements:{get:function(){},define:function(){},whenDefined:function(){}},localStorage:{getItem(i){return null},setItem(i,e){},removeItem(i){}},CustomEvent:function(){},getComputedStyle:function(){},navigator:{languages:[],get userAgent(){return""}},matchMedia(i){return{matches:!1,media:i}},DOMParser:class{parseFromString(e,t){return{body:{textContent:e}}}}},nA="global"in globalThis&&(globalThis==null?void 0:globalThis.global)===globalThis||typeof window=="undefined"||typeof window.customElements=="undefined",aA=Object.keys(ml).every(i=>i in globalThis),L=nA&&!aA?ml:globalThis,He=nA&&!aA?rA:globalThis.document;var oA=new WeakMap,e0=i=>{let e=oA.get(i);return e||oA.set(i,e=new Set),e},lA=new L.ResizeObserver(i=>{for(let e of i)for(let t of e0(e.target))t(e)});function Us(i,e){e0(i).add(e),lA.observe(i)}function Fs(i,e){let t=e0(i);t.delete(e),t.size||lA.unobserve(i)}function Qe(i){let e={};for(let t of i)e[t.name]=t.value;return e}function Ye(i){var e;return(e=Sc(i))!=null?e:is(i,"media-controller")}function Sc(i){var e;let{MEDIA_CONTROLLER:t}=ge,s=i.getAttribute(t);if(s)return(e=pn(i))==null?void 0:e.getElementById(s)}var Ic=(i,e,t=".value")=>{let s=i.querySelector(t);s&&(s.textContent=e)},cM=(i,e)=>{let t=`slot[name="${e}"]`,s=i.shadowRoot.querySelector(t);return s?s.children:[]},Lc=(i,e)=>cM(i,e)[0],Kt=(i,e)=>!i||!e?!1:i!=null&&i.contains(e)?!0:Kt(i,e.getRootNode().host),is=(i,e)=>{if(!i)return null;let t=i.closest(e);return t||is(i.getRootNode().host,e)};function pl(i=document){var e;let t=i==null?void 0:i.activeElement;return t?(e=pl(t.shadowRoot))!=null?e:t:null}function pn(i){var e;let t=(e=i==null?void 0:i.getRootNode)==null?void 0:e.call(i);return t instanceof ShadowRoot||t instanceof Document?t:null}function Rc(i,{depth:e=3,checkOpacity:t=!0,checkVisibilityCSS:s=!0}={}){if(i.checkVisibility)return i.checkVisibility({checkOpacity:t,checkVisibilityCSS:s});let r=i;for(;r&&e>0;){let n=getComputedStyle(r);if(t&&n.opacity==="0"||s&&n.visibility==="hidden"||n.display==="none")return!1;r=r.parentElement,e--}return!0}function dA(i,e,t,s){let r=s.x-t.x,n=s.y-t.y,a=r*r+n*n;if(a===0)return 0;let o=((i-t.x)*r+(e-t.y)*n)/a;return Math.max(0,Math.min(1,o))}function je(i,e){let t=hM(i,s=>s===e);return t||gl(i,e)}function hM(i,e){var t,s;let r;for(r of(t=i.querySelectorAll("style:not([media])"))!=null?t:[]){let n;try{n=(s=r.sheet)==null?void 0:s.cssRules}catch{continue}for(let a of n!=null?n:[])if(e(a.selectorText))return a}}function gl(i,e){var t,s;let r=(t=i.querySelectorAll("style:not([media])"))!=null?t:[],n=r==null?void 0:r[r.length-1];if(!(n!=null&&n.sheet))return console.warn("Media Chrome: No style sheet found on style tag of",i),{style:{setProperty:()=>{},removeProperty:()=>"",getPropertyValue:()=>""}};let a=n==null?void 0:n.sheet.insertRule(`${e}{}`,n.sheet.cssRules.length);return(s=n.sheet.cssRules)==null?void 0:s[a]}function ye(i,e,t=Number.NaN){let s=i.getAttribute(e);return s!=null?+s:t}function Re(i,e,t){let s=+t;if(t==null||Number.isNaN(s)){i.hasAttribute(e)&&i.removeAttribute(e);return}ye(i,e,void 0)!==s&&i.setAttribute(e,`${s}`)}function le(i,e){return i.hasAttribute(e)}function de(i,e,t){if(t==null){i.hasAttribute(e)&&i.removeAttribute(e);return}le(i,e)!=t&&i.toggleAttribute(e,t)}function pe(i,e,t=null){var s;return(s=i.getAttribute(e))!=null?s:t}function me(i,e,t){if(t==null){i.hasAttribute(e)&&i.removeAttribute(e);return}let s=`${t}`;pe(i,e,void 0)!==s&&i.setAttribute(e,s)}var uA=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},Fi=(i,e,t)=>(uA(i,e,"read from private field"),t?t.call(i):e.get(i)),fM=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},xc=(i,e,t,s)=>(uA(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),wt;function mM(i){return`
141
141
  <style>
142
142
  :host {
143
143
  display: var(--media-control-display, var(--media-gesture-receiver-display, inline-block));
144
144
  box-sizing: border-box;
145
145
  }
146
146
  </style>
147
- `}var ba=class extends L.HTMLElement{constructor(){if(super(),fM(this,wt,void 0),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=Qe(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e)}}static get observedAttributes(){return[ge.MEDIA_CONTROLLER,_.MEDIA_PAUSED]}attributeChangedCallback(e,t,s){var r,n,a,o,l;e===ge.MEDIA_CONTROLLER&&(t&&((n=(r=Fi(this,wt))==null?void 0:r.unassociateElement)==null||n.call(r,this),xc(this,wt,null)),s&&this.isConnected&&(xc(this,wt,(a=this.getRootNode())==null?void 0:a.getElementById(s)),(l=(o=Fi(this,wt))==null?void 0:o.associateElement)==null||l.call(o,this)))}connectedCallback(){var e,t;this.tabIndex=-1,this.setAttribute("aria-hidden","true"),xc(this,wt,pM(this)),this.getAttribute(ge.MEDIA_CONTROLLER)&&((t=(e=Fi(this,wt))==null?void 0:e.associateElement)==null||t.call(e,this)),Fi(this,wt)&&(Fi(this,wt).addEventListener("pointerdown",this),Fi(this,wt).addEventListener("click",this),Fi(this,wt).hasAttribute("tabindex")||(Fi(this,wt).tabIndex=0))}disconnectedCallback(){var e,t,s,r;this.getAttribute(ge.MEDIA_CONTROLLER)&&((t=(e=Fi(this,wt))==null?void 0:e.unassociateElement)==null||t.call(e,this)),(s=Fi(this,wt))==null||s.removeEventListener("pointerdown",this),(r=Fi(this,wt))==null||r.removeEventListener("click",this),xc(this,wt,null)}handleEvent(e){var t;let s=(t=e.composedPath())==null?void 0:t[0];if(["video","media-controller"].includes(s==null?void 0:s.localName)){if(e.type==="pointerdown")this._pointerType=e.pointerType;else if(e.type==="click"){let{clientX:n,clientY:a}=e,{left:o,top:l,width:d,height:u}=this.getBoundingClientRect(),c=n-o,h=a-l;if(c<0||h<0||c>d||h>u||d===0&&u===0)return;let f=this._pointerType||"mouse";if(this._pointerType=void 0,f===Ec.TOUCH){this.handleTap(e);return}else if(f===Ec.MOUSE||f===Ec.PEN){this.handleMouseClick(e);return}}}}get mediaPaused(){return le(this,_.MEDIA_PAUSED)}set mediaPaused(e){de(this,_.MEDIA_PAUSED,e)}handleTap(e){}handleMouseClick(e){let t=this.mediaPaused?K.MEDIA_PLAY_REQUEST:K.MEDIA_PAUSE_REQUEST;this.dispatchEvent(new L.CustomEvent(t,{composed:!0,bubbles:!0}))}};wt=new WeakMap;ba.shadowRootOptions={mode:"open"};ba.getTemplateHTML=mM;function pM(i){var e;let t=i.getAttribute(ge.MEDIA_CONTROLLER);return t?(e=i.getRootNode())==null?void 0:e.getElementById(t):is(i,"media-controller")}L.customElements.get("media-gesture-receiver")||L.customElements.define("media-gesture-receiver",ba);var kc=ba;var r0=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},ot=(i,e,t)=>(r0(i,e,"read from private field"),t?t.call(i):e.get(i)),Vt=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},Bi=(i,e,t,s)=>(r0(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),$i=(i,e,t)=>(r0(i,e,"access private method"),t),vl,wc,_a,Ia,Sa,t0,Aa,Dc,i0,cA,s0,hA,El,Mc,Pc,n0,La,yl,Sr,Cc,ae={AUDIO:"audio",AUTOHIDE:"autohide",BREAKPOINTS:"breakpoints",GESTURES_DISABLED:"gesturesdisabled",KEYBOARD_CONTROL:"keyboardcontrol",NO_AUTOHIDE:"noautohide",USER_INACTIVE:"userinactive",AUTOHIDE_OVER_CONTROLS:"autohideovercontrols"};function gM(i){return`
147
+ `}var Ta=class extends L.HTMLElement{constructor(){if(super(),fM(this,wt,void 0),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=Qe(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e)}}static get observedAttributes(){return[ge.MEDIA_CONTROLLER,_.MEDIA_PAUSED]}attributeChangedCallback(e,t,s){var r,n,a,o,l;e===ge.MEDIA_CONTROLLER&&(t&&((n=(r=Fi(this,wt))==null?void 0:r.unassociateElement)==null||n.call(r,this),xc(this,wt,null)),s&&this.isConnected&&(xc(this,wt,(a=this.getRootNode())==null?void 0:a.getElementById(s)),(l=(o=Fi(this,wt))==null?void 0:o.associateElement)==null||l.call(o,this)))}connectedCallback(){var e,t;this.tabIndex=-1,this.setAttribute("aria-hidden","true"),xc(this,wt,pM(this)),this.getAttribute(ge.MEDIA_CONTROLLER)&&((t=(e=Fi(this,wt))==null?void 0:e.associateElement)==null||t.call(e,this)),Fi(this,wt)&&(Fi(this,wt).addEventListener("pointerdown",this),Fi(this,wt).addEventListener("click",this),Fi(this,wt).hasAttribute("tabindex")||(Fi(this,wt).tabIndex=0))}disconnectedCallback(){var e,t,s,r;this.getAttribute(ge.MEDIA_CONTROLLER)&&((t=(e=Fi(this,wt))==null?void 0:e.unassociateElement)==null||t.call(e,this)),(s=Fi(this,wt))==null||s.removeEventListener("pointerdown",this),(r=Fi(this,wt))==null||r.removeEventListener("click",this),xc(this,wt,null)}handleEvent(e){var t;let s=(t=e.composedPath())==null?void 0:t[0];if(["video","media-controller"].includes(s==null?void 0:s.localName)){if(e.type==="pointerdown")this._pointerType=e.pointerType;else if(e.type==="click"){let{clientX:n,clientY:a}=e,{left:o,top:l,width:d,height:u}=this.getBoundingClientRect(),c=n-o,h=a-l;if(c<0||h<0||c>d||h>u||d===0&&u===0)return;let f=this._pointerType||"mouse";if(this._pointerType=void 0,f===Ec.TOUCH){this.handleTap(e);return}else if(f===Ec.MOUSE||f===Ec.PEN){this.handleMouseClick(e);return}}}}get mediaPaused(){return le(this,_.MEDIA_PAUSED)}set mediaPaused(e){de(this,_.MEDIA_PAUSED,e)}handleTap(e){}handleMouseClick(e){let t=this.mediaPaused?K.MEDIA_PLAY_REQUEST:K.MEDIA_PAUSE_REQUEST;this.dispatchEvent(new L.CustomEvent(t,{composed:!0,bubbles:!0}))}};wt=new WeakMap;Ta.shadowRootOptions={mode:"open"};Ta.getTemplateHTML=mM;function pM(i){var e;let t=i.getAttribute(ge.MEDIA_CONTROLLER);return t?(e=i.getRootNode())==null?void 0:e.getElementById(t):is(i,"media-controller")}L.customElements.get("media-gesture-receiver")||L.customElements.define("media-gesture-receiver",Ta);var kc=Ta;var r0=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},ot=(i,e,t)=>(r0(i,e,"read from private field"),t?t.call(i):e.get(i)),Vt=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},Bi=(i,e,t,s)=>(r0(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),$i=(i,e,t)=>(r0(i,e,"access private method"),t),vl,wc,_a,Ia,Sa,t0,Aa,Dc,i0,cA,s0,hA,El,Mc,Pc,n0,La,yl,Sr,Cc,ae={AUDIO:"audio",AUTOHIDE:"autohide",BREAKPOINTS:"breakpoints",GESTURES_DISABLED:"gesturesdisabled",KEYBOARD_CONTROL:"keyboardcontrol",NO_AUTOHIDE:"noautohide",USER_INACTIVE:"userinactive",AUTOHIDE_OVER_CONTROLS:"autohideovercontrols"};function gM(i){return`
148
148
  <style>
149
149
 
150
150
  :host([${_.MEDIA_IS_FULLSCREEN}]) ::slotted([slot=media]) {
@@ -295,7 +295,7 @@ Schedule: ${l.map(p=>Ci(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Remo
295
295
  <slot part="bottom chrome"></slot>
296
296
  </span>
297
297
  <slot name="dialog" part="layer dialog-layer"></slot>
298
- `}var vM=Object.values(_),EM="sm:384 md:576 lg:768 xl:960";function yM(i){fA(i.target,i.contentRect.width)}function fA(i,e){var t;if(!i.isConnected)return;let s=(t=i.getAttribute(ae.BREAKPOINTS))!=null?t:EM,r=TM(s),n=bM(r,e),a=!1;if(Object.keys(r).forEach(o=>{if(n.includes(o)){i.hasAttribute(`breakpoint${o}`)||(i.setAttribute(`breakpoint${o}`,""),a=!0);return}i.hasAttribute(`breakpoint${o}`)&&(i.removeAttribute(`breakpoint${o}`),a=!0)}),a){let o=new CustomEvent(di.BREAKPOINTS_CHANGE,{detail:n});i.dispatchEvent(o)}i.breakpointsComputed||(i.breakpointsComputed=!0,i.dispatchEvent(new CustomEvent(di.BREAKPOINTS_COMPUTED,{bubbles:!0,composed:!0})))}function TM(i){let e=i.split(/\s+/);return Object.fromEntries(e.map(t=>t.split(":")))}function bM(i,e){return Object.keys(i).filter(t=>e>=parseInt(i[t]))}var gn=class extends L.HTMLElement{constructor(){if(super(),Vt(this,i0),Vt(this,s0),Vt(this,El),Vt(this,Pc),Vt(this,La),Vt(this,vl,void 0),Vt(this,wc,0),Vt(this,_a,null),Vt(this,Ia,null),Vt(this,Sa,void 0),this.breakpointsComputed=!1,Vt(this,t0,e=>{let t=this.media;for(let s of e){if(s.type!=="childList")continue;let r=s.removedNodes;for(let n of r){if(n.slot!="media"||s.target!=this)continue;let a=s.previousSibling&&s.previousSibling.previousElementSibling;if(!a||!t)this.mediaUnsetCallback(n);else{let o=a.slot!=="media";for(;(a=a.previousSibling)!==null;)a.slot=="media"&&(o=!1);o&&this.mediaUnsetCallback(n)}}if(t)for(let n of s.addedNodes)n===t&&this.handleMediaUpdated(t)}}),Vt(this,Aa,!1),Vt(this,Dc,e=>{ot(this,Aa)||(setTimeout(()=>{yM(e),Bi(this,Aa,!1)},0),Bi(this,Aa,!0))}),Vt(this,Sr,void 0),Vt(this,Cc,()=>{if(!ot(this,Sr).assignedElements({flatten:!0}).length){ot(this,_a)&&this.mediaUnsetCallback(ot(this,_a));return}this.handleMediaUpdated(this.media)}),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=Qe(this.attributes),t=this.constructor.getTemplateHTML(e);this.shadowRoot.setHTMLUnsafe?this.shadowRoot.setHTMLUnsafe(t):this.shadowRoot.innerHTML=t}Bi(this,vl,new MutationObserver(ot(this,t0)))}static get observedAttributes(){return[ae.AUTOHIDE,ae.GESTURES_DISABLED].concat(vM).filter(e=>![_.MEDIA_RENDITION_LIST,_.MEDIA_AUDIO_TRACK_LIST,_.MEDIA_CHAPTERS_CUES,_.MEDIA_WIDTH,_.MEDIA_HEIGHT,_.MEDIA_ERROR,_.MEDIA_ERROR_MESSAGE].includes(e))}attributeChangedCallback(e,t,s){e.toLowerCase()==ae.AUTOHIDE&&(this.autohide=s)}get media(){let e=this.querySelector(":scope > [slot=media]");return(e==null?void 0:e.nodeName)=="SLOT"&&(e=e.assignedElements({flatten:!0})[0]),e}async handleMediaUpdated(e){e&&(Bi(this,_a,e),e.localName.includes("-")&&await L.customElements.whenDefined(e.localName),this.mediaSetCallback(e))}connectedCallback(){var e;ot(this,vl).observe(this,{childList:!0,subtree:!0}),Us(this,ot(this,Dc));let s=this.getAttribute(ae.AUDIO)!=null?F("audio player"):F("video player");this.setAttribute("role","region"),this.setAttribute("aria-label",s),this.handleMediaUpdated(this.media),this.setAttribute(ae.USER_INACTIVE,""),fA(this,this.getBoundingClientRect().width);let r=this.querySelector(":scope > slot[slot=media]");r&&(Bi(this,Sr,r),ot(this,Sr).addEventListener("slotchange",ot(this,Cc))),this.addEventListener("pointerdown",this),this.addEventListener("pointermove",this),this.addEventListener("pointerup",this),this.addEventListener("mouseleave",this),this.addEventListener("keyup",this),(e=L.window)==null||e.addEventListener("mouseup",this)}disconnectedCallback(){var e;Fs(this,ot(this,Dc)),clearTimeout(ot(this,Ia)),ot(this,vl).disconnect(),this.media&&this.mediaUnsetCallback(this.media),(e=L.window)==null||e.removeEventListener("mouseup",this),this.removeEventListener("pointerdown",this),this.removeEventListener("pointermove",this),this.removeEventListener("pointerup",this),this.removeEventListener("mouseleave",this),this.removeEventListener("keyup",this),ot(this,Sr)&&(ot(this,Sr).removeEventListener("slotchange",ot(this,Cc)),Bi(this,Sr,null)),Bi(this,Aa,!1)}mediaSetCallback(e){}mediaUnsetCallback(e){Bi(this,_a,null)}handleEvent(e){switch(e.type){case"pointerdown":Bi(this,wc,e.timeStamp);break;case"pointermove":$i(this,i0,cA).call(this,e);break;case"pointerup":$i(this,s0,hA).call(this,e);break;case"mouseleave":$i(this,El,Mc).call(this);break;case"mouseup":this.removeAttribute(ae.KEYBOARD_CONTROL);break;case"keyup":$i(this,La,yl).call(this),this.setAttribute(ae.KEYBOARD_CONTROL,"");break}}set autohide(e){let t=Number(e);Bi(this,Sa,isNaN(t)?0:t)}get autohide(){return(ot(this,Sa)===void 0?2:ot(this,Sa)).toString()}get breakpoints(){return pe(this,ae.BREAKPOINTS)}set breakpoints(e){me(this,ae.BREAKPOINTS,e)}get audio(){return le(this,ae.AUDIO)}set audio(e){de(this,ae.AUDIO,e)}get gesturesDisabled(){return le(this,ae.GESTURES_DISABLED)}set gesturesDisabled(e){de(this,ae.GESTURES_DISABLED,e)}get keyboardControl(){return le(this,ae.KEYBOARD_CONTROL)}set keyboardControl(e){de(this,ae.KEYBOARD_CONTROL,e)}get noAutohide(){return le(this,ae.NO_AUTOHIDE)}set noAutohide(e){de(this,ae.NO_AUTOHIDE,e)}get autohideOverControls(){return le(this,ae.AUTOHIDE_OVER_CONTROLS)}set autohideOverControls(e){de(this,ae.AUTOHIDE_OVER_CONTROLS,e)}get userInteractive(){return le(this,ae.USER_INACTIVE)}set userInteractive(e){de(this,ae.USER_INACTIVE,e)}};vl=new WeakMap;wc=new WeakMap;_a=new WeakMap;Ia=new WeakMap;Sa=new WeakMap;t0=new WeakMap;Aa=new WeakMap;Dc=new WeakMap;i0=new WeakSet;cA=function(i){if(i.pointerType!=="mouse"&&i.timeStamp-ot(this,wc)<250)return;$i(this,Pc,n0).call(this),clearTimeout(ot(this,Ia));let e=this.hasAttribute(ae.AUTOHIDE_OVER_CONTROLS);([this,this.media].includes(i.target)||e)&&$i(this,La,yl).call(this)};s0=new WeakSet;hA=function(i){if(i.pointerType==="touch"){let e=!this.hasAttribute(ae.USER_INACTIVE);[this,this.media].includes(i.target)&&e?$i(this,El,Mc).call(this):$i(this,La,yl).call(this)}else i.composedPath().some(e=>["media-play-button","media-fullscreen-button"].includes(e==null?void 0:e.localName))&&$i(this,La,yl).call(this)};El=new WeakSet;Mc=function(){if(ot(this,Sa)<0||this.hasAttribute(ae.USER_INACTIVE))return;this.setAttribute(ae.USER_INACTIVE,"");let i=new L.CustomEvent(di.USER_INACTIVE_CHANGE,{composed:!0,bubbles:!0,detail:!0});this.dispatchEvent(i)};Pc=new WeakSet;n0=function(){if(!this.hasAttribute(ae.USER_INACTIVE))return;this.removeAttribute(ae.USER_INACTIVE);let i=new L.CustomEvent(di.USER_INACTIVE_CHANGE,{composed:!0,bubbles:!0,detail:!1});this.dispatchEvent(i)};La=new WeakSet;yl=function(){$i(this,Pc,n0).call(this),clearTimeout(ot(this,Ia));let i=parseInt(this.autohide);i<0||Bi(this,Ia,setTimeout(()=>{$i(this,El,Mc).call(this)},i*1e3))};Sr=new WeakMap;Cc=new WeakMap;gn.shadowRootOptions={mode:"open"};gn.getTemplateHTML=gM;L.customElements.get("media-container")||L.customElements.define("media-container",gn);var mA=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},xt=(i,e,t)=>(mA(i,e,"read from private field"),t?t.call(i):e.get(i)),Tl=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},Oc=(i,e,t,s)=>(mA(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),Ra,xa,Nc,vn,Bs,Ir,Lr=class{constructor(e,t,{defaultValue:s}={defaultValue:void 0}){Tl(this,Bs),Tl(this,Ra,void 0),Tl(this,xa,void 0),Tl(this,Nc,void 0),Tl(this,vn,new Set),Oc(this,Ra,e),Oc(this,xa,t),Oc(this,Nc,new Set(s))}[Symbol.iterator](){return xt(this,Bs,Ir).values()}get length(){return xt(this,Bs,Ir).size}get value(){var e;return(e=[...xt(this,Bs,Ir)].join(" "))!=null?e:""}set value(e){var t;e!==this.value&&(Oc(this,vn,new Set),this.add(...(t=e==null?void 0:e.split(" "))!=null?t:[]))}toString(){return this.value}item(e){return[...xt(this,Bs,Ir)][e]}values(){return xt(this,Bs,Ir).values()}forEach(e,t){xt(this,Bs,Ir).forEach(e,t)}add(...e){var t,s;e.forEach(r=>xt(this,vn).add(r)),!(this.value===""&&!((t=xt(this,Ra))!=null&&t.hasAttribute(`${xt(this,xa)}`)))&&((s=xt(this,Ra))==null||s.setAttribute(`${xt(this,xa)}`,`${this.value}`))}remove(...e){var t;e.forEach(s=>xt(this,vn).delete(s)),(t=xt(this,Ra))==null||t.setAttribute(`${xt(this,xa)}`,`${this.value}`)}contains(e){return xt(this,Bs,Ir).has(e)}toggle(e,t){return typeof t!="undefined"?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}};Ra=new WeakMap;xa=new WeakMap;Nc=new WeakMap;vn=new WeakMap;Bs=new WeakSet;Ir=function(){return xt(this,vn).size?xt(this,vn):xt(this,Nc)};var _M=(i="")=>i.split(/\s+/),pA=(i="")=>{let[e,t,s]=i.split(":"),r=s?decodeURIComponent(s):void 0;return{kind:e==="cc"?Xt.CAPTIONS:Xt.SUBTITLES,language:t,label:r}},En=(i="",e={})=>_M(i).map(t=>{let s=pA(t);return{...e,...s}}),a0=i=>i?Array.isArray(i)?i.map(e=>typeof e=="string"?pA(e):e):typeof i=="string"?En(i):[i]:[],Uc=({kind:i,label:e,language:t}={kind:"subtitles"})=>e?`${i==="captions"?"cc":"sb"}:${t}:${encodeURIComponent(e)}`:t,$s=(i=[])=>Array.prototype.map.call(i,Uc).join(" "),AM=(i,e)=>t=>t[i]===e,gA=i=>{let e=Object.entries(i).map(([t,s])=>AM(t,s));return t=>e.every(s=>s(t))},yn=(i,e=[],t=[])=>{let s=a0(t).map(gA),r=n=>s.some(a=>a(n));Array.from(e).filter(r).forEach(n=>{n.mode=i})},Tn=(i,e=()=>!0)=>{if(!(i!=null&&i.textTracks))return[];let t=typeof e=="function"?e:gA(e);return Array.from(i.textTracks).filter(t)},Fc=i=>{var e;return!!((e=i.mediaSubtitlesShowing)!=null&&e.length)||i.hasAttribute(_.MEDIA_SUBTITLES_SHOWING)};var EA=i=>{var e;let{media:t,fullscreenElement:s}=i;try{let r=s&&"requestFullscreen"in s?"requestFullscreen":s&&"webkitRequestFullScreen"in s?"webkitRequestFullScreen":void 0;if(r){let n=(e=s[r])==null?void 0:e.call(s);if(n instanceof Promise)return n.catch(()=>{})}else t!=null&&t.webkitEnterFullscreen?t.webkitEnterFullscreen():t!=null&&t.requestFullscreen&&t.requestFullscreen()}catch(r){console.error(r)}},vA="exitFullscreen"in He?"exitFullscreen":"webkitExitFullscreen"in He?"webkitExitFullscreen":"webkitCancelFullScreen"in He?"webkitCancelFullScreen":void 0,yA=i=>{var e;let{documentElement:t}=i;if(vA){let s=(e=t==null?void 0:t[vA])==null?void 0:e.call(t);if(s instanceof Promise)return s.catch(()=>{})}},bl="fullscreenElement"in He?"fullscreenElement":"webkitFullscreenElement"in He?"webkitFullscreenElement":void 0,SM=i=>{let{documentElement:e,media:t}=i,s=e==null?void 0:e[bl];return!s&&"webkitDisplayingFullscreen"in t&&"webkitPresentationMode"in t&&t.webkitDisplayingFullscreen&&t.webkitPresentationMode===j_.FULLSCREEN?t:s},TA=i=>{var e;let{media:t,documentElement:s,fullscreenElement:r=t}=i;if(!t||!s)return!1;let n=SM(i);if(!n)return!1;if(n===r||n===t)return!0;if(n.localName.includes("-")){let a=n.shadowRoot;if(!(bl in a))return Kt(n,r);for(;a!=null&&a[bl];){if(a[bl]===r)return!0;a=(e=a[bl])==null?void 0:e.shadowRoot}}return!1},IM="fullscreenEnabled"in He?"fullscreenEnabled":"webkitFullscreenEnabled"in He?"webkitFullscreenEnabled":void 0,bA=i=>{let{documentElement:e,media:t}=i;return!!(e!=null&&e[IM])||t&&"webkitSupportsFullscreen"in t};var Bc,o0=()=>{var i,e;return Bc||(Bc=(e=(i=He)==null?void 0:i.createElement)==null?void 0:e.call(i,"video"),Bc)},_A=async(i=o0())=>{if(!i)return!1;let e=i.volume;i.volume=e/2+.1;let t=new AbortController,s=await Promise.race([LM(i,t.signal),RM(i,e)]);return t.abort(),s},LM=(i,e)=>new Promise(t=>{i.addEventListener("volumechange",()=>t(!0),{signal:e})}),RM=async(i,e)=>{for(let t=0;t<10;t++){if(i.volume===e)return!1;await Tc(10)}return i.volume!==e},xM=/.*Version\/.*Safari\/.*/.test(L.navigator.userAgent),l0=(i=o0())=>L.matchMedia("(display-mode: standalone)").matches&&xM?!1:typeof(i==null?void 0:i.requestPictureInPicture)=="function",d0=(i=o0())=>bA({documentElement:He,media:i}),AA=d0(),SA=l0(),IA=!!L.WebKitPlaybackTargetAvailabilityEvent,LA=!!L.chrome;var ka=i=>Tn(i.media,e=>[Xt.SUBTITLES,Xt.CAPTIONS].includes(e.kind)).sort((e,t)=>e.kind>=t.kind?1:-1),u0=i=>Tn(i.media,e=>e.mode===Ar.SHOWING&&[Xt.SUBTITLES,Xt.CAPTIONS].includes(e.kind)),$c=(i,e)=>{let t=ka(i),s=u0(i),r=!!s.length;if(t.length){if(e===!1||r&&e!==!0)yn(Ar.DISABLED,t,s);else if(e===!0||!r&&e!==!1){let n=t[0],{options:a}=i;if(!(a!=null&&a.noSubtitlesLangPref)){let u=L.localStorage.getItem("media-chrome-pref-subtitles-lang"),c=u?[u,...L.navigator.languages]:L.navigator.languages,h=t.filter(f=>c.some(m=>f.language.toLowerCase().startsWith(m.split("-")[0]))).sort((f,m)=>{let p=c.findIndex(v=>f.language.toLowerCase().startsWith(v.split("-")[0])),g=c.findIndex(v=>m.language.toLowerCase().startsWith(v.split("-")[0]));return p-g});h[0]&&(n=h[0])}let{language:o,label:l,kind:d}=n;yn(Ar.DISABLED,t,s),yn(Ar.SHOWING,t,[{language:o,label:l,kind:d}])}}},Hc=(i,e)=>i===e?!0:i==null||e==null||typeof i!=typeof e?!1:typeof i=="number"&&Number.isNaN(i)&&Number.isNaN(e)?!0:typeof i!="object"?!1:Array.isArray(i)?kM(i,e):Object.entries(i).every(([t,s])=>t in e&&Hc(s,e[t])),kM=(i,e)=>{let t=Array.isArray(i),s=Array.isArray(e);return t!==s?!1:t||s?i.length!==e.length?!1:i.every((r,n)=>Hc(r,e[n])):!0};var DM=Object.values(Ni),Gc,CM=_A().then(i=>(Gc=i,Gc)),RA=async(...i)=>{await Promise.all(i.filter(e=>e).map(async e=>{if(!("localName"in e&&e instanceof L.HTMLElement))return;let t=e.localName;if(!t.includes("-"))return;let s=L.customElements.get(t);s&&e instanceof s||(await L.customElements.whenDefined(t),L.customElements.upgrade(e))}))},wM=new L.DOMParser,MM=i=>i&&(wM.parseFromString(i,"text/html").body.textContent||i),Da={mediaError:{get(i,e){let{media:t}=i;if((e==null?void 0:e.type)!=="playing")return t==null?void 0:t.error},mediaEvents:["emptied","error","playing"]},mediaErrorCode:{get(i,e){var t;let{media:s}=i;if((e==null?void 0:e.type)!=="playing")return(t=s==null?void 0:s.error)==null?void 0:t.code},mediaEvents:["emptied","error","playing"]},mediaErrorMessage:{get(i,e){var t,s;let{media:r}=i;if((e==null?void 0:e.type)!=="playing")return(s=(t=r==null?void 0:r.error)==null?void 0:t.message)!=null?s:""},mediaEvents:["emptied","error","playing"]},mediaWidth:{get(i){var e;let{media:t}=i;return(e=t==null?void 0:t.videoWidth)!=null?e:0},mediaEvents:["resize"]},mediaHeight:{get(i){var e;let{media:t}=i;return(e=t==null?void 0:t.videoHeight)!=null?e:0},mediaEvents:["resize"]},mediaPaused:{get(i){var e;let{media:t}=i;return(e=t==null?void 0:t.paused)!=null?e:!0},set(i,e){var t;let{media:s}=e;s&&(i?s.pause():(t=s.play())==null||t.catch(()=>{}))},mediaEvents:["play","playing","pause","emptied"]},mediaHasPlayed:{get(i,e){let{media:t}=i;return t?e?e.type==="playing":!t.paused:!1},mediaEvents:["playing","emptied"]},mediaEnded:{get(i){var e;let{media:t}=i;return(e=t==null?void 0:t.ended)!=null?e:!1},mediaEvents:["seeked","ended","emptied"]},mediaPlaybackRate:{get(i){var e;let{media:t}=i;return(e=t==null?void 0:t.playbackRate)!=null?e:1},set(i,e){let{media:t}=e;t&&Number.isFinite(+i)&&(t.playbackRate=+i)},mediaEvents:["ratechange","loadstart"]},mediaMuted:{get(i){var e;let{media:t}=i;return(e=t==null?void 0:t.muted)!=null?e:!1},set(i,e){let{media:t,options:{noMutedPref:s}={}}=e;if(t){t.muted=i;try{let r=L.localStorage.getItem("media-chrome-pref-muted")!==null,n=t.hasAttribute("muted");if(s){r&&L.localStorage.removeItem("media-chrome-pref-muted");return}if(n&&!r)return;L.localStorage.setItem("media-chrome-pref-muted",i?"true":"false")}catch(r){console.debug("Error setting muted pref",r)}}},mediaEvents:["volumechange"],stateOwnersUpdateHandlers:[(i,e)=>{let{options:{noMutedPref:t}}=e,{media:s}=e;if(!(!s||s.muted||t))try{let r=L.localStorage.getItem("media-chrome-pref-muted")==="true";Da.mediaMuted.set(r,e),i(r)}catch(r){console.debug("Error getting muted pref",r)}}]},mediaLoop:{get(i){let{media:e}=i;return e==null?void 0:e.loop},set(i,e){let{media:t}=e;t&&(t.loop=i)},mediaEvents:["medialooprequest"]},mediaVolume:{get(i){var e;let{media:t}=i;return(e=t==null?void 0:t.volume)!=null?e:1},set(i,e){let{media:t,options:{noVolumePref:s}={}}=e;if(t){try{i==null?L.localStorage.removeItem("media-chrome-pref-volume"):!t.hasAttribute("muted")&&!s&&L.localStorage.setItem("media-chrome-pref-volume",i.toString())}catch(r){console.debug("Error setting volume pref",r)}Number.isFinite(+i)&&(t.volume=+i)}},mediaEvents:["volumechange"],stateOwnersUpdateHandlers:[(i,e)=>{let{options:{noVolumePref:t}}=e;if(!t)try{let{media:s}=e;if(!s)return;let r=L.localStorage.getItem("media-chrome-pref-volume");if(r==null)return;Da.mediaVolume.set(+r,e),i(+r)}catch(s){console.debug("Error getting volume pref",s)}}]},mediaVolumeLevel:{get(i){let{media:e}=i;return typeof(e==null?void 0:e.volume)=="undefined"?"high":e.muted||e.volume===0?"off":e.volume<.5?"low":e.volume<.75?"medium":"high"},mediaEvents:["volumechange"]},mediaCurrentTime:{get(i){var e;let{media:t}=i;return(e=t==null?void 0:t.currentTime)!=null?e:0},set(i,e){let{media:t}=e;!t||!Ta(i)||(t.currentTime=i)},mediaEvents:["timeupdate","loadedmetadata"]},mediaDuration:{get(i){let{media:e,options:{defaultDuration:t}={}}=i;return t&&(!e||!e.duration||Number.isNaN(e.duration)||!Number.isFinite(e.duration))?t:Number.isFinite(e==null?void 0:e.duration)?e.duration:Number.NaN},mediaEvents:["durationchange","loadedmetadata","emptied"]},mediaLoading:{get(i){let{media:e}=i;return(e==null?void 0:e.readyState)<3},mediaEvents:["waiting","playing","emptied"]},mediaSeekable:{get(i){var e;let{media:t}=i;if(!((e=t==null?void 0:t.seekable)!=null&&e.length))return;let s=t.seekable.start(0),r=t.seekable.end(t.seekable.length-1);if(!(!s&&!r))return[Number(s.toFixed(3)),Number(r.toFixed(3))]},mediaEvents:["loadedmetadata","emptied","progress","seekablechange"]},mediaBuffered:{get(i){var e;let{media:t}=i,s=(e=t==null?void 0:t.buffered)!=null?e:[];return Array.from(s).map((r,n)=>[Number(s.start(n).toFixed(3)),Number(s.end(n).toFixed(3))])},mediaEvents:["progress","emptied"]},mediaStreamType:{get(i){let{media:e,options:{defaultStreamType:t}={}}=i,s=[Ni.LIVE,Ni.ON_DEMAND].includes(t)?t:void 0;if(!e)return s;let{streamType:r}=e;if(DM.includes(r))return r===Ni.UNKNOWN?s:r;let n=e.duration;return n===1/0?Ni.LIVE:Number.isFinite(n)?Ni.ON_DEMAND:s},mediaEvents:["emptied","durationchange","loadedmetadata","streamtypechange"]},mediaTargetLiveWindow:{get(i){let{media:e}=i;if(!e)return Number.NaN;let{targetLiveWindow:t}=e,s=Da.mediaStreamType.get(i);return(t==null||Number.isNaN(t))&&s===Ni.LIVE?0:t},mediaEvents:["emptied","durationchange","loadedmetadata","streamtypechange","targetlivewindowchange"]},mediaTimeIsLive:{get(i){let{media:e,options:{liveEdgeOffset:t=10}={}}=i;if(!e)return!1;if(typeof e.liveEdgeStart=="number")return Number.isNaN(e.liveEdgeStart)?!1:e.currentTime>=e.liveEdgeStart;if(!(Da.mediaStreamType.get(i)===Ni.LIVE))return!1;let r=e.seekable;if(!r)return!0;if(!r.length)return!1;let n=r.end(r.length-1)-t;return e.currentTime>=n},mediaEvents:["playing","timeupdate","progress","waiting","emptied"]},mediaSubtitlesList:{get(i){return ka(i).map(({kind:e,label:t,language:s})=>({kind:e,label:t,language:s}))},mediaEvents:["loadstart"],textTracksEvents:["addtrack","removetrack"]},mediaSubtitlesShowing:{get(i){return u0(i).map(({kind:e,label:t,language:s})=>({kind:e,label:t,language:s}))},mediaEvents:["loadstart"],textTracksEvents:["addtrack","removetrack","change"],stateOwnersUpdateHandlers:[(i,e)=>{var t,s;let{media:r,options:n}=e;if(!r)return;let a=o=>{var l;!n.defaultSubtitles||o&&![Xt.CAPTIONS,Xt.SUBTITLES].includes((l=o==null?void 0:o.track)==null?void 0:l.kind)||$c(e,!0)};return r.addEventListener("loadstart",a),(t=r.textTracks)==null||t.addEventListener("addtrack",a),(s=r.textTracks)==null||s.addEventListener("removetrack",a),()=>{var o,l;r.removeEventListener("loadstart",a),(o=r.textTracks)==null||o.removeEventListener("addtrack",a),(l=r.textTracks)==null||l.removeEventListener("removetrack",a)}}]},mediaChaptersCues:{get(i){var e;let{media:t}=i;if(!t)return[];let[s]=Tn(t,{kind:Xt.CHAPTERS});return Array.from((e=s==null?void 0:s.cues)!=null?e:[]).map(({text:r,startTime:n,endTime:a})=>({text:MM(r),startTime:n,endTime:a}))},mediaEvents:["loadstart","loadedmetadata"],textTracksEvents:["addtrack","removetrack","change"],stateOwnersUpdateHandlers:[(i,e)=>{var t;let{media:s}=e;if(!s)return;let r=s.querySelector('track[kind="chapters"][default][src]'),n=(t=s.shadowRoot)==null?void 0:t.querySelector(':is(video,audio) > track[kind="chapters"][default][src]');return r==null||r.addEventListener("load",i),n==null||n.addEventListener("load",i),()=>{r==null||r.removeEventListener("load",i),n==null||n.removeEventListener("load",i)}}]},mediaIsPip:{get(i){var e,t;let{media:s,documentElement:r}=i;if(!s||!r||!r.pictureInPictureElement)return!1;if(r.pictureInPictureElement===s)return!0;if(r.pictureInPictureElement instanceof HTMLMediaElement)return(e=s.localName)!=null&&e.includes("-")?Kt(s,r.pictureInPictureElement):!1;if(r.pictureInPictureElement.localName.includes("-")){let n=r.pictureInPictureElement.shadowRoot;for(;n!=null&&n.pictureInPictureElement;){if(n.pictureInPictureElement===s)return!0;n=(t=n.pictureInPictureElement)==null?void 0:t.shadowRoot}}return!1},set(i,e){let{media:t}=e;if(t)if(i){if(!He.pictureInPictureEnabled){console.warn("MediaChrome: Picture-in-picture is not enabled");return}if(!t.requestPictureInPicture){console.warn("MediaChrome: The current media does not support picture-in-picture");return}let s=()=>{console.warn("MediaChrome: The media is not ready for picture-in-picture. It must have a readyState > 0.")};t.requestPictureInPicture().catch(r=>{if(r.code===11){if(!t.src){console.warn("MediaChrome: The media is not ready for picture-in-picture. It must have a src set.");return}if(t.readyState===0&&t.preload==="none"){let n=()=>{t.removeEventListener("loadedmetadata",a),t.preload="none"},a=()=>{t.requestPictureInPicture().catch(s),n()};t.addEventListener("loadedmetadata",a),t.preload="metadata",setTimeout(()=>{t.readyState===0&&s(),n()},1e3)}else throw r}else throw r})}else He.pictureInPictureElement&&He.exitPictureInPicture()},mediaEvents:["enterpictureinpicture","leavepictureinpicture"]},mediaRenditionList:{get(i){var e;let{media:t}=i;return[...(e=t==null?void 0:t.videoRenditions)!=null?e:[]].map(s=>({...s}))},mediaEvents:["emptied","loadstart"],videoRenditionsEvents:["addrendition","removerendition"]},mediaRenditionSelected:{get(i){var e,t,s;let{media:r}=i;return(s=(t=r==null?void 0:r.videoRenditions)==null?void 0:t[(e=r.videoRenditions)==null?void 0:e.selectedIndex])==null?void 0:s.id},set(i,e){let{media:t}=e;if(!(t!=null&&t.videoRenditions)){console.warn("MediaController: Rendition selection not supported by this media.");return}let s=i,r=Array.prototype.findIndex.call(t.videoRenditions,n=>n.id==s);t.videoRenditions.selectedIndex!=r&&(t.videoRenditions.selectedIndex=r)},mediaEvents:["emptied"],videoRenditionsEvents:["addrendition","removerendition","change"]},mediaAudioTrackList:{get(i){var e;let{media:t}=i;return[...(e=t==null?void 0:t.audioTracks)!=null?e:[]]},mediaEvents:["emptied","loadstart"],audioTracksEvents:["addtrack","removetrack"]},mediaAudioTrackEnabled:{get(i){var e,t;let{media:s}=i;return(t=[...(e=s==null?void 0:s.audioTracks)!=null?e:[]].find(r=>r.enabled))==null?void 0:t.id},set(i,e){let{media:t}=e;if(!(t!=null&&t.audioTracks)){console.warn("MediaChrome: Audio track selection not supported by this media.");return}let s=i;for(let r of t.audioTracks)r.enabled=s==r.id},mediaEvents:["emptied"],audioTracksEvents:["addtrack","removetrack","change"]},mediaIsFullscreen:{get(i){return TA(i)},set(i,e,t){var s,r;i?(EA(e),t.detail&&!((s=e.media)!=null&&s.inert)&&((r=e.media)==null||r.focus())):yA(e)},rootEvents:["fullscreenchange","webkitfullscreenchange"],mediaEvents:["webkitbeginfullscreen","webkitendfullscreen","webkitpresentationmodechanged"]},mediaIsCasting:{get(i){var e;let{media:t}=i;return!(t!=null&&t.remote)||((e=t.remote)==null?void 0:e.state)==="disconnected"?!1:!!t.remote.state},set(i,e){var t,s;let{media:r}=e;if(r&&!(i&&((t=r.remote)==null?void 0:t.state)!=="disconnected")&&!(!i&&((s=r.remote)==null?void 0:s.state)!=="connected")){if(typeof r.remote.prompt!="function"){console.warn("MediaChrome: Casting is not supported in this environment");return}r.remote.prompt().catch(()=>{})}},remoteEvents:["connect","connecting","disconnect"]},mediaIsAirplaying:{get(){return!1},set(i,e){let{media:t}=e;if(t){if(!(t.webkitShowPlaybackTargetPicker&&L.WebKitPlaybackTargetAvailabilityEvent)){console.error("MediaChrome: received a request to select AirPlay but AirPlay is not supported in this environment");return}t.webkitShowPlaybackTargetPicker()}},mediaEvents:["webkitcurrentplaybacktargetiswirelesschanged"]},mediaFullscreenUnavailable:{get(i){let{media:e}=i;if(!AA||!d0(e))return Zt.UNSUPPORTED}},mediaPipUnavailable:{get(i){let{media:e}=i;if(!SA||!l0(e))return Zt.UNSUPPORTED;if(e!=null&&e.disablePictureInPicture)return Zt.UNAVAILABLE}},mediaVolumeUnavailable:{get(i){let{media:e}=i;if(Gc===!1||(e==null?void 0:e.volume)==null)return Zt.UNSUPPORTED},stateOwnersUpdateHandlers:[i=>{Gc==null&&CM.then(e=>i(e?void 0:Zt.UNSUPPORTED))}]},mediaCastUnavailable:{get(i,{availability:e="not-available"}={}){var t;let{media:s}=i;if(!LA||!((t=s==null?void 0:s.remote)!=null&&t.state))return Zt.UNSUPPORTED;if(!(e==null||e==="available"))return Zt.UNAVAILABLE},stateOwnersUpdateHandlers:[(i,e)=>{var t;let{media:s}=e;return s?(s.disableRemotePlayback||s.hasAttribute("disableremoteplayback")||(t=s==null?void 0:s.remote)==null||t.watchAvailability(n=>{i({availability:n?"available":"not-available"})}).catch(n=>{n.name==="NotSupportedError"?i({availability:null}):i({availability:"not-available"})}),()=>{var n;(n=s==null?void 0:s.remote)==null||n.cancelWatchAvailability().catch(()=>{})}):void 0}]},mediaAirplayUnavailable:{get(i,e){if(!IA)return Zt.UNSUPPORTED;if((e==null?void 0:e.availability)==="not-available")return Zt.UNAVAILABLE},mediaEvents:["webkitplaybacktargetavailabilitychanged"],stateOwnersUpdateHandlers:[(i,e)=>{var t;let{media:s}=e;return s?(s.disableRemotePlayback||s.hasAttribute("disableremoteplayback")||(t=s==null?void 0:s.remote)==null||t.watchAvailability(n=>{i({availability:n?"available":"not-available"})}).catch(n=>{n.name==="NotSupportedError"?i({availability:null}):i({availability:"not-available"})}),()=>{var n;(n=s==null?void 0:s.remote)==null||n.cancelWatchAvailability().catch(()=>{})}):void 0}]},mediaRenditionUnavailable:{get(i){var e;let{media:t}=i;if(!(t!=null&&t.videoRenditions))return Zt.UNSUPPORTED;if(!((e=t.videoRenditions)!=null&&e.length))return Zt.UNAVAILABLE},mediaEvents:["emptied","loadstart"],videoRenditionsEvents:["addrendition","removerendition"]},mediaAudioTrackUnavailable:{get(i){var e,t;let{media:s}=i;if(!(s!=null&&s.audioTracks))return Zt.UNSUPPORTED;if(((t=(e=s.audioTracks)==null?void 0:e.length)!=null?t:0)<=1)return Zt.UNAVAILABLE},mediaEvents:["emptied","loadstart"],audioTracksEvents:["addtrack","removetrack"]},mediaLang:{get(i){let{options:{mediaLang:e}={}}=i;return e!=null?e:"en"}}};var xA={[K.MEDIA_PREVIEW_REQUEST](i,e,{detail:t}){var s,r,n;let{media:a}=e,o=t!=null?t:void 0,l,d;if(a&&o!=null){let[f]=Tn(a,{kind:Xt.METADATA,label:"thumbnails"}),m=Array.prototype.find.call((s=f==null?void 0:f.cues)!=null?s:[],(p,g,v)=>g===0?p.endTime>o:g===v.length-1?p.startTime<=o:p.startTime<=o&&p.endTime>o);if(m){let p=/'^(?:[a-z]+:)?\/\//i.test(m.text)||(r=a==null?void 0:a.querySelector('track[label="thumbnails"]'))==null?void 0:r.src,g=new URL(m.text,p);d=new URLSearchParams(g.hash).get("#xywh").split(",").map(T=>+T),l=g.href}}let u=i.mediaDuration.get(e),h=(n=i.mediaChaptersCues.get(e).find((f,m,p)=>m===p.length-1&&u===f.endTime?f.startTime<=o&&f.endTime>=o:f.startTime<=o&&f.endTime>o))==null?void 0:n.text;return t!=null&&h==null&&(h=""),{mediaPreviewTime:o,mediaPreviewImage:l,mediaPreviewCoords:d,mediaPreviewChapter:h}},[K.MEDIA_PAUSE_REQUEST](i,e){i["mediaPaused"].set(!0,e)},[K.MEDIA_PLAY_REQUEST](i,e){var t,s,r,n;let a="mediaPaused",l=i.mediaStreamType.get(e)===Ni.LIVE,d=!((t=e.options)!=null&&t.noAutoSeekToLive),u=i.mediaTargetLiveWindow.get(e)>0;if(l&&d&&!u){let c=(s=i.mediaSeekable.get(e))==null?void 0:s[1];if(c){let h=(n=(r=e.options)==null?void 0:r.seekToLiveOffset)!=null?n:0,f=c-h;i.mediaCurrentTime.set(f,e)}}i[a].set(!1,e)},[K.MEDIA_PLAYBACK_RATE_REQUEST](i,e,{detail:t}){let s="mediaPlaybackRate",r=t;i[s].set(r,e)},[K.MEDIA_MUTE_REQUEST](i,e){i["mediaMuted"].set(!0,e)},[K.MEDIA_UNMUTE_REQUEST](i,e){let t="mediaMuted";i.mediaVolume.get(e)||i.mediaVolume.set(.25,e),i[t].set(!1,e)},[K.MEDIA_LOOP_REQUEST](i,e,{detail:t}){let s="mediaLoop",r=!!t;return i[s].set(r,e),{mediaLoop:r}},[K.MEDIA_VOLUME_REQUEST](i,e,{detail:t}){let s="mediaVolume",r=t;r&&i.mediaMuted.get(e)&&i.mediaMuted.set(!1,e),i[s].set(r,e)},[K.MEDIA_SEEK_REQUEST](i,e,{detail:t}){let s="mediaCurrentTime",r=t;i[s].set(r,e)},[K.MEDIA_SEEK_TO_LIVE_REQUEST](i,e){var t,s,r;let n="mediaCurrentTime",a=(t=i.mediaSeekable.get(e))==null?void 0:t[1];if(Number.isNaN(Number(a)))return;let o=(r=(s=e.options)==null?void 0:s.seekToLiveOffset)!=null?r:0,l=a-o;i[n].set(l,e)},[K.MEDIA_SHOW_SUBTITLES_REQUEST](i,e,{detail:t}){var s;let{options:r}=e,n=ka(e),a=a0(t),o=(s=a[0])==null?void 0:s.language;o&&!r.noSubtitlesLangPref&&L.localStorage.setItem("media-chrome-pref-subtitles-lang",o),yn(Ar.SHOWING,n,a)},[K.MEDIA_DISABLE_SUBTITLES_REQUEST](i,e,{detail:t}){let s=ka(e),r=t!=null?t:[];yn(Ar.DISABLED,s,r)},[K.MEDIA_TOGGLE_SUBTITLES_REQUEST](i,e,{detail:t}){$c(e,t)},[K.MEDIA_RENDITION_REQUEST](i,e,{detail:t}){let s="mediaRenditionSelected",r=t;i[s].set(r,e)},[K.MEDIA_AUDIO_TRACK_REQUEST](i,e,{detail:t}){let s="mediaAudioTrackEnabled",r=t;i[s].set(r,e)},[K.MEDIA_ENTER_PIP_REQUEST](i,e){let t="mediaIsPip";i.mediaIsFullscreen.get(e)&&i.mediaIsFullscreen.set(!1,e),i[t].set(!0,e)},[K.MEDIA_EXIT_PIP_REQUEST](i,e){i["mediaIsPip"].set(!1,e)},[K.MEDIA_ENTER_FULLSCREEN_REQUEST](i,e,t){let s="mediaIsFullscreen";i.mediaIsPip.get(e)&&i.mediaIsPip.set(!1,e),i[s].set(!0,e,t)},[K.MEDIA_EXIT_FULLSCREEN_REQUEST](i,e){i["mediaIsFullscreen"].set(!1,e)},[K.MEDIA_ENTER_CAST_REQUEST](i,e){let t="mediaIsCasting";i.mediaIsFullscreen.get(e)&&i.mediaIsFullscreen.set(!1,e),i[t].set(!0,e)},[K.MEDIA_EXIT_CAST_REQUEST](i,e){i["mediaIsCasting"].set(!1,e)},[K.MEDIA_AIRPLAY_REQUEST](i,e){i["mediaIsAirplaying"].set(!0,e)}};var kA=({media:i,fullscreenElement:e,documentElement:t,stateMediator:s=Da,requestMap:r=xA,options:n={},monitorStateOwnersOnlyWithSubscriptions:a=!0})=>{let o=[],l={options:{...n}},d=Object.freeze({mediaPreviewTime:void 0,mediaPreviewImage:void 0,mediaPreviewCoords:void 0,mediaPreviewChapter:void 0}),u=p=>{p!=null&&(Hc(p,d)||(d=Object.freeze({...d,...p}),o.forEach(g=>g(d))))},c=()=>{let p=Object.entries(s).reduce((g,[v,{get:T}])=>(g[v]=T(l),g),{});u(p)},h={},f,m=async(p,g)=>{var v,T,y,b,A,R,I,x,D,S,C,P,N,$,H,U;let j=!!f;if(f={...l,...f!=null?f:{},...p},j)return;await RA(...Object.values(p));let q=o.length>0&&g===0&&a,Z=l.media!==f.media,re=((v=l.media)==null?void 0:v.textTracks)!==((T=f.media)==null?void 0:T.textTracks),V=((y=l.media)==null?void 0:y.videoRenditions)!==((b=f.media)==null?void 0:b.videoRenditions),G=((A=l.media)==null?void 0:A.audioTracks)!==((R=f.media)==null?void 0:R.audioTracks),ce=((I=l.media)==null?void 0:I.remote)!==((x=f.media)==null?void 0:x.remote),Se=l.documentElement!==f.documentElement,he=!!l.media&&(Z||q),Te=!!((D=l.media)!=null&&D.textTracks)&&(re||q),vt=!!((S=l.media)!=null&&S.videoRenditions)&&(V||q),ut=!!((C=l.media)!=null&&C.audioTracks)&&(G||q),Ft=!!((P=l.media)!=null&&P.remote)&&(ce||q),si=!!l.documentElement&&(Se||q),Ii=he||Te||vt||ut||Ft||si,Js=o.length===0&&g===1&&a,Hn=!!f.media&&(Z||Js),Gn=!!((N=f.media)!=null&&N.textTracks)&&(re||Js),qf=!!(($=f.media)!=null&&$.videoRenditions)&&(V||Js),ke=!!((H=f.media)!=null&&H.audioTracks)&&(G||Js),Et=!!((U=f.media)!=null&&U.remote)&&(ce||Js),Bt=!!f.documentElement&&(Se||Js),Yi=Hn||Gn||qf||ke||Et||Bt;if(!(Ii||Yi)){Object.entries(f).forEach(([De,ri])=>{l[De]=ri}),c(),f=void 0;return}Object.entries(s).forEach(([De,{get:ri,mediaEvents:Rd=[],textTracksEvents:Kn=[],videoRenditionsEvents:xd=[],audioTracksEvents:Kr=[],remoteEvents:kd=[],rootEvents:Yf=[],stateOwnersUpdateHandlers:Dd=[]}])=>{h[De]||(h[De]={});let Nt=et=>{let ct=ri(l,et);u({[De]:ct})},Je;Je=h[De].mediaEvents,Rd.forEach(et=>{Je&&he&&(l.media.removeEventListener(et,Je),h[De].mediaEvents=void 0),Hn&&(f.media.addEventListener(et,Nt),h[De].mediaEvents=Nt)}),Je=h[De].textTracksEvents,Kn.forEach(et=>{var ct,Li;Je&&Te&&((ct=l.media.textTracks)==null||ct.removeEventListener(et,Je),h[De].textTracksEvents=void 0),Gn&&((Li=f.media.textTracks)==null||Li.addEventListener(et,Nt),h[De].textTracksEvents=Nt)}),Je=h[De].videoRenditionsEvents,xd.forEach(et=>{var ct,Li;Je&&vt&&((ct=l.media.videoRenditions)==null||ct.removeEventListener(et,Je),h[De].videoRenditionsEvents=void 0),qf&&((Li=f.media.videoRenditions)==null||Li.addEventListener(et,Nt),h[De].videoRenditionsEvents=Nt)}),Je=h[De].audioTracksEvents,Kr.forEach(et=>{var ct,Li;Je&&ut&&((ct=l.media.audioTracks)==null||ct.removeEventListener(et,Je),h[De].audioTracksEvents=void 0),ke&&((Li=f.media.audioTracks)==null||Li.addEventListener(et,Nt),h[De].audioTracksEvents=Nt)}),Je=h[De].remoteEvents,kd.forEach(et=>{var ct,Li;Je&&Ft&&((ct=l.media.remote)==null||ct.removeEventListener(et,Je),h[De].remoteEvents=void 0),Et&&((Li=f.media.remote)==null||Li.addEventListener(et,Nt),h[De].remoteEvents=Nt)}),Je=h[De].rootEvents,Yf.forEach(et=>{Je&&si&&(l.documentElement.removeEventListener(et,Je),h[De].rootEvents=void 0),Bt&&(f.documentElement.addEventListener(et,Nt),h[De].rootEvents=Nt)});let Cd=h[De].stateOwnersUpdateHandlers;if(Cd&&Ii&&(Array.isArray(Cd)?Cd:[Cd]).forEach(ct=>{typeof ct=="function"&&ct()}),Yi){let et=Dd.map(ct=>ct(Nt,f)).filter(ct=>typeof ct=="function");h[De].stateOwnersUpdateHandlers=et.length===1?et[0]:et}else Ii&&(h[De].stateOwnersUpdateHandlers=void 0)}),Object.entries(f).forEach(([De,ri])=>{l[De]=ri}),c(),f=void 0};return m({media:i,fullscreenElement:e,documentElement:t,options:n}),{dispatch(p){let{type:g,detail:v}=p;if(r[g]&&d.mediaErrorCode==null){u(r[g](s,l,p));return}g==="mediaelementchangerequest"?m({media:v}):g==="fullscreenelementchangerequest"?m({fullscreenElement:v}):g==="documentelementchangerequest"?m({documentElement:v}):g==="optionschangerequest"&&(Object.entries(v!=null?v:{}).forEach(([T,y])=>{l.options[T]=y}),c())},getState(){return d},subscribe(p){return m({},o.length+1),o.push(p),p(d),()=>{let g=o.indexOf(p);g>=0&&(m({},o.length-1),o.splice(g,1))}}}};var p0=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},ie=(i,e,t)=>(p0(i,e,"read from private field"),t?t.call(i):e.get(i)),yi=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},Hi=(i,e,t,s)=>(p0(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),_l=(i,e,t)=>(p0(i,e,"access private method"),t),Hs,Al,xe,rs,Sl,ss,Kc,Il,Vc,c0,_n,Wc,h0,f0,NA,UA=["ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Enter"," ","f","m","k","c","l","j",">","<","p"],DA=10,CA=.025,wA=.25,PM=.25,OM=2,W={DEFAULT_SUBTITLES:"defaultsubtitles",DEFAULT_STREAM_TYPE:"defaultstreamtype",DEFAULT_DURATION:"defaultduration",FULLSCREEN_ELEMENT:"fullscreenelement",HOTKEYS:"hotkeys",KEYBOARD_BACKWARD_SEEK_OFFSET:"keyboardbackwardseekoffset",KEYBOARD_FORWARD_SEEK_OFFSET:"keyboardforwardseekoffset",KEYBOARD_DOWN_VOLUME_STEP:"keyboarddownvolumestep",KEYBOARD_UP_VOLUME_STEP:"keyboardupvolumestep",KEYS_USED:"keysused",LANG:"lang",LOOP:"loop",LIVE_EDGE_OFFSET:"liveedgeoffset",NO_AUTO_SEEK_TO_LIVE:"noautoseektolive",NO_DEFAULT_STORE:"nodefaultstore",NO_HOTKEYS:"nohotkeys",NO_MUTED_PREF:"nomutedpref",NO_SUBTITLES_LANG_PREF:"nosubtitleslangpref",NO_VOLUME_PREF:"novolumepref",SEEK_TO_LIVE_OFFSET:"seektoliveoffset"},qc=class extends gn{constructor(){super(),yi(this,Vc),yi(this,Wc),yi(this,f0),this.mediaStateReceivers=[],this.associatedElementSubscriptions=new Map,yi(this,Hs,new Lr(this,W.HOTKEYS)),yi(this,Al,void 0),yi(this,xe,void 0),yi(this,rs,null),yi(this,Sl,void 0),yi(this,ss,void 0),yi(this,Kc,t=>{var s;(s=ie(this,xe))==null||s.dispatch(t)}),yi(this,Il,void 0),yi(this,_n,t=>{let{key:s,shiftKey:r}=t;if(!(r&&(s==="/"||s==="?")||UA.includes(s))){this.removeEventListener("keyup",ie(this,_n));return}this.keyboardShortcutHandler(t)}),this.associateElement(this);let e={};Hi(this,Sl,t=>{Object.entries(t).forEach(([s,r])=>{if(s in e&&e[s]===r)return;this.propagateMediaState(s,r);let n=s.toLowerCase(),a=new L.CustomEvent(Y_[n],{composed:!0,detail:r});this.dispatchEvent(a)}),e=t})}static get observedAttributes(){return super.observedAttributes.concat(W.NO_HOTKEYS,W.HOTKEYS,W.DEFAULT_STREAM_TYPE,W.DEFAULT_SUBTITLES,W.DEFAULT_DURATION,W.NO_MUTED_PREF,W.NO_VOLUME_PREF,W.LANG,W.LOOP,W.LIVE_EDGE_OFFSET,W.SEEK_TO_LIVE_OFFSET,W.NO_AUTO_SEEK_TO_LIVE)}get mediaStore(){return ie(this,xe)}set mediaStore(e){var t,s;if(ie(this,xe)&&((t=ie(this,ss))==null||t.call(this),Hi(this,ss,void 0)),Hi(this,xe,e),!ie(this,xe)&&!this.hasAttribute(W.NO_DEFAULT_STORE)){_l(this,Vc,c0).call(this);return}Hi(this,ss,(s=ie(this,xe))==null?void 0:s.subscribe(ie(this,Sl)))}get fullscreenElement(){var e;return(e=ie(this,Al))!=null?e:this}set fullscreenElement(e){var t;this.hasAttribute(W.FULLSCREEN_ELEMENT)&&this.removeAttribute(W.FULLSCREEN_ELEMENT),Hi(this,Al,e),(t=ie(this,xe))==null||t.dispatch({type:"fullscreenelementchangerequest",detail:this.fullscreenElement})}get defaultSubtitles(){return le(this,W.DEFAULT_SUBTITLES)}set defaultSubtitles(e){de(this,W.DEFAULT_SUBTITLES,e)}get defaultStreamType(){return pe(this,W.DEFAULT_STREAM_TYPE)}set defaultStreamType(e){me(this,W.DEFAULT_STREAM_TYPE,e)}get defaultDuration(){return ye(this,W.DEFAULT_DURATION)}set defaultDuration(e){Re(this,W.DEFAULT_DURATION,e)}get noHotkeys(){return le(this,W.NO_HOTKEYS)}set noHotkeys(e){de(this,W.NO_HOTKEYS,e)}get keysUsed(){return pe(this,W.KEYS_USED)}set keysUsed(e){me(this,W.KEYS_USED,e)}get liveEdgeOffset(){return ye(this,W.LIVE_EDGE_OFFSET)}set liveEdgeOffset(e){Re(this,W.LIVE_EDGE_OFFSET,e)}get noAutoSeekToLive(){return le(this,W.NO_AUTO_SEEK_TO_LIVE)}set noAutoSeekToLive(e){de(this,W.NO_AUTO_SEEK_TO_LIVE,e)}get noVolumePref(){return le(this,W.NO_VOLUME_PREF)}set noVolumePref(e){de(this,W.NO_VOLUME_PREF,e)}get noMutedPref(){return le(this,W.NO_MUTED_PREF)}set noMutedPref(e){de(this,W.NO_MUTED_PREF,e)}get noSubtitlesLangPref(){return le(this,W.NO_SUBTITLES_LANG_PREF)}set noSubtitlesLangPref(e){de(this,W.NO_SUBTITLES_LANG_PREF,e)}get noDefaultStore(){return le(this,W.NO_DEFAULT_STORE)}set noDefaultStore(e){de(this,W.NO_DEFAULT_STORE,e)}attributeChangedCallback(e,t,s){var r,n,a,o,l,d,u,c,h,f,m,p;if(super.attributeChangedCallback(e,t,s),e===W.NO_HOTKEYS)s!==t&&s===""?(this.hasAttribute(W.HOTKEYS)&&console.warn("Media Chrome: Both `hotkeys` and `nohotkeys` have been set. All hotkeys will be disabled."),this.disableHotkeys()):s!==t&&s===null&&this.enableHotkeys();else if(e===W.HOTKEYS)ie(this,Hs).value=s;else if(e===W.DEFAULT_SUBTITLES&&s!==t)(r=ie(this,xe))==null||r.dispatch({type:"optionschangerequest",detail:{defaultSubtitles:this.hasAttribute(W.DEFAULT_SUBTITLES)}});else if(e===W.DEFAULT_STREAM_TYPE)(a=ie(this,xe))==null||a.dispatch({type:"optionschangerequest",detail:{defaultStreamType:(n=this.getAttribute(W.DEFAULT_STREAM_TYPE))!=null?n:void 0}});else if(e===W.LIVE_EDGE_OFFSET&&s!==t)(o=ie(this,xe))==null||o.dispatch({type:"optionschangerequest",detail:{liveEdgeOffset:this.hasAttribute(W.LIVE_EDGE_OFFSET)?+this.getAttribute(W.LIVE_EDGE_OFFSET):void 0,seekToLiveOffset:this.hasAttribute(W.SEEK_TO_LIVE_OFFSET)?+this.getAttribute(W.SEEK_TO_LIVE_OFFSET):this.hasAttribute(W.LIVE_EDGE_OFFSET)?+this.getAttribute(W.LIVE_EDGE_OFFSET):void 0}});else if(e===W.SEEK_TO_LIVE_OFFSET&&s!==t)(l=ie(this,xe))==null||l.dispatch({type:"optionschangerequest",detail:{seekToLiveOffset:this.hasAttribute(W.SEEK_TO_LIVE_OFFSET)?+this.getAttribute(W.SEEK_TO_LIVE_OFFSET):this.hasAttribute(W.LIVE_EDGE_OFFSET)?+this.getAttribute(W.LIVE_EDGE_OFFSET):void 0}});else if(e===W.NO_AUTO_SEEK_TO_LIVE)(d=ie(this,xe))==null||d.dispatch({type:"optionschangerequest",detail:{noAutoSeekToLive:this.hasAttribute(W.NO_AUTO_SEEK_TO_LIVE)}});else if(e===W.FULLSCREEN_ELEMENT){let g=s?(u=this.getRootNode())==null?void 0:u.getElementById(s):void 0;Hi(this,Al,g),(c=ie(this,xe))==null||c.dispatch({type:"fullscreenelementchangerequest",detail:this.fullscreenElement})}else e===W.LANG&&s!==t?(iA(s),(h=ie(this,xe))==null||h.dispatch({type:"optionschangerequest",detail:{mediaLang:s}})):e===W.LOOP&&s!==t?(f=ie(this,xe))==null||f.dispatch({type:K.MEDIA_LOOP_REQUEST,detail:s!=null}):e===W.NO_VOLUME_PREF&&s!==t?(m=ie(this,xe))==null||m.dispatch({type:"optionschangerequest",detail:{noVolumePref:this.hasAttribute(W.NO_VOLUME_PREF)}}):e===W.NO_MUTED_PREF&&s!==t&&((p=ie(this,xe))==null||p.dispatch({type:"optionschangerequest",detail:{noMutedPref:this.hasAttribute(W.NO_MUTED_PREF)}}))}connectedCallback(){var e,t,s;this.associateElement(this),!ie(this,xe)&&!this.hasAttribute(W.NO_DEFAULT_STORE)&&_l(this,Vc,c0).call(this),(e=ie(this,xe))==null||e.dispatch({type:"documentelementchangerequest",detail:He}),(t=ie(this,xe))==null||t.dispatch({type:"fullscreenelementchangerequest",detail:this.fullscreenElement}),super.connectedCallback(),ie(this,xe)&&!ie(this,ss)&&Hi(this,ss,(s=ie(this,xe))==null?void 0:s.subscribe(ie(this,Sl))),ie(this,Il)!==void 0&&ie(this,xe)&&this.media&&setTimeout(()=>{var r,n,a;(n=(r=this.media)==null?void 0:r.textTracks)!=null&&n.length&&((a=ie(this,xe))==null||a.dispatch({type:K.MEDIA_TOGGLE_SUBTITLES_REQUEST,detail:ie(this,Il)}))},0),this.hasAttribute(W.NO_HOTKEYS)?this.disableHotkeys():this.enableHotkeys()}disconnectedCallback(){var e,t,s,r,n,a;if((e=super.disconnectedCallback)==null||e.call(this),this.disableHotkeys(),ie(this,xe)){let o=ie(this,xe).getState();Hi(this,Il,!!((t=o.mediaSubtitlesShowing)!=null&&t.length)),(s=ie(this,xe))==null||s.dispatch({type:"fullscreenelementchangerequest",detail:void 0}),(r=ie(this,xe))==null||r.dispatch({type:"documentelementchangerequest",detail:void 0}),(n=ie(this,xe))==null||n.dispatch({type:K.MEDIA_TOGGLE_SUBTITLES_REQUEST,detail:!1})}ie(this,ss)&&((a=ie(this,ss))==null||a.call(this),Hi(this,ss,void 0)),this.unassociateElement(this),ie(this,rs)&&(ie(this,rs).remove(),Hi(this,rs,null))}mediaSetCallback(e){var t;super.mediaSetCallback(e),(t=ie(this,xe))==null||t.dispatch({type:"mediaelementchangerequest",detail:e}),e.hasAttribute("tabindex")||(e.tabIndex=-1)}mediaUnsetCallback(e){var t;super.mediaUnsetCallback(e),(t=ie(this,xe))==null||t.dispatch({type:"mediaelementchangerequest",detail:void 0})}propagateMediaState(e,t){OA(this.mediaStateReceivers,e,t)}associateElement(e){if(!e)return;let{associatedElementSubscriptions:t}=this;if(t.has(e))return;let s=this.registerMediaStateReceiver.bind(this),r=this.unregisterMediaStateReceiver.bind(this),n=HM(e,s,r);Object.values(K).forEach(a=>{e.addEventListener(a,ie(this,Kc))}),t.set(e,n)}unassociateElement(e){if(!e)return;let{associatedElementSubscriptions:t}=this;if(!t.has(e))return;t.get(e)(),t.delete(e),Object.values(K).forEach(r=>{e.removeEventListener(r,ie(this,Kc))})}registerMediaStateReceiver(e){if(!e)return;let t=this.mediaStateReceivers;t.indexOf(e)>-1||(t.push(e),ie(this,xe)&&Object.entries(ie(this,xe).getState()).forEach(([r,n])=>{OA([e],r,n)}))}unregisterMediaStateReceiver(e){let t=this.mediaStateReceivers,s=t.indexOf(e);s<0||t.splice(s,1)}enableHotkeys(){this.addEventListener("keydown",_l(this,Wc,h0))}disableHotkeys(){this.removeEventListener("keydown",_l(this,Wc,h0)),this.removeEventListener("keyup",ie(this,_n))}get hotkeys(){return ie(this,Hs)}set hotkeys(e){me(this,W.HOTKEYS,e)}keyboardShortcutHandler(e){var t,s,r,n,a,o,l,d,u;let c=e.target;if(((r=(s=(t=c.getAttribute(W.KEYS_USED))==null?void 0:t.split(" "))!=null?s:c==null?void 0:c.keysUsed)!=null?r:[]).map(v=>v==="Space"?" ":v).filter(Boolean).includes(e.key))return;let f,m,p;if(!(ie(this,Hs).contains(`no${e.key.toLowerCase()}`)||e.key===" "&&ie(this,Hs).contains("nospace")||e.shiftKey&&(e.key==="/"||e.key==="?")&&ie(this,Hs).contains("noshift+/")))switch(e.key){case" ":case"k":f=ie(this,xe).getState().mediaPaused?K.MEDIA_PLAY_REQUEST:K.MEDIA_PAUSE_REQUEST,this.dispatchEvent(new L.CustomEvent(f,{composed:!0,bubbles:!0}));break;case"m":f=this.mediaStore.getState().mediaVolumeLevel==="off"?K.MEDIA_UNMUTE_REQUEST:K.MEDIA_MUTE_REQUEST,this.dispatchEvent(new L.CustomEvent(f,{composed:!0,bubbles:!0}));break;case"f":f=this.mediaStore.getState().mediaIsFullscreen?K.MEDIA_EXIT_FULLSCREEN_REQUEST:K.MEDIA_ENTER_FULLSCREEN_REQUEST,this.dispatchEvent(new L.CustomEvent(f,{composed:!0,bubbles:!0}));break;case"c":this.dispatchEvent(new L.CustomEvent(K.MEDIA_TOGGLE_SUBTITLES_REQUEST,{composed:!0,bubbles:!0}));break;case"ArrowLeft":case"j":{let v=this.hasAttribute(W.KEYBOARD_BACKWARD_SEEK_OFFSET)?+this.getAttribute(W.KEYBOARD_BACKWARD_SEEK_OFFSET):DA;m=Math.max(((n=this.mediaStore.getState().mediaCurrentTime)!=null?n:0)-v,0),p=new L.CustomEvent(K.MEDIA_SEEK_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case"ArrowRight":case"l":{let v=this.hasAttribute(W.KEYBOARD_FORWARD_SEEK_OFFSET)?+this.getAttribute(W.KEYBOARD_FORWARD_SEEK_OFFSET):DA;m=Math.max(((a=this.mediaStore.getState().mediaCurrentTime)!=null?a:0)+v,0),p=new L.CustomEvent(K.MEDIA_SEEK_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case"ArrowUp":{let v=this.hasAttribute(W.KEYBOARD_UP_VOLUME_STEP)?+this.getAttribute(W.KEYBOARD_UP_VOLUME_STEP):CA;m=Math.min(((o=this.mediaStore.getState().mediaVolume)!=null?o:1)+v,1),p=new L.CustomEvent(K.MEDIA_VOLUME_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case"ArrowDown":{let v=this.hasAttribute(W.KEYBOARD_DOWN_VOLUME_STEP)?+this.getAttribute(W.KEYBOARD_DOWN_VOLUME_STEP):CA;m=Math.max(((l=this.mediaStore.getState().mediaVolume)!=null?l:1)-v,0),p=new L.CustomEvent(K.MEDIA_VOLUME_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case"<":{let v=(d=this.mediaStore.getState().mediaPlaybackRate)!=null?d:1;m=Math.max(v-wA,PM).toFixed(2),p=new L.CustomEvent(K.MEDIA_PLAYBACK_RATE_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case">":{let v=(u=this.mediaStore.getState().mediaPlaybackRate)!=null?u:1;m=Math.min(v+wA,OM).toFixed(2),p=new L.CustomEvent(K.MEDIA_PLAYBACK_RATE_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case"/":case"?":{e.shiftKey&&_l(this,f0,NA).call(this);break}case"p":{f=this.mediaStore.getState().mediaIsPip?K.MEDIA_EXIT_PIP_REQUEST:K.MEDIA_ENTER_PIP_REQUEST,p=new L.CustomEvent(f,{composed:!0,bubbles:!0}),this.dispatchEvent(p);break}default:break}}};Hs=new WeakMap;Al=new WeakMap;xe=new WeakMap;rs=new WeakMap;Sl=new WeakMap;ss=new WeakMap;Kc=new WeakMap;Il=new WeakMap;Vc=new WeakSet;c0=function(){var i;this.mediaStore=kA({media:this.media,fullscreenElement:this.fullscreenElement,options:{defaultSubtitles:this.hasAttribute(W.DEFAULT_SUBTITLES),defaultDuration:this.hasAttribute(W.DEFAULT_DURATION)?+this.getAttribute(W.DEFAULT_DURATION):void 0,defaultStreamType:(i=this.getAttribute(W.DEFAULT_STREAM_TYPE))!=null?i:void 0,liveEdgeOffset:this.hasAttribute(W.LIVE_EDGE_OFFSET)?+this.getAttribute(W.LIVE_EDGE_OFFSET):void 0,seekToLiveOffset:this.hasAttribute(W.SEEK_TO_LIVE_OFFSET)?+this.getAttribute(W.SEEK_TO_LIVE_OFFSET):this.hasAttribute(W.LIVE_EDGE_OFFSET)?+this.getAttribute(W.LIVE_EDGE_OFFSET):void 0,noAutoSeekToLive:this.hasAttribute(W.NO_AUTO_SEEK_TO_LIVE),noVolumePref:this.hasAttribute(W.NO_VOLUME_PREF),noMutedPref:this.hasAttribute(W.NO_MUTED_PREF),noSubtitlesLangPref:this.hasAttribute(W.NO_SUBTITLES_LANG_PREF)}})};_n=new WeakMap;Wc=new WeakSet;h0=function(i){var e;let{metaKey:t,altKey:s,key:r,shiftKey:n}=i,a=n&&(r==="/"||r==="?");if(a&&((e=ie(this,rs))!=null&&e.open)){this.removeEventListener("keyup",ie(this,_n));return}if(t||s||!a&&!UA.includes(r)){this.removeEventListener("keyup",ie(this,_n));return}let o=i.target,l=o instanceof HTMLElement&&(o.tagName.toLowerCase()==="media-volume-range"||o.tagName.toLowerCase()==="media-time-range");[" ","ArrowLeft","ArrowRight","ArrowUp","ArrowDown"].includes(r)&&!(ie(this,Hs).contains(`no${r.toLowerCase()}`)||r===" "&&ie(this,Hs).contains("nospace"))&&!l&&i.preventDefault(),this.addEventListener("keyup",ie(this,_n),{once:!0})};f0=new WeakSet;NA=function(){ie(this,rs)||(Hi(this,rs,He.createElement("media-keyboard-shortcuts-dialog")),this.appendChild(ie(this,rs))),ie(this,rs).open=!0};var NM=Object.values(_),UM=Object.values(Qg),FA=i=>{var e,t,s,r;let{observedAttributes:n}=i.constructor;!n&&((e=i.nodeName)!=null&&e.includes("-"))&&(L.customElements.upgrade(i),{observedAttributes:n}=i.constructor);let a=(r=(s=(t=i==null?void 0:i.getAttribute)==null?void 0:t.call(i,ge.MEDIA_CHROME_ATTRIBUTES))==null?void 0:s.split)==null?void 0:r.call(s,/\s+/);return Array.isArray(n||a)?(n||a).filter(o=>NM.includes(o)):[]},FM=i=>{var e,t;return(e=i.nodeName)!=null&&e.includes("-")&&L.customElements.get((t=i.nodeName)==null?void 0:t.toLowerCase())&&!(i instanceof L.customElements.get(i.nodeName.toLowerCase()))&&L.customElements.upgrade(i),UM.some(s=>s in i)},m0=i=>FM(i)||!!FA(i).length,MA=i=>{var e;return(e=i==null?void 0:i.join)==null?void 0:e.call(i,":")},PA={[_.MEDIA_SUBTITLES_LIST]:$s,[_.MEDIA_SUBTITLES_SHOWING]:$s,[_.MEDIA_SEEKABLE]:MA,[_.MEDIA_BUFFERED]:i=>i==null?void 0:i.map(MA).join(" "),[_.MEDIA_PREVIEW_COORDS]:i=>i==null?void 0:i.join(" "),[_.MEDIA_RENDITION_LIST]:z_,[_.MEDIA_AUDIO_TRACK_LIST]:X_},BM=async(i,e,t)=>{var s,r;if(i.isConnected||await Tc(0),typeof t=="boolean"||t==null)return de(i,e,t);if(typeof t=="number")return Re(i,e,t);if(typeof t=="string")return me(i,e,t);if(Array.isArray(t)&&!t.length)return i.removeAttribute(e);let n=(r=(s=PA[e])==null?void 0:s.call(PA,t))!=null?r:t;return i.setAttribute(e,n)},$M=i=>{var e;return!!((e=i.closest)!=null&&e.call(i,'*[slot="media"]'))},bn=(i,e)=>{if($M(i))return;let t=(r,n)=>{var a,o;m0(r)&&n(r);let{children:l=[]}=r!=null?r:{},d=(o=(a=r==null?void 0:r.shadowRoot)==null?void 0:a.children)!=null?o:[];[...l,...d].forEach(c=>bn(c,n))},s=i==null?void 0:i.nodeName.toLowerCase();if(s.includes("-")&&!m0(i)){L.customElements.whenDefined(s).then(()=>{t(i,e)});return}t(i,e)},OA=(i,e,t)=>{i.forEach(s=>{if(e in s){s[e]=t;return}let r=FA(s),n=e.toLowerCase();r.includes(n)&&BM(s,n,t)})},HM=(i,e,t)=>{bn(i,e);let s=u=>{var c;let h=(c=u==null?void 0:u.composedPath()[0])!=null?c:u.target;e(h)},r=u=>{var c;let h=(c=u==null?void 0:u.composedPath()[0])!=null?c:u.target;t(h)};i.addEventListener(K.REGISTER_MEDIA_STATE_RECEIVER,s),i.addEventListener(K.UNREGISTER_MEDIA_STATE_RECEIVER,r);let n=u=>{u.forEach(c=>{let{addedNodes:h=[],removedNodes:f=[],type:m,target:p,attributeName:g}=c;m==="childList"?(Array.prototype.forEach.call(h,v=>bn(v,e)),Array.prototype.forEach.call(f,v=>bn(v,t))):m==="attributes"&&g===ge.MEDIA_CHROME_ATTRIBUTES&&(m0(p)?e(p):t(p))})},a=[],o=u=>{let c=u.target;c.name!=="media"&&(a.forEach(h=>bn(h,t)),a=[...c.assignedElements({flatten:!0})],a.forEach(h=>bn(h,e)))};i.addEventListener("slotchange",o);let l=new MutationObserver(n);return l.observe(i,{childList:!0,attributes:!0,subtree:!0}),()=>{bn(i,t),i.removeEventListener("slotchange",o),l.disconnect(),i.removeEventListener(K.REGISTER_MEDIA_STATE_RECEIVER,s),i.removeEventListener(K.UNREGISTER_MEDIA_STATE_RECEIVER,r)}};L.customElements.get("media-controller")||L.customElements.define("media-controller",qc);var g0=qc;var Ca={PLACEMENT:"placement",BOUNDS:"bounds"};function GM(i){return`
298
+ `}var vM=Object.values(_),EM="sm:384 md:576 lg:768 xl:960";function yM(i){fA(i.target,i.contentRect.width)}function fA(i,e){var t;if(!i.isConnected)return;let s=(t=i.getAttribute(ae.BREAKPOINTS))!=null?t:EM,r=bM(s),n=TM(r,e),a=!1;if(Object.keys(r).forEach(o=>{if(n.includes(o)){i.hasAttribute(`breakpoint${o}`)||(i.setAttribute(`breakpoint${o}`,""),a=!0);return}i.hasAttribute(`breakpoint${o}`)&&(i.removeAttribute(`breakpoint${o}`),a=!0)}),a){let o=new CustomEvent(di.BREAKPOINTS_CHANGE,{detail:n});i.dispatchEvent(o)}i.breakpointsComputed||(i.breakpointsComputed=!0,i.dispatchEvent(new CustomEvent(di.BREAKPOINTS_COMPUTED,{bubbles:!0,composed:!0})))}function bM(i){let e=i.split(/\s+/);return Object.fromEntries(e.map(t=>t.split(":")))}function TM(i,e){return Object.keys(i).filter(t=>e>=parseInt(i[t]))}var gn=class extends L.HTMLElement{constructor(){if(super(),Vt(this,i0),Vt(this,s0),Vt(this,El),Vt(this,Pc),Vt(this,La),Vt(this,vl,void 0),Vt(this,wc,0),Vt(this,_a,null),Vt(this,Ia,null),Vt(this,Sa,void 0),this.breakpointsComputed=!1,Vt(this,t0,e=>{let t=this.media;for(let s of e){if(s.type!=="childList")continue;let r=s.removedNodes;for(let n of r){if(n.slot!="media"||s.target!=this)continue;let a=s.previousSibling&&s.previousSibling.previousElementSibling;if(!a||!t)this.mediaUnsetCallback(n);else{let o=a.slot!=="media";for(;(a=a.previousSibling)!==null;)a.slot=="media"&&(o=!1);o&&this.mediaUnsetCallback(n)}}if(t)for(let n of s.addedNodes)n===t&&this.handleMediaUpdated(t)}}),Vt(this,Aa,!1),Vt(this,Dc,e=>{ot(this,Aa)||(setTimeout(()=>{yM(e),Bi(this,Aa,!1)},0),Bi(this,Aa,!0))}),Vt(this,Sr,void 0),Vt(this,Cc,()=>{if(!ot(this,Sr).assignedElements({flatten:!0}).length){ot(this,_a)&&this.mediaUnsetCallback(ot(this,_a));return}this.handleMediaUpdated(this.media)}),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=Qe(this.attributes),t=this.constructor.getTemplateHTML(e);this.shadowRoot.setHTMLUnsafe?this.shadowRoot.setHTMLUnsafe(t):this.shadowRoot.innerHTML=t}Bi(this,vl,new MutationObserver(ot(this,t0)))}static get observedAttributes(){return[ae.AUTOHIDE,ae.GESTURES_DISABLED].concat(vM).filter(e=>![_.MEDIA_RENDITION_LIST,_.MEDIA_AUDIO_TRACK_LIST,_.MEDIA_CHAPTERS_CUES,_.MEDIA_WIDTH,_.MEDIA_HEIGHT,_.MEDIA_ERROR,_.MEDIA_ERROR_MESSAGE].includes(e))}attributeChangedCallback(e,t,s){e.toLowerCase()==ae.AUTOHIDE&&(this.autohide=s)}get media(){let e=this.querySelector(":scope > [slot=media]");return(e==null?void 0:e.nodeName)=="SLOT"&&(e=e.assignedElements({flatten:!0})[0]),e}async handleMediaUpdated(e){e&&(Bi(this,_a,e),e.localName.includes("-")&&await L.customElements.whenDefined(e.localName),this.mediaSetCallback(e))}connectedCallback(){var e;ot(this,vl).observe(this,{childList:!0,subtree:!0}),Us(this,ot(this,Dc));let s=this.getAttribute(ae.AUDIO)!=null?F("audio player"):F("video player");this.setAttribute("role","region"),this.setAttribute("aria-label",s),this.handleMediaUpdated(this.media),this.setAttribute(ae.USER_INACTIVE,""),fA(this,this.getBoundingClientRect().width);let r=this.querySelector(":scope > slot[slot=media]");r&&(Bi(this,Sr,r),ot(this,Sr).addEventListener("slotchange",ot(this,Cc))),this.addEventListener("pointerdown",this),this.addEventListener("pointermove",this),this.addEventListener("pointerup",this),this.addEventListener("mouseleave",this),this.addEventListener("keyup",this),(e=L.window)==null||e.addEventListener("mouseup",this)}disconnectedCallback(){var e;Fs(this,ot(this,Dc)),clearTimeout(ot(this,Ia)),ot(this,vl).disconnect(),this.media&&this.mediaUnsetCallback(this.media),(e=L.window)==null||e.removeEventListener("mouseup",this),this.removeEventListener("pointerdown",this),this.removeEventListener("pointermove",this),this.removeEventListener("pointerup",this),this.removeEventListener("mouseleave",this),this.removeEventListener("keyup",this),ot(this,Sr)&&(ot(this,Sr).removeEventListener("slotchange",ot(this,Cc)),Bi(this,Sr,null)),Bi(this,Aa,!1)}mediaSetCallback(e){}mediaUnsetCallback(e){Bi(this,_a,null)}handleEvent(e){switch(e.type){case"pointerdown":Bi(this,wc,e.timeStamp);break;case"pointermove":$i(this,i0,cA).call(this,e);break;case"pointerup":$i(this,s0,hA).call(this,e);break;case"mouseleave":$i(this,El,Mc).call(this);break;case"mouseup":this.removeAttribute(ae.KEYBOARD_CONTROL);break;case"keyup":$i(this,La,yl).call(this),this.setAttribute(ae.KEYBOARD_CONTROL,"");break}}set autohide(e){let t=Number(e);Bi(this,Sa,isNaN(t)?0:t)}get autohide(){return(ot(this,Sa)===void 0?2:ot(this,Sa)).toString()}get breakpoints(){return pe(this,ae.BREAKPOINTS)}set breakpoints(e){me(this,ae.BREAKPOINTS,e)}get audio(){return le(this,ae.AUDIO)}set audio(e){de(this,ae.AUDIO,e)}get gesturesDisabled(){return le(this,ae.GESTURES_DISABLED)}set gesturesDisabled(e){de(this,ae.GESTURES_DISABLED,e)}get keyboardControl(){return le(this,ae.KEYBOARD_CONTROL)}set keyboardControl(e){de(this,ae.KEYBOARD_CONTROL,e)}get noAutohide(){return le(this,ae.NO_AUTOHIDE)}set noAutohide(e){de(this,ae.NO_AUTOHIDE,e)}get autohideOverControls(){return le(this,ae.AUTOHIDE_OVER_CONTROLS)}set autohideOverControls(e){de(this,ae.AUTOHIDE_OVER_CONTROLS,e)}get userInteractive(){return le(this,ae.USER_INACTIVE)}set userInteractive(e){de(this,ae.USER_INACTIVE,e)}};vl=new WeakMap;wc=new WeakMap;_a=new WeakMap;Ia=new WeakMap;Sa=new WeakMap;t0=new WeakMap;Aa=new WeakMap;Dc=new WeakMap;i0=new WeakSet;cA=function(i){if(i.pointerType!=="mouse"&&i.timeStamp-ot(this,wc)<250)return;$i(this,Pc,n0).call(this),clearTimeout(ot(this,Ia));let e=this.hasAttribute(ae.AUTOHIDE_OVER_CONTROLS);([this,this.media].includes(i.target)||e)&&$i(this,La,yl).call(this)};s0=new WeakSet;hA=function(i){if(i.pointerType==="touch"){let e=!this.hasAttribute(ae.USER_INACTIVE);[this,this.media].includes(i.target)&&e?$i(this,El,Mc).call(this):$i(this,La,yl).call(this)}else i.composedPath().some(e=>["media-play-button","media-fullscreen-button"].includes(e==null?void 0:e.localName))&&$i(this,La,yl).call(this)};El=new WeakSet;Mc=function(){if(ot(this,Sa)<0||this.hasAttribute(ae.USER_INACTIVE))return;this.setAttribute(ae.USER_INACTIVE,"");let i=new L.CustomEvent(di.USER_INACTIVE_CHANGE,{composed:!0,bubbles:!0,detail:!0});this.dispatchEvent(i)};Pc=new WeakSet;n0=function(){if(!this.hasAttribute(ae.USER_INACTIVE))return;this.removeAttribute(ae.USER_INACTIVE);let i=new L.CustomEvent(di.USER_INACTIVE_CHANGE,{composed:!0,bubbles:!0,detail:!1});this.dispatchEvent(i)};La=new WeakSet;yl=function(){$i(this,Pc,n0).call(this),clearTimeout(ot(this,Ia));let i=parseInt(this.autohide);i<0||Bi(this,Ia,setTimeout(()=>{$i(this,El,Mc).call(this)},i*1e3))};Sr=new WeakMap;Cc=new WeakMap;gn.shadowRootOptions={mode:"open"};gn.getTemplateHTML=gM;L.customElements.get("media-container")||L.customElements.define("media-container",gn);var mA=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},xt=(i,e,t)=>(mA(i,e,"read from private field"),t?t.call(i):e.get(i)),bl=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},Oc=(i,e,t,s)=>(mA(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),Ra,xa,Nc,vn,Bs,Ir,Lr=class{constructor(e,t,{defaultValue:s}={defaultValue:void 0}){bl(this,Bs),bl(this,Ra,void 0),bl(this,xa,void 0),bl(this,Nc,void 0),bl(this,vn,new Set),Oc(this,Ra,e),Oc(this,xa,t),Oc(this,Nc,new Set(s))}[Symbol.iterator](){return xt(this,Bs,Ir).values()}get length(){return xt(this,Bs,Ir).size}get value(){var e;return(e=[...xt(this,Bs,Ir)].join(" "))!=null?e:""}set value(e){var t;e!==this.value&&(Oc(this,vn,new Set),this.add(...(t=e==null?void 0:e.split(" "))!=null?t:[]))}toString(){return this.value}item(e){return[...xt(this,Bs,Ir)][e]}values(){return xt(this,Bs,Ir).values()}forEach(e,t){xt(this,Bs,Ir).forEach(e,t)}add(...e){var t,s;e.forEach(r=>xt(this,vn).add(r)),!(this.value===""&&!((t=xt(this,Ra))!=null&&t.hasAttribute(`${xt(this,xa)}`)))&&((s=xt(this,Ra))==null||s.setAttribute(`${xt(this,xa)}`,`${this.value}`))}remove(...e){var t;e.forEach(s=>xt(this,vn).delete(s)),(t=xt(this,Ra))==null||t.setAttribute(`${xt(this,xa)}`,`${this.value}`)}contains(e){return xt(this,Bs,Ir).has(e)}toggle(e,t){return typeof t!="undefined"?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}};Ra=new WeakMap;xa=new WeakMap;Nc=new WeakMap;vn=new WeakMap;Bs=new WeakSet;Ir=function(){return xt(this,vn).size?xt(this,vn):xt(this,Nc)};var _M=(i="")=>i.split(/\s+/),pA=(i="")=>{let[e,t,s]=i.split(":"),r=s?decodeURIComponent(s):void 0;return{kind:e==="cc"?Xt.CAPTIONS:Xt.SUBTITLES,language:t,label:r}},En=(i="",e={})=>_M(i).map(t=>{let s=pA(t);return{...e,...s}}),a0=i=>i?Array.isArray(i)?i.map(e=>typeof e=="string"?pA(e):e):typeof i=="string"?En(i):[i]:[],Uc=({kind:i,label:e,language:t}={kind:"subtitles"})=>e?`${i==="captions"?"cc":"sb"}:${t}:${encodeURIComponent(e)}`:t,$s=(i=[])=>Array.prototype.map.call(i,Uc).join(" "),AM=(i,e)=>t=>t[i]===e,gA=i=>{let e=Object.entries(i).map(([t,s])=>AM(t,s));return t=>e.every(s=>s(t))},yn=(i,e=[],t=[])=>{let s=a0(t).map(gA),r=n=>s.some(a=>a(n));Array.from(e).filter(r).forEach(n=>{n.mode=i})},bn=(i,e=()=>!0)=>{if(!(i!=null&&i.textTracks))return[];let t=typeof e=="function"?e:gA(e);return Array.from(i.textTracks).filter(t)},Fc=i=>{var e;return!!((e=i.mediaSubtitlesShowing)!=null&&e.length)||i.hasAttribute(_.MEDIA_SUBTITLES_SHOWING)};var EA=i=>{var e;let{media:t,fullscreenElement:s}=i;try{let r=s&&"requestFullscreen"in s?"requestFullscreen":s&&"webkitRequestFullScreen"in s?"webkitRequestFullScreen":void 0;if(r){let n=(e=s[r])==null?void 0:e.call(s);if(n instanceof Promise)return n.catch(()=>{})}else t!=null&&t.webkitEnterFullscreen?t.webkitEnterFullscreen():t!=null&&t.requestFullscreen&&t.requestFullscreen()}catch(r){console.error(r)}},vA="exitFullscreen"in He?"exitFullscreen":"webkitExitFullscreen"in He?"webkitExitFullscreen":"webkitCancelFullScreen"in He?"webkitCancelFullScreen":void 0,yA=i=>{var e;let{documentElement:t}=i;if(vA){let s=(e=t==null?void 0:t[vA])==null?void 0:e.call(t);if(s instanceof Promise)return s.catch(()=>{})}},Tl="fullscreenElement"in He?"fullscreenElement":"webkitFullscreenElement"in He?"webkitFullscreenElement":void 0,SM=i=>{let{documentElement:e,media:t}=i,s=e==null?void 0:e[Tl];return!s&&"webkitDisplayingFullscreen"in t&&"webkitPresentationMode"in t&&t.webkitDisplayingFullscreen&&t.webkitPresentationMode===j_.FULLSCREEN?t:s},bA=i=>{var e;let{media:t,documentElement:s,fullscreenElement:r=t}=i;if(!t||!s)return!1;let n=SM(i);if(!n)return!1;if(n===r||n===t)return!0;if(n.localName.includes("-")){let a=n.shadowRoot;if(!(Tl in a))return Kt(n,r);for(;a!=null&&a[Tl];){if(a[Tl]===r)return!0;a=(e=a[Tl])==null?void 0:e.shadowRoot}}return!1},IM="fullscreenEnabled"in He?"fullscreenEnabled":"webkitFullscreenEnabled"in He?"webkitFullscreenEnabled":void 0,TA=i=>{let{documentElement:e,media:t}=i;return!!(e!=null&&e[IM])||t&&"webkitSupportsFullscreen"in t};var Bc,o0=()=>{var i,e;return Bc||(Bc=(e=(i=He)==null?void 0:i.createElement)==null?void 0:e.call(i,"video"),Bc)},_A=async(i=o0())=>{if(!i)return!1;let e=i.volume;i.volume=e/2+.1;let t=new AbortController,s=await Promise.race([LM(i,t.signal),RM(i,e)]);return t.abort(),s},LM=(i,e)=>new Promise(t=>{i.addEventListener("volumechange",()=>t(!0),{signal:e})}),RM=async(i,e)=>{for(let t=0;t<10;t++){if(i.volume===e)return!1;await bc(10)}return i.volume!==e},xM=/.*Version\/.*Safari\/.*/.test(L.navigator.userAgent),l0=(i=o0())=>L.matchMedia("(display-mode: standalone)").matches&&xM?!1:typeof(i==null?void 0:i.requestPictureInPicture)=="function",d0=(i=o0())=>TA({documentElement:He,media:i}),AA=d0(),SA=l0(),IA=!!L.WebKitPlaybackTargetAvailabilityEvent,LA=!!L.chrome;var ka=i=>bn(i.media,e=>[Xt.SUBTITLES,Xt.CAPTIONS].includes(e.kind)).sort((e,t)=>e.kind>=t.kind?1:-1),u0=i=>bn(i.media,e=>e.mode===Ar.SHOWING&&[Xt.SUBTITLES,Xt.CAPTIONS].includes(e.kind)),$c=(i,e)=>{let t=ka(i),s=u0(i),r=!!s.length;if(t.length){if(e===!1||r&&e!==!0)yn(Ar.DISABLED,t,s);else if(e===!0||!r&&e!==!1){let n=t[0],{options:a}=i;if(!(a!=null&&a.noSubtitlesLangPref)){let u=L.localStorage.getItem("media-chrome-pref-subtitles-lang"),c=u?[u,...L.navigator.languages]:L.navigator.languages,h=t.filter(f=>c.some(m=>f.language.toLowerCase().startsWith(m.split("-")[0]))).sort((f,m)=>{let p=c.findIndex(v=>f.language.toLowerCase().startsWith(v.split("-")[0])),g=c.findIndex(v=>m.language.toLowerCase().startsWith(v.split("-")[0]));return p-g});h[0]&&(n=h[0])}let{language:o,label:l,kind:d}=n;yn(Ar.DISABLED,t,s),yn(Ar.SHOWING,t,[{language:o,label:l,kind:d}])}}},Hc=(i,e)=>i===e?!0:i==null||e==null||typeof i!=typeof e?!1:typeof i=="number"&&Number.isNaN(i)&&Number.isNaN(e)?!0:typeof i!="object"?!1:Array.isArray(i)?kM(i,e):Object.entries(i).every(([t,s])=>t in e&&Hc(s,e[t])),kM=(i,e)=>{let t=Array.isArray(i),s=Array.isArray(e);return t!==s?!1:t||s?i.length!==e.length?!1:i.every((r,n)=>Hc(r,e[n])):!0};var DM=Object.values(Ni),Gc,CM=_A().then(i=>(Gc=i,Gc)),RA=async(...i)=>{await Promise.all(i.filter(e=>e).map(async e=>{if(!("localName"in e&&e instanceof L.HTMLElement))return;let t=e.localName;if(!t.includes("-"))return;let s=L.customElements.get(t);s&&e instanceof s||(await L.customElements.whenDefined(t),L.customElements.upgrade(e))}))},wM=new L.DOMParser,MM=i=>i&&(wM.parseFromString(i,"text/html").body.textContent||i),Da={mediaError:{get(i,e){let{media:t}=i;if((e==null?void 0:e.type)!=="playing")return t==null?void 0:t.error},mediaEvents:["emptied","error","playing"]},mediaErrorCode:{get(i,e){var t;let{media:s}=i;if((e==null?void 0:e.type)!=="playing")return(t=s==null?void 0:s.error)==null?void 0:t.code},mediaEvents:["emptied","error","playing"]},mediaErrorMessage:{get(i,e){var t,s;let{media:r}=i;if((e==null?void 0:e.type)!=="playing")return(s=(t=r==null?void 0:r.error)==null?void 0:t.message)!=null?s:""},mediaEvents:["emptied","error","playing"]},mediaWidth:{get(i){var e;let{media:t}=i;return(e=t==null?void 0:t.videoWidth)!=null?e:0},mediaEvents:["resize"]},mediaHeight:{get(i){var e;let{media:t}=i;return(e=t==null?void 0:t.videoHeight)!=null?e:0},mediaEvents:["resize"]},mediaPaused:{get(i){var e;let{media:t}=i;return(e=t==null?void 0:t.paused)!=null?e:!0},set(i,e){var t;let{media:s}=e;s&&(i?s.pause():(t=s.play())==null||t.catch(()=>{}))},mediaEvents:["play","playing","pause","emptied"]},mediaHasPlayed:{get(i,e){let{media:t}=i;return t?e?e.type==="playing":!t.paused:!1},mediaEvents:["playing","emptied"]},mediaEnded:{get(i){var e;let{media:t}=i;return(e=t==null?void 0:t.ended)!=null?e:!1},mediaEvents:["seeked","ended","emptied"]},mediaPlaybackRate:{get(i){var e;let{media:t}=i;return(e=t==null?void 0:t.playbackRate)!=null?e:1},set(i,e){let{media:t}=e;t&&Number.isFinite(+i)&&(t.playbackRate=+i)},mediaEvents:["ratechange","loadstart"]},mediaMuted:{get(i){var e;let{media:t}=i;return(e=t==null?void 0:t.muted)!=null?e:!1},set(i,e){let{media:t,options:{noMutedPref:s}={}}=e;if(t){t.muted=i;try{let r=L.localStorage.getItem("media-chrome-pref-muted")!==null,n=t.hasAttribute("muted");if(s){r&&L.localStorage.removeItem("media-chrome-pref-muted");return}if(n&&!r)return;L.localStorage.setItem("media-chrome-pref-muted",i?"true":"false")}catch(r){console.debug("Error setting muted pref",r)}}},mediaEvents:["volumechange"],stateOwnersUpdateHandlers:[(i,e)=>{let{options:{noMutedPref:t}}=e,{media:s}=e;if(!(!s||s.muted||t))try{let r=L.localStorage.getItem("media-chrome-pref-muted")==="true";Da.mediaMuted.set(r,e),i(r)}catch(r){console.debug("Error getting muted pref",r)}}]},mediaLoop:{get(i){let{media:e}=i;return e==null?void 0:e.loop},set(i,e){let{media:t}=e;t&&(t.loop=i)},mediaEvents:["medialooprequest"]},mediaVolume:{get(i){var e;let{media:t}=i;return(e=t==null?void 0:t.volume)!=null?e:1},set(i,e){let{media:t,options:{noVolumePref:s}={}}=e;if(t){try{i==null?L.localStorage.removeItem("media-chrome-pref-volume"):!t.hasAttribute("muted")&&!s&&L.localStorage.setItem("media-chrome-pref-volume",i.toString())}catch(r){console.debug("Error setting volume pref",r)}Number.isFinite(+i)&&(t.volume=+i)}},mediaEvents:["volumechange"],stateOwnersUpdateHandlers:[(i,e)=>{let{options:{noVolumePref:t}}=e;if(!t)try{let{media:s}=e;if(!s)return;let r=L.localStorage.getItem("media-chrome-pref-volume");if(r==null)return;Da.mediaVolume.set(+r,e),i(+r)}catch(s){console.debug("Error getting volume pref",s)}}]},mediaVolumeLevel:{get(i){let{media:e}=i;return typeof(e==null?void 0:e.volume)=="undefined"?"high":e.muted||e.volume===0?"off":e.volume<.5?"low":e.volume<.75?"medium":"high"},mediaEvents:["volumechange"]},mediaCurrentTime:{get(i){var e;let{media:t}=i;return(e=t==null?void 0:t.currentTime)!=null?e:0},set(i,e){let{media:t}=e;!t||!ba(i)||(t.currentTime=i)},mediaEvents:["timeupdate","loadedmetadata"]},mediaDuration:{get(i){let{media:e,options:{defaultDuration:t}={}}=i;return t&&(!e||!e.duration||Number.isNaN(e.duration)||!Number.isFinite(e.duration))?t:Number.isFinite(e==null?void 0:e.duration)?e.duration:Number.NaN},mediaEvents:["durationchange","loadedmetadata","emptied"]},mediaLoading:{get(i){let{media:e}=i;return(e==null?void 0:e.readyState)<3},mediaEvents:["waiting","playing","emptied"]},mediaSeekable:{get(i){var e;let{media:t}=i;if(!((e=t==null?void 0:t.seekable)!=null&&e.length))return;let s=t.seekable.start(0),r=t.seekable.end(t.seekable.length-1);if(!(!s&&!r))return[Number(s.toFixed(3)),Number(r.toFixed(3))]},mediaEvents:["loadedmetadata","emptied","progress","seekablechange"]},mediaBuffered:{get(i){var e;let{media:t}=i,s=(e=t==null?void 0:t.buffered)!=null?e:[];return Array.from(s).map((r,n)=>[Number(s.start(n).toFixed(3)),Number(s.end(n).toFixed(3))])},mediaEvents:["progress","emptied"]},mediaStreamType:{get(i){let{media:e,options:{defaultStreamType:t}={}}=i,s=[Ni.LIVE,Ni.ON_DEMAND].includes(t)?t:void 0;if(!e)return s;let{streamType:r}=e;if(DM.includes(r))return r===Ni.UNKNOWN?s:r;let n=e.duration;return n===1/0?Ni.LIVE:Number.isFinite(n)?Ni.ON_DEMAND:s},mediaEvents:["emptied","durationchange","loadedmetadata","streamtypechange"]},mediaTargetLiveWindow:{get(i){let{media:e}=i;if(!e)return Number.NaN;let{targetLiveWindow:t}=e,s=Da.mediaStreamType.get(i);return(t==null||Number.isNaN(t))&&s===Ni.LIVE?0:t},mediaEvents:["emptied","durationchange","loadedmetadata","streamtypechange","targetlivewindowchange"]},mediaTimeIsLive:{get(i){let{media:e,options:{liveEdgeOffset:t=10}={}}=i;if(!e)return!1;if(typeof e.liveEdgeStart=="number")return Number.isNaN(e.liveEdgeStart)?!1:e.currentTime>=e.liveEdgeStart;if(!(Da.mediaStreamType.get(i)===Ni.LIVE))return!1;let r=e.seekable;if(!r)return!0;if(!r.length)return!1;let n=r.end(r.length-1)-t;return e.currentTime>=n},mediaEvents:["playing","timeupdate","progress","waiting","emptied"]},mediaSubtitlesList:{get(i){return ka(i).map(({kind:e,label:t,language:s})=>({kind:e,label:t,language:s}))},mediaEvents:["loadstart"],textTracksEvents:["addtrack","removetrack"]},mediaSubtitlesShowing:{get(i){return u0(i).map(({kind:e,label:t,language:s})=>({kind:e,label:t,language:s}))},mediaEvents:["loadstart"],textTracksEvents:["addtrack","removetrack","change"],stateOwnersUpdateHandlers:[(i,e)=>{var t,s;let{media:r,options:n}=e;if(!r)return;let a=o=>{var l;!n.defaultSubtitles||o&&![Xt.CAPTIONS,Xt.SUBTITLES].includes((l=o==null?void 0:o.track)==null?void 0:l.kind)||$c(e,!0)};return r.addEventListener("loadstart",a),(t=r.textTracks)==null||t.addEventListener("addtrack",a),(s=r.textTracks)==null||s.addEventListener("removetrack",a),()=>{var o,l;r.removeEventListener("loadstart",a),(o=r.textTracks)==null||o.removeEventListener("addtrack",a),(l=r.textTracks)==null||l.removeEventListener("removetrack",a)}}]},mediaChaptersCues:{get(i){var e;let{media:t}=i;if(!t)return[];let[s]=bn(t,{kind:Xt.CHAPTERS});return Array.from((e=s==null?void 0:s.cues)!=null?e:[]).map(({text:r,startTime:n,endTime:a})=>({text:MM(r),startTime:n,endTime:a}))},mediaEvents:["loadstart","loadedmetadata"],textTracksEvents:["addtrack","removetrack","change"],stateOwnersUpdateHandlers:[(i,e)=>{var t;let{media:s}=e;if(!s)return;let r=s.querySelector('track[kind="chapters"][default][src]'),n=(t=s.shadowRoot)==null?void 0:t.querySelector(':is(video,audio) > track[kind="chapters"][default][src]');return r==null||r.addEventListener("load",i),n==null||n.addEventListener("load",i),()=>{r==null||r.removeEventListener("load",i),n==null||n.removeEventListener("load",i)}}]},mediaIsPip:{get(i){var e,t;let{media:s,documentElement:r}=i;if(!s||!r||!r.pictureInPictureElement)return!1;if(r.pictureInPictureElement===s)return!0;if(r.pictureInPictureElement instanceof HTMLMediaElement)return(e=s.localName)!=null&&e.includes("-")?Kt(s,r.pictureInPictureElement):!1;if(r.pictureInPictureElement.localName.includes("-")){let n=r.pictureInPictureElement.shadowRoot;for(;n!=null&&n.pictureInPictureElement;){if(n.pictureInPictureElement===s)return!0;n=(t=n.pictureInPictureElement)==null?void 0:t.shadowRoot}}return!1},set(i,e){let{media:t}=e;if(t)if(i){if(!He.pictureInPictureEnabled){console.warn("MediaChrome: Picture-in-picture is not enabled");return}if(!t.requestPictureInPicture){console.warn("MediaChrome: The current media does not support picture-in-picture");return}let s=()=>{console.warn("MediaChrome: The media is not ready for picture-in-picture. It must have a readyState > 0.")};t.requestPictureInPicture().catch(r=>{if(r.code===11){if(!t.src){console.warn("MediaChrome: The media is not ready for picture-in-picture. It must have a src set.");return}if(t.readyState===0&&t.preload==="none"){let n=()=>{t.removeEventListener("loadedmetadata",a),t.preload="none"},a=()=>{t.requestPictureInPicture().catch(s),n()};t.addEventListener("loadedmetadata",a),t.preload="metadata",setTimeout(()=>{t.readyState===0&&s(),n()},1e3)}else throw r}else throw r})}else He.pictureInPictureElement&&He.exitPictureInPicture()},mediaEvents:["enterpictureinpicture","leavepictureinpicture"]},mediaRenditionList:{get(i){var e;let{media:t}=i;return[...(e=t==null?void 0:t.videoRenditions)!=null?e:[]].map(s=>({...s}))},mediaEvents:["emptied","loadstart"],videoRenditionsEvents:["addrendition","removerendition"]},mediaRenditionSelected:{get(i){var e,t,s;let{media:r}=i;return(s=(t=r==null?void 0:r.videoRenditions)==null?void 0:t[(e=r.videoRenditions)==null?void 0:e.selectedIndex])==null?void 0:s.id},set(i,e){let{media:t}=e;if(!(t!=null&&t.videoRenditions)){console.warn("MediaController: Rendition selection not supported by this media.");return}let s=i,r=Array.prototype.findIndex.call(t.videoRenditions,n=>n.id==s);t.videoRenditions.selectedIndex!=r&&(t.videoRenditions.selectedIndex=r)},mediaEvents:["emptied"],videoRenditionsEvents:["addrendition","removerendition","change"]},mediaAudioTrackList:{get(i){var e;let{media:t}=i;return[...(e=t==null?void 0:t.audioTracks)!=null?e:[]]},mediaEvents:["emptied","loadstart"],audioTracksEvents:["addtrack","removetrack"]},mediaAudioTrackEnabled:{get(i){var e,t;let{media:s}=i;return(t=[...(e=s==null?void 0:s.audioTracks)!=null?e:[]].find(r=>r.enabled))==null?void 0:t.id},set(i,e){let{media:t}=e;if(!(t!=null&&t.audioTracks)){console.warn("MediaChrome: Audio track selection not supported by this media.");return}let s=i;for(let r of t.audioTracks)r.enabled=s==r.id},mediaEvents:["emptied"],audioTracksEvents:["addtrack","removetrack","change"]},mediaIsFullscreen:{get(i){return bA(i)},set(i,e,t){var s,r;i?(EA(e),t.detail&&!((s=e.media)!=null&&s.inert)&&((r=e.media)==null||r.focus())):yA(e)},rootEvents:["fullscreenchange","webkitfullscreenchange"],mediaEvents:["webkitbeginfullscreen","webkitendfullscreen","webkitpresentationmodechanged"]},mediaIsCasting:{get(i){var e;let{media:t}=i;return!(t!=null&&t.remote)||((e=t.remote)==null?void 0:e.state)==="disconnected"?!1:!!t.remote.state},set(i,e){var t,s;let{media:r}=e;if(r&&!(i&&((t=r.remote)==null?void 0:t.state)!=="disconnected")&&!(!i&&((s=r.remote)==null?void 0:s.state)!=="connected")){if(typeof r.remote.prompt!="function"){console.warn("MediaChrome: Casting is not supported in this environment");return}r.remote.prompt().catch(()=>{})}},remoteEvents:["connect","connecting","disconnect"]},mediaIsAirplaying:{get(){return!1},set(i,e){let{media:t}=e;if(t){if(!(t.webkitShowPlaybackTargetPicker&&L.WebKitPlaybackTargetAvailabilityEvent)){console.error("MediaChrome: received a request to select AirPlay but AirPlay is not supported in this environment");return}t.webkitShowPlaybackTargetPicker()}},mediaEvents:["webkitcurrentplaybacktargetiswirelesschanged"]},mediaFullscreenUnavailable:{get(i){let{media:e}=i;if(!AA||!d0(e))return Zt.UNSUPPORTED}},mediaPipUnavailable:{get(i){let{media:e}=i;if(!SA||!l0(e))return Zt.UNSUPPORTED;if(e!=null&&e.disablePictureInPicture)return Zt.UNAVAILABLE}},mediaVolumeUnavailable:{get(i){let{media:e}=i;if(Gc===!1||(e==null?void 0:e.volume)==null)return Zt.UNSUPPORTED},stateOwnersUpdateHandlers:[i=>{Gc==null&&CM.then(e=>i(e?void 0:Zt.UNSUPPORTED))}]},mediaCastUnavailable:{get(i,{availability:e="not-available"}={}){var t;let{media:s}=i;if(!LA||!((t=s==null?void 0:s.remote)!=null&&t.state))return Zt.UNSUPPORTED;if(!(e==null||e==="available"))return Zt.UNAVAILABLE},stateOwnersUpdateHandlers:[(i,e)=>{var t;let{media:s}=e;return s?(s.disableRemotePlayback||s.hasAttribute("disableremoteplayback")||(t=s==null?void 0:s.remote)==null||t.watchAvailability(n=>{i({availability:n?"available":"not-available"})}).catch(n=>{n.name==="NotSupportedError"?i({availability:null}):i({availability:"not-available"})}),()=>{var n;(n=s==null?void 0:s.remote)==null||n.cancelWatchAvailability().catch(()=>{})}):void 0}]},mediaAirplayUnavailable:{get(i,e){if(!IA)return Zt.UNSUPPORTED;if((e==null?void 0:e.availability)==="not-available")return Zt.UNAVAILABLE},mediaEvents:["webkitplaybacktargetavailabilitychanged"],stateOwnersUpdateHandlers:[(i,e)=>{var t;let{media:s}=e;return s?(s.disableRemotePlayback||s.hasAttribute("disableremoteplayback")||(t=s==null?void 0:s.remote)==null||t.watchAvailability(n=>{i({availability:n?"available":"not-available"})}).catch(n=>{n.name==="NotSupportedError"?i({availability:null}):i({availability:"not-available"})}),()=>{var n;(n=s==null?void 0:s.remote)==null||n.cancelWatchAvailability().catch(()=>{})}):void 0}]},mediaRenditionUnavailable:{get(i){var e;let{media:t}=i;if(!(t!=null&&t.videoRenditions))return Zt.UNSUPPORTED;if(!((e=t.videoRenditions)!=null&&e.length))return Zt.UNAVAILABLE},mediaEvents:["emptied","loadstart"],videoRenditionsEvents:["addrendition","removerendition"]},mediaAudioTrackUnavailable:{get(i){var e,t;let{media:s}=i;if(!(s!=null&&s.audioTracks))return Zt.UNSUPPORTED;if(((t=(e=s.audioTracks)==null?void 0:e.length)!=null?t:0)<=1)return Zt.UNAVAILABLE},mediaEvents:["emptied","loadstart"],audioTracksEvents:["addtrack","removetrack"]},mediaLang:{get(i){let{options:{mediaLang:e}={}}=i;return e!=null?e:"en"}}};var xA={[K.MEDIA_PREVIEW_REQUEST](i,e,{detail:t}){var s,r,n;let{media:a}=e,o=t!=null?t:void 0,l,d;if(a&&o!=null){let[f]=bn(a,{kind:Xt.METADATA,label:"thumbnails"}),m=Array.prototype.find.call((s=f==null?void 0:f.cues)!=null?s:[],(p,g,v)=>g===0?p.endTime>o:g===v.length-1?p.startTime<=o:p.startTime<=o&&p.endTime>o);if(m){let p=/'^(?:[a-z]+:)?\/\//i.test(m.text)||(r=a==null?void 0:a.querySelector('track[label="thumbnails"]'))==null?void 0:r.src,g=new URL(m.text,p);d=new URLSearchParams(g.hash).get("#xywh").split(",").map(b=>+b),l=g.href}}let u=i.mediaDuration.get(e),h=(n=i.mediaChaptersCues.get(e).find((f,m,p)=>m===p.length-1&&u===f.endTime?f.startTime<=o&&f.endTime>=o:f.startTime<=o&&f.endTime>o))==null?void 0:n.text;return t!=null&&h==null&&(h=""),{mediaPreviewTime:o,mediaPreviewImage:l,mediaPreviewCoords:d,mediaPreviewChapter:h}},[K.MEDIA_PAUSE_REQUEST](i,e){i["mediaPaused"].set(!0,e)},[K.MEDIA_PLAY_REQUEST](i,e){var t,s,r,n;let a="mediaPaused",l=i.mediaStreamType.get(e)===Ni.LIVE,d=!((t=e.options)!=null&&t.noAutoSeekToLive),u=i.mediaTargetLiveWindow.get(e)>0;if(l&&d&&!u){let c=(s=i.mediaSeekable.get(e))==null?void 0:s[1];if(c){let h=(n=(r=e.options)==null?void 0:r.seekToLiveOffset)!=null?n:0,f=c-h;i.mediaCurrentTime.set(f,e)}}i[a].set(!1,e)},[K.MEDIA_PLAYBACK_RATE_REQUEST](i,e,{detail:t}){let s="mediaPlaybackRate",r=t;i[s].set(r,e)},[K.MEDIA_MUTE_REQUEST](i,e){i["mediaMuted"].set(!0,e)},[K.MEDIA_UNMUTE_REQUEST](i,e){let t="mediaMuted";i.mediaVolume.get(e)||i.mediaVolume.set(.25,e),i[t].set(!1,e)},[K.MEDIA_LOOP_REQUEST](i,e,{detail:t}){let s="mediaLoop",r=!!t;return i[s].set(r,e),{mediaLoop:r}},[K.MEDIA_VOLUME_REQUEST](i,e,{detail:t}){let s="mediaVolume",r=t;r&&i.mediaMuted.get(e)&&i.mediaMuted.set(!1,e),i[s].set(r,e)},[K.MEDIA_SEEK_REQUEST](i,e,{detail:t}){let s="mediaCurrentTime",r=t;i[s].set(r,e)},[K.MEDIA_SEEK_TO_LIVE_REQUEST](i,e){var t,s,r;let n="mediaCurrentTime",a=(t=i.mediaSeekable.get(e))==null?void 0:t[1];if(Number.isNaN(Number(a)))return;let o=(r=(s=e.options)==null?void 0:s.seekToLiveOffset)!=null?r:0,l=a-o;i[n].set(l,e)},[K.MEDIA_SHOW_SUBTITLES_REQUEST](i,e,{detail:t}){var s;let{options:r}=e,n=ka(e),a=a0(t),o=(s=a[0])==null?void 0:s.language;o&&!r.noSubtitlesLangPref&&L.localStorage.setItem("media-chrome-pref-subtitles-lang",o),yn(Ar.SHOWING,n,a)},[K.MEDIA_DISABLE_SUBTITLES_REQUEST](i,e,{detail:t}){let s=ka(e),r=t!=null?t:[];yn(Ar.DISABLED,s,r)},[K.MEDIA_TOGGLE_SUBTITLES_REQUEST](i,e,{detail:t}){$c(e,t)},[K.MEDIA_RENDITION_REQUEST](i,e,{detail:t}){let s="mediaRenditionSelected",r=t;i[s].set(r,e)},[K.MEDIA_AUDIO_TRACK_REQUEST](i,e,{detail:t}){let s="mediaAudioTrackEnabled",r=t;i[s].set(r,e)},[K.MEDIA_ENTER_PIP_REQUEST](i,e){let t="mediaIsPip";i.mediaIsFullscreen.get(e)&&i.mediaIsFullscreen.set(!1,e),i[t].set(!0,e)},[K.MEDIA_EXIT_PIP_REQUEST](i,e){i["mediaIsPip"].set(!1,e)},[K.MEDIA_ENTER_FULLSCREEN_REQUEST](i,e,t){let s="mediaIsFullscreen";i.mediaIsPip.get(e)&&i.mediaIsPip.set(!1,e),i[s].set(!0,e,t)},[K.MEDIA_EXIT_FULLSCREEN_REQUEST](i,e){i["mediaIsFullscreen"].set(!1,e)},[K.MEDIA_ENTER_CAST_REQUEST](i,e){let t="mediaIsCasting";i.mediaIsFullscreen.get(e)&&i.mediaIsFullscreen.set(!1,e),i[t].set(!0,e)},[K.MEDIA_EXIT_CAST_REQUEST](i,e){i["mediaIsCasting"].set(!1,e)},[K.MEDIA_AIRPLAY_REQUEST](i,e){i["mediaIsAirplaying"].set(!0,e)}};var kA=({media:i,fullscreenElement:e,documentElement:t,stateMediator:s=Da,requestMap:r=xA,options:n={},monitorStateOwnersOnlyWithSubscriptions:a=!0})=>{let o=[],l={options:{...n}},d=Object.freeze({mediaPreviewTime:void 0,mediaPreviewImage:void 0,mediaPreviewCoords:void 0,mediaPreviewChapter:void 0}),u=p=>{p!=null&&(Hc(p,d)||(d=Object.freeze({...d,...p}),o.forEach(g=>g(d))))},c=()=>{let p=Object.entries(s).reduce((g,[v,{get:b}])=>(g[v]=b(l),g),{});u(p)},h={},f,m=async(p,g)=>{var v,b,y,T,A,R,I,x,D,S,C,P,N,$,H,U;let j=!!f;if(f={...l,...f!=null?f:{},...p},j)return;await RA(...Object.values(p));let q=o.length>0&&g===0&&a,Z=l.media!==f.media,re=((v=l.media)==null?void 0:v.textTracks)!==((b=f.media)==null?void 0:b.textTracks),V=((y=l.media)==null?void 0:y.videoRenditions)!==((T=f.media)==null?void 0:T.videoRenditions),G=((A=l.media)==null?void 0:A.audioTracks)!==((R=f.media)==null?void 0:R.audioTracks),ce=((I=l.media)==null?void 0:I.remote)!==((x=f.media)==null?void 0:x.remote),Se=l.documentElement!==f.documentElement,he=!!l.media&&(Z||q),be=!!((D=l.media)!=null&&D.textTracks)&&(re||q),vt=!!((S=l.media)!=null&&S.videoRenditions)&&(V||q),ut=!!((C=l.media)!=null&&C.audioTracks)&&(G||q),Ft=!!((P=l.media)!=null&&P.remote)&&(ce||q),si=!!l.documentElement&&(Se||q),Ii=he||be||vt||ut||Ft||si,Js=o.length===0&&g===1&&a,Hn=!!f.media&&(Z||Js),Gn=!!((N=f.media)!=null&&N.textTracks)&&(re||Js),qf=!!(($=f.media)!=null&&$.videoRenditions)&&(V||Js),ke=!!((H=f.media)!=null&&H.audioTracks)&&(G||Js),Et=!!((U=f.media)!=null&&U.remote)&&(ce||Js),Bt=!!f.documentElement&&(Se||Js),Yi=Hn||Gn||qf||ke||Et||Bt;if(!(Ii||Yi)){Object.entries(f).forEach(([De,ri])=>{l[De]=ri}),c(),f=void 0;return}Object.entries(s).forEach(([De,{get:ri,mediaEvents:Rd=[],textTracksEvents:Kn=[],videoRenditionsEvents:xd=[],audioTracksEvents:Kr=[],remoteEvents:kd=[],rootEvents:Yf=[],stateOwnersUpdateHandlers:Dd=[]}])=>{h[De]||(h[De]={});let Nt=et=>{let ct=ri(l,et);u({[De]:ct})},Je;Je=h[De].mediaEvents,Rd.forEach(et=>{Je&&he&&(l.media.removeEventListener(et,Je),h[De].mediaEvents=void 0),Hn&&(f.media.addEventListener(et,Nt),h[De].mediaEvents=Nt)}),Je=h[De].textTracksEvents,Kn.forEach(et=>{var ct,Li;Je&&be&&((ct=l.media.textTracks)==null||ct.removeEventListener(et,Je),h[De].textTracksEvents=void 0),Gn&&((Li=f.media.textTracks)==null||Li.addEventListener(et,Nt),h[De].textTracksEvents=Nt)}),Je=h[De].videoRenditionsEvents,xd.forEach(et=>{var ct,Li;Je&&vt&&((ct=l.media.videoRenditions)==null||ct.removeEventListener(et,Je),h[De].videoRenditionsEvents=void 0),qf&&((Li=f.media.videoRenditions)==null||Li.addEventListener(et,Nt),h[De].videoRenditionsEvents=Nt)}),Je=h[De].audioTracksEvents,Kr.forEach(et=>{var ct,Li;Je&&ut&&((ct=l.media.audioTracks)==null||ct.removeEventListener(et,Je),h[De].audioTracksEvents=void 0),ke&&((Li=f.media.audioTracks)==null||Li.addEventListener(et,Nt),h[De].audioTracksEvents=Nt)}),Je=h[De].remoteEvents,kd.forEach(et=>{var ct,Li;Je&&Ft&&((ct=l.media.remote)==null||ct.removeEventListener(et,Je),h[De].remoteEvents=void 0),Et&&((Li=f.media.remote)==null||Li.addEventListener(et,Nt),h[De].remoteEvents=Nt)}),Je=h[De].rootEvents,Yf.forEach(et=>{Je&&si&&(l.documentElement.removeEventListener(et,Je),h[De].rootEvents=void 0),Bt&&(f.documentElement.addEventListener(et,Nt),h[De].rootEvents=Nt)});let Cd=h[De].stateOwnersUpdateHandlers;if(Cd&&Ii&&(Array.isArray(Cd)?Cd:[Cd]).forEach(ct=>{typeof ct=="function"&&ct()}),Yi){let et=Dd.map(ct=>ct(Nt,f)).filter(ct=>typeof ct=="function");h[De].stateOwnersUpdateHandlers=et.length===1?et[0]:et}else Ii&&(h[De].stateOwnersUpdateHandlers=void 0)}),Object.entries(f).forEach(([De,ri])=>{l[De]=ri}),c(),f=void 0};return m({media:i,fullscreenElement:e,documentElement:t,options:n}),{dispatch(p){let{type:g,detail:v}=p;if(r[g]&&d.mediaErrorCode==null){u(r[g](s,l,p));return}g==="mediaelementchangerequest"?m({media:v}):g==="fullscreenelementchangerequest"?m({fullscreenElement:v}):g==="documentelementchangerequest"?m({documentElement:v}):g==="optionschangerequest"&&(Object.entries(v!=null?v:{}).forEach(([b,y])=>{l.options[b]=y}),c())},getState(){return d},subscribe(p){return m({},o.length+1),o.push(p),p(d),()=>{let g=o.indexOf(p);g>=0&&(m({},o.length-1),o.splice(g,1))}}}};var p0=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},ie=(i,e,t)=>(p0(i,e,"read from private field"),t?t.call(i):e.get(i)),yi=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},Hi=(i,e,t,s)=>(p0(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),_l=(i,e,t)=>(p0(i,e,"access private method"),t),Hs,Al,xe,rs,Sl,ss,Kc,Il,Vc,c0,_n,Wc,h0,f0,NA,UA=["ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Enter"," ","f","m","k","c","l","j",">","<","p"],DA=10,CA=.025,wA=.25,PM=.25,OM=2,W={DEFAULT_SUBTITLES:"defaultsubtitles",DEFAULT_STREAM_TYPE:"defaultstreamtype",DEFAULT_DURATION:"defaultduration",FULLSCREEN_ELEMENT:"fullscreenelement",HOTKEYS:"hotkeys",KEYBOARD_BACKWARD_SEEK_OFFSET:"keyboardbackwardseekoffset",KEYBOARD_FORWARD_SEEK_OFFSET:"keyboardforwardseekoffset",KEYBOARD_DOWN_VOLUME_STEP:"keyboarddownvolumestep",KEYBOARD_UP_VOLUME_STEP:"keyboardupvolumestep",KEYS_USED:"keysused",LANG:"lang",LOOP:"loop",LIVE_EDGE_OFFSET:"liveedgeoffset",NO_AUTO_SEEK_TO_LIVE:"noautoseektolive",NO_DEFAULT_STORE:"nodefaultstore",NO_HOTKEYS:"nohotkeys",NO_MUTED_PREF:"nomutedpref",NO_SUBTITLES_LANG_PREF:"nosubtitleslangpref",NO_VOLUME_PREF:"novolumepref",SEEK_TO_LIVE_OFFSET:"seektoliveoffset"},qc=class extends gn{constructor(){super(),yi(this,Vc),yi(this,Wc),yi(this,f0),this.mediaStateReceivers=[],this.associatedElementSubscriptions=new Map,yi(this,Hs,new Lr(this,W.HOTKEYS)),yi(this,Al,void 0),yi(this,xe,void 0),yi(this,rs,null),yi(this,Sl,void 0),yi(this,ss,void 0),yi(this,Kc,t=>{var s;(s=ie(this,xe))==null||s.dispatch(t)}),yi(this,Il,void 0),yi(this,_n,t=>{let{key:s,shiftKey:r}=t;if(!(r&&(s==="/"||s==="?")||UA.includes(s))){this.removeEventListener("keyup",ie(this,_n));return}this.keyboardShortcutHandler(t)}),this.associateElement(this);let e={};Hi(this,Sl,t=>{Object.entries(t).forEach(([s,r])=>{if(s in e&&e[s]===r)return;this.propagateMediaState(s,r);let n=s.toLowerCase(),a=new L.CustomEvent(Y_[n],{composed:!0,detail:r});this.dispatchEvent(a)}),e=t})}static get observedAttributes(){return super.observedAttributes.concat(W.NO_HOTKEYS,W.HOTKEYS,W.DEFAULT_STREAM_TYPE,W.DEFAULT_SUBTITLES,W.DEFAULT_DURATION,W.NO_MUTED_PREF,W.NO_VOLUME_PREF,W.LANG,W.LOOP,W.LIVE_EDGE_OFFSET,W.SEEK_TO_LIVE_OFFSET,W.NO_AUTO_SEEK_TO_LIVE)}get mediaStore(){return ie(this,xe)}set mediaStore(e){var t,s;if(ie(this,xe)&&((t=ie(this,ss))==null||t.call(this),Hi(this,ss,void 0)),Hi(this,xe,e),!ie(this,xe)&&!this.hasAttribute(W.NO_DEFAULT_STORE)){_l(this,Vc,c0).call(this);return}Hi(this,ss,(s=ie(this,xe))==null?void 0:s.subscribe(ie(this,Sl)))}get fullscreenElement(){var e;return(e=ie(this,Al))!=null?e:this}set fullscreenElement(e){var t;this.hasAttribute(W.FULLSCREEN_ELEMENT)&&this.removeAttribute(W.FULLSCREEN_ELEMENT),Hi(this,Al,e),(t=ie(this,xe))==null||t.dispatch({type:"fullscreenelementchangerequest",detail:this.fullscreenElement})}get defaultSubtitles(){return le(this,W.DEFAULT_SUBTITLES)}set defaultSubtitles(e){de(this,W.DEFAULT_SUBTITLES,e)}get defaultStreamType(){return pe(this,W.DEFAULT_STREAM_TYPE)}set defaultStreamType(e){me(this,W.DEFAULT_STREAM_TYPE,e)}get defaultDuration(){return ye(this,W.DEFAULT_DURATION)}set defaultDuration(e){Re(this,W.DEFAULT_DURATION,e)}get noHotkeys(){return le(this,W.NO_HOTKEYS)}set noHotkeys(e){de(this,W.NO_HOTKEYS,e)}get keysUsed(){return pe(this,W.KEYS_USED)}set keysUsed(e){me(this,W.KEYS_USED,e)}get liveEdgeOffset(){return ye(this,W.LIVE_EDGE_OFFSET)}set liveEdgeOffset(e){Re(this,W.LIVE_EDGE_OFFSET,e)}get noAutoSeekToLive(){return le(this,W.NO_AUTO_SEEK_TO_LIVE)}set noAutoSeekToLive(e){de(this,W.NO_AUTO_SEEK_TO_LIVE,e)}get noVolumePref(){return le(this,W.NO_VOLUME_PREF)}set noVolumePref(e){de(this,W.NO_VOLUME_PREF,e)}get noMutedPref(){return le(this,W.NO_MUTED_PREF)}set noMutedPref(e){de(this,W.NO_MUTED_PREF,e)}get noSubtitlesLangPref(){return le(this,W.NO_SUBTITLES_LANG_PREF)}set noSubtitlesLangPref(e){de(this,W.NO_SUBTITLES_LANG_PREF,e)}get noDefaultStore(){return le(this,W.NO_DEFAULT_STORE)}set noDefaultStore(e){de(this,W.NO_DEFAULT_STORE,e)}attributeChangedCallback(e,t,s){var r,n,a,o,l,d,u,c,h,f,m,p;if(super.attributeChangedCallback(e,t,s),e===W.NO_HOTKEYS)s!==t&&s===""?(this.hasAttribute(W.HOTKEYS)&&console.warn("Media Chrome: Both `hotkeys` and `nohotkeys` have been set. All hotkeys will be disabled."),this.disableHotkeys()):s!==t&&s===null&&this.enableHotkeys();else if(e===W.HOTKEYS)ie(this,Hs).value=s;else if(e===W.DEFAULT_SUBTITLES&&s!==t)(r=ie(this,xe))==null||r.dispatch({type:"optionschangerequest",detail:{defaultSubtitles:this.hasAttribute(W.DEFAULT_SUBTITLES)}});else if(e===W.DEFAULT_STREAM_TYPE)(a=ie(this,xe))==null||a.dispatch({type:"optionschangerequest",detail:{defaultStreamType:(n=this.getAttribute(W.DEFAULT_STREAM_TYPE))!=null?n:void 0}});else if(e===W.LIVE_EDGE_OFFSET&&s!==t)(o=ie(this,xe))==null||o.dispatch({type:"optionschangerequest",detail:{liveEdgeOffset:this.hasAttribute(W.LIVE_EDGE_OFFSET)?+this.getAttribute(W.LIVE_EDGE_OFFSET):void 0,seekToLiveOffset:this.hasAttribute(W.SEEK_TO_LIVE_OFFSET)?+this.getAttribute(W.SEEK_TO_LIVE_OFFSET):this.hasAttribute(W.LIVE_EDGE_OFFSET)?+this.getAttribute(W.LIVE_EDGE_OFFSET):void 0}});else if(e===W.SEEK_TO_LIVE_OFFSET&&s!==t)(l=ie(this,xe))==null||l.dispatch({type:"optionschangerequest",detail:{seekToLiveOffset:this.hasAttribute(W.SEEK_TO_LIVE_OFFSET)?+this.getAttribute(W.SEEK_TO_LIVE_OFFSET):this.hasAttribute(W.LIVE_EDGE_OFFSET)?+this.getAttribute(W.LIVE_EDGE_OFFSET):void 0}});else if(e===W.NO_AUTO_SEEK_TO_LIVE)(d=ie(this,xe))==null||d.dispatch({type:"optionschangerequest",detail:{noAutoSeekToLive:this.hasAttribute(W.NO_AUTO_SEEK_TO_LIVE)}});else if(e===W.FULLSCREEN_ELEMENT){let g=s?(u=this.getRootNode())==null?void 0:u.getElementById(s):void 0;Hi(this,Al,g),(c=ie(this,xe))==null||c.dispatch({type:"fullscreenelementchangerequest",detail:this.fullscreenElement})}else e===W.LANG&&s!==t?(iA(s),(h=ie(this,xe))==null||h.dispatch({type:"optionschangerequest",detail:{mediaLang:s}})):e===W.LOOP&&s!==t?(f=ie(this,xe))==null||f.dispatch({type:K.MEDIA_LOOP_REQUEST,detail:s!=null}):e===W.NO_VOLUME_PREF&&s!==t?(m=ie(this,xe))==null||m.dispatch({type:"optionschangerequest",detail:{noVolumePref:this.hasAttribute(W.NO_VOLUME_PREF)}}):e===W.NO_MUTED_PREF&&s!==t&&((p=ie(this,xe))==null||p.dispatch({type:"optionschangerequest",detail:{noMutedPref:this.hasAttribute(W.NO_MUTED_PREF)}}))}connectedCallback(){var e,t,s;this.associateElement(this),!ie(this,xe)&&!this.hasAttribute(W.NO_DEFAULT_STORE)&&_l(this,Vc,c0).call(this),(e=ie(this,xe))==null||e.dispatch({type:"documentelementchangerequest",detail:He}),(t=ie(this,xe))==null||t.dispatch({type:"fullscreenelementchangerequest",detail:this.fullscreenElement}),super.connectedCallback(),ie(this,xe)&&!ie(this,ss)&&Hi(this,ss,(s=ie(this,xe))==null?void 0:s.subscribe(ie(this,Sl))),ie(this,Il)!==void 0&&ie(this,xe)&&this.media&&setTimeout(()=>{var r,n,a;(n=(r=this.media)==null?void 0:r.textTracks)!=null&&n.length&&((a=ie(this,xe))==null||a.dispatch({type:K.MEDIA_TOGGLE_SUBTITLES_REQUEST,detail:ie(this,Il)}))},0),this.hasAttribute(W.NO_HOTKEYS)?this.disableHotkeys():this.enableHotkeys()}disconnectedCallback(){var e,t,s,r,n,a;if((e=super.disconnectedCallback)==null||e.call(this),this.disableHotkeys(),ie(this,xe)){let o=ie(this,xe).getState();Hi(this,Il,!!((t=o.mediaSubtitlesShowing)!=null&&t.length)),(s=ie(this,xe))==null||s.dispatch({type:"fullscreenelementchangerequest",detail:void 0}),(r=ie(this,xe))==null||r.dispatch({type:"documentelementchangerequest",detail:void 0}),(n=ie(this,xe))==null||n.dispatch({type:K.MEDIA_TOGGLE_SUBTITLES_REQUEST,detail:!1})}ie(this,ss)&&((a=ie(this,ss))==null||a.call(this),Hi(this,ss,void 0)),this.unassociateElement(this),ie(this,rs)&&(ie(this,rs).remove(),Hi(this,rs,null))}mediaSetCallback(e){var t;super.mediaSetCallback(e),(t=ie(this,xe))==null||t.dispatch({type:"mediaelementchangerequest",detail:e}),e.hasAttribute("tabindex")||(e.tabIndex=-1)}mediaUnsetCallback(e){var t;super.mediaUnsetCallback(e),(t=ie(this,xe))==null||t.dispatch({type:"mediaelementchangerequest",detail:void 0})}propagateMediaState(e,t){OA(this.mediaStateReceivers,e,t)}associateElement(e){if(!e)return;let{associatedElementSubscriptions:t}=this;if(t.has(e))return;let s=this.registerMediaStateReceiver.bind(this),r=this.unregisterMediaStateReceiver.bind(this),n=HM(e,s,r);Object.values(K).forEach(a=>{e.addEventListener(a,ie(this,Kc))}),t.set(e,n)}unassociateElement(e){if(!e)return;let{associatedElementSubscriptions:t}=this;if(!t.has(e))return;t.get(e)(),t.delete(e),Object.values(K).forEach(r=>{e.removeEventListener(r,ie(this,Kc))})}registerMediaStateReceiver(e){if(!e)return;let t=this.mediaStateReceivers;t.indexOf(e)>-1||(t.push(e),ie(this,xe)&&Object.entries(ie(this,xe).getState()).forEach(([r,n])=>{OA([e],r,n)}))}unregisterMediaStateReceiver(e){let t=this.mediaStateReceivers,s=t.indexOf(e);s<0||t.splice(s,1)}enableHotkeys(){this.addEventListener("keydown",_l(this,Wc,h0))}disableHotkeys(){this.removeEventListener("keydown",_l(this,Wc,h0)),this.removeEventListener("keyup",ie(this,_n))}get hotkeys(){return ie(this,Hs)}set hotkeys(e){me(this,W.HOTKEYS,e)}keyboardShortcutHandler(e){var t,s,r,n,a,o,l,d,u;let c=e.target;if(((r=(s=(t=c.getAttribute(W.KEYS_USED))==null?void 0:t.split(" "))!=null?s:c==null?void 0:c.keysUsed)!=null?r:[]).map(v=>v==="Space"?" ":v).filter(Boolean).includes(e.key))return;let f,m,p;if(!(ie(this,Hs).contains(`no${e.key.toLowerCase()}`)||e.key===" "&&ie(this,Hs).contains("nospace")||e.shiftKey&&(e.key==="/"||e.key==="?")&&ie(this,Hs).contains("noshift+/")))switch(e.key){case" ":case"k":f=ie(this,xe).getState().mediaPaused?K.MEDIA_PLAY_REQUEST:K.MEDIA_PAUSE_REQUEST,this.dispatchEvent(new L.CustomEvent(f,{composed:!0,bubbles:!0}));break;case"m":f=this.mediaStore.getState().mediaVolumeLevel==="off"?K.MEDIA_UNMUTE_REQUEST:K.MEDIA_MUTE_REQUEST,this.dispatchEvent(new L.CustomEvent(f,{composed:!0,bubbles:!0}));break;case"f":f=this.mediaStore.getState().mediaIsFullscreen?K.MEDIA_EXIT_FULLSCREEN_REQUEST:K.MEDIA_ENTER_FULLSCREEN_REQUEST,this.dispatchEvent(new L.CustomEvent(f,{composed:!0,bubbles:!0}));break;case"c":this.dispatchEvent(new L.CustomEvent(K.MEDIA_TOGGLE_SUBTITLES_REQUEST,{composed:!0,bubbles:!0}));break;case"ArrowLeft":case"j":{let v=this.hasAttribute(W.KEYBOARD_BACKWARD_SEEK_OFFSET)?+this.getAttribute(W.KEYBOARD_BACKWARD_SEEK_OFFSET):DA;m=Math.max(((n=this.mediaStore.getState().mediaCurrentTime)!=null?n:0)-v,0),p=new L.CustomEvent(K.MEDIA_SEEK_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case"ArrowRight":case"l":{let v=this.hasAttribute(W.KEYBOARD_FORWARD_SEEK_OFFSET)?+this.getAttribute(W.KEYBOARD_FORWARD_SEEK_OFFSET):DA;m=Math.max(((a=this.mediaStore.getState().mediaCurrentTime)!=null?a:0)+v,0),p=new L.CustomEvent(K.MEDIA_SEEK_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case"ArrowUp":{let v=this.hasAttribute(W.KEYBOARD_UP_VOLUME_STEP)?+this.getAttribute(W.KEYBOARD_UP_VOLUME_STEP):CA;m=Math.min(((o=this.mediaStore.getState().mediaVolume)!=null?o:1)+v,1),p=new L.CustomEvent(K.MEDIA_VOLUME_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case"ArrowDown":{let v=this.hasAttribute(W.KEYBOARD_DOWN_VOLUME_STEP)?+this.getAttribute(W.KEYBOARD_DOWN_VOLUME_STEP):CA;m=Math.max(((l=this.mediaStore.getState().mediaVolume)!=null?l:1)-v,0),p=new L.CustomEvent(K.MEDIA_VOLUME_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case"<":{let v=(d=this.mediaStore.getState().mediaPlaybackRate)!=null?d:1;m=Math.max(v-wA,PM).toFixed(2),p=new L.CustomEvent(K.MEDIA_PLAYBACK_RATE_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case">":{let v=(u=this.mediaStore.getState().mediaPlaybackRate)!=null?u:1;m=Math.min(v+wA,OM).toFixed(2),p=new L.CustomEvent(K.MEDIA_PLAYBACK_RATE_REQUEST,{composed:!0,bubbles:!0,detail:m}),this.dispatchEvent(p);break}case"/":case"?":{e.shiftKey&&_l(this,f0,NA).call(this);break}case"p":{f=this.mediaStore.getState().mediaIsPip?K.MEDIA_EXIT_PIP_REQUEST:K.MEDIA_ENTER_PIP_REQUEST,p=new L.CustomEvent(f,{composed:!0,bubbles:!0}),this.dispatchEvent(p);break}default:break}}};Hs=new WeakMap;Al=new WeakMap;xe=new WeakMap;rs=new WeakMap;Sl=new WeakMap;ss=new WeakMap;Kc=new WeakMap;Il=new WeakMap;Vc=new WeakSet;c0=function(){var i;this.mediaStore=kA({media:this.media,fullscreenElement:this.fullscreenElement,options:{defaultSubtitles:this.hasAttribute(W.DEFAULT_SUBTITLES),defaultDuration:this.hasAttribute(W.DEFAULT_DURATION)?+this.getAttribute(W.DEFAULT_DURATION):void 0,defaultStreamType:(i=this.getAttribute(W.DEFAULT_STREAM_TYPE))!=null?i:void 0,liveEdgeOffset:this.hasAttribute(W.LIVE_EDGE_OFFSET)?+this.getAttribute(W.LIVE_EDGE_OFFSET):void 0,seekToLiveOffset:this.hasAttribute(W.SEEK_TO_LIVE_OFFSET)?+this.getAttribute(W.SEEK_TO_LIVE_OFFSET):this.hasAttribute(W.LIVE_EDGE_OFFSET)?+this.getAttribute(W.LIVE_EDGE_OFFSET):void 0,noAutoSeekToLive:this.hasAttribute(W.NO_AUTO_SEEK_TO_LIVE),noVolumePref:this.hasAttribute(W.NO_VOLUME_PREF),noMutedPref:this.hasAttribute(W.NO_MUTED_PREF),noSubtitlesLangPref:this.hasAttribute(W.NO_SUBTITLES_LANG_PREF)}})};_n=new WeakMap;Wc=new WeakSet;h0=function(i){var e;let{metaKey:t,altKey:s,key:r,shiftKey:n}=i,a=n&&(r==="/"||r==="?");if(a&&((e=ie(this,rs))!=null&&e.open)){this.removeEventListener("keyup",ie(this,_n));return}if(t||s||!a&&!UA.includes(r)){this.removeEventListener("keyup",ie(this,_n));return}let o=i.target,l=o instanceof HTMLElement&&(o.tagName.toLowerCase()==="media-volume-range"||o.tagName.toLowerCase()==="media-time-range");[" ","ArrowLeft","ArrowRight","ArrowUp","ArrowDown"].includes(r)&&!(ie(this,Hs).contains(`no${r.toLowerCase()}`)||r===" "&&ie(this,Hs).contains("nospace"))&&!l&&i.preventDefault(),this.addEventListener("keyup",ie(this,_n),{once:!0})};f0=new WeakSet;NA=function(){ie(this,rs)||(Hi(this,rs,He.createElement("media-keyboard-shortcuts-dialog")),this.appendChild(ie(this,rs))),ie(this,rs).open=!0};var NM=Object.values(_),UM=Object.values(Qg),FA=i=>{var e,t,s,r;let{observedAttributes:n}=i.constructor;!n&&((e=i.nodeName)!=null&&e.includes("-"))&&(L.customElements.upgrade(i),{observedAttributes:n}=i.constructor);let a=(r=(s=(t=i==null?void 0:i.getAttribute)==null?void 0:t.call(i,ge.MEDIA_CHROME_ATTRIBUTES))==null?void 0:s.split)==null?void 0:r.call(s,/\s+/);return Array.isArray(n||a)?(n||a).filter(o=>NM.includes(o)):[]},FM=i=>{var e,t;return(e=i.nodeName)!=null&&e.includes("-")&&L.customElements.get((t=i.nodeName)==null?void 0:t.toLowerCase())&&!(i instanceof L.customElements.get(i.nodeName.toLowerCase()))&&L.customElements.upgrade(i),UM.some(s=>s in i)},m0=i=>FM(i)||!!FA(i).length,MA=i=>{var e;return(e=i==null?void 0:i.join)==null?void 0:e.call(i,":")},PA={[_.MEDIA_SUBTITLES_LIST]:$s,[_.MEDIA_SUBTITLES_SHOWING]:$s,[_.MEDIA_SEEKABLE]:MA,[_.MEDIA_BUFFERED]:i=>i==null?void 0:i.map(MA).join(" "),[_.MEDIA_PREVIEW_COORDS]:i=>i==null?void 0:i.join(" "),[_.MEDIA_RENDITION_LIST]:z_,[_.MEDIA_AUDIO_TRACK_LIST]:X_},BM=async(i,e,t)=>{var s,r;if(i.isConnected||await bc(0),typeof t=="boolean"||t==null)return de(i,e,t);if(typeof t=="number")return Re(i,e,t);if(typeof t=="string")return me(i,e,t);if(Array.isArray(t)&&!t.length)return i.removeAttribute(e);let n=(r=(s=PA[e])==null?void 0:s.call(PA,t))!=null?r:t;return i.setAttribute(e,n)},$M=i=>{var e;return!!((e=i.closest)!=null&&e.call(i,'*[slot="media"]'))},Tn=(i,e)=>{if($M(i))return;let t=(r,n)=>{var a,o;m0(r)&&n(r);let{children:l=[]}=r!=null?r:{},d=(o=(a=r==null?void 0:r.shadowRoot)==null?void 0:a.children)!=null?o:[];[...l,...d].forEach(c=>Tn(c,n))},s=i==null?void 0:i.nodeName.toLowerCase();if(s.includes("-")&&!m0(i)){L.customElements.whenDefined(s).then(()=>{t(i,e)});return}t(i,e)},OA=(i,e,t)=>{i.forEach(s=>{if(e in s){s[e]=t;return}let r=FA(s),n=e.toLowerCase();r.includes(n)&&BM(s,n,t)})},HM=(i,e,t)=>{Tn(i,e);let s=u=>{var c;let h=(c=u==null?void 0:u.composedPath()[0])!=null?c:u.target;e(h)},r=u=>{var c;let h=(c=u==null?void 0:u.composedPath()[0])!=null?c:u.target;t(h)};i.addEventListener(K.REGISTER_MEDIA_STATE_RECEIVER,s),i.addEventListener(K.UNREGISTER_MEDIA_STATE_RECEIVER,r);let n=u=>{u.forEach(c=>{let{addedNodes:h=[],removedNodes:f=[],type:m,target:p,attributeName:g}=c;m==="childList"?(Array.prototype.forEach.call(h,v=>Tn(v,e)),Array.prototype.forEach.call(f,v=>Tn(v,t))):m==="attributes"&&g===ge.MEDIA_CHROME_ATTRIBUTES&&(m0(p)?e(p):t(p))})},a=[],o=u=>{let c=u.target;c.name!=="media"&&(a.forEach(h=>Tn(h,t)),a=[...c.assignedElements({flatten:!0})],a.forEach(h=>Tn(h,e)))};i.addEventListener("slotchange",o);let l=new MutationObserver(n);return l.observe(i,{childList:!0,attributes:!0,subtree:!0}),()=>{Tn(i,t),i.removeEventListener("slotchange",o),l.disconnect(),i.removeEventListener(K.REGISTER_MEDIA_STATE_RECEIVER,s),i.removeEventListener(K.UNREGISTER_MEDIA_STATE_RECEIVER,r)}};L.customElements.get("media-controller")||L.customElements.define("media-controller",qc);var g0=qc;var Ca={PLACEMENT:"placement",BOUNDS:"bounds"};function GM(i){return`
299
299
  <style>
300
300
  :host {
301
301
  --_tooltip-background-color: var(--media-tooltip-background-color, var(--media-secondary-color, rgba(20, 20, 30, .7)));
@@ -567,7 +567,7 @@ Schedule: ${l.map(p=>Ci(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Remo
567
567
  `}function iP(){return`
568
568
  <slot name="tooltip-enter">${F("Start casting")}</slot>
569
569
  <slot name="tooltip-exit">${F("Stop casting")}</slot>
570
- `}var WA=i=>{let e=i.mediaIsCasting?F("stop casting"):F("start casting");i.setAttribute("aria-label",e)},xl=class extends Pe{static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_IS_CASTING,_.MEDIA_CAST_UNAVAILABLE]}connectedCallback(){super.connectedCallback(),WA(this)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===_.MEDIA_IS_CASTING&&WA(this)}get mediaIsCasting(){return le(this,_.MEDIA_IS_CASTING)}set mediaIsCasting(e){de(this,_.MEDIA_IS_CASTING,e)}get mediaCastUnavailable(){return pe(this,_.MEDIA_CAST_UNAVAILABLE)}set mediaCastUnavailable(e){me(this,_.MEDIA_CAST_UNAVAILABLE,e)}handleClick(){let e=this.mediaIsCasting?K.MEDIA_EXIT_CAST_REQUEST:K.MEDIA_ENTER_CAST_REQUEST;this.dispatchEvent(new L.CustomEvent(e,{composed:!0,bubbles:!0}))}};xl.getSlotTemplateHTML=tP;xl.getTooltipContentHTML=iP;L.customElements.get("media-cast-button")||L.customElements.define("media-cast-button",xl);var I0=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},Sn=(i,e,t)=>(I0(i,e,"read from private field"),t?t.call(i):e.get(i)),Gs=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},L0=(i,e,t,s)=>(I0(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),An=(i,e,t)=>(I0(i,e,"access private method"),t),Xc,Dl,In,Qc,y0,T0,qA,b0,YA,_0,jA,A0,zA,S0,QA;function sP(i){return`
570
+ `}var WA=i=>{let e=i.mediaIsCasting?F("stop casting"):F("start casting");i.setAttribute("aria-label",e)},xl=class extends Pe{static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_IS_CASTING,_.MEDIA_CAST_UNAVAILABLE]}connectedCallback(){super.connectedCallback(),WA(this)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===_.MEDIA_IS_CASTING&&WA(this)}get mediaIsCasting(){return le(this,_.MEDIA_IS_CASTING)}set mediaIsCasting(e){de(this,_.MEDIA_IS_CASTING,e)}get mediaCastUnavailable(){return pe(this,_.MEDIA_CAST_UNAVAILABLE)}set mediaCastUnavailable(e){me(this,_.MEDIA_CAST_UNAVAILABLE,e)}handleClick(){let e=this.mediaIsCasting?K.MEDIA_EXIT_CAST_REQUEST:K.MEDIA_ENTER_CAST_REQUEST;this.dispatchEvent(new L.CustomEvent(e,{composed:!0,bubbles:!0}))}};xl.getSlotTemplateHTML=tP;xl.getTooltipContentHTML=iP;L.customElements.get("media-cast-button")||L.customElements.define("media-cast-button",xl);var I0=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},Sn=(i,e,t)=>(I0(i,e,"read from private field"),t?t.call(i):e.get(i)),Gs=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},L0=(i,e,t,s)=>(I0(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),An=(i,e,t)=>(I0(i,e,"access private method"),t),Xc,Dl,In,Qc,y0,b0,qA,T0,YA,_0,jA,A0,zA,S0,QA;function sP(i){return`
571
571
  <style>
572
572
  :host {
573
573
  font: var(--media-font,
@@ -610,7 +610,7 @@ Schedule: ${l.map(p=>Ci(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Remo
610
610
  ${this.getSlotTemplateHTML(i)}
611
611
  `}function rP(i){return`
612
612
  <slot id="content"></slot>
613
- `}var kl={OPEN:"open",ANCHOR:"anchor"},as=class extends L.HTMLElement{constructor(){super(),Gs(this,Qc),Gs(this,T0),Gs(this,b0),Gs(this,_0),Gs(this,A0),Gs(this,S0),Gs(this,Xc,!1),Gs(this,Dl,null),Gs(this,In,null)}static get observedAttributes(){return[kl.OPEN,kl.ANCHOR]}get open(){return le(this,kl.OPEN)}set open(e){de(this,kl.OPEN,e)}handleEvent(e){switch(e.type){case"invoke":An(this,_0,jA).call(this,e);break;case"focusout":An(this,A0,zA).call(this,e);break;case"keydown":An(this,S0,QA).call(this,e);break}}connectedCallback(){An(this,Qc,y0).call(this),this.role||(this.role="dialog"),this.addEventListener("invoke",this),this.addEventListener("focusout",this),this.addEventListener("keydown",this)}disconnectedCallback(){this.removeEventListener("invoke",this),this.removeEventListener("focusout",this),this.removeEventListener("keydown",this)}attributeChangedCallback(e,t,s){An(this,Qc,y0).call(this),e===kl.OPEN&&s!==t&&(this.open?An(this,T0,qA).call(this):An(this,b0,YA).call(this))}focus(){L0(this,Dl,pl());let e=!this.dispatchEvent(new Event("focus",{composed:!0,cancelable:!0})),t=!this.dispatchEvent(new Event("focusin",{composed:!0,bubbles:!0,cancelable:!0}));if(e||t)return;let s=this.querySelector('[autofocus], [tabindex]:not([tabindex="-1"]), [role="menu"]');s==null||s.focus()}get keysUsed(){return["Escape","Tab"]}};Xc=new WeakMap;Dl=new WeakMap;In=new WeakMap;Qc=new WeakSet;y0=function(){if(!Sn(this,Xc)&&(L0(this,Xc,!0),!this.shadowRoot)){this.attachShadow(this.constructor.shadowRootOptions);let i=Qe(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(i),queueMicrotask(()=>{let{style:e}=je(this.shadowRoot,":host");e.setProperty("transition","display .15s, visibility .15s, opacity .15s ease-in, transform .15s ease-in")})}};T0=new WeakSet;qA=function(){var i;(i=Sn(this,In))==null||i.setAttribute("aria-expanded","true"),this.dispatchEvent(new Event("open",{composed:!0,bubbles:!0})),this.addEventListener("transitionend",()=>this.focus(),{once:!0})};b0=new WeakSet;YA=function(){var i;(i=Sn(this,In))==null||i.setAttribute("aria-expanded","false"),this.dispatchEvent(new Event("close",{composed:!0,bubbles:!0}))};_0=new WeakSet;jA=function(i){L0(this,In,i.relatedTarget),Kt(this,i.relatedTarget)||(this.open=!this.open)};A0=new WeakSet;zA=function(i){var e;Kt(this,i.relatedTarget)||((e=Sn(this,Dl))==null||e.focus(),Sn(this,In)&&Sn(this,In)!==i.relatedTarget&&this.open&&(this.open=!1))};S0=new WeakSet;QA=function(i){var e,t,s,r,n;let{key:a,ctrlKey:o,altKey:l,metaKey:d}=i;o||l||d||this.keysUsed.includes(a)&&(i.preventDefault(),i.stopPropagation(),a==="Tab"?(i.shiftKey?(t=(e=this.previousElementSibling)==null?void 0:e.focus)==null||t.call(e):(r=(s=this.nextElementSibling)==null?void 0:s.focus)==null||r.call(s),this.blur()):a==="Escape"&&((n=Sn(this,Dl))==null||n.focus(),this.open=!1))};as.shadowRootOptions={mode:"open"};as.getTemplateHTML=sP;as.getSlotTemplateHTML=rP;L.customElements.get("media-chrome-dialog")||L.customElements.define("media-chrome-dialog",as);var M0=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},st=(i,e,t)=>(M0(i,e,"read from private field"),t?t.call(i):e.get(i)),Mt=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},kr=(i,e,t,s)=>(M0(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),Gi=(i,e,t)=>(M0(i,e,"access private method"),t),os,oh,Zc,Jc,Ki,nh,eh,th,ih,P0,XA,sh,R0,rh,x0,ah,O0,k0,ZA,D0,JA,C0,eS,w0,tS;function nP(i){return`
613
+ `}var kl={OPEN:"open",ANCHOR:"anchor"},as=class extends L.HTMLElement{constructor(){super(),Gs(this,Qc),Gs(this,b0),Gs(this,T0),Gs(this,_0),Gs(this,A0),Gs(this,S0),Gs(this,Xc,!1),Gs(this,Dl,null),Gs(this,In,null)}static get observedAttributes(){return[kl.OPEN,kl.ANCHOR]}get open(){return le(this,kl.OPEN)}set open(e){de(this,kl.OPEN,e)}handleEvent(e){switch(e.type){case"invoke":An(this,_0,jA).call(this,e);break;case"focusout":An(this,A0,zA).call(this,e);break;case"keydown":An(this,S0,QA).call(this,e);break}}connectedCallback(){An(this,Qc,y0).call(this),this.role||(this.role="dialog"),this.addEventListener("invoke",this),this.addEventListener("focusout",this),this.addEventListener("keydown",this)}disconnectedCallback(){this.removeEventListener("invoke",this),this.removeEventListener("focusout",this),this.removeEventListener("keydown",this)}attributeChangedCallback(e,t,s){An(this,Qc,y0).call(this),e===kl.OPEN&&s!==t&&(this.open?An(this,b0,qA).call(this):An(this,T0,YA).call(this))}focus(){L0(this,Dl,pl());let e=!this.dispatchEvent(new Event("focus",{composed:!0,cancelable:!0})),t=!this.dispatchEvent(new Event("focusin",{composed:!0,bubbles:!0,cancelable:!0}));if(e||t)return;let s=this.querySelector('[autofocus], [tabindex]:not([tabindex="-1"]), [role="menu"]');s==null||s.focus()}get keysUsed(){return["Escape","Tab"]}};Xc=new WeakMap;Dl=new WeakMap;In=new WeakMap;Qc=new WeakSet;y0=function(){if(!Sn(this,Xc)&&(L0(this,Xc,!0),!this.shadowRoot)){this.attachShadow(this.constructor.shadowRootOptions);let i=Qe(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(i),queueMicrotask(()=>{let{style:e}=je(this.shadowRoot,":host");e.setProperty("transition","display .15s, visibility .15s, opacity .15s ease-in, transform .15s ease-in")})}};b0=new WeakSet;qA=function(){var i;(i=Sn(this,In))==null||i.setAttribute("aria-expanded","true"),this.dispatchEvent(new Event("open",{composed:!0,bubbles:!0})),this.addEventListener("transitionend",()=>this.focus(),{once:!0})};T0=new WeakSet;YA=function(){var i;(i=Sn(this,In))==null||i.setAttribute("aria-expanded","false"),this.dispatchEvent(new Event("close",{composed:!0,bubbles:!0}))};_0=new WeakSet;jA=function(i){L0(this,In,i.relatedTarget),Kt(this,i.relatedTarget)||(this.open=!this.open)};A0=new WeakSet;zA=function(i){var e;Kt(this,i.relatedTarget)||((e=Sn(this,Dl))==null||e.focus(),Sn(this,In)&&Sn(this,In)!==i.relatedTarget&&this.open&&(this.open=!1))};S0=new WeakSet;QA=function(i){var e,t,s,r,n;let{key:a,ctrlKey:o,altKey:l,metaKey:d}=i;o||l||d||this.keysUsed.includes(a)&&(i.preventDefault(),i.stopPropagation(),a==="Tab"?(i.shiftKey?(t=(e=this.previousElementSibling)==null?void 0:e.focus)==null||t.call(e):(r=(s=this.nextElementSibling)==null?void 0:s.focus)==null||r.call(s),this.blur()):a==="Escape"&&((n=Sn(this,Dl))==null||n.focus(),this.open=!1))};as.shadowRootOptions={mode:"open"};as.getTemplateHTML=sP;as.getSlotTemplateHTML=rP;L.customElements.get("media-chrome-dialog")||L.customElements.define("media-chrome-dialog",as);var M0=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},st=(i,e,t)=>(M0(i,e,"read from private field"),t?t.call(i):e.get(i)),Mt=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},kr=(i,e,t,s)=>(M0(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),Gi=(i,e,t)=>(M0(i,e,"access private method"),t),os,oh,Zc,Jc,Ki,nh,eh,th,ih,P0,XA,sh,R0,rh,x0,ah,O0,k0,ZA,D0,JA,C0,eS,w0,tS;function nP(i){return`
614
614
  <style>
615
615
  :host {
616
616
  --_focus-box-shadow: var(--media-focus-box-shadow, inset 0 0 0 2px rgb(27 127 204 / .9));
@@ -913,7 +913,7 @@ Schedule: ${l.map(p=>Ci(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Remo
913
913
  <slot></slot>
914
914
  `}var Jt=class extends L.HTMLElement{constructor(){if(super(),dP(this,us,void 0),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=Qe(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e)}}static get observedAttributes(){return[ge.MEDIA_CONTROLLER]}attributeChangedCallback(e,t,s){var r,n,a,o,l;e===ge.MEDIA_CONTROLLER&&(t&&((n=(r=uh(this,us))==null?void 0:r.unassociateElement)==null||n.call(r,this),ch(this,us,null)),s&&this.isConnected&&(ch(this,us,(a=this.getRootNode())==null?void 0:a.getElementById(s)),(l=(o=uh(this,us))==null?void 0:o.associateElement)==null||l.call(o,this)))}connectedCallback(){var e,t,s;let{style:r}=je(this.shadowRoot,":host");r.setProperty("display",`var(--media-control-display, var(--${this.localName}-display, inline-flex))`);let n=this.getAttribute(ge.MEDIA_CONTROLLER);n&&(ch(this,us,(e=this.getRootNode())==null?void 0:e.getElementById(n)),(s=(t=uh(this,us))==null?void 0:t.associateElement)==null||s.call(t,this))}disconnectedCallback(){var e,t;(t=(e=uh(this,us))==null?void 0:e.unassociateElement)==null||t.call(e,this),ch(this,us,null)}};us=new WeakMap;Jt.shadowRootOptions={mode:"open"};Jt.getTemplateHTML=uP;Jt.getSlotTemplateHTML=cP;L.customElements.get("media-text-display")||L.customElements.define("media-text-display",Jt);var nS=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},rS=(i,e,t)=>(nS(i,e,"read from private field"),t?t.call(i):e.get(i)),hP=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},fP=(i,e,t,s)=>(nS(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),wl;function mP(i,e){return`
915
915
  <slot>${Ui(e.mediaDuration)}</slot>
916
- `}var hh=class extends Jt{constructor(){var e;super(),hP(this,wl,void 0),fP(this,wl,this.shadowRoot.querySelector("slot")),rS(this,wl).textContent=Ui((e=this.mediaDuration)!=null?e:0)}static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_DURATION]}attributeChangedCallback(e,t,s){e===_.MEDIA_DURATION&&(rS(this,wl).textContent=Ui(+s)),super.attributeChangedCallback(e,t,s)}get mediaDuration(){return ye(this,_.MEDIA_DURATION)}set mediaDuration(e){Re(this,_.MEDIA_DURATION,e)}};wl=new WeakMap;hh.getSlotTemplateHTML=mP;L.customElements.get("media-duration-display")||L.customElements.define("media-duration-display",hh);var pP={2:F("Network Error"),3:F("Decode Error"),4:F("Source Not Supported"),5:F("Encryption Error")},gP={2:F("A network error caused the media download to fail."),3:F("A media error caused playback to be aborted. The media could be corrupt or your browser does not support this format."),4:F("An unsupported error occurred. The server or network failed, or your browser does not support this format."),5:F("The media is encrypted and there are no keys to decrypt it.")},fh=i=>{var e,t;return i.code===1?null:{title:(e=pP[i.code])!=null?e:`Error ${i.code}`,message:(t=gP[i.code])!=null?t:i.message}};var oS=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},vP=(i,e,t)=>(oS(i,e,"read from private field"),t?t.call(i):e.get(i)),EP=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},yP=(i,e,t,s)=>(oS(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),mh;function TP(i){return`
916
+ `}var hh=class extends Jt{constructor(){var e;super(),hP(this,wl,void 0),fP(this,wl,this.shadowRoot.querySelector("slot")),rS(this,wl).textContent=Ui((e=this.mediaDuration)!=null?e:0)}static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_DURATION]}attributeChangedCallback(e,t,s){e===_.MEDIA_DURATION&&(rS(this,wl).textContent=Ui(+s)),super.attributeChangedCallback(e,t,s)}get mediaDuration(){return ye(this,_.MEDIA_DURATION)}set mediaDuration(e){Re(this,_.MEDIA_DURATION,e)}};wl=new WeakMap;hh.getSlotTemplateHTML=mP;L.customElements.get("media-duration-display")||L.customElements.define("media-duration-display",hh);var pP={2:F("Network Error"),3:F("Decode Error"),4:F("Source Not Supported"),5:F("Encryption Error")},gP={2:F("A network error caused the media download to fail."),3:F("A media error caused playback to be aborted. The media could be corrupt or your browser does not support this format."),4:F("An unsupported error occurred. The server or network failed, or your browser does not support this format."),5:F("The media is encrypted and there are no keys to decrypt it.")},fh=i=>{var e,t;return i.code===1?null:{title:(e=pP[i.code])!=null?e:`Error ${i.code}`,message:(t=gP[i.code])!=null?t:i.message}};var oS=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},vP=(i,e,t)=>(oS(i,e,"read from private field"),t?t.call(i):e.get(i)),EP=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},yP=(i,e,t,s)=>(oS(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),mh;function bP(i){return`
917
917
  <style>
918
918
  :host {
919
919
  background: rgb(20 20 30 / .8);
@@ -932,7 +932,7 @@ Schedule: ${l.map(p=>Ci(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Remo
932
932
  <slot name="error-${i.mediaerrorcode}" id="content">
933
933
  ${lS({code:+i.mediaerrorcode,message:i.mediaerrormessage})}
934
934
  </slot>
935
- `}function bP(i){return i.code&&fh(i)!==null}function lS(i){var e;let{title:t,message:s}=(e=fh(i))!=null?e:{},r="";return t&&(r+=`<slot name="error-${i.code}-title"><h3>${t}</h3></slot>`),s&&(r+=`<slot name="error-${i.code}-message"><p>${s}</p></slot>`),r}var aS=[_.MEDIA_ERROR_CODE,_.MEDIA_ERROR_MESSAGE],Na=class extends as{constructor(){super(...arguments),EP(this,mh,null)}static get observedAttributes(){return[...super.observedAttributes,...aS]}formatErrorMessage(e){return this.constructor.formatErrorMessage(e)}attributeChangedCallback(e,t,s){var r;if(super.attributeChangedCallback(e,t,s),!aS.includes(e))return;let n=(r=this.mediaError)!=null?r:{code:this.mediaErrorCode,message:this.mediaErrorMessage};if(this.open=bP(n),this.open&&(this.shadowRoot.querySelector("slot").name=`error-${this.mediaErrorCode}`,this.shadowRoot.querySelector("#content").innerHTML=this.formatErrorMessage(n),!this.hasAttribute("aria-label"))){let{title:a}=fh(n);a&&this.setAttribute("aria-label",a)}}get mediaError(){return vP(this,mh)}set mediaError(e){yP(this,mh,e)}get mediaErrorCode(){return ye(this,"mediaerrorcode")}set mediaErrorCode(e){Re(this,"mediaerrorcode",e)}get mediaErrorMessage(){return pe(this,"mediaerrormessage")}set mediaErrorMessage(e){me(this,"mediaerrormessage",e)}};mh=new WeakMap;Na.getSlotTemplateHTML=TP;Na.formatErrorMessage=lS;L.customElements.get("media-error-dialog")||L.customElements.define("media-error-dialog",Na);var ph=Na;var _P=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},Dr=(i,e,t)=>(_P(i,e,"read from private field"),t?t.call(i):e.get(i)),dS=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},Ua,Fa;function AP(i){return`
935
+ `}function TP(i){return i.code&&fh(i)!==null}function lS(i){var e;let{title:t,message:s}=(e=fh(i))!=null?e:{},r="";return t&&(r+=`<slot name="error-${i.code}-title"><h3>${t}</h3></slot>`),s&&(r+=`<slot name="error-${i.code}-message"><p>${s}</p></slot>`),r}var aS=[_.MEDIA_ERROR_CODE,_.MEDIA_ERROR_MESSAGE],Na=class extends as{constructor(){super(...arguments),EP(this,mh,null)}static get observedAttributes(){return[...super.observedAttributes,...aS]}formatErrorMessage(e){return this.constructor.formatErrorMessage(e)}attributeChangedCallback(e,t,s){var r;if(super.attributeChangedCallback(e,t,s),!aS.includes(e))return;let n=(r=this.mediaError)!=null?r:{code:this.mediaErrorCode,message:this.mediaErrorMessage};if(this.open=TP(n),this.open&&(this.shadowRoot.querySelector("slot").name=`error-${this.mediaErrorCode}`,this.shadowRoot.querySelector("#content").innerHTML=this.formatErrorMessage(n),!this.hasAttribute("aria-label"))){let{title:a}=fh(n);a&&this.setAttribute("aria-label",a)}}get mediaError(){return vP(this,mh)}set mediaError(e){yP(this,mh,e)}get mediaErrorCode(){return ye(this,"mediaerrorcode")}set mediaErrorCode(e){Re(this,"mediaerrorcode",e)}get mediaErrorMessage(){return pe(this,"mediaerrormessage")}set mediaErrorMessage(e){me(this,"mediaerrormessage",e)}};mh=new WeakMap;Na.getSlotTemplateHTML=bP;Na.formatErrorMessage=lS;L.customElements.get("media-error-dialog")||L.customElements.define("media-error-dialog",Na);var ph=Na;var _P=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},Dr=(i,e,t)=>(_P(i,e,"read from private field"),t?t.call(i):e.get(i)),dS=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},Ua,Fa;function AP(i){return`
936
936
  <style>
937
937
  :host {
938
938
  position: fixed;
@@ -1088,7 +1088,7 @@ Schedule: ${l.map(p=>Ci(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Remo
1088
1088
  <slot name="indicator">${PP}</slot>
1089
1089
 
1090
1090
  <slot name="spacer">&nbsp;</slot><slot name="text">${F("live")}</slot>
1091
- `}var hS=i=>{var e;let t=i.mediaPaused||!i.mediaTimeIsLive,s=t?F("seek to live"):F("playing live");i.setAttribute("aria-label",s);let r=(e=i.shadowRoot)==null?void 0:e.querySelector('slot[name="text"]');r&&(r.textContent=F("live")),t?i.removeAttribute("aria-disabled"):i.setAttribute("aria-disabled","true")},yh=class extends Pe{static get observedAttributes(){return[...super.observedAttributes,Eh,Pl]}connectedCallback(){super.connectedCallback(),hS(this)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),hS(this)}get mediaPaused(){return le(this,_.MEDIA_PAUSED)}set mediaPaused(e){de(this,_.MEDIA_PAUSED,e)}get mediaTimeIsLive(){return le(this,_.MEDIA_TIME_IS_LIVE)}set mediaTimeIsLive(e){de(this,_.MEDIA_TIME_IS_LIVE,e)}handleClick(){!this.mediaPaused&&this.mediaTimeIsLive||(this.dispatchEvent(new L.CustomEvent(wP,{composed:!0,bubbles:!0})),this.hasAttribute(Pl)&&this.dispatchEvent(new L.CustomEvent(MP,{composed:!0,bubbles:!0})))}};yh.getSlotTemplateHTML=OP;L.customElements.get("media-live-button")||L.customElements.define("media-live-button",yh);var mS=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},Ol=(i,e,t)=>(mS(i,e,"read from private field"),t?t.call(i):e.get(i)),fS=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},Nl=(i,e,t,s)=>(mS(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),cs,bh,Th={LOADING_DELAY:"loadingdelay",NO_AUTOHIDE:"noautohide"},pS=500,NP=`
1091
+ `}var hS=i=>{var e;let t=i.mediaPaused||!i.mediaTimeIsLive,s=t?F("seek to live"):F("playing live");i.setAttribute("aria-label",s);let r=(e=i.shadowRoot)==null?void 0:e.querySelector('slot[name="text"]');r&&(r.textContent=F("live")),t?i.removeAttribute("aria-disabled"):i.setAttribute("aria-disabled","true")},yh=class extends Pe{static get observedAttributes(){return[...super.observedAttributes,Eh,Pl]}connectedCallback(){super.connectedCallback(),hS(this)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),hS(this)}get mediaPaused(){return le(this,_.MEDIA_PAUSED)}set mediaPaused(e){de(this,_.MEDIA_PAUSED,e)}get mediaTimeIsLive(){return le(this,_.MEDIA_TIME_IS_LIVE)}set mediaTimeIsLive(e){de(this,_.MEDIA_TIME_IS_LIVE,e)}handleClick(){!this.mediaPaused&&this.mediaTimeIsLive||(this.dispatchEvent(new L.CustomEvent(wP,{composed:!0,bubbles:!0})),this.hasAttribute(Pl)&&this.dispatchEvent(new L.CustomEvent(MP,{composed:!0,bubbles:!0})))}};yh.getSlotTemplateHTML=OP;L.customElements.get("media-live-button")||L.customElements.define("media-live-button",yh);var mS=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},Ol=(i,e,t)=>(mS(i,e,"read from private field"),t?t.call(i):e.get(i)),fS=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},Nl=(i,e,t,s)=>(mS(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),cs,Th,bh={LOADING_DELAY:"loadingdelay",NO_AUTOHIDE:"noautohide"},pS=500,NP=`
1092
1092
  <svg aria-hidden="true" viewBox="0 0 100 100">
1093
1093
  <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">
1094
1094
  <animateTransform
@@ -1148,7 +1148,7 @@ Schedule: ${l.map(p=>Ci(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Remo
1148
1148
 
1149
1149
  <slot name="icon">${NP}</slot>
1150
1150
  <div id="status" role="status" aria-live="polite">${F("media loading")}</div>
1151
- `}var Ul=class extends L.HTMLElement{constructor(){if(super(),fS(this,cs,void 0),fS(this,bh,pS),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=Qe(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e)}}static get observedAttributes(){return[ge.MEDIA_CONTROLLER,_.MEDIA_PAUSED,_.MEDIA_LOADING,Th.LOADING_DELAY]}attributeChangedCallback(e,t,s){var r,n,a,o,l;e===Th.LOADING_DELAY&&t!==s?this.loadingDelay=Number(s):e===ge.MEDIA_CONTROLLER&&(t&&((n=(r=Ol(this,cs))==null?void 0:r.unassociateElement)==null||n.call(r,this),Nl(this,cs,null)),s&&this.isConnected&&(Nl(this,cs,(a=this.getRootNode())==null?void 0:a.getElementById(s)),(l=(o=Ol(this,cs))==null?void 0:o.associateElement)==null||l.call(o,this)))}connectedCallback(){var e,t,s;let r=this.getAttribute(ge.MEDIA_CONTROLLER);r&&(Nl(this,cs,(e=this.getRootNode())==null?void 0:e.getElementById(r)),(s=(t=Ol(this,cs))==null?void 0:t.associateElement)==null||s.call(t,this))}disconnectedCallback(){var e,t;(t=(e=Ol(this,cs))==null?void 0:e.unassociateElement)==null||t.call(e,this),Nl(this,cs,null)}get loadingDelay(){return Ol(this,bh)}set loadingDelay(e){Nl(this,bh,e);let{style:t}=je(this.shadowRoot,":host");t.setProperty("--_loading-indicator-delay",`var(--media-loading-indicator-transition-delay, ${e}ms)`)}get mediaPaused(){return le(this,_.MEDIA_PAUSED)}set mediaPaused(e){de(this,_.MEDIA_PAUSED,e)}get mediaLoading(){return le(this,_.MEDIA_LOADING)}set mediaLoading(e){de(this,_.MEDIA_LOADING,e)}get mediaController(){return pe(this,ge.MEDIA_CONTROLLER)}set mediaController(e){me(this,ge.MEDIA_CONTROLLER,e)}get noAutohide(){return le(this,Th.NO_AUTOHIDE)}set noAutohide(e){de(this,Th.NO_AUTOHIDE,e)}};cs=new WeakMap;bh=new WeakMap;Ul.shadowRootOptions={mode:"open"};Ul.getTemplateHTML=UP;L.customElements.get("media-loading-indicator")||L.customElements.define("media-loading-indicator",Ul);var FP=`<svg aria-hidden="true" viewBox="0 0 24 24">
1151
+ `}var Ul=class extends L.HTMLElement{constructor(){if(super(),fS(this,cs,void 0),fS(this,Th,pS),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=Qe(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e)}}static get observedAttributes(){return[ge.MEDIA_CONTROLLER,_.MEDIA_PAUSED,_.MEDIA_LOADING,bh.LOADING_DELAY]}attributeChangedCallback(e,t,s){var r,n,a,o,l;e===bh.LOADING_DELAY&&t!==s?this.loadingDelay=Number(s):e===ge.MEDIA_CONTROLLER&&(t&&((n=(r=Ol(this,cs))==null?void 0:r.unassociateElement)==null||n.call(r,this),Nl(this,cs,null)),s&&this.isConnected&&(Nl(this,cs,(a=this.getRootNode())==null?void 0:a.getElementById(s)),(l=(o=Ol(this,cs))==null?void 0:o.associateElement)==null||l.call(o,this)))}connectedCallback(){var e,t,s;let r=this.getAttribute(ge.MEDIA_CONTROLLER);r&&(Nl(this,cs,(e=this.getRootNode())==null?void 0:e.getElementById(r)),(s=(t=Ol(this,cs))==null?void 0:t.associateElement)==null||s.call(t,this))}disconnectedCallback(){var e,t;(t=(e=Ol(this,cs))==null?void 0:e.unassociateElement)==null||t.call(e,this),Nl(this,cs,null)}get loadingDelay(){return Ol(this,Th)}set loadingDelay(e){Nl(this,Th,e);let{style:t}=je(this.shadowRoot,":host");t.setProperty("--_loading-indicator-delay",`var(--media-loading-indicator-transition-delay, ${e}ms)`)}get mediaPaused(){return le(this,_.MEDIA_PAUSED)}set mediaPaused(e){de(this,_.MEDIA_PAUSED,e)}get mediaLoading(){return le(this,_.MEDIA_LOADING)}set mediaLoading(e){de(this,_.MEDIA_LOADING,e)}get mediaController(){return pe(this,ge.MEDIA_CONTROLLER)}set mediaController(e){me(this,ge.MEDIA_CONTROLLER,e)}get noAutohide(){return le(this,bh.NO_AUTOHIDE)}set noAutohide(e){de(this,bh.NO_AUTOHIDE,e)}};cs=new WeakMap;Th=new WeakMap;Ul.shadowRootOptions={mode:"open"};Ul.getTemplateHTML=UP;L.customElements.get("media-loading-indicator")||L.customElements.define("media-loading-indicator",Ul);var FP=`<svg aria-hidden="true" viewBox="0 0 24 24">
1152
1152
  <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"/>
1153
1153
  </svg>`,gS=`<svg aria-hidden="true" viewBox="0 0 24 24">
1154
1154
  <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"/>
@@ -1245,7 +1245,7 @@ Schedule: ${l.map(p=>Ci(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Remo
1245
1245
  `}function XP(){return`
1246
1246
  <slot name="tooltip-play">${F("Play")}</slot>
1247
1247
  <slot name="tooltip-pause">${F("Pause")}</slot>
1248
- `}var TS=i=>{let e=i.mediaPaused?F("play"):F("pause");i.setAttribute("aria-label",e)},Hl=class extends Pe{static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_PAUSED,_.MEDIA_ENDED]}connectedCallback(){super.connectedCallback(),TS(this)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),(e===_.MEDIA_PAUSED||e===_.MEDIA_LANG)&&TS(this)}get mediaPaused(){return le(this,_.MEDIA_PAUSED)}set mediaPaused(e){de(this,_.MEDIA_PAUSED,e)}handleClick(){let e=this.mediaPaused?K.MEDIA_PLAY_REQUEST:K.MEDIA_PAUSE_REQUEST;this.dispatchEvent(new L.CustomEvent(e,{composed:!0,bubbles:!0}))}};Hl.getSlotTemplateHTML=QP;Hl.getTooltipContentHTML=XP;L.customElements.get("media-play-button")||L.customElements.define("media-play-button",Hl);var hs={PLACEHOLDER_SRC:"placeholdersrc",SRC:"src"};function ZP(i){return`
1248
+ `}var bS=i=>{let e=i.mediaPaused?F("play"):F("pause");i.setAttribute("aria-label",e)},Hl=class extends Pe{static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_PAUSED,_.MEDIA_ENDED]}connectedCallback(){super.connectedCallback(),bS(this)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),(e===_.MEDIA_PAUSED||e===_.MEDIA_LANG)&&bS(this)}get mediaPaused(){return le(this,_.MEDIA_PAUSED)}set mediaPaused(e){de(this,_.MEDIA_PAUSED,e)}handleClick(){let e=this.mediaPaused?K.MEDIA_PLAY_REQUEST:K.MEDIA_PAUSE_REQUEST;this.dispatchEvent(new L.CustomEvent(e,{composed:!0,bubbles:!0}))}};Hl.getSlotTemplateHTML=QP;Hl.getTooltipContentHTML=XP;L.customElements.get("media-play-button")||L.customElements.define("media-play-button",Hl);var hs={PLACEHOLDER_SRC:"placeholdersrc",SRC:"src"};function ZP(i){return`
1249
1249
  <style>
1250
1250
  :host {
1251
1251
  pointer-events: none;
@@ -1267,7 +1267,7 @@ Schedule: ${l.map(p=>Ci(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Remo
1267
1267
  </style>
1268
1268
 
1269
1269
  <img part="poster img" aria-hidden="true" id="image"/>
1270
- `}var JP=i=>{i.style.removeProperty("background-image")},eO=(i,e)=>{i.style["background-image"]=`url('${e}')`},Gl=class extends L.HTMLElement{static get observedAttributes(){return[hs.PLACEHOLDER_SRC,hs.SRC]}constructor(){if(super(),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=Qe(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e)}this.image=this.shadowRoot.querySelector("#image")}attributeChangedCallback(e,t,s){e===hs.SRC&&(s==null?this.image.removeAttribute(hs.SRC):this.image.setAttribute(hs.SRC,s)),e===hs.PLACEHOLDER_SRC&&(s==null?JP(this.image):eO(this.image,s))}get placeholderSrc(){return pe(this,hs.PLACEHOLDER_SRC)}set placeholderSrc(e){me(this,hs.SRC,e)}get src(){return pe(this,hs.SRC)}set src(e){me(this,hs.SRC,e)}};Gl.shadowRootOptions={mode:"open"};Gl.getTemplateHTML=ZP;L.customElements.get("media-poster-image")||L.customElements.define("media-poster-image",Gl);var bS=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},tO=(i,e,t)=>(bS(i,e,"read from private field"),t?t.call(i):e.get(i)),iO=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},sO=(i,e,t,s)=>(bS(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),_h,F0=class extends Jt{constructor(){super(),iO(this,_h,void 0),sO(this,_h,this.shadowRoot.querySelector("slot"))}static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_PREVIEW_CHAPTER,_.MEDIA_LANG]}attributeChangedCallback(e,t,s){if(super.attributeChangedCallback(e,t,s),(e===_.MEDIA_PREVIEW_CHAPTER||e===_.MEDIA_LANG)&&s!==t&&s!=null)if(tO(this,_h).textContent=s,s!==""){let r=F("chapter: {chapterName}",{chapterName:s});this.setAttribute("aria-valuetext",r)}else this.removeAttribute("aria-valuetext")}get mediaPreviewChapter(){return pe(this,_.MEDIA_PREVIEW_CHAPTER)}set mediaPreviewChapter(e){me(this,_.MEDIA_PREVIEW_CHAPTER,e)}};_h=new WeakMap;L.customElements.get("media-preview-chapter-display")||L.customElements.define("media-preview-chapter-display",F0);var _S=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},Ah=(i,e,t)=>(_S(i,e,"read from private field"),t?t.call(i):e.get(i)),rO=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},Sh=(i,e,t,s)=>(_S(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),fs;function nO(i){return`
1270
+ `}var JP=i=>{i.style.removeProperty("background-image")},eO=(i,e)=>{i.style["background-image"]=`url('${e}')`},Gl=class extends L.HTMLElement{static get observedAttributes(){return[hs.PLACEHOLDER_SRC,hs.SRC]}constructor(){if(super(),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=Qe(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e)}this.image=this.shadowRoot.querySelector("#image")}attributeChangedCallback(e,t,s){e===hs.SRC&&(s==null?this.image.removeAttribute(hs.SRC):this.image.setAttribute(hs.SRC,s)),e===hs.PLACEHOLDER_SRC&&(s==null?JP(this.image):eO(this.image,s))}get placeholderSrc(){return pe(this,hs.PLACEHOLDER_SRC)}set placeholderSrc(e){me(this,hs.SRC,e)}get src(){return pe(this,hs.SRC)}set src(e){me(this,hs.SRC,e)}};Gl.shadowRootOptions={mode:"open"};Gl.getTemplateHTML=ZP;L.customElements.get("media-poster-image")||L.customElements.define("media-poster-image",Gl);var TS=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},tO=(i,e,t)=>(TS(i,e,"read from private field"),t?t.call(i):e.get(i)),iO=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},sO=(i,e,t,s)=>(TS(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),_h,F0=class extends Jt{constructor(){super(),iO(this,_h,void 0),sO(this,_h,this.shadowRoot.querySelector("slot"))}static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_PREVIEW_CHAPTER,_.MEDIA_LANG]}attributeChangedCallback(e,t,s){if(super.attributeChangedCallback(e,t,s),(e===_.MEDIA_PREVIEW_CHAPTER||e===_.MEDIA_LANG)&&s!==t&&s!=null)if(tO(this,_h).textContent=s,s!==""){let r=F("chapter: {chapterName}",{chapterName:s});this.setAttribute("aria-valuetext",r)}else this.removeAttribute("aria-valuetext")}get mediaPreviewChapter(){return pe(this,_.MEDIA_PREVIEW_CHAPTER)}set mediaPreviewChapter(e){me(this,_.MEDIA_PREVIEW_CHAPTER,e)}};_h=new WeakMap;L.customElements.get("media-preview-chapter-display")||L.customElements.define("media-preview-chapter-display",F0);var _S=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},Ah=(i,e,t)=>(_S(i,e,"read from private field"),t?t.call(i):e.get(i)),rO=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},Sh=(i,e,t,s)=>(_S(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),fs;function nO(i){return`
1271
1271
  <style>
1272
1272
  :host {
1273
1273
  box-sizing: border-box;
@@ -1281,7 +1281,7 @@ Schedule: ${l.map(p=>Ci(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Remo
1281
1281
  }
1282
1282
  </style>
1283
1283
  <img crossorigin loading="eager" decoding="async">
1284
- `}var $a=class extends L.HTMLElement{constructor(){if(super(),rO(this,fs,void 0),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=Qe(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e)}}static get observedAttributes(){return[ge.MEDIA_CONTROLLER,_.MEDIA_PREVIEW_IMAGE,_.MEDIA_PREVIEW_COORDS]}connectedCallback(){var e,t,s;let r=this.getAttribute(ge.MEDIA_CONTROLLER);r&&(Sh(this,fs,(e=this.getRootNode())==null?void 0:e.getElementById(r)),(s=(t=Ah(this,fs))==null?void 0:t.associateElement)==null||s.call(t,this))}disconnectedCallback(){var e,t;(t=(e=Ah(this,fs))==null?void 0:e.unassociateElement)==null||t.call(e,this),Sh(this,fs,null)}attributeChangedCallback(e,t,s){var r,n,a,o,l;[_.MEDIA_PREVIEW_IMAGE,_.MEDIA_PREVIEW_COORDS].includes(e)&&this.update(),e===ge.MEDIA_CONTROLLER&&(t&&((n=(r=Ah(this,fs))==null?void 0:r.unassociateElement)==null||n.call(r,this),Sh(this,fs,null)),s&&this.isConnected&&(Sh(this,fs,(a=this.getRootNode())==null?void 0:a.getElementById(s)),(l=(o=Ah(this,fs))==null?void 0:o.associateElement)==null||l.call(o,this)))}get mediaPreviewImage(){return pe(this,_.MEDIA_PREVIEW_IMAGE)}set mediaPreviewImage(e){me(this,_.MEDIA_PREVIEW_IMAGE,e)}get mediaPreviewCoords(){let e=this.getAttribute(_.MEDIA_PREVIEW_COORDS);if(e)return e.split(/\s+/).map(t=>+t)}set mediaPreviewCoords(e){if(!e){this.removeAttribute(_.MEDIA_PREVIEW_COORDS);return}this.setAttribute(_.MEDIA_PREVIEW_COORDS,e.join(" "))}update(){let e=this.mediaPreviewCoords,t=this.mediaPreviewImage;if(!(e&&t))return;let[s,r,n,a]=e,o=t.split("#")[0],l=getComputedStyle(this),{maxWidth:d,maxHeight:u,minWidth:c,minHeight:h}=l,f=l.getPropertyValue("--media-preview-thumbnail-object-fit").trim()||"contain",m,p;if(f==="fill"){let R=parseInt(d)/n,I=parseInt(u)/a,x=parseInt(c)/n,D=parseInt(h)/a;m=R<1?R:Math.max(R,x),p=I<1?I:Math.max(I,D)}else{let R=Math.min(parseInt(d)/n,parseInt(u)/a),I=Math.max(parseInt(c)/n,parseInt(h)/a),D=R<1?R:I>1?I:1;m=D,p=D}let{style:g}=je(this.shadowRoot,":host"),v=je(this.shadowRoot,"img").style,T=this.shadowRoot.querySelector("img"),b=Math.min(m,p)<1?"min":"max";g.setProperty(`${b}-width`,"initial","important"),g.setProperty(`${b}-height`,"initial","important"),g.width=`${n*m}px`,g.height=`${a*p}px`;let A=()=>{v.width=`${this.imgWidth*m}px`,v.height=`${this.imgHeight*p}px`,v.display="block"};T.src!==o&&(T.onload=()=>{this.imgWidth=T.naturalWidth,this.imgHeight=T.naturalHeight,A(),T.onload=null},T.src=o,A()),A(),v.transform=`translate(-${s*m}px, -${r*p}px)`}};fs=new WeakMap;$a.shadowRootOptions={mode:"open"};$a.getTemplateHTML=nO;L.customElements.get("media-preview-thumbnail")||L.customElements.define("media-preview-thumbnail",$a);var Ih=$a;var SS=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},AS=(i,e,t)=>(SS(i,e,"read from private field"),t?t.call(i):e.get(i)),aO=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},oO=(i,e,t,s)=>(SS(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),Kl,B0=class extends Jt{constructor(){super(),aO(this,Kl,void 0),oO(this,Kl,this.shadowRoot.querySelector("slot")),AS(this,Kl).textContent=Ui(0)}static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_PREVIEW_TIME]}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===_.MEDIA_PREVIEW_TIME&&s!=null&&(AS(this,Kl).textContent=Ui(parseFloat(s)))}get mediaPreviewTime(){return ye(this,_.MEDIA_PREVIEW_TIME)}set mediaPreviewTime(e){Re(this,_.MEDIA_PREVIEW_TIME,e)}};Kl=new WeakMap;L.customElements.get("media-preview-time-display")||L.customElements.define("media-preview-time-display",B0);var Ha={SEEK_OFFSET:"seekoffset"},$0=30,lO=i=>`
1284
+ `}var $a=class extends L.HTMLElement{constructor(){if(super(),rO(this,fs,void 0),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=Qe(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e)}}static get observedAttributes(){return[ge.MEDIA_CONTROLLER,_.MEDIA_PREVIEW_IMAGE,_.MEDIA_PREVIEW_COORDS]}connectedCallback(){var e,t,s;let r=this.getAttribute(ge.MEDIA_CONTROLLER);r&&(Sh(this,fs,(e=this.getRootNode())==null?void 0:e.getElementById(r)),(s=(t=Ah(this,fs))==null?void 0:t.associateElement)==null||s.call(t,this))}disconnectedCallback(){var e,t;(t=(e=Ah(this,fs))==null?void 0:e.unassociateElement)==null||t.call(e,this),Sh(this,fs,null)}attributeChangedCallback(e,t,s){var r,n,a,o,l;[_.MEDIA_PREVIEW_IMAGE,_.MEDIA_PREVIEW_COORDS].includes(e)&&this.update(),e===ge.MEDIA_CONTROLLER&&(t&&((n=(r=Ah(this,fs))==null?void 0:r.unassociateElement)==null||n.call(r,this),Sh(this,fs,null)),s&&this.isConnected&&(Sh(this,fs,(a=this.getRootNode())==null?void 0:a.getElementById(s)),(l=(o=Ah(this,fs))==null?void 0:o.associateElement)==null||l.call(o,this)))}get mediaPreviewImage(){return pe(this,_.MEDIA_PREVIEW_IMAGE)}set mediaPreviewImage(e){me(this,_.MEDIA_PREVIEW_IMAGE,e)}get mediaPreviewCoords(){let e=this.getAttribute(_.MEDIA_PREVIEW_COORDS);if(e)return e.split(/\s+/).map(t=>+t)}set mediaPreviewCoords(e){if(!e){this.removeAttribute(_.MEDIA_PREVIEW_COORDS);return}this.setAttribute(_.MEDIA_PREVIEW_COORDS,e.join(" "))}update(){let e=this.mediaPreviewCoords,t=this.mediaPreviewImage;if(!(e&&t))return;let[s,r,n,a]=e,o=t.split("#")[0],l=getComputedStyle(this),{maxWidth:d,maxHeight:u,minWidth:c,minHeight:h}=l,f=l.getPropertyValue("--media-preview-thumbnail-object-fit").trim()||"contain",m,p;if(f==="fill"){let R=parseInt(d)/n,I=parseInt(u)/a,x=parseInt(c)/n,D=parseInt(h)/a;m=R<1?R:Math.max(R,x),p=I<1?I:Math.max(I,D)}else{let R=Math.min(parseInt(d)/n,parseInt(u)/a),I=Math.max(parseInt(c)/n,parseInt(h)/a),D=R<1?R:I>1?I:1;m=D,p=D}let{style:g}=je(this.shadowRoot,":host"),v=je(this.shadowRoot,"img").style,b=this.shadowRoot.querySelector("img"),T=Math.min(m,p)<1?"min":"max";g.setProperty(`${T}-width`,"initial","important"),g.setProperty(`${T}-height`,"initial","important"),g.width=`${n*m}px`,g.height=`${a*p}px`;let A=()=>{v.width=`${this.imgWidth*m}px`,v.height=`${this.imgHeight*p}px`,v.display="block"};b.src!==o&&(b.onload=()=>{this.imgWidth=b.naturalWidth,this.imgHeight=b.naturalHeight,A(),b.onload=null},b.src=o,A()),A(),v.transform=`translate(-${s*m}px, -${r*p}px)`}};fs=new WeakMap;$a.shadowRootOptions={mode:"open"};$a.getTemplateHTML=nO;L.customElements.get("media-preview-thumbnail")||L.customElements.define("media-preview-thumbnail",$a);var Ih=$a;var SS=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},AS=(i,e,t)=>(SS(i,e,"read from private field"),t?t.call(i):e.get(i)),aO=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},oO=(i,e,t,s)=>(SS(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),Kl,B0=class extends Jt{constructor(){super(),aO(this,Kl,void 0),oO(this,Kl,this.shadowRoot.querySelector("slot")),AS(this,Kl).textContent=Ui(0)}static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_PREVIEW_TIME]}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===_.MEDIA_PREVIEW_TIME&&s!=null&&(AS(this,Kl).textContent=Ui(parseFloat(s)))}get mediaPreviewTime(){return ye(this,_.MEDIA_PREVIEW_TIME)}set mediaPreviewTime(e){Re(this,_.MEDIA_PREVIEW_TIME,e)}};Kl=new WeakMap;L.customElements.get("media-preview-time-display")||L.customElements.define("media-preview-time-display",B0);var Ha={SEEK_OFFSET:"seekoffset"},$0=30,lO=i=>`
1285
1285
  <svg aria-hidden="true" viewBox="0 0 20 24">
1286
1286
  <defs>
1287
1287
  <style>.text{font-size:8px;font-family:Arial-BoldMT, Arial;font-weight:700;}</style>
@@ -1299,9 +1299,9 @@ Schedule: ${l.map(p=>Ci(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Remo
1299
1299
  <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"/>
1300
1300
  </svg>`;function mO(i,e){return`
1301
1301
  <slot name="icon">${fO(e.seekOffset)}</slot>
1302
- `}var pO=(i,e)=>{i.setAttribute("aria-label",F("seek forward {seekOffset} seconds",{seekOffset:e}))};function gO(){return F("Seek forward")}var vO=0,Wl=class extends Pe{static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_CURRENT_TIME,Ga.SEEK_OFFSET]}connectedCallback(){super.connectedCallback(),this.seekOffset=ye(this,Ga.SEEK_OFFSET,H0)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),pO(this,this.seekOffset),e===Ga.SEEK_OFFSET&&(this.seekOffset=ye(this,Ga.SEEK_OFFSET,H0))}get seekOffset(){return ye(this,Ga.SEEK_OFFSET,H0)}set seekOffset(e){Re(this,Ga.SEEK_OFFSET,e),this.setAttribute("aria-label",F("seek forward {seekOffset} seconds",{seekOffset:this.seekOffset})),Ic(Lc(this,"icon"),this.seekOffset)}get mediaCurrentTime(){return ye(this,_.MEDIA_CURRENT_TIME,vO)}set mediaCurrentTime(e){Re(this,_.MEDIA_CURRENT_TIME,e)}handleClick(){let e=this.mediaCurrentTime+this.seekOffset,t=new L.CustomEvent(K.MEDIA_SEEK_REQUEST,{composed:!0,bubbles:!0,detail:e});this.dispatchEvent(t)}};Wl.getSlotTemplateHTML=mO;Wl.getTooltipContentHTML=gO;L.customElements.get("media-seek-forward-button")||L.customElements.define("media-seek-forward-button",Wl);var V0=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},Vi=(i,e,t)=>(V0(i,e,"read from private field"),t?t.call(i):e.get(i)),Rn=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},W0=(i,e,t,s)=>(V0(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),Mr=(i,e,t)=>(V0(i,e,"access private method"),t),Ka,ms,Dh,q0,LS,xh,Y0,ql,Lh,Rh,G0,wr={REMAINING:"remaining",SHOW_DURATION:"showduration",NO_TOGGLE:"notoggle"},IS=[...Object.values(wr),_.MEDIA_CURRENT_TIME,_.MEDIA_DURATION,_.MEDIA_SEEKABLE],RS=["Enter"," "],EO="&nbsp;/&nbsp;",K0=(i,{timesSep:e=EO}={})=>{var t,s;let r=(t=i.mediaCurrentTime)!=null?t:0,[,n]=(s=i.mediaSeekable)!=null?s:[],a=0;Number.isFinite(i.mediaDuration)?a=i.mediaDuration:Number.isFinite(n)&&(a=n);let o=i.remaining?Ui(0-(a-r)):Ui(r);return i.showDuration?`${o}${e}${Ui(a)}`:o},yO=i=>{var e;let t=i.mediaCurrentTime,[,s]=(e=i.mediaSeekable)!=null?e:[],r=null;if(Number.isFinite(i.mediaDuration)?r=i.mediaDuration:Number.isFinite(s)&&(r=s),t==null||r===null){i.setAttribute("aria-description",F("video not loaded, unknown time."));return}let n=i.remaining?mn(0-(r-t)):mn(t);if(!i.showDuration){i.setAttribute("aria-description",n);return}let a=mn(r),o=F("{currentTime} of {totalTime}",{currentTime:n,totalTime:a});i.setAttribute("aria-description",o)};function TO(i,e){return`
1302
+ `}var pO=(i,e)=>{i.setAttribute("aria-label",F("seek forward {seekOffset} seconds",{seekOffset:e}))};function gO(){return F("Seek forward")}var vO=0,Wl=class extends Pe{static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_CURRENT_TIME,Ga.SEEK_OFFSET]}connectedCallback(){super.connectedCallback(),this.seekOffset=ye(this,Ga.SEEK_OFFSET,H0)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),pO(this,this.seekOffset),e===Ga.SEEK_OFFSET&&(this.seekOffset=ye(this,Ga.SEEK_OFFSET,H0))}get seekOffset(){return ye(this,Ga.SEEK_OFFSET,H0)}set seekOffset(e){Re(this,Ga.SEEK_OFFSET,e),this.setAttribute("aria-label",F("seek forward {seekOffset} seconds",{seekOffset:this.seekOffset})),Ic(Lc(this,"icon"),this.seekOffset)}get mediaCurrentTime(){return ye(this,_.MEDIA_CURRENT_TIME,vO)}set mediaCurrentTime(e){Re(this,_.MEDIA_CURRENT_TIME,e)}handleClick(){let e=this.mediaCurrentTime+this.seekOffset,t=new L.CustomEvent(K.MEDIA_SEEK_REQUEST,{composed:!0,bubbles:!0,detail:e});this.dispatchEvent(t)}};Wl.getSlotTemplateHTML=mO;Wl.getTooltipContentHTML=gO;L.customElements.get("media-seek-forward-button")||L.customElements.define("media-seek-forward-button",Wl);var V0=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},Vi=(i,e,t)=>(V0(i,e,"read from private field"),t?t.call(i):e.get(i)),Rn=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},W0=(i,e,t,s)=>(V0(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),Mr=(i,e,t)=>(V0(i,e,"access private method"),t),Ka,ms,Dh,q0,LS,xh,Y0,ql,Lh,Rh,G0,wr={REMAINING:"remaining",SHOW_DURATION:"showduration",NO_TOGGLE:"notoggle"},IS=[...Object.values(wr),_.MEDIA_CURRENT_TIME,_.MEDIA_DURATION,_.MEDIA_SEEKABLE],RS=["Enter"," "],EO="&nbsp;/&nbsp;",K0=(i,{timesSep:e=EO}={})=>{var t,s;let r=(t=i.mediaCurrentTime)!=null?t:0,[,n]=(s=i.mediaSeekable)!=null?s:[],a=0;Number.isFinite(i.mediaDuration)?a=i.mediaDuration:Number.isFinite(n)&&(a=n);let o=i.remaining?Ui(0-(a-r)):Ui(r);return i.showDuration?`${o}${e}${Ui(a)}`:o},yO=i=>{var e;let t=i.mediaCurrentTime,[,s]=(e=i.mediaSeekable)!=null?e:[],r=null;if(Number.isFinite(i.mediaDuration)?r=i.mediaDuration:Number.isFinite(s)&&(r=s),t==null||r===null){i.setAttribute("aria-description",F("video not loaded, unknown time."));return}let n=i.remaining?mn(0-(r-t)):mn(t);if(!i.showDuration){i.setAttribute("aria-description",n);return}let a=mn(r),o=F("{currentTime} of {totalTime}",{currentTime:n,totalTime:a});i.setAttribute("aria-description",o)};function bO(i,e){return`
1303
1303
  <slot>${K0(e)}</slot>
1304
- `}var bO=i=>{i.setAttribute("aria-label",F("playback time"))},kh=class extends Jt{constructor(){super(),Rn(this,q0),Rn(this,xh),Rn(this,ql),Rn(this,Rh),Rn(this,Ka,void 0),Rn(this,ms,null),Rn(this,Dh,e=>{let{metaKey:t,altKey:s,key:r}=e;if(t||s||!RS.includes(r)){this.removeEventListener("keyup",Vi(this,ms));return}this.addEventListener("keyup",Vi(this,ms))}),W0(this,Ka,this.shadowRoot.querySelector("slot")),Vi(this,Ka).innerHTML=`${K0(this)}`}static get observedAttributes(){return[...super.observedAttributes,...IS,"disabled"]}connectedCallback(){let{style:e}=je(this.shadowRoot,":host(:hover:not([notoggle]))");e.setProperty("cursor","var(--media-cursor, pointer)"),e.setProperty("background","var(--media-control-hover-background, rgba(50 50 70 / .7))"),this.setAttribute("aria-label",F("playback time")),Mr(this,ql,Lh).call(this),super.connectedCallback()}toggleTimeDisplay(){this.noToggle||(this.hasAttribute("remaining")?this.removeAttribute("remaining"):this.setAttribute("remaining",""))}disconnectedCallback(){this.disable(),Mr(this,xh,Y0).call(this),super.disconnectedCallback()}attributeChangedCallback(e,t,s){bO(this),IS.includes(e)?this.update():e==="disabled"&&s!==t?s==null?Mr(this,ql,Lh).call(this):Mr(this,Rh,G0).call(this):e===wr.NO_TOGGLE&&s!==t&&(this.noToggle?Mr(this,Rh,G0).call(this):Mr(this,ql,Lh).call(this)),super.attributeChangedCallback(e,t,s)}enable(){this.noToggle||(this.tabIndex=0)}disable(){this.tabIndex=-1}get remaining(){return le(this,wr.REMAINING)}set remaining(e){de(this,wr.REMAINING,e)}get showDuration(){return le(this,wr.SHOW_DURATION)}set showDuration(e){de(this,wr.SHOW_DURATION,e)}get noToggle(){return le(this,wr.NO_TOGGLE)}set noToggle(e){de(this,wr.NO_TOGGLE,e)}get mediaDuration(){return ye(this,_.MEDIA_DURATION)}set mediaDuration(e){Re(this,_.MEDIA_DURATION,e)}get mediaCurrentTime(){return ye(this,_.MEDIA_CURRENT_TIME)}set mediaCurrentTime(e){Re(this,_.MEDIA_CURRENT_TIME,e)}get mediaSeekable(){let e=this.getAttribute(_.MEDIA_SEEKABLE);if(e)return e.split(":").map(t=>+t)}set mediaSeekable(e){if(e==null){this.removeAttribute(_.MEDIA_SEEKABLE);return}this.setAttribute(_.MEDIA_SEEKABLE,e.join(":"))}update(){let e=K0(this);yO(this),e!==Vi(this,Ka).innerHTML&&(Vi(this,Ka).innerHTML=e)}};Ka=new WeakMap;ms=new WeakMap;Dh=new WeakMap;q0=new WeakSet;LS=function(){Vi(this,ms)||(W0(this,ms,i=>{let{key:e}=i;if(!RS.includes(e)){this.removeEventListener("keyup",Vi(this,ms));return}this.toggleTimeDisplay()}),this.addEventListener("keydown",Vi(this,Dh)),this.addEventListener("click",this.toggleTimeDisplay))};xh=new WeakSet;Y0=function(){Vi(this,ms)&&(this.removeEventListener("keyup",Vi(this,ms)),this.removeEventListener("keydown",Vi(this,Dh)),this.removeEventListener("click",this.toggleTimeDisplay),W0(this,ms,null))};ql=new WeakSet;Lh=function(){!this.noToggle&&!this.hasAttribute("disabled")&&(this.setAttribute("role","button"),this.enable(),Mr(this,q0,LS).call(this))};Rh=new WeakSet;G0=function(){this.removeAttribute("role"),this.disable(),Mr(this,xh,Y0).call(this)};kh.getSlotTemplateHTML=TO;L.customElements.get("media-time-display")||L.customElements.define("media-time-display",kh);var xS=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},kt=(i,e,t)=>(xS(i,e,"read from private field"),t?t.call(i):e.get(i)),ps=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},ui=(i,e,t,s)=>(xS(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),_O=(i,e,t,s)=>({set _(r){ui(i,e,r,t)},get _(){return kt(i,e,s)}}),Va,Ch,Wa,Yl,wh,Mh,Ph,qa,xn,Oh,Nh=class{constructor(e,t,s){ps(this,Va,void 0),ps(this,Ch,void 0),ps(this,Wa,void 0),ps(this,Yl,void 0),ps(this,wh,void 0),ps(this,Mh,void 0),ps(this,Ph,void 0),ps(this,qa,void 0),ps(this,xn,0),ps(this,Oh,(r=performance.now())=>{ui(this,xn,requestAnimationFrame(kt(this,Oh))),ui(this,Yl,performance.now()-kt(this,Wa));let n=1e3/this.fps;if(kt(this,Yl)>n){ui(this,Wa,r-kt(this,Yl)%n);let a=1e3/((r-kt(this,Ch))/++_O(this,wh)._),o=(r-kt(this,Mh))/1e3/this.duration,l=kt(this,Ph)+o*this.playbackRate;l-kt(this,Va).valueAsNumber>0?ui(this,qa,this.playbackRate/this.duration/a):(ui(this,qa,.995*kt(this,qa)),l=kt(this,Va).valueAsNumber+kt(this,qa)),this.callback(l)}}),ui(this,Va,e),this.callback=t,this.fps=s}start(){kt(this,xn)===0&&(ui(this,Wa,performance.now()),ui(this,Ch,kt(this,Wa)),ui(this,wh,0),kt(this,Oh).call(this))}stop(){kt(this,xn)!==0&&(cancelAnimationFrame(kt(this,xn)),ui(this,xn,0))}update({start:e,duration:t,playbackRate:s}){let r=e-kt(this,Va).valueAsNumber,n=Math.abs(t-this.duration);(r>0||r<-.03||n>=.5)&&this.callback(e),ui(this,Ph,e),ui(this,Mh,performance.now()),this.duration=t,this.playbackRate=s}};Va=new WeakMap;Ch=new WeakMap;Wa=new WeakMap;Yl=new WeakMap;wh=new WeakMap;Mh=new WeakMap;Ph=new WeakMap;qa=new WeakMap;xn=new WeakMap;Oh=new WeakMap;var Z0=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},Ze=(i,e,t)=>(Z0(i,e,"read from private field"),t?t.call(i):e.get(i)),St=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},Ti=(i,e,t,s)=>(Z0(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),bi=(i,e,t)=>(Z0(i,e,"access private method"),t),Ya,Pr,Bh,zl,$h,Fh,Ql,Xl,ja,za,jl,j0,kS,z0,Hh,J0,Gh,ev,Kh,tv,Q0,DS,Zl,Vh,X0,CS,AO=i=>{let e=i.range,t=mn(+wS(i)),s=mn(+i.mediaSeekableEnd),r=t&&s?F("{currentTime} of {totalTime}",{currentTime:t,totalTime:s}):F("video not loaded, unknown time.");e.setAttribute("aria-valuetext",r)};function SO(i){return`
1304
+ `}var TO=i=>{i.setAttribute("aria-label",F("playback time"))},kh=class extends Jt{constructor(){super(),Rn(this,q0),Rn(this,xh),Rn(this,ql),Rn(this,Rh),Rn(this,Ka,void 0),Rn(this,ms,null),Rn(this,Dh,e=>{let{metaKey:t,altKey:s,key:r}=e;if(t||s||!RS.includes(r)){this.removeEventListener("keyup",Vi(this,ms));return}this.addEventListener("keyup",Vi(this,ms))}),W0(this,Ka,this.shadowRoot.querySelector("slot")),Vi(this,Ka).innerHTML=`${K0(this)}`}static get observedAttributes(){return[...super.observedAttributes,...IS,"disabled"]}connectedCallback(){let{style:e}=je(this.shadowRoot,":host(:hover:not([notoggle]))");e.setProperty("cursor","var(--media-cursor, pointer)"),e.setProperty("background","var(--media-control-hover-background, rgba(50 50 70 / .7))"),this.setAttribute("aria-label",F("playback time")),Mr(this,ql,Lh).call(this),super.connectedCallback()}toggleTimeDisplay(){this.noToggle||(this.hasAttribute("remaining")?this.removeAttribute("remaining"):this.setAttribute("remaining",""))}disconnectedCallback(){this.disable(),Mr(this,xh,Y0).call(this),super.disconnectedCallback()}attributeChangedCallback(e,t,s){TO(this),IS.includes(e)?this.update():e==="disabled"&&s!==t?s==null?Mr(this,ql,Lh).call(this):Mr(this,Rh,G0).call(this):e===wr.NO_TOGGLE&&s!==t&&(this.noToggle?Mr(this,Rh,G0).call(this):Mr(this,ql,Lh).call(this)),super.attributeChangedCallback(e,t,s)}enable(){this.noToggle||(this.tabIndex=0)}disable(){this.tabIndex=-1}get remaining(){return le(this,wr.REMAINING)}set remaining(e){de(this,wr.REMAINING,e)}get showDuration(){return le(this,wr.SHOW_DURATION)}set showDuration(e){de(this,wr.SHOW_DURATION,e)}get noToggle(){return le(this,wr.NO_TOGGLE)}set noToggle(e){de(this,wr.NO_TOGGLE,e)}get mediaDuration(){return ye(this,_.MEDIA_DURATION)}set mediaDuration(e){Re(this,_.MEDIA_DURATION,e)}get mediaCurrentTime(){return ye(this,_.MEDIA_CURRENT_TIME)}set mediaCurrentTime(e){Re(this,_.MEDIA_CURRENT_TIME,e)}get mediaSeekable(){let e=this.getAttribute(_.MEDIA_SEEKABLE);if(e)return e.split(":").map(t=>+t)}set mediaSeekable(e){if(e==null){this.removeAttribute(_.MEDIA_SEEKABLE);return}this.setAttribute(_.MEDIA_SEEKABLE,e.join(":"))}update(){let e=K0(this);yO(this),e!==Vi(this,Ka).innerHTML&&(Vi(this,Ka).innerHTML=e)}};Ka=new WeakMap;ms=new WeakMap;Dh=new WeakMap;q0=new WeakSet;LS=function(){Vi(this,ms)||(W0(this,ms,i=>{let{key:e}=i;if(!RS.includes(e)){this.removeEventListener("keyup",Vi(this,ms));return}this.toggleTimeDisplay()}),this.addEventListener("keydown",Vi(this,Dh)),this.addEventListener("click",this.toggleTimeDisplay))};xh=new WeakSet;Y0=function(){Vi(this,ms)&&(this.removeEventListener("keyup",Vi(this,ms)),this.removeEventListener("keydown",Vi(this,Dh)),this.removeEventListener("click",this.toggleTimeDisplay),W0(this,ms,null))};ql=new WeakSet;Lh=function(){!this.noToggle&&!this.hasAttribute("disabled")&&(this.setAttribute("role","button"),this.enable(),Mr(this,q0,LS).call(this))};Rh=new WeakSet;G0=function(){this.removeAttribute("role"),this.disable(),Mr(this,xh,Y0).call(this)};kh.getSlotTemplateHTML=bO;L.customElements.get("media-time-display")||L.customElements.define("media-time-display",kh);var xS=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},kt=(i,e,t)=>(xS(i,e,"read from private field"),t?t.call(i):e.get(i)),ps=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},ui=(i,e,t,s)=>(xS(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),_O=(i,e,t,s)=>({set _(r){ui(i,e,r,t)},get _(){return kt(i,e,s)}}),Va,Ch,Wa,Yl,wh,Mh,Ph,qa,xn,Oh,Nh=class{constructor(e,t,s){ps(this,Va,void 0),ps(this,Ch,void 0),ps(this,Wa,void 0),ps(this,Yl,void 0),ps(this,wh,void 0),ps(this,Mh,void 0),ps(this,Ph,void 0),ps(this,qa,void 0),ps(this,xn,0),ps(this,Oh,(r=performance.now())=>{ui(this,xn,requestAnimationFrame(kt(this,Oh))),ui(this,Yl,performance.now()-kt(this,Wa));let n=1e3/this.fps;if(kt(this,Yl)>n){ui(this,Wa,r-kt(this,Yl)%n);let a=1e3/((r-kt(this,Ch))/++_O(this,wh)._),o=(r-kt(this,Mh))/1e3/this.duration,l=kt(this,Ph)+o*this.playbackRate;l-kt(this,Va).valueAsNumber>0?ui(this,qa,this.playbackRate/this.duration/a):(ui(this,qa,.995*kt(this,qa)),l=kt(this,Va).valueAsNumber+kt(this,qa)),this.callback(l)}}),ui(this,Va,e),this.callback=t,this.fps=s}start(){kt(this,xn)===0&&(ui(this,Wa,performance.now()),ui(this,Ch,kt(this,Wa)),ui(this,wh,0),kt(this,Oh).call(this))}stop(){kt(this,xn)!==0&&(cancelAnimationFrame(kt(this,xn)),ui(this,xn,0))}update({start:e,duration:t,playbackRate:s}){let r=e-kt(this,Va).valueAsNumber,n=Math.abs(t-this.duration);(r>0||r<-.03||n>=.5)&&this.callback(e),ui(this,Ph,e),ui(this,Mh,performance.now()),this.duration=t,this.playbackRate=s}};Va=new WeakMap;Ch=new WeakMap;Wa=new WeakMap;Yl=new WeakMap;wh=new WeakMap;Mh=new WeakMap;Ph=new WeakMap;qa=new WeakMap;xn=new WeakMap;Oh=new WeakMap;var Z0=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},Ze=(i,e,t)=>(Z0(i,e,"read from private field"),t?t.call(i):e.get(i)),St=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},bi=(i,e,t,s)=>(Z0(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),Ti=(i,e,t)=>(Z0(i,e,"access private method"),t),Ya,Pr,Bh,zl,$h,Fh,Ql,Xl,ja,za,jl,j0,kS,z0,Hh,J0,Gh,ev,Kh,tv,Q0,DS,Zl,Vh,X0,CS,AO=i=>{let e=i.range,t=mn(+wS(i)),s=mn(+i.mediaSeekableEnd),r=t&&s?F("{currentTime} of {totalTime}",{currentTime:t,totalTime:s}):F("video not loaded, unknown time.");e.setAttribute("aria-valuetext",r)};function SO(i){return`
1305
1305
  <style>
1306
1306
  :host {
1307
1307
  --media-box-border-radius: 4px;
@@ -1518,7 +1518,7 @@ Schedule: ${l.map(p=>Ci(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Remo
1518
1518
 
1519
1519
  </slot>
1520
1520
  </div>
1521
- `}var Uh=(i,e=i.mediaCurrentTime)=>{let t=Number.isFinite(i.mediaSeekableStart)?i.mediaSeekableStart:0,s=Number.isFinite(i.mediaDuration)?i.mediaDuration:i.mediaSeekableEnd;if(Number.isNaN(s))return 0;let r=(e-t)/(s-t);return Math.max(0,Math.min(r,1))},wS=(i,e=i.range.valueAsNumber)=>{let t=Number.isFinite(i.mediaSeekableStart)?i.mediaSeekableStart:0,s=Number.isFinite(i.mediaDuration)?i.mediaDuration:i.mediaSeekableEnd;return Number.isNaN(s)?0:e*(s-t)+t},Jl=class extends ls{constructor(){super(),St(this,j0),St(this,Hh),St(this,Gh),St(this,Kh),St(this,Q0),St(this,Zl),St(this,X0),St(this,Ya,null),St(this,Pr,void 0),St(this,Bh,void 0),St(this,zl,void 0),St(this,$h,void 0),St(this,Fh,void 0),St(this,Ql,void 0),St(this,Xl,void 0),St(this,ja,void 0),St(this,za,void 0),St(this,jl,()=>{bi(this,j0,kS).call(this)?Ze(this,Pr).start():Ze(this,Pr).stop()}),St(this,z0,s=>{this.dragging||(Ta(s)&&(this.range.valueAsNumber=s),Ze(this,za)||this.updateBar())}),this.shadowRoot.querySelector("#track").insertAdjacentHTML("afterbegin",'<div id="buffered" part="buffered"></div>'),Ti(this,Bh,this.shadowRoot.querySelectorAll('[part~="box"]')),Ti(this,$h,this.shadowRoot.querySelector('[part~="preview-box"]')),Ti(this,Fh,this.shadowRoot.querySelector('[part~="current-box"]'));let t=getComputedStyle(this);Ti(this,Ql,parseInt(t.getPropertyValue("--media-box-padding-left"))),Ti(this,Xl,parseInt(t.getPropertyValue("--media-box-padding-right"))),Ti(this,Pr,new Nh(this.range,Ze(this,z0),60))}static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_PAUSED,_.MEDIA_DURATION,_.MEDIA_SEEKABLE,_.MEDIA_CURRENT_TIME,_.MEDIA_PREVIEW_IMAGE,_.MEDIA_PREVIEW_TIME,_.MEDIA_PREVIEW_CHAPTER,_.MEDIA_BUFFERED,_.MEDIA_PLAYBACK_RATE,_.MEDIA_LOADING,_.MEDIA_ENDED]}connectedCallback(){var e;super.connectedCallback(),this.range.setAttribute("aria-label",F("seek")),Ze(this,jl).call(this),Ti(this,Ya,this.getRootNode()),(e=Ze(this,Ya))==null||e.addEventListener("transitionstart",this)}disconnectedCallback(){var e;super.disconnectedCallback(),Ze(this,Pr).stop(),(e=Ze(this,Ya))==null||e.removeEventListener("transitionstart",this),Ti(this,Ya,null)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),t!=s&&(e===_.MEDIA_CURRENT_TIME||e===_.MEDIA_PAUSED||e===_.MEDIA_ENDED||e===_.MEDIA_LOADING||e===_.MEDIA_DURATION||e===_.MEDIA_SEEKABLE?(Ze(this,Pr).update({start:Uh(this),duration:this.mediaSeekableEnd-this.mediaSeekableStart,playbackRate:this.mediaPlaybackRate}),Ze(this,jl).call(this),AO(this)):e===_.MEDIA_BUFFERED&&this.updateBufferedBar(),(e===_.MEDIA_DURATION||e===_.MEDIA_SEEKABLE)&&(this.mediaChaptersCues=Ze(this,ja),this.updateBar()))}get mediaChaptersCues(){return Ze(this,ja)}set mediaChaptersCues(e){var t;Ti(this,ja,e),this.updateSegments((t=Ze(this,ja))==null?void 0:t.map(s=>({start:Uh(this,s.startTime),end:Uh(this,s.endTime)})))}get mediaPaused(){return le(this,_.MEDIA_PAUSED)}set mediaPaused(e){de(this,_.MEDIA_PAUSED,e)}get mediaLoading(){return le(this,_.MEDIA_LOADING)}set mediaLoading(e){de(this,_.MEDIA_LOADING,e)}get mediaDuration(){return ye(this,_.MEDIA_DURATION)}set mediaDuration(e){Re(this,_.MEDIA_DURATION,e)}get mediaCurrentTime(){return ye(this,_.MEDIA_CURRENT_TIME)}set mediaCurrentTime(e){Re(this,_.MEDIA_CURRENT_TIME,e)}get mediaPlaybackRate(){return ye(this,_.MEDIA_PLAYBACK_RATE,1)}set mediaPlaybackRate(e){Re(this,_.MEDIA_PLAYBACK_RATE,e)}get mediaBuffered(){let e=this.getAttribute(_.MEDIA_BUFFERED);return e?e.split(" ").map(t=>t.split(":").map(s=>+s)):[]}set mediaBuffered(e){if(!e){this.removeAttribute(_.MEDIA_BUFFERED);return}let t=e.map(s=>s.join(":")).join(" ");this.setAttribute(_.MEDIA_BUFFERED,t)}get mediaSeekable(){let e=this.getAttribute(_.MEDIA_SEEKABLE);if(e)return e.split(":").map(t=>+t)}set mediaSeekable(e){if(e==null){this.removeAttribute(_.MEDIA_SEEKABLE);return}this.setAttribute(_.MEDIA_SEEKABLE,e.join(":"))}get mediaSeekableEnd(){var e;let[,t=this.mediaDuration]=(e=this.mediaSeekable)!=null?e:[];return t}get mediaSeekableStart(){var e;let[t=0]=(e=this.mediaSeekable)!=null?e:[];return t}get mediaPreviewImage(){return pe(this,_.MEDIA_PREVIEW_IMAGE)}set mediaPreviewImage(e){me(this,_.MEDIA_PREVIEW_IMAGE,e)}get mediaPreviewTime(){return ye(this,_.MEDIA_PREVIEW_TIME)}set mediaPreviewTime(e){Re(this,_.MEDIA_PREVIEW_TIME,e)}get mediaEnded(){return le(this,_.MEDIA_ENDED)}set mediaEnded(e){de(this,_.MEDIA_ENDED,e)}updateBar(){super.updateBar(),this.updateBufferedBar(),this.updateCurrentBox()}updateBufferedBar(){var e;let t=this.mediaBuffered;if(!t.length)return;let s;if(this.mediaEnded)s=1;else{let n=this.mediaCurrentTime,[,a=this.mediaSeekableStart]=(e=t.find(([o,l])=>o<=n&&n<=l))!=null?e:[];s=Uh(this,a)}let{style:r}=je(this.shadowRoot,"#buffered");r.setProperty("width",`${s*100}%`)}updateCurrentBox(){if(!this.shadowRoot.querySelector('slot[name="current"]').assignedElements().length)return;let t=je(this.shadowRoot,"#current-rail"),s=je(this.shadowRoot,'[part~="current-box"]'),r=bi(this,Hh,J0).call(this,Ze(this,Fh)),n=bi(this,Gh,ev).call(this,r,this.range.valueAsNumber),a=bi(this,Kh,tv).call(this,r,this.range.valueAsNumber);t.style.transform=`translateX(${n})`,t.style.setProperty("--_range-width",`${r.range.width}`),s.style.setProperty("--_box-shift",`${a}`),s.style.setProperty("--_box-width",`${r.box.width}px`),s.style.setProperty("visibility","initial")}handleEvent(e){switch(super.handleEvent(e),e.type){case"input":bi(this,X0,CS).call(this);break;case"pointermove":bi(this,Q0,DS).call(this,e);break;case"pointerup":Ze(this,za)&&Ti(this,za,!1);break;case"pointerdown":Ti(this,za,!0);break;case"pointerleave":bi(this,Zl,Vh).call(this,null);break;case"transitionstart":Kt(e.target,this)&&setTimeout(()=>Ze(this,jl).call(this),0);break}}};Ya=new WeakMap;Pr=new WeakMap;Bh=new WeakMap;zl=new WeakMap;$h=new WeakMap;Fh=new WeakMap;Ql=new WeakMap;Xl=new WeakMap;ja=new WeakMap;za=new WeakMap;jl=new WeakMap;j0=new WeakSet;kS=function(){return this.isConnected&&!this.mediaPaused&&!this.mediaLoading&&!this.mediaEnded&&this.mediaSeekableEnd>0&&Rc(this)};z0=new WeakMap;Hh=new WeakSet;J0=function(i){var e;let s=((e=this.getAttribute("bounds")?is(this,`#${this.getAttribute("bounds")}`):this.parentElement)!=null?e:this).getBoundingClientRect(),r=this.range.getBoundingClientRect(),n=i.offsetWidth,a=-(r.left-s.left-n/2),o=s.right-r.left-n/2;return{box:{width:n,min:a,max:o},bounds:s,range:r}};Gh=new WeakSet;ev=function(i,e){let t=`${e*100}%`,{width:s,min:r,max:n}=i.box;if(!s)return t;if(Number.isNaN(r)||(t=`max(${`calc(1 / var(--_range-width) * 100 * ${r}% + var(--media-box-padding-left))`}, ${t})`),!Number.isNaN(n)){let o=`calc(1 / var(--_range-width) * 100 * ${n}% - var(--media-box-padding-right))`;t=`min(${t}, ${o})`}return t};Kh=new WeakSet;tv=function(i,e){let{width:t,min:s,max:r}=i.box,n=e*i.range.width;if(n<s+Ze(this,Ql)){let a=i.range.left-i.bounds.left-Ze(this,Ql);return`${n-t/2+a}px`}if(n>r-Ze(this,Xl)){let a=i.bounds.right-i.range.right-Ze(this,Xl);return`${n+t/2-a-i.range.width}px`}return 0};Q0=new WeakSet;DS=function(i){let e=[...Ze(this,Bh)].some(u=>i.composedPath().includes(u));if(!this.dragging&&(e||!i.composedPath().includes(this))){bi(this,Zl,Vh).call(this,null);return}let t=this.mediaSeekableEnd;if(!t)return;let s=je(this.shadowRoot,"#preview-rail"),r=je(this.shadowRoot,'[part~="preview-box"]'),n=bi(this,Hh,J0).call(this,Ze(this,$h)),a=(i.clientX-n.range.left)/n.range.width;a=Math.max(0,Math.min(1,a));let o=bi(this,Gh,ev).call(this,n,a),l=bi(this,Kh,tv).call(this,n,a);s.style.transform=`translateX(${o})`,s.style.setProperty("--_range-width",`${n.range.width}`),r.style.setProperty("--_box-shift",`${l}`),r.style.setProperty("--_box-width",`${n.box.width}px`);let d=Math.round(Ze(this,zl))-Math.round(a*t);Math.abs(d)<1&&a>.01&&a<.99||(Ti(this,zl,a*t),bi(this,Zl,Vh).call(this,Ze(this,zl)))};Zl=new WeakSet;Vh=function(i){this.dispatchEvent(new L.CustomEvent(K.MEDIA_PREVIEW_REQUEST,{composed:!0,bubbles:!0,detail:i}))};X0=new WeakSet;CS=function(){Ze(this,Pr).stop();let i=wS(this);this.dispatchEvent(new L.CustomEvent(K.MEDIA_SEEK_REQUEST,{composed:!0,bubbles:!0,detail:i}))};Jl.shadowRootOptions={mode:"open"};Jl.getContainerTemplateHTML=SO;L.customElements.get("media-time-range")||L.customElements.define("media-time-range",Jl);var IO=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},MS=(i,e,t)=>(IO(i,e,"read from private field"),t?t.call(i):e.get(i)),LO=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},Wh,RO=1,xO=i=>i.mediaMuted?0:i.mediaVolume,kO=i=>`${Math.round(i*100)}%`,iv=class extends ls{constructor(){super(...arguments),LO(this,Wh,()=>{let e=this.range.value,t=new L.CustomEvent(K.MEDIA_VOLUME_REQUEST,{composed:!0,bubbles:!0,detail:e});this.dispatchEvent(t)})}static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_VOLUME,_.MEDIA_MUTED,_.MEDIA_VOLUME_UNAVAILABLE]}connectedCallback(){super.connectedCallback(),this.range.setAttribute("aria-label",F("volume")),this.range.addEventListener("input",MS(this,Wh))}disconnectedCallback(){this.range.removeEventListener("input",MS(this,Wh)),super.disconnectedCallback()}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),(e===_.MEDIA_VOLUME||e===_.MEDIA_MUTED)&&(this.range.valueAsNumber=xO(this),this.range.setAttribute("aria-valuetext",kO(this.range.valueAsNumber)),this.updateBar())}get mediaVolume(){return ye(this,_.MEDIA_VOLUME,RO)}set mediaVolume(e){Re(this,_.MEDIA_VOLUME,e)}get mediaMuted(){return le(this,_.MEDIA_MUTED)}set mediaMuted(e){de(this,_.MEDIA_MUTED,e)}get mediaVolumeUnavailable(){return pe(this,_.MEDIA_VOLUME_UNAVAILABLE)}set mediaVolumeUnavailable(e){me(this,_.MEDIA_VOLUME_UNAVAILABLE,e)}};Wh=new WeakMap;L.customElements.get("media-volume-range")||L.customElements.define("media-volume-range",iv);function DO(i){return`
1521
+ `}var Uh=(i,e=i.mediaCurrentTime)=>{let t=Number.isFinite(i.mediaSeekableStart)?i.mediaSeekableStart:0,s=Number.isFinite(i.mediaDuration)?i.mediaDuration:i.mediaSeekableEnd;if(Number.isNaN(s))return 0;let r=(e-t)/(s-t);return Math.max(0,Math.min(r,1))},wS=(i,e=i.range.valueAsNumber)=>{let t=Number.isFinite(i.mediaSeekableStart)?i.mediaSeekableStart:0,s=Number.isFinite(i.mediaDuration)?i.mediaDuration:i.mediaSeekableEnd;return Number.isNaN(s)?0:e*(s-t)+t},Jl=class extends ls{constructor(){super(),St(this,j0),St(this,Hh),St(this,Gh),St(this,Kh),St(this,Q0),St(this,Zl),St(this,X0),St(this,Ya,null),St(this,Pr,void 0),St(this,Bh,void 0),St(this,zl,void 0),St(this,$h,void 0),St(this,Fh,void 0),St(this,Ql,void 0),St(this,Xl,void 0),St(this,ja,void 0),St(this,za,void 0),St(this,jl,()=>{Ti(this,j0,kS).call(this)?Ze(this,Pr).start():Ze(this,Pr).stop()}),St(this,z0,s=>{this.dragging||(ba(s)&&(this.range.valueAsNumber=s),Ze(this,za)||this.updateBar())}),this.shadowRoot.querySelector("#track").insertAdjacentHTML("afterbegin",'<div id="buffered" part="buffered"></div>'),bi(this,Bh,this.shadowRoot.querySelectorAll('[part~="box"]')),bi(this,$h,this.shadowRoot.querySelector('[part~="preview-box"]')),bi(this,Fh,this.shadowRoot.querySelector('[part~="current-box"]'));let t=getComputedStyle(this);bi(this,Ql,parseInt(t.getPropertyValue("--media-box-padding-left"))),bi(this,Xl,parseInt(t.getPropertyValue("--media-box-padding-right"))),bi(this,Pr,new Nh(this.range,Ze(this,z0),60))}static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_PAUSED,_.MEDIA_DURATION,_.MEDIA_SEEKABLE,_.MEDIA_CURRENT_TIME,_.MEDIA_PREVIEW_IMAGE,_.MEDIA_PREVIEW_TIME,_.MEDIA_PREVIEW_CHAPTER,_.MEDIA_BUFFERED,_.MEDIA_PLAYBACK_RATE,_.MEDIA_LOADING,_.MEDIA_ENDED]}connectedCallback(){var e;super.connectedCallback(),this.range.setAttribute("aria-label",F("seek")),Ze(this,jl).call(this),bi(this,Ya,this.getRootNode()),(e=Ze(this,Ya))==null||e.addEventListener("transitionstart",this)}disconnectedCallback(){var e;super.disconnectedCallback(),Ze(this,Pr).stop(),(e=Ze(this,Ya))==null||e.removeEventListener("transitionstart",this),bi(this,Ya,null)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),t!=s&&(e===_.MEDIA_CURRENT_TIME||e===_.MEDIA_PAUSED||e===_.MEDIA_ENDED||e===_.MEDIA_LOADING||e===_.MEDIA_DURATION||e===_.MEDIA_SEEKABLE?(Ze(this,Pr).update({start:Uh(this),duration:this.mediaSeekableEnd-this.mediaSeekableStart,playbackRate:this.mediaPlaybackRate}),Ze(this,jl).call(this),AO(this)):e===_.MEDIA_BUFFERED&&this.updateBufferedBar(),(e===_.MEDIA_DURATION||e===_.MEDIA_SEEKABLE)&&(this.mediaChaptersCues=Ze(this,ja),this.updateBar()))}get mediaChaptersCues(){return Ze(this,ja)}set mediaChaptersCues(e){var t;bi(this,ja,e),this.updateSegments((t=Ze(this,ja))==null?void 0:t.map(s=>({start:Uh(this,s.startTime),end:Uh(this,s.endTime)})))}get mediaPaused(){return le(this,_.MEDIA_PAUSED)}set mediaPaused(e){de(this,_.MEDIA_PAUSED,e)}get mediaLoading(){return le(this,_.MEDIA_LOADING)}set mediaLoading(e){de(this,_.MEDIA_LOADING,e)}get mediaDuration(){return ye(this,_.MEDIA_DURATION)}set mediaDuration(e){Re(this,_.MEDIA_DURATION,e)}get mediaCurrentTime(){return ye(this,_.MEDIA_CURRENT_TIME)}set mediaCurrentTime(e){Re(this,_.MEDIA_CURRENT_TIME,e)}get mediaPlaybackRate(){return ye(this,_.MEDIA_PLAYBACK_RATE,1)}set mediaPlaybackRate(e){Re(this,_.MEDIA_PLAYBACK_RATE,e)}get mediaBuffered(){let e=this.getAttribute(_.MEDIA_BUFFERED);return e?e.split(" ").map(t=>t.split(":").map(s=>+s)):[]}set mediaBuffered(e){if(!e){this.removeAttribute(_.MEDIA_BUFFERED);return}let t=e.map(s=>s.join(":")).join(" ");this.setAttribute(_.MEDIA_BUFFERED,t)}get mediaSeekable(){let e=this.getAttribute(_.MEDIA_SEEKABLE);if(e)return e.split(":").map(t=>+t)}set mediaSeekable(e){if(e==null){this.removeAttribute(_.MEDIA_SEEKABLE);return}this.setAttribute(_.MEDIA_SEEKABLE,e.join(":"))}get mediaSeekableEnd(){var e;let[,t=this.mediaDuration]=(e=this.mediaSeekable)!=null?e:[];return t}get mediaSeekableStart(){var e;let[t=0]=(e=this.mediaSeekable)!=null?e:[];return t}get mediaPreviewImage(){return pe(this,_.MEDIA_PREVIEW_IMAGE)}set mediaPreviewImage(e){me(this,_.MEDIA_PREVIEW_IMAGE,e)}get mediaPreviewTime(){return ye(this,_.MEDIA_PREVIEW_TIME)}set mediaPreviewTime(e){Re(this,_.MEDIA_PREVIEW_TIME,e)}get mediaEnded(){return le(this,_.MEDIA_ENDED)}set mediaEnded(e){de(this,_.MEDIA_ENDED,e)}updateBar(){super.updateBar(),this.updateBufferedBar(),this.updateCurrentBox()}updateBufferedBar(){var e;let t=this.mediaBuffered;if(!t.length)return;let s;if(this.mediaEnded)s=1;else{let n=this.mediaCurrentTime,[,a=this.mediaSeekableStart]=(e=t.find(([o,l])=>o<=n&&n<=l))!=null?e:[];s=Uh(this,a)}let{style:r}=je(this.shadowRoot,"#buffered");r.setProperty("width",`${s*100}%`)}updateCurrentBox(){if(!this.shadowRoot.querySelector('slot[name="current"]').assignedElements().length)return;let t=je(this.shadowRoot,"#current-rail"),s=je(this.shadowRoot,'[part~="current-box"]'),r=Ti(this,Hh,J0).call(this,Ze(this,Fh)),n=Ti(this,Gh,ev).call(this,r,this.range.valueAsNumber),a=Ti(this,Kh,tv).call(this,r,this.range.valueAsNumber);t.style.transform=`translateX(${n})`,t.style.setProperty("--_range-width",`${r.range.width}`),s.style.setProperty("--_box-shift",`${a}`),s.style.setProperty("--_box-width",`${r.box.width}px`),s.style.setProperty("visibility","initial")}handleEvent(e){switch(super.handleEvent(e),e.type){case"input":Ti(this,X0,CS).call(this);break;case"pointermove":Ti(this,Q0,DS).call(this,e);break;case"pointerup":Ze(this,za)&&bi(this,za,!1);break;case"pointerdown":bi(this,za,!0);break;case"pointerleave":Ti(this,Zl,Vh).call(this,null);break;case"transitionstart":Kt(e.target,this)&&setTimeout(()=>Ze(this,jl).call(this),0);break}}};Ya=new WeakMap;Pr=new WeakMap;Bh=new WeakMap;zl=new WeakMap;$h=new WeakMap;Fh=new WeakMap;Ql=new WeakMap;Xl=new WeakMap;ja=new WeakMap;za=new WeakMap;jl=new WeakMap;j0=new WeakSet;kS=function(){return this.isConnected&&!this.mediaPaused&&!this.mediaLoading&&!this.mediaEnded&&this.mediaSeekableEnd>0&&Rc(this)};z0=new WeakMap;Hh=new WeakSet;J0=function(i){var e;let s=((e=this.getAttribute("bounds")?is(this,`#${this.getAttribute("bounds")}`):this.parentElement)!=null?e:this).getBoundingClientRect(),r=this.range.getBoundingClientRect(),n=i.offsetWidth,a=-(r.left-s.left-n/2),o=s.right-r.left-n/2;return{box:{width:n,min:a,max:o},bounds:s,range:r}};Gh=new WeakSet;ev=function(i,e){let t=`${e*100}%`,{width:s,min:r,max:n}=i.box;if(!s)return t;if(Number.isNaN(r)||(t=`max(${`calc(1 / var(--_range-width) * 100 * ${r}% + var(--media-box-padding-left))`}, ${t})`),!Number.isNaN(n)){let o=`calc(1 / var(--_range-width) * 100 * ${n}% - var(--media-box-padding-right))`;t=`min(${t}, ${o})`}return t};Kh=new WeakSet;tv=function(i,e){let{width:t,min:s,max:r}=i.box,n=e*i.range.width;if(n<s+Ze(this,Ql)){let a=i.range.left-i.bounds.left-Ze(this,Ql);return`${n-t/2+a}px`}if(n>r-Ze(this,Xl)){let a=i.bounds.right-i.range.right-Ze(this,Xl);return`${n+t/2-a-i.range.width}px`}return 0};Q0=new WeakSet;DS=function(i){let e=[...Ze(this,Bh)].some(u=>i.composedPath().includes(u));if(!this.dragging&&(e||!i.composedPath().includes(this))){Ti(this,Zl,Vh).call(this,null);return}let t=this.mediaSeekableEnd;if(!t)return;let s=je(this.shadowRoot,"#preview-rail"),r=je(this.shadowRoot,'[part~="preview-box"]'),n=Ti(this,Hh,J0).call(this,Ze(this,$h)),a=(i.clientX-n.range.left)/n.range.width;a=Math.max(0,Math.min(1,a));let o=Ti(this,Gh,ev).call(this,n,a),l=Ti(this,Kh,tv).call(this,n,a);s.style.transform=`translateX(${o})`,s.style.setProperty("--_range-width",`${n.range.width}`),r.style.setProperty("--_box-shift",`${l}`),r.style.setProperty("--_box-width",`${n.box.width}px`);let d=Math.round(Ze(this,zl))-Math.round(a*t);Math.abs(d)<1&&a>.01&&a<.99||(bi(this,zl,a*t),Ti(this,Zl,Vh).call(this,Ze(this,zl)))};Zl=new WeakSet;Vh=function(i){this.dispatchEvent(new L.CustomEvent(K.MEDIA_PREVIEW_REQUEST,{composed:!0,bubbles:!0,detail:i}))};X0=new WeakSet;CS=function(){Ze(this,Pr).stop();let i=wS(this);this.dispatchEvent(new L.CustomEvent(K.MEDIA_SEEK_REQUEST,{composed:!0,bubbles:!0,detail:i}))};Jl.shadowRootOptions={mode:"open"};Jl.getContainerTemplateHTML=SO;L.customElements.get("media-time-range")||L.customElements.define("media-time-range",Jl);var IO=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},MS=(i,e,t)=>(IO(i,e,"read from private field"),t?t.call(i):e.get(i)),LO=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},Wh,RO=1,xO=i=>i.mediaMuted?0:i.mediaVolume,kO=i=>`${Math.round(i*100)}%`,iv=class extends ls{constructor(){super(...arguments),LO(this,Wh,()=>{let e=this.range.value,t=new L.CustomEvent(K.MEDIA_VOLUME_REQUEST,{composed:!0,bubbles:!0,detail:e});this.dispatchEvent(t)})}static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_VOLUME,_.MEDIA_MUTED,_.MEDIA_VOLUME_UNAVAILABLE]}connectedCallback(){super.connectedCallback(),this.range.setAttribute("aria-label",F("volume")),this.range.addEventListener("input",MS(this,Wh))}disconnectedCallback(){this.range.removeEventListener("input",MS(this,Wh)),super.disconnectedCallback()}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),(e===_.MEDIA_VOLUME||e===_.MEDIA_MUTED)&&(this.range.valueAsNumber=xO(this),this.range.setAttribute("aria-valuetext",kO(this.range.valueAsNumber)),this.updateBar())}get mediaVolume(){return ye(this,_.MEDIA_VOLUME,RO)}set mediaVolume(e){Re(this,_.MEDIA_VOLUME,e)}get mediaMuted(){return le(this,_.MEDIA_MUTED)}set mediaMuted(e){de(this,_.MEDIA_MUTED,e)}get mediaVolumeUnavailable(){return pe(this,_.MEDIA_VOLUME_UNAVAILABLE)}set mediaVolumeUnavailable(e){me(this,_.MEDIA_VOLUME_UNAVAILABLE,e)}};Wh=new WeakMap;L.customElements.get("media-volume-range")||L.customElements.define("media-volume-range",iv);function DO(i){return`
1522
1522
  <style>
1523
1523
  :host {
1524
1524
  min-width: 4ch;
@@ -1574,7 +1574,7 @@ Schedule: ${l.map(p=>Ci(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Remo
1574
1574
  display: none;
1575
1575
  }
1576
1576
  </style>
1577
- `;var Pn=class extends L.HTMLElement{constructor(){super(),Mn(this,ov),Mn(this,Jh),Mn(this,Ja,void 0),Mn(this,Zh,void 0),Mn(this,eo,void 0),Mn(this,Za,void 0),Mn(this,nd,void 0),this.shadowRoot?this.renderRoot=this.shadowRoot:(this.renderRoot=this.attachShadow({mode:"open"}),this.createRenderer()),qs(this,Za,new MutationObserver(e=>{var t;this.mediaController&&!((t=this.mediaController)!=null&&t.breakpointsComputed)||e.some(s=>{let r=s.target;return r===this?!0:r.localName!=="media-controller"?!1:!!(av[s.attributeName]||s.attributeName.startsWith("breakpoint"))})&&this.render()})),qs(this,nd,this.render.bind(this)),nv(this,ov,VS).call(this,"template")}get mediaController(){return this.renderRoot.querySelector("media-controller")}get template(){var e;return(e=Fr(this,Ja))!=null?e:this.constructor.template}set template(e){if(e===null){this.removeAttribute("template");return}typeof e=="string"?this.setAttribute("template",e):e instanceof HTMLTemplateElement&&(qs(this,Ja,e),qs(this,eo,null),this.createRenderer())}get props(){var e,t,s;let r=[...Array.from((t=(e=this.mediaController)==null?void 0:e.attributes)!=null?t:[]).filter(({name:a})=>av[a]||a.startsWith("breakpoint")),...Array.from(this.attributes)],n={};for(let a of r){let o=(s=av[a.name])!=null?s:J_(a.name),{value:l}=a;l!=null?(yc(l)&&(l=parseFloat(l)),n[o]=l===""?!0:l):n[o]=!1}return n}attributeChangedCallback(e,t,s){e==="template"&&t!=s&&nv(this,Jh,lv).call(this)}connectedCallback(){this.addEventListener(di.BREAKPOINTS_COMPUTED,Fr(this,nd)),Fr(this,Za).observe(this,{attributes:!0}),Fr(this,Za).observe(this.renderRoot,{attributes:!0,subtree:!0}),nv(this,Jh,lv).call(this)}disconnectedCallback(){this.removeEventListener(di.BREAKPOINTS_COMPUTED,Fr(this,nd)),Fr(this,Za).disconnect()}createRenderer(){this.template instanceof HTMLTemplateElement&&this.template!==Fr(this,Zh)&&(qs(this,Zh,this.template),this.renderer=new Vs(this.template,this.props,this.constructor.processor),this.renderRoot.textContent="",this.renderRoot.append(WS.content.cloneNode(!0),this.renderer))}render(){var e;(e=this.renderer)==null||e.update(this.props)}};Ja=new WeakMap;Zh=new WeakMap;eo=new WeakMap;Za=new WeakMap;ov=new WeakSet;VS=function(i){if(Object.prototype.hasOwnProperty.call(this,i)){let e=this[i];delete this[i],this[i]=e}};Jh=new WeakSet;lv=function(){var i;let e=this.getAttribute("template");if(!e||e===Fr(this,eo))return;let t=this.getRootNode(),s=(i=t==null?void 0:t.getElementById)==null?void 0:i.call(t,e);if(s){qs(this,eo,e),qs(this,Ja,s),this.createRenderer();return}BO(e)&&(qs(this,eo,e),$O(e).then(r=>{let n=He.createElement("template");n.innerHTML=r,qs(this,Ja,n),this.createRenderer()}).catch(console.error))};nd=new WeakMap;Pn.observedAttributes=["template"];Pn.processor=Xh;function BO(i){if(!/^(\/|\.\/|https?:\/\/)/.test(i))return!1;let e=/^https?:\/\//.test(i)?void 0:location.origin;try{new URL(i,e)}catch{return!1}return!0}async function $O(i){let e=await fetch(i);if(e.status!==200)throw new Error(`Failed to load resource: the server responded with a status of ${e.status}`);return e.text()}L.customElements.get("media-theme")||L.customElements.define("media-theme",Pn);function qS({anchor:i,floating:e,placement:t}){let s=HO({anchor:i,floating:e}),{x:r,y:n}=KO(s,t);return{x:r,y:n}}function HO({anchor:i,floating:e}){return{anchor:GO(i,e.offsetParent),floating:{x:0,y:0,width:e.offsetWidth,height:e.offsetHeight}}}function GO(i,e){var t;let s=i.getBoundingClientRect(),r=(t=e==null?void 0:e.getBoundingClientRect())!=null?t:{x:0,y:0};return{x:s.x-r.x,y:s.y-r.y,width:s.width,height:s.height}}function KO({anchor:i,floating:e},t){let s=VO(t)==="x"?"y":"x",r=s==="y"?"height":"width",n=YS(t),a=i.x+i.width/2-e.width/2,o=i.y+i.height/2-e.height/2,l=i[r]/2-e[r]/2,d;switch(n){case"top":d={x:a,y:i.y-e.height};break;case"bottom":d={x:a,y:i.y+i.height};break;case"right":d={x:i.x+i.width,y:o};break;case"left":d={x:i.x-e.width,y:o};break;default:d={x:i.x,y:i.y}}switch(t.split("-")[1]){case"start":d[s]-=l;break;case"end":d[s]+=l;break}return d}function YS(i){return i.split("-")[0]}function VO(i){return["top","bottom"].includes(YS(i))?"y":"x"}var Br=class extends Event{constructor({action:e="auto",relatedTarget:t,...s}){super("invoke",s),this.action=e,this.relatedTarget=t}},ef=class extends Event{constructor({newState:e,oldState:t,...s}){super("toggle",s),this.newState=e,this.oldState=t}};var bv=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},Oe=(i,e,t)=>(bv(i,e,"read from private field"),t?t.call(i):e.get(i)),Ge=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},_i=(i,e,t,s)=>(bv(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),Ke=(i,e,t)=>(bv(i,e,"access private method"),t),vs,$r,Ys,tf,ad,Nn,dd,uv,jS,nf,_v,af,sf,cv,hv,zS,fv,QS,mv,XS,to,io,so,ud,of,Av,pv,ZS,Sv,JS,gv,e1,Iv,t1,vv,i1,Ev,s1,od,lf,yv,r1,ld,df,rf,Tv;function Es({type:i,text:e,value:t,checked:s}){let r=He.createElement("media-chrome-menu-item");r.type=i!=null?i:"",r.part.add("menu-item"),i&&r.part.add(i),r.value=t,r.checked=s;let n=He.createElement("span");return n.textContent=e,r.append(n),r}function qi(i,e){let t=i.querySelector(`:scope > [slot="${e}"]`);if((t==null?void 0:t.nodeName)=="SLOT"&&(t=t.assignedElements({flatten:!0})[0]),t)return t=t.cloneNode(!0),t;let s=i.shadowRoot.querySelector(`[name="${e}"] > svg`);return s?s.cloneNode(!0):""}function WO(i){return`
1577
+ `;var Pn=class extends L.HTMLElement{constructor(){super(),Mn(this,ov),Mn(this,Jh),Mn(this,Ja,void 0),Mn(this,Zh,void 0),Mn(this,eo,void 0),Mn(this,Za,void 0),Mn(this,nd,void 0),this.shadowRoot?this.renderRoot=this.shadowRoot:(this.renderRoot=this.attachShadow({mode:"open"}),this.createRenderer()),qs(this,Za,new MutationObserver(e=>{var t;this.mediaController&&!((t=this.mediaController)!=null&&t.breakpointsComputed)||e.some(s=>{let r=s.target;return r===this?!0:r.localName!=="media-controller"?!1:!!(av[s.attributeName]||s.attributeName.startsWith("breakpoint"))})&&this.render()})),qs(this,nd,this.render.bind(this)),nv(this,ov,VS).call(this,"template")}get mediaController(){return this.renderRoot.querySelector("media-controller")}get template(){var e;return(e=Fr(this,Ja))!=null?e:this.constructor.template}set template(e){if(e===null){this.removeAttribute("template");return}typeof e=="string"?this.setAttribute("template",e):e instanceof HTMLTemplateElement&&(qs(this,Ja,e),qs(this,eo,null),this.createRenderer())}get props(){var e,t,s;let r=[...Array.from((t=(e=this.mediaController)==null?void 0:e.attributes)!=null?t:[]).filter(({name:a})=>av[a]||a.startsWith("breakpoint")),...Array.from(this.attributes)],n={};for(let a of r){let o=(s=av[a.name])!=null?s:J_(a.name),{value:l}=a;l!=null?(yc(l)&&(l=parseFloat(l)),n[o]=l===""?!0:l):n[o]=!1}return n}attributeChangedCallback(e,t,s){e==="template"&&t!=s&&nv(this,Jh,lv).call(this)}connectedCallback(){this.addEventListener(di.BREAKPOINTS_COMPUTED,Fr(this,nd)),Fr(this,Za).observe(this,{attributes:!0}),Fr(this,Za).observe(this.renderRoot,{attributes:!0,subtree:!0}),nv(this,Jh,lv).call(this)}disconnectedCallback(){this.removeEventListener(di.BREAKPOINTS_COMPUTED,Fr(this,nd)),Fr(this,Za).disconnect()}createRenderer(){this.template instanceof HTMLTemplateElement&&this.template!==Fr(this,Zh)&&(qs(this,Zh,this.template),this.renderer=new Vs(this.template,this.props,this.constructor.processor),this.renderRoot.textContent="",this.renderRoot.append(WS.content.cloneNode(!0),this.renderer))}render(){var e;(e=this.renderer)==null||e.update(this.props)}};Ja=new WeakMap;Zh=new WeakMap;eo=new WeakMap;Za=new WeakMap;ov=new WeakSet;VS=function(i){if(Object.prototype.hasOwnProperty.call(this,i)){let e=this[i];delete this[i],this[i]=e}};Jh=new WeakSet;lv=function(){var i;let e=this.getAttribute("template");if(!e||e===Fr(this,eo))return;let t=this.getRootNode(),s=(i=t==null?void 0:t.getElementById)==null?void 0:i.call(t,e);if(s){qs(this,eo,e),qs(this,Ja,s),this.createRenderer();return}BO(e)&&(qs(this,eo,e),$O(e).then(r=>{let n=He.createElement("template");n.innerHTML=r,qs(this,Ja,n),this.createRenderer()}).catch(console.error))};nd=new WeakMap;Pn.observedAttributes=["template"];Pn.processor=Xh;function BO(i){if(!/^(\/|\.\/|https?:\/\/)/.test(i))return!1;let e=/^https?:\/\//.test(i)?void 0:location.origin;try{new URL(i,e)}catch{return!1}return!0}async function $O(i){let e=await fetch(i);if(e.status!==200)throw new Error(`Failed to load resource: the server responded with a status of ${e.status}`);return e.text()}L.customElements.get("media-theme")||L.customElements.define("media-theme",Pn);function qS({anchor:i,floating:e,placement:t}){let s=HO({anchor:i,floating:e}),{x:r,y:n}=KO(s,t);return{x:r,y:n}}function HO({anchor:i,floating:e}){return{anchor:GO(i,e.offsetParent),floating:{x:0,y:0,width:e.offsetWidth,height:e.offsetHeight}}}function GO(i,e){var t;let s=i.getBoundingClientRect(),r=(t=e==null?void 0:e.getBoundingClientRect())!=null?t:{x:0,y:0};return{x:s.x-r.x,y:s.y-r.y,width:s.width,height:s.height}}function KO({anchor:i,floating:e},t){let s=VO(t)==="x"?"y":"x",r=s==="y"?"height":"width",n=YS(t),a=i.x+i.width/2-e.width/2,o=i.y+i.height/2-e.height/2,l=i[r]/2-e[r]/2,d;switch(n){case"top":d={x:a,y:i.y-e.height};break;case"bottom":d={x:a,y:i.y+i.height};break;case"right":d={x:i.x+i.width,y:o};break;case"left":d={x:i.x-e.width,y:o};break;default:d={x:i.x,y:i.y}}switch(t.split("-")[1]){case"start":d[s]-=l;break;case"end":d[s]+=l;break}return d}function YS(i){return i.split("-")[0]}function VO(i){return["top","bottom"].includes(YS(i))?"y":"x"}var Br=class extends Event{constructor({action:e="auto",relatedTarget:t,...s}){super("invoke",s),this.action=e,this.relatedTarget=t}},ef=class extends Event{constructor({newState:e,oldState:t,...s}){super("toggle",s),this.newState=e,this.oldState=t}};var Tv=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},Oe=(i,e,t)=>(Tv(i,e,"read from private field"),t?t.call(i):e.get(i)),Ge=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},_i=(i,e,t,s)=>(Tv(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),Ke=(i,e,t)=>(Tv(i,e,"access private method"),t),vs,$r,Ys,tf,ad,Nn,dd,uv,jS,nf,_v,af,sf,cv,hv,zS,fv,QS,mv,XS,to,io,so,ud,of,Av,pv,ZS,Sv,JS,gv,e1,Iv,t1,vv,i1,Ev,s1,od,lf,yv,r1,ld,df,rf,bv;function Es({type:i,text:e,value:t,checked:s}){let r=He.createElement("media-chrome-menu-item");r.type=i!=null?i:"",r.part.add("menu-item"),i&&r.part.add(i),r.value=t,r.checked=s;let n=He.createElement("span");return n.textContent=e,r.append(n),r}function qi(i,e){let t=i.querySelector(`:scope > [slot="${e}"]`);if((t==null?void 0:t.nodeName)=="SLOT"&&(t=t.assignedElements({flatten:!0})[0]),t)return t=t.cloneNode(!0),t;let s=i.shadowRoot.querySelector(`[name="${e}"] > svg`);return s?s.cloneNode(!0):""}function WO(i){return`
1578
1578
  <style>
1579
1579
  :host {
1580
1580
  font: var(--media-font,
@@ -1749,7 +1749,7 @@ Schedule: ${l.map(p=>Ci(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Remo
1749
1749
  <slot></slot>
1750
1750
  </div>
1751
1751
  <slot name="checked-indicator" hidden></slot>
1752
- `}var On={STYLE:"style",HIDDEN:"hidden",DISABLED:"disabled",ANCHOR:"anchor"},lt=class extends L.HTMLElement{constructor(){if(super(),Ge(this,uv),Ge(this,nf),Ge(this,sf),Ge(this,hv),Ge(this,fv),Ge(this,mv),Ge(this,so),Ge(this,of),Ge(this,pv),Ge(this,Sv),Ge(this,gv),Ge(this,Iv),Ge(this,vv),Ge(this,Ev),Ge(this,od),Ge(this,yv),Ge(this,ld),Ge(this,rf),Ge(this,vs,null),Ge(this,$r,null),Ge(this,Ys,null),Ge(this,tf,new Set),Ge(this,ad,void 0),Ge(this,Nn,!1),Ge(this,dd,null),Ge(this,af,()=>{let e=Oe(this,tf),t=new Set(this.items);for(let s of e)t.has(s)||this.dispatchEvent(new CustomEvent("removemenuitem",{detail:s}));for(let s of t)e.has(s)||this.dispatchEvent(new CustomEvent("addmenuitem",{detail:s}));_i(this,tf,t)}),Ge(this,to,()=>{Ke(this,so,ud).call(this),Ke(this,of,Av).call(this,!1)}),Ge(this,io,()=>{Ke(this,so,ud).call(this)}),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=Qe(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e)}this.container=this.shadowRoot.querySelector("#container"),this.defaultSlot=this.shadowRoot.querySelector("slot:not([name])"),_i(this,ad,new MutationObserver(Oe(this,af)))}static get observedAttributes(){return[On.DISABLED,On.HIDDEN,On.STYLE,On.ANCHOR,ge.MEDIA_CONTROLLER]}static formatMenuItemText(e,t){return e}enable(){this.addEventListener("click",this),this.addEventListener("focusout",this),this.addEventListener("keydown",this),this.addEventListener("invoke",this),this.addEventListener("toggle",this)}disable(){this.removeEventListener("click",this),this.removeEventListener("focusout",this),this.removeEventListener("keyup",this),this.removeEventListener("invoke",this),this.removeEventListener("toggle",this)}handleEvent(e){switch(e.type){case"slotchange":Ke(this,uv,jS).call(this,e);break;case"invoke":Ke(this,hv,zS).call(this,e);break;case"click":Ke(this,pv,ZS).call(this,e);break;case"toggle":Ke(this,gv,e1).call(this,e);break;case"focusout":Ke(this,vv,i1).call(this,e);break;case"keydown":Ke(this,Ev,s1).call(this,e);break}}connectedCallback(){var e,t;Oe(this,ad).observe(this.defaultSlot,{childList:!0}),_i(this,dd,gl(this.shadowRoot,":host")),Ke(this,sf,cv).call(this),this.hasAttribute("disabled")||this.enable(),this.role||(this.role="menu"),_i(this,vs,Sc(this)),(t=(e=Oe(this,vs))==null?void 0:e.associateElement)==null||t.call(e,this),this.hidden||(Us(cd(this),Oe(this,to)),Us(this,Oe(this,io))),Ke(this,nf,_v).call(this),this.shadowRoot.addEventListener("slotchange",this)}disconnectedCallback(){var e,t;Oe(this,ad).disconnect(),Fs(cd(this),Oe(this,to)),Fs(this,Oe(this,io)),this.disable(),(t=(e=Oe(this,vs))==null?void 0:e.unassociateElement)==null||t.call(e,this),_i(this,vs,null),_i(this,$r,null),_i(this,Ys,null),this.shadowRoot.removeEventListener("slotchange",this)}attributeChangedCallback(e,t,s){var r,n,a,o;e===On.HIDDEN&&s!==t?(Oe(this,Nn)||_i(this,Nn,!0),this.hidden?Ke(this,mv,XS).call(this):Ke(this,fv,QS).call(this),this.dispatchEvent(new ef({oldState:this.hidden?"open":"closed",newState:this.hidden?"closed":"open",bubbles:!0}))):e===ge.MEDIA_CONTROLLER?(t&&((n=(r=Oe(this,vs))==null?void 0:r.unassociateElement)==null||n.call(r,this),_i(this,vs,null)),s&&this.isConnected&&(_i(this,vs,Sc(this)),(o=(a=Oe(this,vs))==null?void 0:a.associateElement)==null||o.call(a,this))):e===On.DISABLED&&s!==t?s==null?this.enable():this.disable():e===On.STYLE&&s!==t&&Ke(this,sf,cv).call(this)}formatMenuItemText(e,t){return this.constructor.formatMenuItemText(e,t)}get anchor(){return this.getAttribute("anchor")}set anchor(e){this.setAttribute("anchor",`${e}`)}get anchorElement(){var e;return this.anchor?(e=pn(this))==null?void 0:e.querySelector(`#${this.anchor}`):null}get items(){return this.defaultSlot.assignedElements({flatten:!0}).filter(qO)}get radioGroupItems(){return this.items.filter(e=>e.role==="menuitemradio")}get checkedItems(){return this.items.filter(e=>e.checked)}get value(){var e,t;return(t=(e=this.checkedItems[0])==null?void 0:e.value)!=null?t:""}set value(e){let t=this.items.find(s=>s.value===e);t&&Ke(this,rf,Tv).call(this,t)}focus(){if(_i(this,$r,pl()),this.items.length){Ke(this,ld,df).call(this,this.items[0]),this.items[0].focus();return}let e=this.querySelector('[autofocus], [tabindex]:not([tabindex="-1"]), [role="menu"]');e==null||e.focus()}handleSelect(e){var t;let s=Ke(this,od,lf).call(this,e);s&&(Ke(this,rf,Tv).call(this,s,s.type==="checkbox"),Oe(this,Ys)&&!this.hidden&&((t=Oe(this,$r))==null||t.focus(),this.hidden=!0))}get keysUsed(){return["Enter","Escape","Tab"," ","ArrowDown","ArrowUp","Home","End"]}handleMove(e){var t,s;let{key:r}=e,n=this.items,a=(s=(t=Ke(this,od,lf).call(this,e))!=null?t:Ke(this,yv,r1).call(this))!=null?s:n[0],o=n.indexOf(a),l=Math.max(0,o);r==="ArrowDown"?l++:r==="ArrowUp"?l--:e.key==="Home"?l=0:e.key==="End"&&(l=n.length-1),l<0&&(l=n.length-1),l>n.length-1&&(l=0),Ke(this,ld,df).call(this,n[l]),n[l].focus()}};vs=new WeakMap;$r=new WeakMap;Ys=new WeakMap;tf=new WeakMap;ad=new WeakMap;Nn=new WeakMap;dd=new WeakMap;uv=new WeakSet;jS=function(i){let e=i.target;for(let t of e.assignedNodes({flatten:!0}))t.nodeType===3&&t.textContent.trim()===""&&t.remove();["header","title"].includes(e.name)&&Ke(this,nf,_v).call(this),e.name||Oe(this,af).call(this)};nf=new WeakSet;_v=function(){let i=this.shadowRoot.querySelector('slot[name="header"]'),e=this.shadowRoot.querySelector('slot[name="title"]');i.hidden=e.assignedNodes().length===0&&i.assignedNodes().length===0};af=new WeakMap;sf=new WeakSet;cv=function(){var i;let e=this.shadowRoot.querySelector("#layout-row"),t=(i=getComputedStyle(this).getPropertyValue("--media-menu-layout"))==null?void 0:i.trim();e.setAttribute("media",t==="row"?"":"width:0")};hv=new WeakSet;zS=function(i){_i(this,Ys,i.relatedTarget),Kt(this,i.relatedTarget)||(this.hidden=!this.hidden)};fv=new WeakSet;QS=function(){var i;(i=Oe(this,Ys))==null||i.setAttribute("aria-expanded","true"),this.addEventListener("transitionend",()=>this.focus(),{once:!0}),Us(cd(this),Oe(this,to)),Us(this,Oe(this,io))};mv=new WeakSet;XS=function(){var i;(i=Oe(this,Ys))==null||i.setAttribute("aria-expanded","false"),Fs(cd(this),Oe(this,to)),Fs(this,Oe(this,io))};to=new WeakMap;io=new WeakMap;so=new WeakSet;ud=function(i){if(this.hasAttribute("mediacontroller")&&!this.anchor||this.hidden||!this.anchorElement)return;let{x:e,y:t}=qS({anchor:this.anchorElement,floating:this,placement:"top-start"});i!=null||(i=this.offsetWidth);let r=cd(this).getBoundingClientRect(),n=r.width-e-i,a=r.height-t-this.offsetHeight,{style:o}=Oe(this,dd);o.setProperty("position","absolute"),o.setProperty("right",`${Math.max(0,n)}px`),o.setProperty("--_menu-bottom",`${a}px`);let l=getComputedStyle(this),u=o.getPropertyValue("--_menu-bottom")===l.bottom?a:parseFloat(l.bottom),c=r.height-u-parseFloat(l.marginBottom);this.style.setProperty("--_menu-max-height",`${c}px`)};of=new WeakSet;Av=function(i){let e=this.querySelector('[role="menuitem"][aria-haspopup][aria-expanded="true"]'),t=e==null?void 0:e.querySelector('[role="menu"]'),{style:s}=Oe(this,dd);if(i||s.setProperty("--media-menu-transition-in","none"),t){let r=t.offsetHeight,n=Math.max(t.offsetWidth,e.offsetWidth);this.style.setProperty("min-width",`${n}px`),this.style.setProperty("min-height",`${r}px`),Ke(this,so,ud).call(this,n)}else this.style.removeProperty("min-width"),this.style.removeProperty("min-height"),Ke(this,so,ud).call(this);s.removeProperty("--media-menu-transition-in")};pv=new WeakSet;ZS=function(i){var e;if(i.stopPropagation(),i.composedPath().includes(Oe(this,Sv,JS))){(e=Oe(this,$r))==null||e.focus(),this.hidden=!0;return}let t=Ke(this,od,lf).call(this,i);!t||t.hasAttribute("disabled")||(Ke(this,ld,df).call(this,t),this.handleSelect(i))};Sv=new WeakSet;JS=function(){var i;return(i=this.shadowRoot.querySelector('slot[name="header"]').assignedElements({flatten:!0}))==null?void 0:i.find(t=>t.matches('button[part~="back"]'))};gv=new WeakSet;e1=function(i){if(i.target===this)return;Ke(this,Iv,t1).call(this);let e=Array.from(this.querySelectorAll('[role="menuitem"][aria-haspopup]'));for(let t of e)t.invokeTargetElement!=i.target&&i.newState=="open"&&t.getAttribute("aria-expanded")=="true"&&!t.invokeTargetElement.hidden&&t.invokeTargetElement.dispatchEvent(new Br({relatedTarget:t}));for(let t of e)t.setAttribute("aria-expanded",`${!t.submenuElement.hidden}`);Ke(this,of,Av).call(this,!0)};Iv=new WeakSet;t1=function(){let e=this.querySelector('[role="menuitem"] > [role="menu"]:not([hidden])');this.container.classList.toggle("has-expanded",!!e)};vv=new WeakSet;i1=function(i){var e;Kt(this,i.relatedTarget)||(Oe(this,Nn)&&((e=Oe(this,$r))==null||e.focus()),Oe(this,Ys)&&Oe(this,Ys)!==i.relatedTarget&&!this.hidden&&(this.hidden=!0))};Ev=new WeakSet;s1=function(i){var e,t,s,r,n;let{key:a,ctrlKey:o,altKey:l,metaKey:d}=i;if(!(o||l||d)&&this.keysUsed.includes(a))if(i.preventDefault(),i.stopPropagation(),a==="Tab"){if(Oe(this,Nn)){this.hidden=!0;return}i.shiftKey?(t=(e=this.previousElementSibling)==null?void 0:e.focus)==null||t.call(e):(r=(s=this.nextElementSibling)==null?void 0:s.focus)==null||r.call(s),this.blur()}else a==="Escape"?((n=Oe(this,$r))==null||n.focus(),Oe(this,Nn)&&(this.hidden=!0)):a==="Enter"||a===" "?this.handleSelect(i):this.handleMove(i)};od=new WeakSet;lf=function(i){return i.composedPath().find(e=>["menuitemradio","menuitemcheckbox"].includes(e.role))};yv=new WeakSet;r1=function(){return this.items.find(i=>i.tabIndex===0)};ld=new WeakSet;df=function(i){for(let e of this.items)e.tabIndex=e===i?0:-1};rf=new WeakSet;Tv=function(i,e){let t=[...this.checkedItems];i.type==="radio"&&this.radioGroupItems.forEach(s=>s.checked=!1),e?i.checked=!i.checked:i.checked=!0,this.checkedItems.some((s,r)=>s!=t[r])&&this.dispatchEvent(new Event("change",{bubbles:!0,composed:!0}))};lt.shadowRootOptions={mode:"open"};lt.getTemplateHTML=WO;function qO(i){return["menuitem","menuitemradio","menuitemcheckbox"].includes(i==null?void 0:i.role)}function cd(i){var e;return(e=i.getAttribute("bounds")?is(i,`#${i.getAttribute("bounds")}`):Ye(i)||i.parentElement)!=null?e:i}L.customElements.get("media-chrome-menu")||L.customElements.define("media-chrome-menu",lt);var Cv=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},qt=(i,e,t)=>(Cv(i,e,"read from private field"),t?t.call(i):e.get(i)),js=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},Lv=(i,e,t,s)=>(Cv(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),no=(i,e,t)=>(Cv(i,e,"access private method"),t),uf,fd,Rv,n1,hf,wv,Mv,a1,ys,ro,xv,cf,kv;function YO(i){return`
1752
+ `}var On={STYLE:"style",HIDDEN:"hidden",DISABLED:"disabled",ANCHOR:"anchor"},lt=class extends L.HTMLElement{constructor(){if(super(),Ge(this,uv),Ge(this,nf),Ge(this,sf),Ge(this,hv),Ge(this,fv),Ge(this,mv),Ge(this,so),Ge(this,of),Ge(this,pv),Ge(this,Sv),Ge(this,gv),Ge(this,Iv),Ge(this,vv),Ge(this,Ev),Ge(this,od),Ge(this,yv),Ge(this,ld),Ge(this,rf),Ge(this,vs,null),Ge(this,$r,null),Ge(this,Ys,null),Ge(this,tf,new Set),Ge(this,ad,void 0),Ge(this,Nn,!1),Ge(this,dd,null),Ge(this,af,()=>{let e=Oe(this,tf),t=new Set(this.items);for(let s of e)t.has(s)||this.dispatchEvent(new CustomEvent("removemenuitem",{detail:s}));for(let s of t)e.has(s)||this.dispatchEvent(new CustomEvent("addmenuitem",{detail:s}));_i(this,tf,t)}),Ge(this,to,()=>{Ke(this,so,ud).call(this),Ke(this,of,Av).call(this,!1)}),Ge(this,io,()=>{Ke(this,so,ud).call(this)}),!this.shadowRoot){this.attachShadow(this.constructor.shadowRootOptions);let e=Qe(this.attributes);this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e)}this.container=this.shadowRoot.querySelector("#container"),this.defaultSlot=this.shadowRoot.querySelector("slot:not([name])"),_i(this,ad,new MutationObserver(Oe(this,af)))}static get observedAttributes(){return[On.DISABLED,On.HIDDEN,On.STYLE,On.ANCHOR,ge.MEDIA_CONTROLLER]}static formatMenuItemText(e,t){return e}enable(){this.addEventListener("click",this),this.addEventListener("focusout",this),this.addEventListener("keydown",this),this.addEventListener("invoke",this),this.addEventListener("toggle",this)}disable(){this.removeEventListener("click",this),this.removeEventListener("focusout",this),this.removeEventListener("keyup",this),this.removeEventListener("invoke",this),this.removeEventListener("toggle",this)}handleEvent(e){switch(e.type){case"slotchange":Ke(this,uv,jS).call(this,e);break;case"invoke":Ke(this,hv,zS).call(this,e);break;case"click":Ke(this,pv,ZS).call(this,e);break;case"toggle":Ke(this,gv,e1).call(this,e);break;case"focusout":Ke(this,vv,i1).call(this,e);break;case"keydown":Ke(this,Ev,s1).call(this,e);break}}connectedCallback(){var e,t;Oe(this,ad).observe(this.defaultSlot,{childList:!0}),_i(this,dd,gl(this.shadowRoot,":host")),Ke(this,sf,cv).call(this),this.hasAttribute("disabled")||this.enable(),this.role||(this.role="menu"),_i(this,vs,Sc(this)),(t=(e=Oe(this,vs))==null?void 0:e.associateElement)==null||t.call(e,this),this.hidden||(Us(cd(this),Oe(this,to)),Us(this,Oe(this,io))),Ke(this,nf,_v).call(this),this.shadowRoot.addEventListener("slotchange",this)}disconnectedCallback(){var e,t;Oe(this,ad).disconnect(),Fs(cd(this),Oe(this,to)),Fs(this,Oe(this,io)),this.disable(),(t=(e=Oe(this,vs))==null?void 0:e.unassociateElement)==null||t.call(e,this),_i(this,vs,null),_i(this,$r,null),_i(this,Ys,null),this.shadowRoot.removeEventListener("slotchange",this)}attributeChangedCallback(e,t,s){var r,n,a,o;e===On.HIDDEN&&s!==t?(Oe(this,Nn)||_i(this,Nn,!0),this.hidden?Ke(this,mv,XS).call(this):Ke(this,fv,QS).call(this),this.dispatchEvent(new ef({oldState:this.hidden?"open":"closed",newState:this.hidden?"closed":"open",bubbles:!0}))):e===ge.MEDIA_CONTROLLER?(t&&((n=(r=Oe(this,vs))==null?void 0:r.unassociateElement)==null||n.call(r,this),_i(this,vs,null)),s&&this.isConnected&&(_i(this,vs,Sc(this)),(o=(a=Oe(this,vs))==null?void 0:a.associateElement)==null||o.call(a,this))):e===On.DISABLED&&s!==t?s==null?this.enable():this.disable():e===On.STYLE&&s!==t&&Ke(this,sf,cv).call(this)}formatMenuItemText(e,t){return this.constructor.formatMenuItemText(e,t)}get anchor(){return this.getAttribute("anchor")}set anchor(e){this.setAttribute("anchor",`${e}`)}get anchorElement(){var e;return this.anchor?(e=pn(this))==null?void 0:e.querySelector(`#${this.anchor}`):null}get items(){return this.defaultSlot.assignedElements({flatten:!0}).filter(qO)}get radioGroupItems(){return this.items.filter(e=>e.role==="menuitemradio")}get checkedItems(){return this.items.filter(e=>e.checked)}get value(){var e,t;return(t=(e=this.checkedItems[0])==null?void 0:e.value)!=null?t:""}set value(e){let t=this.items.find(s=>s.value===e);t&&Ke(this,rf,bv).call(this,t)}focus(){if(_i(this,$r,pl()),this.items.length){Ke(this,ld,df).call(this,this.items[0]),this.items[0].focus();return}let e=this.querySelector('[autofocus], [tabindex]:not([tabindex="-1"]), [role="menu"]');e==null||e.focus()}handleSelect(e){var t;let s=Ke(this,od,lf).call(this,e);s&&(Ke(this,rf,bv).call(this,s,s.type==="checkbox"),Oe(this,Ys)&&!this.hidden&&((t=Oe(this,$r))==null||t.focus(),this.hidden=!0))}get keysUsed(){return["Enter","Escape","Tab"," ","ArrowDown","ArrowUp","Home","End"]}handleMove(e){var t,s;let{key:r}=e,n=this.items,a=(s=(t=Ke(this,od,lf).call(this,e))!=null?t:Ke(this,yv,r1).call(this))!=null?s:n[0],o=n.indexOf(a),l=Math.max(0,o);r==="ArrowDown"?l++:r==="ArrowUp"?l--:e.key==="Home"?l=0:e.key==="End"&&(l=n.length-1),l<0&&(l=n.length-1),l>n.length-1&&(l=0),Ke(this,ld,df).call(this,n[l]),n[l].focus()}};vs=new WeakMap;$r=new WeakMap;Ys=new WeakMap;tf=new WeakMap;ad=new WeakMap;Nn=new WeakMap;dd=new WeakMap;uv=new WeakSet;jS=function(i){let e=i.target;for(let t of e.assignedNodes({flatten:!0}))t.nodeType===3&&t.textContent.trim()===""&&t.remove();["header","title"].includes(e.name)&&Ke(this,nf,_v).call(this),e.name||Oe(this,af).call(this)};nf=new WeakSet;_v=function(){let i=this.shadowRoot.querySelector('slot[name="header"]'),e=this.shadowRoot.querySelector('slot[name="title"]');i.hidden=e.assignedNodes().length===0&&i.assignedNodes().length===0};af=new WeakMap;sf=new WeakSet;cv=function(){var i;let e=this.shadowRoot.querySelector("#layout-row"),t=(i=getComputedStyle(this).getPropertyValue("--media-menu-layout"))==null?void 0:i.trim();e.setAttribute("media",t==="row"?"":"width:0")};hv=new WeakSet;zS=function(i){_i(this,Ys,i.relatedTarget),Kt(this,i.relatedTarget)||(this.hidden=!this.hidden)};fv=new WeakSet;QS=function(){var i;(i=Oe(this,Ys))==null||i.setAttribute("aria-expanded","true"),this.addEventListener("transitionend",()=>this.focus(),{once:!0}),Us(cd(this),Oe(this,to)),Us(this,Oe(this,io))};mv=new WeakSet;XS=function(){var i;(i=Oe(this,Ys))==null||i.setAttribute("aria-expanded","false"),Fs(cd(this),Oe(this,to)),Fs(this,Oe(this,io))};to=new WeakMap;io=new WeakMap;so=new WeakSet;ud=function(i){if(this.hasAttribute("mediacontroller")&&!this.anchor||this.hidden||!this.anchorElement)return;let{x:e,y:t}=qS({anchor:this.anchorElement,floating:this,placement:"top-start"});i!=null||(i=this.offsetWidth);let r=cd(this).getBoundingClientRect(),n=r.width-e-i,a=r.height-t-this.offsetHeight,{style:o}=Oe(this,dd);o.setProperty("position","absolute"),o.setProperty("right",`${Math.max(0,n)}px`),o.setProperty("--_menu-bottom",`${a}px`);let l=getComputedStyle(this),u=o.getPropertyValue("--_menu-bottom")===l.bottom?a:parseFloat(l.bottom),c=r.height-u-parseFloat(l.marginBottom);this.style.setProperty("--_menu-max-height",`${c}px`)};of=new WeakSet;Av=function(i){let e=this.querySelector('[role="menuitem"][aria-haspopup][aria-expanded="true"]'),t=e==null?void 0:e.querySelector('[role="menu"]'),{style:s}=Oe(this,dd);if(i||s.setProperty("--media-menu-transition-in","none"),t){let r=t.offsetHeight,n=Math.max(t.offsetWidth,e.offsetWidth);this.style.setProperty("min-width",`${n}px`),this.style.setProperty("min-height",`${r}px`),Ke(this,so,ud).call(this,n)}else this.style.removeProperty("min-width"),this.style.removeProperty("min-height"),Ke(this,so,ud).call(this);s.removeProperty("--media-menu-transition-in")};pv=new WeakSet;ZS=function(i){var e;if(i.stopPropagation(),i.composedPath().includes(Oe(this,Sv,JS))){(e=Oe(this,$r))==null||e.focus(),this.hidden=!0;return}let t=Ke(this,od,lf).call(this,i);!t||t.hasAttribute("disabled")||(Ke(this,ld,df).call(this,t),this.handleSelect(i))};Sv=new WeakSet;JS=function(){var i;return(i=this.shadowRoot.querySelector('slot[name="header"]').assignedElements({flatten:!0}))==null?void 0:i.find(t=>t.matches('button[part~="back"]'))};gv=new WeakSet;e1=function(i){if(i.target===this)return;Ke(this,Iv,t1).call(this);let e=Array.from(this.querySelectorAll('[role="menuitem"][aria-haspopup]'));for(let t of e)t.invokeTargetElement!=i.target&&i.newState=="open"&&t.getAttribute("aria-expanded")=="true"&&!t.invokeTargetElement.hidden&&t.invokeTargetElement.dispatchEvent(new Br({relatedTarget:t}));for(let t of e)t.setAttribute("aria-expanded",`${!t.submenuElement.hidden}`);Ke(this,of,Av).call(this,!0)};Iv=new WeakSet;t1=function(){let e=this.querySelector('[role="menuitem"] > [role="menu"]:not([hidden])');this.container.classList.toggle("has-expanded",!!e)};vv=new WeakSet;i1=function(i){var e;Kt(this,i.relatedTarget)||(Oe(this,Nn)&&((e=Oe(this,$r))==null||e.focus()),Oe(this,Ys)&&Oe(this,Ys)!==i.relatedTarget&&!this.hidden&&(this.hidden=!0))};Ev=new WeakSet;s1=function(i){var e,t,s,r,n;let{key:a,ctrlKey:o,altKey:l,metaKey:d}=i;if(!(o||l||d)&&this.keysUsed.includes(a))if(i.preventDefault(),i.stopPropagation(),a==="Tab"){if(Oe(this,Nn)){this.hidden=!0;return}i.shiftKey?(t=(e=this.previousElementSibling)==null?void 0:e.focus)==null||t.call(e):(r=(s=this.nextElementSibling)==null?void 0:s.focus)==null||r.call(s),this.blur()}else a==="Escape"?((n=Oe(this,$r))==null||n.focus(),Oe(this,Nn)&&(this.hidden=!0)):a==="Enter"||a===" "?this.handleSelect(i):this.handleMove(i)};od=new WeakSet;lf=function(i){return i.composedPath().find(e=>["menuitemradio","menuitemcheckbox"].includes(e.role))};yv=new WeakSet;r1=function(){return this.items.find(i=>i.tabIndex===0)};ld=new WeakSet;df=function(i){for(let e of this.items)e.tabIndex=e===i?0:-1};rf=new WeakSet;bv=function(i,e){let t=[...this.checkedItems];i.type==="radio"&&this.radioGroupItems.forEach(s=>s.checked=!1),e?i.checked=!i.checked:i.checked=!0,this.checkedItems.some((s,r)=>s!=t[r])&&this.dispatchEvent(new Event("change",{bubbles:!0,composed:!0}))};lt.shadowRootOptions={mode:"open"};lt.getTemplateHTML=WO;function qO(i){return["menuitem","menuitemradio","menuitemcheckbox"].includes(i==null?void 0:i.role)}function cd(i){var e;return(e=i.getAttribute("bounds")?is(i,`#${i.getAttribute("bounds")}`):Ye(i)||i.parentElement)!=null?e:i}L.customElements.get("media-chrome-menu")||L.customElements.define("media-chrome-menu",lt);var Cv=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},qt=(i,e,t)=>(Cv(i,e,"read from private field"),t?t.call(i):e.get(i)),js=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},Lv=(i,e,t,s)=>(Cv(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),no=(i,e,t)=>(Cv(i,e,"access private method"),t),uf,fd,Rv,n1,hf,wv,Mv,a1,ys,ro,xv,cf,kv;function YO(i){return`
1753
1753
  <style>
1754
1754
  :host {
1755
1755
  transition: var(--media-menu-item-transition,
@@ -1938,13 +1938,13 @@ Schedule: ${l.map(p=>Ci(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Remo
1938
1938
  }
1939
1939
  </style>
1940
1940
  <slot name="icon">${e2}</slot>
1941
- `}function i2(){return F("Audio")}var l1=i=>{let e=F("Audio");i.setAttribute("aria-label",e)},oo=class extends ei{static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_AUDIO_TRACK_ENABLED,_.MEDIA_AUDIO_TRACK_UNAVAILABLE]}connectedCallback(){super.connectedCallback(),l1(this)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===_.MEDIA_LANG&&l1(this)}get invokeTargetElement(){var e;return this.invokeTarget!=null?super.invokeTargetElement:(e=Ye(this))==null?void 0:e.querySelector("media-audio-track-menu")}get mediaAudioTrackEnabled(){var e;return(e=pe(this,_.MEDIA_AUDIO_TRACK_ENABLED))!=null?e:""}set mediaAudioTrackEnabled(e){me(this,_.MEDIA_AUDIO_TRACK_ENABLED,e)}};oo.getSlotTemplateHTML=t2;oo.getTooltipContentHTML=i2;L.customElements.get("media-audio-track-menu-button")||L.customElements.define("media-audio-track-menu-button",oo);var Hv=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},s2=(i,e,t)=>(Hv(i,e,"read from private field"),t?t.call(i):e.get(i)),Fv=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},r2=(i,e,t,s)=>(Hv(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),yf=(i,e,t)=>(Hv(i,e,"access private method"),t),_f,Tf,Bv,bf,$v,n2=`
1941
+ `}function i2(){return F("Audio")}var l1=i=>{let e=F("Audio");i.setAttribute("aria-label",e)},oo=class extends ei{static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_AUDIO_TRACK_ENABLED,_.MEDIA_AUDIO_TRACK_UNAVAILABLE]}connectedCallback(){super.connectedCallback(),l1(this)}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===_.MEDIA_LANG&&l1(this)}get invokeTargetElement(){var e;return this.invokeTarget!=null?super.invokeTargetElement:(e=Ye(this))==null?void 0:e.querySelector("media-audio-track-menu")}get mediaAudioTrackEnabled(){var e;return(e=pe(this,_.MEDIA_AUDIO_TRACK_ENABLED))!=null?e:""}set mediaAudioTrackEnabled(e){me(this,_.MEDIA_AUDIO_TRACK_ENABLED,e)}};oo.getSlotTemplateHTML=t2;oo.getTooltipContentHTML=i2;L.customElements.get("media-audio-track-menu-button")||L.customElements.define("media-audio-track-menu-button",oo);var Hv=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},s2=(i,e,t)=>(Hv(i,e,"read from private field"),t?t.call(i):e.get(i)),Fv=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},r2=(i,e,t,s)=>(Hv(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),yf=(i,e,t)=>(Hv(i,e,"access private method"),t),_f,bf,Bv,Tf,$v,n2=`
1942
1942
  <svg aria-hidden="true" viewBox="0 0 26 24" part="captions-indicator indicator">
1943
1943
  <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"/>
1944
1944
  </svg>`;function a2(i){return`
1945
1945
  ${lt.getTemplateHTML(i)}
1946
1946
  <slot name="captions-indicator" hidden>${n2}</slot>
1947
- `}var gd=class extends lt{constructor(){super(...arguments),Fv(this,Tf),Fv(this,bf),Fv(this,_f,void 0)}static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_SUBTITLES_LIST,_.MEDIA_SUBTITLES_SHOWING]}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===_.MEDIA_SUBTITLES_LIST&&t!==s?yf(this,Tf,Bv).call(this):e===_.MEDIA_SUBTITLES_SHOWING&&t!==s&&(this.value=s||"",yf(this,Tf,Bv).call(this))}connectedCallback(){super.connectedCallback(),this.addEventListener("change",yf(this,bf,$v))}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("change",yf(this,bf,$v))}get anchorElement(){return this.anchor!=="auto"?super.anchorElement:Ye(this).querySelector("media-captions-menu-button")}get mediaSubtitlesList(){return d1(this,_.MEDIA_SUBTITLES_LIST)}set mediaSubtitlesList(e){u1(this,_.MEDIA_SUBTITLES_LIST,e)}get mediaSubtitlesShowing(){return d1(this,_.MEDIA_SUBTITLES_SHOWING)}set mediaSubtitlesShowing(e){u1(this,_.MEDIA_SUBTITLES_SHOWING,e)}};_f=new WeakMap;Tf=new WeakSet;Bv=function(){var i;let e=s2(this,_f)!==JSON.stringify(this.mediaSubtitlesList),t=this.value!==this.getAttribute(_.MEDIA_SUBTITLES_SHOWING);if(!e&&!t)return;r2(this,_f,JSON.stringify(this.mediaSubtitlesList)),this.defaultSlot.textContent="";let s=!this.value,r=Es({type:"radio",text:this.formatMenuItemText(F("Off")),value:"off",checked:s});r.prepend(qi(this,"checked-indicator")),this.defaultSlot.append(r);let n=this.mediaSubtitlesList;for(let a of n){let o=Es({type:"radio",text:this.formatMenuItemText(a.label,a),value:Uc(a),checked:this.value==Uc(a)});o.prepend(qi(this,"checked-indicator")),((i=a.kind)!=null?i:"subs")==="captions"&&o.append(qi(this,"captions-indicator")),this.defaultSlot.append(o)}};bf=new WeakSet;$v=function(){let i=this.mediaSubtitlesShowing,e=this.getAttribute(_.MEDIA_SUBTITLES_SHOWING),t=this.value!==e;if(i!=null&&i.length&&t&&this.dispatchEvent(new L.CustomEvent(K.MEDIA_DISABLE_SUBTITLES_REQUEST,{composed:!0,bubbles:!0,detail:i})),!this.value||!t)return;let s=new L.CustomEvent(K.MEDIA_SHOW_SUBTITLES_REQUEST,{composed:!0,bubbles:!0,detail:this.value});this.dispatchEvent(s)};gd.getTemplateHTML=a2;var d1=(i,e)=>{let t=i.getAttribute(e);return t?En(t):[]},u1=(i,e,t)=>{if(!(t!=null&&t.length)){i.removeAttribute(e);return}let s=$s(t);i.getAttribute(e)!==s&&i.setAttribute(e,s)};L.customElements.get("media-captions-menu")||L.customElements.define("media-captions-menu",gd);var o2=`<svg aria-hidden="true" viewBox="0 0 26 24">
1947
+ `}var gd=class extends lt{constructor(){super(...arguments),Fv(this,bf),Fv(this,Tf),Fv(this,_f,void 0)}static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_SUBTITLES_LIST,_.MEDIA_SUBTITLES_SHOWING]}attributeChangedCallback(e,t,s){super.attributeChangedCallback(e,t,s),e===_.MEDIA_SUBTITLES_LIST&&t!==s?yf(this,bf,Bv).call(this):e===_.MEDIA_SUBTITLES_SHOWING&&t!==s&&(this.value=s||"",yf(this,bf,Bv).call(this))}connectedCallback(){super.connectedCallback(),this.addEventListener("change",yf(this,Tf,$v))}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("change",yf(this,Tf,$v))}get anchorElement(){return this.anchor!=="auto"?super.anchorElement:Ye(this).querySelector("media-captions-menu-button")}get mediaSubtitlesList(){return d1(this,_.MEDIA_SUBTITLES_LIST)}set mediaSubtitlesList(e){u1(this,_.MEDIA_SUBTITLES_LIST,e)}get mediaSubtitlesShowing(){return d1(this,_.MEDIA_SUBTITLES_SHOWING)}set mediaSubtitlesShowing(e){u1(this,_.MEDIA_SUBTITLES_SHOWING,e)}};_f=new WeakMap;bf=new WeakSet;Bv=function(){var i;let e=s2(this,_f)!==JSON.stringify(this.mediaSubtitlesList),t=this.value!==this.getAttribute(_.MEDIA_SUBTITLES_SHOWING);if(!e&&!t)return;r2(this,_f,JSON.stringify(this.mediaSubtitlesList)),this.defaultSlot.textContent="";let s=!this.value,r=Es({type:"radio",text:this.formatMenuItemText(F("Off")),value:"off",checked:s});r.prepend(qi(this,"checked-indicator")),this.defaultSlot.append(r);let n=this.mediaSubtitlesList;for(let a of n){let o=Es({type:"radio",text:this.formatMenuItemText(a.label,a),value:Uc(a),checked:this.value==Uc(a)});o.prepend(qi(this,"checked-indicator")),((i=a.kind)!=null?i:"subs")==="captions"&&o.append(qi(this,"captions-indicator")),this.defaultSlot.append(o)}};Tf=new WeakSet;$v=function(){let i=this.mediaSubtitlesShowing,e=this.getAttribute(_.MEDIA_SUBTITLES_SHOWING),t=this.value!==e;if(i!=null&&i.length&&t&&this.dispatchEvent(new L.CustomEvent(K.MEDIA_DISABLE_SUBTITLES_REQUEST,{composed:!0,bubbles:!0,detail:i})),!this.value||!t)return;let s=new L.CustomEvent(K.MEDIA_SHOW_SUBTITLES_REQUEST,{composed:!0,bubbles:!0,detail:this.value});this.dispatchEvent(s)};gd.getTemplateHTML=a2;var d1=(i,e)=>{let t=i.getAttribute(e);return t?En(t):[]},u1=(i,e,t)=>{if(!(t!=null&&t.length)){i.removeAttribute(e);return}let s=$s(t);i.getAttribute(e)!==s&&i.setAttribute(e,s)};L.customElements.get("media-captions-menu")||L.customElements.define("media-captions-menu",gd);var o2=`<svg aria-hidden="true" viewBox="0 0 26 24">
1948
1948
  <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"/>
1949
1949
  </svg>`,l2=`<svg aria-hidden="true" viewBox="0 0 26 24">
1950
1950
  <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"/>
@@ -1984,7 +1984,7 @@ Schedule: ${l.map(p=>Ci(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Remo
1984
1984
  }
1985
1985
  </style>
1986
1986
  <slot name="icon">${i.mediaplaybackrate||If}x</slot>
1987
- `}function h2(){return F("Playback rate")}var fo=class extends ei{static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_PLAYBACK_RATE]}constructor(){var e;super(),this.container=this.shadowRoot.querySelector('slot[name="icon"]'),this.container.innerHTML=`${(e=this.mediaPlaybackRate)!=null?e:If}x`}attributeChangedCallback(e,t,s){if(super.attributeChangedCallback(e,t,s),e===_.MEDIA_PLAYBACK_RATE){let r=s?+s:Number.NaN,n=Number.isNaN(r)?If:r;this.container.innerHTML=`${n}x`,this.setAttribute("aria-label",F("Playback rate {playbackRate}",{playbackRate:n}))}}get invokeTargetElement(){return this.invokeTarget!=null?super.invokeTargetElement:Ye(this).querySelector("media-playback-rate-menu")}get mediaPlaybackRate(){return ye(this,_.MEDIA_PLAYBACK_RATE,If)}set mediaPlaybackRate(e){Re(this,_.MEDIA_PLAYBACK_RATE,e)}};fo.getSlotTemplateHTML=c2;fo.getTooltipContentHTML=h2;L.customElements.get("media-playback-rate-menu-button")||L.customElements.define("media-playback-rate-menu-button",fo);var qv=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},zs=(i,e,t)=>(qv(i,e,"read from private field"),t?t.call(i):e.get(i)),Lf=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},g1=(i,e,t,s)=>(qv(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),mo=(i,e,t)=>(qv(i,e,"access private method"),t),Ed,Ts,po,yd,Rf,Wv,xf=class extends lt{constructor(){super(...arguments),Lf(this,po),Lf(this,Rf),Lf(this,Ed,[]),Lf(this,Ts,{})}static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_RENDITION_LIST,_.MEDIA_RENDITION_SELECTED,_.MEDIA_RENDITION_UNAVAILABLE,_.MEDIA_HEIGHT,_.MEDIA_WIDTH]}static formatMenuItemText(e,t){return super.formatMenuItemText(e,t)}static formatRendition(e,{showBitrate:t=!1}={}){let s=`${Math.min(e.width,e.height)}p`;if(t&&e.bitrate){let r=e.bitrate/1e6,n=`${r.toFixed(r<1?1:0)} Mbps`;return`${s} (${n})`}return this.formatMenuItemText(s,e)}static compareRendition(e,t){var s,r;return t.height===e.height?((s=t.bitrate)!=null?s:0)-((r=e.bitrate)!=null?r:0):t.height-e.height}attributeChangedCallback(e,t,s){if(super.attributeChangedCallback(e,t,s),t!==s)switch(e){case _.MEDIA_RENDITION_SELECTED:this.value=s!=null?s:"auto",mo(this,po,yd).call(this);break;case _.MEDIA_RENDITION_LIST:g1(this,Ed,Q_(s)),mo(this,po,yd).call(this);break;case _.MEDIA_HEIGHT:case _.MEDIA_WIDTH:mo(this,po,yd).call(this);break}}connectedCallback(){super.connectedCallback(),this.addEventListener("change",mo(this,Rf,Wv))}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("change",mo(this,Rf,Wv))}get anchorElement(){return this.anchor!=="auto"?super.anchorElement:Ye(this).querySelector("media-rendition-menu-button")}get mediaRenditionList(){return zs(this,Ed)}set mediaRenditionList(e){g1(this,Ed,e),mo(this,po,yd).call(this)}get mediaRenditionSelected(){return pe(this,_.MEDIA_RENDITION_SELECTED)}set mediaRenditionSelected(e){me(this,_.MEDIA_RENDITION_SELECTED,e)}get mediaHeight(){return ye(this,_.MEDIA_HEIGHT)}set mediaHeight(e){Re(this,_.MEDIA_HEIGHT,e)}get mediaWidth(){return ye(this,_.MEDIA_WIDTH)}set mediaWidth(e){Re(this,_.MEDIA_WIDTH,e)}compareRendition(e,t){return this.constructor.compareRendition(e,t)}formatMenuItemText(e,t){return this.constructor.formatMenuItemText(e,t)}formatRendition(e,t){return this.constructor.formatRendition(e,t)}showRenditionBitrate(e){return this.mediaRenditionList.some(t=>t!==e&&t.height===e.height&&t.bitrate!==e.bitrate)}};Ed=new WeakMap;Ts=new WeakMap;po=new WeakSet;yd=function(){let i=!this.mediaRenditionSelected;if(zs(this,Ts).mediaRenditionList===JSON.stringify(this.mediaRenditionList)&&zs(this,Ts).mediaHeight===this.mediaHeight&&zs(this,Ts).mediaWidth===this.mediaWidth&&zs(this,Ts).isAuto===i)return;zs(this,Ts).mediaRenditionList=JSON.stringify(this.mediaRenditionList),zs(this,Ts).mediaHeight=this.mediaHeight,zs(this,Ts).mediaWidth=this.mediaWidth,zs(this,Ts).isAuto=i;let e=this.mediaRenditionList.sort(this.compareRendition.bind(this)),t=e.find(a=>a.id===this.mediaRenditionSelected);for(let a of e)a.selected=a===t;this.defaultSlot.textContent="";for(let a of e){let o=this.formatRendition(a,{showBitrate:this.showRenditionBitrate(a)}),l=Es({type:"radio",text:o,value:`${a.id}`,checked:a.selected&&!i});l.prepend(qi(this,"checked-indicator")),this.defaultSlot.append(l)}let s=t&&this.showRenditionBitrate(t),r;i&&(t?r=this.formatMenuItemText(`${F("Auto")} \u2022 ${this.formatRendition(t,{showBitrate:s})}`,t):this.mediaHeight>0&&this.mediaWidth>0&&(r=this.formatMenuItemText(`${F("Auto")} (${Math.min(this.mediaWidth,this.mediaHeight)}p)`))),r||(r=this.formatMenuItemText(F("Auto")));let n=Es({type:"radio",text:r,value:"auto",checked:i});n.dataset.description=r,n.prepend(qi(this,"checked-indicator")),this.defaultSlot.append(n)};Rf=new WeakSet;Wv=function(){if(this.value==null)return;let i=new L.CustomEvent(K.MEDIA_RENDITION_REQUEST,{composed:!0,bubbles:!0,detail:this.value});this.dispatchEvent(i)};L.customElements.get("media-rendition-menu")||L.customElements.define("media-rendition-menu",xf);var f2=`<svg aria-hidden="true" viewBox="0 0 24 24">
1987
+ `}function h2(){return F("Playback rate")}var fo=class extends ei{static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_PLAYBACK_RATE]}constructor(){var e;super(),this.container=this.shadowRoot.querySelector('slot[name="icon"]'),this.container.innerHTML=`${(e=this.mediaPlaybackRate)!=null?e:If}x`}attributeChangedCallback(e,t,s){if(super.attributeChangedCallback(e,t,s),e===_.MEDIA_PLAYBACK_RATE){let r=s?+s:Number.NaN,n=Number.isNaN(r)?If:r;this.container.innerHTML=`${n}x`,this.setAttribute("aria-label",F("Playback rate {playbackRate}",{playbackRate:n}))}}get invokeTargetElement(){return this.invokeTarget!=null?super.invokeTargetElement:Ye(this).querySelector("media-playback-rate-menu")}get mediaPlaybackRate(){return ye(this,_.MEDIA_PLAYBACK_RATE,If)}set mediaPlaybackRate(e){Re(this,_.MEDIA_PLAYBACK_RATE,e)}};fo.getSlotTemplateHTML=c2;fo.getTooltipContentHTML=h2;L.customElements.get("media-playback-rate-menu-button")||L.customElements.define("media-playback-rate-menu-button",fo);var qv=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},zs=(i,e,t)=>(qv(i,e,"read from private field"),t?t.call(i):e.get(i)),Lf=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},g1=(i,e,t,s)=>(qv(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),mo=(i,e,t)=>(qv(i,e,"access private method"),t),Ed,bs,po,yd,Rf,Wv,xf=class extends lt{constructor(){super(...arguments),Lf(this,po),Lf(this,Rf),Lf(this,Ed,[]),Lf(this,bs,{})}static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_RENDITION_LIST,_.MEDIA_RENDITION_SELECTED,_.MEDIA_RENDITION_UNAVAILABLE,_.MEDIA_HEIGHT,_.MEDIA_WIDTH]}static formatMenuItemText(e,t){return super.formatMenuItemText(e,t)}static formatRendition(e,{showBitrate:t=!1}={}){let s=`${Math.min(e.width,e.height)}p`;if(t&&e.bitrate){let r=e.bitrate/1e6,n=`${r.toFixed(r<1?1:0)} Mbps`;return`${s} (${n})`}return this.formatMenuItemText(s,e)}static compareRendition(e,t){var s,r;return t.height===e.height?((s=t.bitrate)!=null?s:0)-((r=e.bitrate)!=null?r:0):t.height-e.height}attributeChangedCallback(e,t,s){if(super.attributeChangedCallback(e,t,s),t!==s)switch(e){case _.MEDIA_RENDITION_SELECTED:this.value=s!=null?s:"auto",mo(this,po,yd).call(this);break;case _.MEDIA_RENDITION_LIST:g1(this,Ed,Q_(s)),mo(this,po,yd).call(this);break;case _.MEDIA_HEIGHT:case _.MEDIA_WIDTH:mo(this,po,yd).call(this);break}}connectedCallback(){super.connectedCallback(),this.addEventListener("change",mo(this,Rf,Wv))}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("change",mo(this,Rf,Wv))}get anchorElement(){return this.anchor!=="auto"?super.anchorElement:Ye(this).querySelector("media-rendition-menu-button")}get mediaRenditionList(){return zs(this,Ed)}set mediaRenditionList(e){g1(this,Ed,e),mo(this,po,yd).call(this)}get mediaRenditionSelected(){return pe(this,_.MEDIA_RENDITION_SELECTED)}set mediaRenditionSelected(e){me(this,_.MEDIA_RENDITION_SELECTED,e)}get mediaHeight(){return ye(this,_.MEDIA_HEIGHT)}set mediaHeight(e){Re(this,_.MEDIA_HEIGHT,e)}get mediaWidth(){return ye(this,_.MEDIA_WIDTH)}set mediaWidth(e){Re(this,_.MEDIA_WIDTH,e)}compareRendition(e,t){return this.constructor.compareRendition(e,t)}formatMenuItemText(e,t){return this.constructor.formatMenuItemText(e,t)}formatRendition(e,t){return this.constructor.formatRendition(e,t)}showRenditionBitrate(e){return this.mediaRenditionList.some(t=>t!==e&&t.height===e.height&&t.bitrate!==e.bitrate)}};Ed=new WeakMap;bs=new WeakMap;po=new WeakSet;yd=function(){let i=!this.mediaRenditionSelected;if(zs(this,bs).mediaRenditionList===JSON.stringify(this.mediaRenditionList)&&zs(this,bs).mediaHeight===this.mediaHeight&&zs(this,bs).mediaWidth===this.mediaWidth&&zs(this,bs).isAuto===i)return;zs(this,bs).mediaRenditionList=JSON.stringify(this.mediaRenditionList),zs(this,bs).mediaHeight=this.mediaHeight,zs(this,bs).mediaWidth=this.mediaWidth,zs(this,bs).isAuto=i;let e=this.mediaRenditionList.sort(this.compareRendition.bind(this)),t=e.find(a=>a.id===this.mediaRenditionSelected);for(let a of e)a.selected=a===t;this.defaultSlot.textContent="";for(let a of e){let o=this.formatRendition(a,{showBitrate:this.showRenditionBitrate(a)}),l=Es({type:"radio",text:o,value:`${a.id}`,checked:a.selected&&!i});l.prepend(qi(this,"checked-indicator")),this.defaultSlot.append(l)}let s=t&&this.showRenditionBitrate(t),r;i&&(t?r=this.formatMenuItemText(`${F("Auto")} \u2022 ${this.formatRendition(t,{showBitrate:s})}`,t):this.mediaHeight>0&&this.mediaWidth>0&&(r=this.formatMenuItemText(`${F("Auto")} (${Math.min(this.mediaWidth,this.mediaHeight)}p)`))),r||(r=this.formatMenuItemText(F("Auto")));let n=Es({type:"radio",text:r,value:"auto",checked:i});n.dataset.description=r,n.prepend(qi(this,"checked-indicator")),this.defaultSlot.append(n)};Rf=new WeakSet;Wv=function(){if(this.value==null)return;let i=new L.CustomEvent(K.MEDIA_RENDITION_REQUEST,{composed:!0,bubbles:!0,detail:this.value});this.dispatchEvent(i)};L.customElements.get("media-rendition-menu")||L.customElements.define("media-rendition-menu",xf);var f2=`<svg aria-hidden="true" viewBox="0 0 24 24">
1988
1988
  <path d="M13.5 2.5h2v6h-2v-2h-11v-2h11v-2Zm4 2h4v2h-4v-2Zm-12 4h2v6h-2v-2h-3v-2h3v-2Zm4 2h12v2h-12v-2Zm1 4h2v6h-2v-2h-8v-2h8v-2Zm4 2h7v2h-7v-2Z" />
1989
1989
  </svg>`;function m2(){return`
1990
1990
  <style>
@@ -1993,7 +1993,7 @@ Schedule: ${l.map(p=>Ci(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Remo
1993
1993
  }
1994
1994
  </style>
1995
1995
  <slot name="icon">${f2}</slot>
1996
- `}function p2(){return F("Quality")}var go=class extends ei{static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_RENDITION_SELECTED,_.MEDIA_RENDITION_UNAVAILABLE,_.MEDIA_HEIGHT]}connectedCallback(){super.connectedCallback(),this.setAttribute("aria-label",F("quality"))}get invokeTargetElement(){return this.invokeTarget!=null?super.invokeTargetElement:Ye(this).querySelector("media-rendition-menu")}get mediaRenditionSelected(){return pe(this,_.MEDIA_RENDITION_SELECTED)}set mediaRenditionSelected(e){me(this,_.MEDIA_RENDITION_SELECTED,e)}get mediaHeight(){return ye(this,_.MEDIA_HEIGHT)}set mediaHeight(e){Re(this,_.MEDIA_HEIGHT,e)}};go.getSlotTemplateHTML=m2;go.getTooltipContentHTML=p2;L.customElements.get("media-rendition-menu-button")||L.customElements.define("media-rendition-menu-button",go);var zv=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},_s=(i,e,t)=>(zv(i,e,"read from private field"),t?t.call(i):e.get(i)),bs=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},v1=(i,e,t,s)=>(zv(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),Si=(i,e,t)=>(zv(i,e,"access private method"),t),Eo,Td,Pf,Fn,vo,Qv,E1,kf,Yv,Df,jv,y1,wf,Mf,Cf;function g2(i){return`
1996
+ `}function p2(){return F("Quality")}var go=class extends ei{static get observedAttributes(){return[...super.observedAttributes,_.MEDIA_RENDITION_SELECTED,_.MEDIA_RENDITION_UNAVAILABLE,_.MEDIA_HEIGHT]}connectedCallback(){super.connectedCallback(),this.setAttribute("aria-label",F("quality"))}get invokeTargetElement(){return this.invokeTarget!=null?super.invokeTargetElement:Ye(this).querySelector("media-rendition-menu")}get mediaRenditionSelected(){return pe(this,_.MEDIA_RENDITION_SELECTED)}set mediaRenditionSelected(e){me(this,_.MEDIA_RENDITION_SELECTED,e)}get mediaHeight(){return ye(this,_.MEDIA_HEIGHT)}set mediaHeight(e){Re(this,_.MEDIA_HEIGHT,e)}};go.getSlotTemplateHTML=m2;go.getTooltipContentHTML=p2;L.customElements.get("media-rendition-menu-button")||L.customElements.define("media-rendition-menu-button",go);var zv=(i,e,t)=>{if(!e.has(i))throw TypeError("Cannot "+t)},_s=(i,e,t)=>(zv(i,e,"read from private field"),t?t.call(i):e.get(i)),Ts=(i,e,t)=>{if(e.has(i))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(i):e.set(i,t)},v1=(i,e,t,s)=>(zv(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),Si=(i,e,t)=>(zv(i,e,"access private method"),t),Eo,bd,Pf,Fn,vo,Qv,E1,kf,Yv,Df,jv,y1,wf,Mf,Cf;function g2(i){return`
1997
1997
  ${lt.getTemplateHTML(i)}
1998
1998
  <style>
1999
1999
  :host {
@@ -2007,7 +2007,7 @@ Schedule: ${l.map(p=>Ci(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Remo
2007
2007
  overflow: hidden;
2008
2008
  }
2009
2009
  </style>
2010
- `}var bd=class extends lt{constructor(){super(),bs(this,Td),bs(this,Fn),bs(this,Qv),bs(this,kf),bs(this,jv),bs(this,Eo,!1),bs(this,Df,e=>{let t=e.target,s=(t==null?void 0:t.nodeName)==="VIDEO",r=Si(this,kf,Yv).call(this,t);(s||r)&&(_s(this,Eo)?Si(this,Fn,vo).call(this):Si(this,jv,y1).call(this,e))}),bs(this,wf,e=>{let t=e.target,s=this.contains(t),r=e.button===2,n=(t==null?void 0:t.nodeName)==="VIDEO",a=Si(this,kf,Yv).call(this,t);s||r&&(n||a)||Si(this,Fn,vo).call(this)}),bs(this,Mf,e=>{e.key==="Escape"&&Si(this,Fn,vo).call(this)}),bs(this,Cf,e=>{var t,s;let r=e.target;if((t=r.matches)!=null&&t.call(r,'button[invoke="copy"]')){let n=(s=r.closest("media-context-menu-item"))==null?void 0:s.querySelector('input[slot="copy"]');n&&navigator.clipboard.writeText(n.value)}Si(this,Fn,vo).call(this)}),this.setAttribute("noautohide",""),Si(this,Td,Pf).call(this)}connectedCallback(){super.connectedCallback(),Ye(this).addEventListener("contextmenu",_s(this,Df)),this.addEventListener("click",_s(this,Cf))}disconnectedCallback(){super.disconnectedCallback(),Ye(this).removeEventListener("contextmenu",_s(this,Df)),this.removeEventListener("click",_s(this,Cf)),document.removeEventListener("mousedown",_s(this,wf)),document.removeEventListener("keydown",_s(this,Mf))}};Eo=new WeakMap;Td=new WeakSet;Pf=function(){this.hidden=!_s(this,Eo)};Fn=new WeakSet;vo=function(){v1(this,Eo,!1),Si(this,Td,Pf).call(this)};Qv=new WeakSet;E1=function(){document.querySelectorAll("media-context-menu").forEach(e=>{var t;e!==this&&Si(t=e,Fn,vo).call(t)})};kf=new WeakSet;Yv=function(i){return i?i.hasAttribute("slot")&&i.getAttribute("slot")==="media"?!0:i.nodeName.includes("-")&&i.tagName.includes("-")?i.hasAttribute("src")||i.hasAttribute("poster")||i.hasAttribute("preload")||i.hasAttribute("playsinline"):!1:!1};Df=new WeakMap;jv=new WeakSet;y1=function(i){i.preventDefault(),Si(this,Qv,E1).call(this),v1(this,Eo,!0),this.style.position="fixed",this.style.left=`${i.clientX}px`,this.style.top=`${i.clientY}px`,Si(this,Td,Pf).call(this),document.addEventListener("mousedown",_s(this,wf),{once:!0}),document.addEventListener("keydown",_s(this,Mf),{once:!0})};wf=new WeakMap;Mf=new WeakMap;Cf=new WeakMap;bd.getTemplateHTML=g2;L.customElements.get("media-context-menu")||L.customElements.define("media-context-menu",bd);function v2(i){return`
2010
+ `}var Td=class extends lt{constructor(){super(),Ts(this,bd),Ts(this,Fn),Ts(this,Qv),Ts(this,kf),Ts(this,jv),Ts(this,Eo,!1),Ts(this,Df,e=>{let t=e.target,s=(t==null?void 0:t.nodeName)==="VIDEO",r=Si(this,kf,Yv).call(this,t);(s||r)&&(_s(this,Eo)?Si(this,Fn,vo).call(this):Si(this,jv,y1).call(this,e))}),Ts(this,wf,e=>{let t=e.target,s=this.contains(t),r=e.button===2,n=(t==null?void 0:t.nodeName)==="VIDEO",a=Si(this,kf,Yv).call(this,t);s||r&&(n||a)||Si(this,Fn,vo).call(this)}),Ts(this,Mf,e=>{e.key==="Escape"&&Si(this,Fn,vo).call(this)}),Ts(this,Cf,e=>{var t,s;let r=e.target;if((t=r.matches)!=null&&t.call(r,'button[invoke="copy"]')){let n=(s=r.closest("media-context-menu-item"))==null?void 0:s.querySelector('input[slot="copy"]');n&&navigator.clipboard.writeText(n.value)}Si(this,Fn,vo).call(this)}),this.setAttribute("noautohide",""),Si(this,bd,Pf).call(this)}connectedCallback(){super.connectedCallback(),Ye(this).addEventListener("contextmenu",_s(this,Df)),this.addEventListener("click",_s(this,Cf))}disconnectedCallback(){super.disconnectedCallback(),Ye(this).removeEventListener("contextmenu",_s(this,Df)),this.removeEventListener("click",_s(this,Cf)),document.removeEventListener("mousedown",_s(this,wf)),document.removeEventListener("keydown",_s(this,Mf))}};Eo=new WeakMap;bd=new WeakSet;Pf=function(){this.hidden=!_s(this,Eo)};Fn=new WeakSet;vo=function(){v1(this,Eo,!1),Si(this,bd,Pf).call(this)};Qv=new WeakSet;E1=function(){document.querySelectorAll("media-context-menu").forEach(e=>{var t;e!==this&&Si(t=e,Fn,vo).call(t)})};kf=new WeakSet;Yv=function(i){return i?i.hasAttribute("slot")&&i.getAttribute("slot")==="media"?!0:i.nodeName.includes("-")&&i.tagName.includes("-")?i.hasAttribute("src")||i.hasAttribute("poster")||i.hasAttribute("preload")||i.hasAttribute("playsinline"):!1:!1};Df=new WeakMap;jv=new WeakSet;y1=function(i){i.preventDefault(),Si(this,Qv,E1).call(this),v1(this,Eo,!0),this.style.position="fixed",this.style.left=`${i.clientX}px`,this.style.top=`${i.clientY}px`,Si(this,bd,Pf).call(this),document.addEventListener("mousedown",_s(this,wf),{once:!0}),document.addEventListener("keydown",_s(this,Mf),{once:!0})};wf=new WeakMap;Mf=new WeakMap;Cf=new WeakMap;Td.getTemplateHTML=g2;L.customElements.get("media-context-menu")||L.customElements.define("media-context-menu",Td);function v2(i){return`
2011
2011
  ${ci.getTemplateHTML.call(this,i)}
2012
2012
  <style>
2013
2013
  ::slotted(*) {
@@ -2020,8 +2020,8 @@ Schedule: ${l.map(p=>Ci(p))} pos: ${this.timelinePos}`),u.length&&this.log(`Remo
2020
2020
  min-height: var(--media-control-height, 24px);
2021
2021
  }
2022
2022
  </style>
2023
- `}var yo=class extends ci{};yo.shadowRootOptions={mode:"open"};yo.getTemplateHTML=v2;L.customElements.get("media-context-menu-item")||L.customElements.define("media-context-menu-item",yo);var O1=i=>{throw TypeError(i)},iE=(i,e,t)=>e.has(i)||O1("Cannot "+t),ve=(i,e,t)=>(iE(i,e,"read from private field"),t?t.call(i):e.get(i)),Ot=(i,e,t)=>e.has(i)?O1("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),ii=(i,e,t,s)=>(iE(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),dt=(i,e,t)=>(iE(i,e,"access private method"),t),Vf=class{addEventListener(){}removeEventListener(){}dispatchEvent(i){return!0}};if(typeof DocumentFragment=="undefined"){class i extends Vf{}globalThis.DocumentFragment=i}var sE=class extends Vf{},E2=class extends Vf{},y2={get(i){},define(i,e,t){},getName(i){return null},upgrade(i){},whenDefined(i){return Promise.resolve(sE)}},Of,T2=class{constructor(i,e={}){Ot(this,Of),ii(this,Of,e==null?void 0:e.detail)}get detail(){return ve(this,Of)}initCustomEvent(){}};Of=new WeakMap;function b2(i,e){return new sE}var N1={document:{createElement:b2},DocumentFragment,customElements:y2,CustomEvent:T2,EventTarget:Vf,HTMLElement:sE,HTMLVideoElement:E2},U1=typeof window=="undefined"||typeof globalThis.customElements=="undefined",Ss=U1?N1:globalThis,$f=U1?N1.document:globalThis.document;function _2(i){let e="";return Object.entries(i).forEach(([t,s])=>{s!=null&&(e+=`${Zv(t)}: ${s}; `)}),e?e.trim():void 0}function Zv(i){return i.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function F1(i){return i.replace(/[-_]([a-z])/g,(e,t)=>t.toUpperCase())}function Ut(i){if(i==null)return;let e=+i;return Number.isNaN(e)?void 0:e}function B1(i){let e=A2(i).toString();return e?"?"+e:""}function A2(i){let e={};for(let t in i)i[t]!=null&&(e[t]=i[t]);return new URLSearchParams(e)}var $1=(i,e)=>!i||!e?!1:i.contains(e)?!0:$1(i,e.getRootNode().host),H1="mux.com",S2=()=>{try{return"3.13.0"}catch{}return"UNKNOWN"},I2=S2(),G1=()=>I2,L2=(i,{token:e,customDomain:t=H1,thumbnailTime:s,programTime:r}={})=>{var n;let a=e==null?s:void 0,{aud:o}=(n=dr(e))!=null?n:{};if(!(e&&o!=="t"))return`https://image.${t}/${i}/thumbnail.webp${B1({token:e,time:a,program_time:r})}`},R2=(i,{token:e,customDomain:t=H1,programStartTime:s,programEndTime:r}={})=>{var n;let{aud:a}=(n=dr(e))!=null?n:{};if(!(e&&a!=="s"))return`https://image.${t}/${i}/storyboard.vtt${B1({token:e,format:"webp",program_start_time:s,program_end_time:r})}`},rE=i=>{if(i){if([we.LIVE,we.ON_DEMAND].includes(i))return i;if(i!=null&&i.includes("live"))return we.LIVE}},x2={crossorigin:"crossOrigin",playsinline:"playsInline"};function k2(i){var e;return(e=x2[i])!=null?e:F1(i)}var To,bo,ti,D2=class{constructor(i,e){Ot(this,To),Ot(this,bo),Ot(this,ti,[]),ii(this,To,i),ii(this,bo,e)}[Symbol.iterator](){return ve(this,ti).values()}get length(){return ve(this,ti).length}get value(){var i;return(i=ve(this,ti).join(" "))!=null?i:""}set value(i){var e;i!==this.value&&(ii(this,ti,[]),this.add(...(e=i==null?void 0:i.split(" "))!=null?e:[]))}toString(){return this.value}item(i){return ve(this,ti)[i]}values(){return ve(this,ti).values()}keys(){return ve(this,ti).keys()}forEach(i){ve(this,ti).forEach(i)}add(...i){var e,t;i.forEach(s=>{this.contains(s)||ve(this,ti).push(s)}),!(this.value===""&&!((e=ve(this,To))!=null&&e.hasAttribute(`${ve(this,bo)}`)))&&((t=ve(this,To))==null||t.setAttribute(`${ve(this,bo)}`,`${this.value}`))}remove(...i){var e;i.forEach(t=>{ve(this,ti).splice(ve(this,ti).indexOf(t),1)}),(e=ve(this,To))==null||e.setAttribute(`${ve(this,bo)}`,`${this.value}`)}contains(i){return ve(this,ti).includes(i)}toggle(i,e){return typeof e!="undefined"?e?(this.add(i),!0):(this.remove(i),!1):this.contains(i)?(this.remove(i),!1):(this.add(i),!0)}replace(i,e){this.remove(i),this.add(e)}};To=new WeakMap,bo=new WeakMap,ti=new WeakMap;var K1=`[mux-player ${G1()}]`;function Qs(...i){console.warn(K1,...i)}function hi(...i){console.error(K1,...i)}function T1(i){var e;let t=(e=i.message)!=null?e:"";i.context&&(t+=` ${i.context}`),i.file&&(t+=` ${te("Read more: ")}
2024
- https://github.com/muxinc/elements/blob/main/errors/${i.file}`),Qs(t)}var Pt={AUTOPLAY:"autoplay",CROSSORIGIN:"crossorigin",LOOP:"loop",MUTED:"muted",PLAYSINLINE:"playsinline",PRELOAD:"preload"},Gr={VOLUME:"volume",PLAYBACKRATE:"playbackrate",MUTED:"muted"},Z6={...Pt,...Gr},b1=Object.freeze({length:0,start(i){let e=i>>>0;if(e>=this.length)throw new DOMException(`Failed to execute 'start' on 'TimeRanges': The index provided (${e}) is greater than or equal to the maximum bound (${this.length}).`);return 0},end(i){let e=i>>>0;if(e>=this.length)throw new DOMException(`Failed to execute 'end' on 'TimeRanges': The index provided (${e}) is greater than or equal to the maximum bound (${this.length}).`);return 0}}),C2=Object.values(Pt).filter(i=>Pt.PLAYSINLINE!==i),w2=Object.values(Gr),M2=[...C2,...w2],P2=class extends Ss.HTMLElement{static get observedAttributes(){return M2}constructor(){super()}attributeChangedCallback(i,e,t){var s,r;switch(i){case Gr.MUTED:{this.media&&(this.media.muted=t!=null,this.media.defaultMuted=t!=null);return}case Gr.VOLUME:{let n=(s=Ut(t))!=null?s:1;this.media&&(this.media.volume=n);return}case Gr.PLAYBACKRATE:{let n=(r=Ut(t))!=null?r:1;this.media&&(this.media.playbackRate=n,this.media.defaultPlaybackRate=n);return}}}play(){var i,e;return(e=(i=this.media)==null?void 0:i.play())!=null?e:Promise.reject()}pause(){var i;(i=this.media)==null||i.pause()}load(){var i;(i=this.media)==null||i.load()}get media(){var i;return(i=this.shadowRoot)==null?void 0:i.querySelector("mux-video")}get audioTracks(){return this.media.audioTracks}get videoTracks(){return this.media.videoTracks}get audioRenditions(){return this.media.audioRenditions}get videoRenditions(){return this.media.videoRenditions}get paused(){var i,e;return(e=(i=this.media)==null?void 0:i.paused)!=null?e:!0}get duration(){var i,e;return(e=(i=this.media)==null?void 0:i.duration)!=null?e:NaN}get ended(){var i,e;return(e=(i=this.media)==null?void 0:i.ended)!=null?e:!1}get buffered(){var i,e;return(e=(i=this.media)==null?void 0:i.buffered)!=null?e:b1}get seekable(){var i,e;return(e=(i=this.media)==null?void 0:i.seekable)!=null?e:b1}get readyState(){var i,e;return(e=(i=this.media)==null?void 0:i.readyState)!=null?e:0}get videoWidth(){var i,e;return(e=(i=this.media)==null?void 0:i.videoWidth)!=null?e:0}get videoHeight(){var i,e;return(e=(i=this.media)==null?void 0:i.videoHeight)!=null?e:0}get currentSrc(){var i,e;return(e=(i=this.media)==null?void 0:i.currentSrc)!=null?e:""}get currentTime(){var i,e;return(e=(i=this.media)==null?void 0:i.currentTime)!=null?e:0}set currentTime(i){this.media&&(this.media.currentTime=Number(i))}get volume(){var i,e;return(e=(i=this.media)==null?void 0:i.volume)!=null?e:1}set volume(i){this.media&&(this.media.volume=Number(i))}get playbackRate(){var i,e;return(e=(i=this.media)==null?void 0:i.playbackRate)!=null?e:1}set playbackRate(i){this.media&&(this.media.playbackRate=Number(i))}get defaultPlaybackRate(){var i;return(i=Ut(this.getAttribute(Gr.PLAYBACKRATE)))!=null?i:1}set defaultPlaybackRate(i){i!=null?this.setAttribute(Gr.PLAYBACKRATE,`${i}`):this.removeAttribute(Gr.PLAYBACKRATE)}get crossOrigin(){return _d(this,Pt.CROSSORIGIN)}set crossOrigin(i){this.setAttribute(Pt.CROSSORIGIN,`${i}`)}get autoplay(){return _d(this,Pt.AUTOPLAY)!=null}set autoplay(i){i?this.setAttribute(Pt.AUTOPLAY,typeof i=="string"?i:""):this.removeAttribute(Pt.AUTOPLAY)}get loop(){return _d(this,Pt.LOOP)!=null}set loop(i){i?this.setAttribute(Pt.LOOP,""):this.removeAttribute(Pt.LOOP)}get muted(){var i,e;return(e=(i=this.media)==null?void 0:i.muted)!=null?e:!1}set muted(i){this.media&&(this.media.muted=!!i)}get defaultMuted(){return _d(this,Pt.MUTED)!=null}set defaultMuted(i){i?this.setAttribute(Pt.MUTED,""):this.removeAttribute(Pt.MUTED)}get playsInline(){return _d(this,Pt.PLAYSINLINE)!=null}set playsInline(i){hi("playsInline is set to true by default and is not currently supported as a setter.")}get preload(){return this.media?this.media.preload:this.getAttribute("preload")}set preload(i){["","none","metadata","auto"].includes(i)?this.setAttribute(Pt.PRELOAD,i):this.removeAttribute(Pt.PRELOAD)}};function _d(i,e){return i.media?i.media.getAttribute(e):i.getAttribute(e)}var _1=P2,O2=`:host {
2023
+ `}var yo=class extends ci{};yo.shadowRootOptions={mode:"open"};yo.getTemplateHTML=v2;L.customElements.get("media-context-menu-item")||L.customElements.define("media-context-menu-item",yo);var O1=i=>{throw TypeError(i)},iE=(i,e,t)=>e.has(i)||O1("Cannot "+t),ve=(i,e,t)=>(iE(i,e,"read from private field"),t?t.call(i):e.get(i)),Ot=(i,e,t)=>e.has(i)?O1("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),ii=(i,e,t,s)=>(iE(i,e,"write to private field"),s?s.call(i,t):e.set(i,t),t),dt=(i,e,t)=>(iE(i,e,"access private method"),t),Vf=class{addEventListener(){}removeEventListener(){}dispatchEvent(i){return!0}};if(typeof DocumentFragment=="undefined"){class i extends Vf{}globalThis.DocumentFragment=i}var sE=class extends Vf{},E2=class extends Vf{},y2={get(i){},define(i,e,t){},getName(i){return null},upgrade(i){},whenDefined(i){return Promise.resolve(sE)}},Of,b2=class{constructor(i,e={}){Ot(this,Of),ii(this,Of,e==null?void 0:e.detail)}get detail(){return ve(this,Of)}initCustomEvent(){}};Of=new WeakMap;function T2(i,e){return new sE}var N1={document:{createElement:T2},DocumentFragment,customElements:y2,CustomEvent:b2,EventTarget:Vf,HTMLElement:sE,HTMLVideoElement:E2},U1=typeof window=="undefined"||typeof globalThis.customElements=="undefined",Ss=U1?N1:globalThis,$f=U1?N1.document:globalThis.document;function _2(i){let e="";return Object.entries(i).forEach(([t,s])=>{s!=null&&(e+=`${Zv(t)}: ${s}; `)}),e?e.trim():void 0}function Zv(i){return i.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function F1(i){return i.replace(/[-_]([a-z])/g,(e,t)=>t.toUpperCase())}function Ut(i){if(i==null)return;let e=+i;return Number.isNaN(e)?void 0:e}function B1(i){let e=A2(i).toString();return e?"?"+e:""}function A2(i){let e={};for(let t in i)i[t]!=null&&(e[t]=i[t]);return new URLSearchParams(e)}var $1=(i,e)=>!i||!e?!1:i.contains(e)?!0:$1(i,e.getRootNode().host),H1="mux.com",S2=()=>{try{return"3.13.0"}catch{}return"UNKNOWN"},I2=S2(),G1=()=>I2,L2=(i,{token:e,customDomain:t=H1,thumbnailTime:s,programTime:r}={})=>{var n;let a=e==null?s:void 0,{aud:o}=(n=dr(e))!=null?n:{};if(!(e&&o!=="t"))return`https://image.${t}/${i}/thumbnail.webp${B1({token:e,time:a,program_time:r})}`},R2=(i,{token:e,customDomain:t=H1,programStartTime:s,programEndTime:r}={})=>{var n;let{aud:a}=(n=dr(e))!=null?n:{};if(!(e&&a!=="s"))return`https://image.${t}/${i}/storyboard.vtt${B1({token:e,format:"webp",program_start_time:s,program_end_time:r})}`},rE=i=>{if(i){if([we.LIVE,we.ON_DEMAND].includes(i))return i;if(i!=null&&i.includes("live"))return we.LIVE}},x2={crossorigin:"crossOrigin",playsinline:"playsInline"};function k2(i){var e;return(e=x2[i])!=null?e:F1(i)}var bo,To,ti,D2=class{constructor(i,e){Ot(this,bo),Ot(this,To),Ot(this,ti,[]),ii(this,bo,i),ii(this,To,e)}[Symbol.iterator](){return ve(this,ti).values()}get length(){return ve(this,ti).length}get value(){var i;return(i=ve(this,ti).join(" "))!=null?i:""}set value(i){var e;i!==this.value&&(ii(this,ti,[]),this.add(...(e=i==null?void 0:i.split(" "))!=null?e:[]))}toString(){return this.value}item(i){return ve(this,ti)[i]}values(){return ve(this,ti).values()}keys(){return ve(this,ti).keys()}forEach(i){ve(this,ti).forEach(i)}add(...i){var e,t;i.forEach(s=>{this.contains(s)||ve(this,ti).push(s)}),!(this.value===""&&!((e=ve(this,bo))!=null&&e.hasAttribute(`${ve(this,To)}`)))&&((t=ve(this,bo))==null||t.setAttribute(`${ve(this,To)}`,`${this.value}`))}remove(...i){var e;i.forEach(t=>{ve(this,ti).splice(ve(this,ti).indexOf(t),1)}),(e=ve(this,bo))==null||e.setAttribute(`${ve(this,To)}`,`${this.value}`)}contains(i){return ve(this,ti).includes(i)}toggle(i,e){return typeof e!="undefined"?e?(this.add(i),!0):(this.remove(i),!1):this.contains(i)?(this.remove(i),!1):(this.add(i),!0)}replace(i,e){this.remove(i),this.add(e)}};bo=new WeakMap,To=new WeakMap,ti=new WeakMap;var K1=`[mux-player ${G1()}]`;function Qs(...i){console.warn(K1,...i)}function hi(...i){console.error(K1,...i)}function b1(i){var e;let t=(e=i.message)!=null?e:"";i.context&&(t+=` ${i.context}`),i.file&&(t+=` ${te("Read more: ")}
2024
+ https://github.com/muxinc/elements/blob/main/errors/${i.file}`),Qs(t)}var Pt={AUTOPLAY:"autoplay",CROSSORIGIN:"crossorigin",LOOP:"loop",MUTED:"muted",PLAYSINLINE:"playsinline",PRELOAD:"preload"},Gr={VOLUME:"volume",PLAYBACKRATE:"playbackrate",MUTED:"muted"},Z6={...Pt,...Gr},T1=Object.freeze({length:0,start(i){let e=i>>>0;if(e>=this.length)throw new DOMException(`Failed to execute 'start' on 'TimeRanges': The index provided (${e}) is greater than or equal to the maximum bound (${this.length}).`);return 0},end(i){let e=i>>>0;if(e>=this.length)throw new DOMException(`Failed to execute 'end' on 'TimeRanges': The index provided (${e}) is greater than or equal to the maximum bound (${this.length}).`);return 0}}),C2=Object.values(Pt).filter(i=>Pt.PLAYSINLINE!==i),w2=Object.values(Gr),M2=[...C2,...w2],P2=class extends Ss.HTMLElement{static get observedAttributes(){return M2}constructor(){super()}attributeChangedCallback(i,e,t){var s,r;switch(i){case Gr.MUTED:{this.media&&(this.media.muted=t!=null,this.media.defaultMuted=t!=null);return}case Gr.VOLUME:{let n=(s=Ut(t))!=null?s:1;this.media&&(this.media.volume=n);return}case Gr.PLAYBACKRATE:{let n=(r=Ut(t))!=null?r:1;this.media&&(this.media.playbackRate=n,this.media.defaultPlaybackRate=n);return}}}play(){var i,e;return(e=(i=this.media)==null?void 0:i.play())!=null?e:Promise.reject()}pause(){var i;(i=this.media)==null||i.pause()}load(){var i;(i=this.media)==null||i.load()}get media(){var i;return(i=this.shadowRoot)==null?void 0:i.querySelector("mux-video")}get audioTracks(){return this.media.audioTracks}get videoTracks(){return this.media.videoTracks}get audioRenditions(){return this.media.audioRenditions}get videoRenditions(){return this.media.videoRenditions}get paused(){var i,e;return(e=(i=this.media)==null?void 0:i.paused)!=null?e:!0}get duration(){var i,e;return(e=(i=this.media)==null?void 0:i.duration)!=null?e:NaN}get ended(){var i,e;return(e=(i=this.media)==null?void 0:i.ended)!=null?e:!1}get buffered(){var i,e;return(e=(i=this.media)==null?void 0:i.buffered)!=null?e:T1}get seekable(){var i,e;return(e=(i=this.media)==null?void 0:i.seekable)!=null?e:T1}get readyState(){var i,e;return(e=(i=this.media)==null?void 0:i.readyState)!=null?e:0}get videoWidth(){var i,e;return(e=(i=this.media)==null?void 0:i.videoWidth)!=null?e:0}get videoHeight(){var i,e;return(e=(i=this.media)==null?void 0:i.videoHeight)!=null?e:0}get currentSrc(){var i,e;return(e=(i=this.media)==null?void 0:i.currentSrc)!=null?e:""}get currentTime(){var i,e;return(e=(i=this.media)==null?void 0:i.currentTime)!=null?e:0}set currentTime(i){this.media&&(this.media.currentTime=Number(i))}get volume(){var i,e;return(e=(i=this.media)==null?void 0:i.volume)!=null?e:1}set volume(i){this.media&&(this.media.volume=Number(i))}get playbackRate(){var i,e;return(e=(i=this.media)==null?void 0:i.playbackRate)!=null?e:1}set playbackRate(i){this.media&&(this.media.playbackRate=Number(i))}get defaultPlaybackRate(){var i;return(i=Ut(this.getAttribute(Gr.PLAYBACKRATE)))!=null?i:1}set defaultPlaybackRate(i){i!=null?this.setAttribute(Gr.PLAYBACKRATE,`${i}`):this.removeAttribute(Gr.PLAYBACKRATE)}get crossOrigin(){return _d(this,Pt.CROSSORIGIN)}set crossOrigin(i){this.setAttribute(Pt.CROSSORIGIN,`${i}`)}get autoplay(){return _d(this,Pt.AUTOPLAY)!=null}set autoplay(i){i?this.setAttribute(Pt.AUTOPLAY,typeof i=="string"?i:""):this.removeAttribute(Pt.AUTOPLAY)}get loop(){return _d(this,Pt.LOOP)!=null}set loop(i){i?this.setAttribute(Pt.LOOP,""):this.removeAttribute(Pt.LOOP)}get muted(){var i,e;return(e=(i=this.media)==null?void 0:i.muted)!=null?e:!1}set muted(i){this.media&&(this.media.muted=!!i)}get defaultMuted(){return _d(this,Pt.MUTED)!=null}set defaultMuted(i){i?this.setAttribute(Pt.MUTED,""):this.removeAttribute(Pt.MUTED)}get playsInline(){return _d(this,Pt.PLAYSINLINE)!=null}set playsInline(i){hi("playsInline is set to true by default and is not currently supported as a setter.")}get preload(){return this.media?this.media.preload:this.getAttribute("preload")}set preload(i){["","none","metadata","auto"].includes(i)?this.setAttribute(Pt.PRELOAD,i):this.removeAttribute(Pt.PRELOAD)}};function _d(i,e){return i.media?i.media.getAttribute(e):i.getAttribute(e)}var _1=P2,O2=`:host {
2025
2025
  --media-control-display: var(--controls);
2026
2026
  --media-loading-indicator-display: var(--loading-indicator);
2027
2027
  --media-dialog-display: var(--dialog);
@@ -2177,7 +2177,7 @@ media-poster-image:not([src]):not([placeholdersrc]) {
2177
2177
  ${O2}
2178
2178
  </style>
2179
2179
  ${Z2(i)}
2180
- `,z2=i=>{let e=i.hotKeys?`${i.hotKeys}`:"";return rE(i.streamType)==="live"&&(e+=" noarrowleft noarrowright"),e},Q2={TOP:"top",CENTER:"center",BOTTOM:"bottom",LAYER:"layer",MEDIA_LAYER:"media-layer",POSTER_LAYER:"poster-layer",VERTICAL_LAYER:"vertical-layer",CENTERED_LAYER:"centered-layer",GESTURE_LAYER:"gesture-layer",CONTROLLER_LAYER:"controller",BUTTON:"button",RANGE:"range",THUMB:"thumb",DISPLAY:"display",CONTROL_BAR:"control-bar",MENU_BUTTON:"menu-button",MENU:"menu",MENU_ITEM:"menu-item",OPTION:"option",POSTER:"poster",LIVE:"live",PLAY:"play",PRE_PLAY:"pre-play",SEEK_BACKWARD:"seek-backward",SEEK_FORWARD:"seek-forward",MUTE:"mute",CAPTIONS:"captions",AIRPLAY:"airplay",PIP:"pip",FULLSCREEN:"fullscreen",CAST:"cast",PLAYBACK_RATE:"playback-rate",VOLUME:"volume",TIME:"time",TITLE:"title",AUDIO_TRACK:"audio-track",RENDITION:"rendition"},X2=Object.values(Q2).join(", "),Z2=i=>{var e,t,s,r,n,a,o,l,d,u,c,h,f,m,p,g,v,T,y,b,A,R,I,x,D,S,C,P,N,$,H,U,j,q,Z,re,V,G,ce,Se,he;return Nf`
2180
+ `,z2=i=>{let e=i.hotKeys?`${i.hotKeys}`:"";return rE(i.streamType)==="live"&&(e+=" noarrowleft noarrowright"),e},Q2={TOP:"top",CENTER:"center",BOTTOM:"bottom",LAYER:"layer",MEDIA_LAYER:"media-layer",POSTER_LAYER:"poster-layer",VERTICAL_LAYER:"vertical-layer",CENTERED_LAYER:"centered-layer",GESTURE_LAYER:"gesture-layer",CONTROLLER_LAYER:"controller",BUTTON:"button",RANGE:"range",THUMB:"thumb",DISPLAY:"display",CONTROL_BAR:"control-bar",MENU_BUTTON:"menu-button",MENU:"menu",MENU_ITEM:"menu-item",OPTION:"option",POSTER:"poster",LIVE:"live",PLAY:"play",PRE_PLAY:"pre-play",SEEK_BACKWARD:"seek-backward",SEEK_FORWARD:"seek-forward",MUTE:"mute",CAPTIONS:"captions",AIRPLAY:"airplay",PIP:"pip",FULLSCREEN:"fullscreen",CAST:"cast",PLAYBACK_RATE:"playback-rate",VOLUME:"volume",TIME:"time",TITLE:"title",AUDIO_TRACK:"audio-track",RENDITION:"rendition"},X2=Object.values(Q2).join(", "),Z2=i=>{var e,t,s,r,n,a,o,l,d,u,c,h,f,m,p,g,v,b,y,T,A,R,I,x,D,S,C,P,N,$,H,U,j,q,Z,re,V,G,ce,Se,he;return Nf`
2181
2181
  <media-theme
2182
2182
  template="${i.themeTemplate||!1}"
2183
2183
  defaultstreamtype="${(e=i.defaultStreamType)!=null?e:!1}"
@@ -2210,9 +2210,9 @@ media-poster-image:not([src]):not([placeholdersrc]) {
2210
2210
  stream-type="${(g=rE(i.streamType))!=null?g:!1}"
2211
2211
  crossorigin="${(v=i.crossOrigin)!=null?v:""}"
2212
2212
  playsinline
2213
- autoplay="${(T=i.autoplay)!=null?T:!1}"
2213
+ autoplay="${(b=i.autoplay)!=null?b:!1}"
2214
2214
  muted="${(y=i.muted)!=null?y:!1}"
2215
- loop="${(b=i.loop)!=null?b:!1}"
2215
+ loop="${(T=i.loop)!=null?T:!1}"
2216
2216
  preload="${(A=i.preload)!=null?A:!1}"
2217
2217
  debug="${(R=i.debug)!=null?R:!1}"
2218
2218
  prefer-cmcd="${(I=i.preferCmcd)!=null?I:!1}"
@@ -3395,7 +3395,7 @@ media-poster-image:not([src]):not([placeholdersrc]) {
3395
3395
  >${(t=s.linkText)!=null?t:s.linkUrl}</a
3396
3396
  >`:""}
3397
3397
  </p>`:""}
3398
- `}return aN(i)};function oN(i){var e,t;let s=i.theme;if(s){let r=(t=(e=i.getRootNode())==null?void 0:e.getElementById)==null?void 0:t.call(e,s);if(r&&r instanceof HTMLTemplateElement)return r;s.startsWith("media-theme-")||(s=`media-theme-${s}`);let n=Ss.customElements.get(s);if(n!=null&&n.template)return n.template}}function lN(i){var e;let t=(e=i.mediaController)==null?void 0:e.querySelector("media-time-display");return t&&getComputedStyle(t).getPropertyValue("--media-duration-display-display").trim()==="none"}function R1(i){let e=i.videoTitle?{video_title:i.videoTitle}:{};return i.getAttributeNames().filter(t=>t.startsWith("metadata-")).reduce((t,s)=>{let r=i.getAttribute(s);return r!==null&&(t[s.replace(/^metadata-/,"").replace(/-/g,"_")]=r),t},e)}var dN=Object.values(k),uN=Object.values(Xs),cN=Object.values(B),x1=G1(),k1="mux-player",D1={isDialogOpen:!1},hN={redundant_streams:!0},Uf,Sd,Ff,Bn,Bf,Id,Hf,Gf,_o,Ld,Ao,Kf,rt,Zs,z1,tE,$n,C1,w1,M1,P1,fN=class extends _1{constructor(){super(),Ot(this,rt),Ot(this,Uf),Ot(this,Sd,!1),Ot(this,Ff,{}),Ot(this,Bn,!0),Ot(this,Bf,new D2(this,"hotkeys")),Ot(this,Id),Ot(this,Hf,()=>dt(this,rt,$n).call(this)),Ot(this,Gf,()=>dt(this,rt,$n).call(this)),Ot(this,_o,()=>dt(this,rt,$n).call(this)),Ot(this,Ld),Ot(this,Ao,{...D1,onCloseErrorDialog:i=>{var e;((e=i.composedPath()[0])==null?void 0:e.localName)==="media-error-dialog"&&dt(this,rt,tE).call(this,{isDialogOpen:!1})},onFocusInErrorDialog:i=>{var e;((e=i.composedPath()[0])==null?void 0:e.localName)==="media-error-dialog"&&($1(this,$f.activeElement)||i.preventDefault())}}),Ot(this,Kf,i=>{var e;let t=(e=this.media)==null?void 0:e.error;if(!(t instanceof z)){let{message:r,code:n}=t!=null?t:{};t=new z(r,n)}if(!(t!=null&&t.fatal)){Qs(t),t.data&&Qs(`${t.name} data:`,t.data);return}let s=Y1(t,!1);s.message&&T1(s),hi(t),t.data&&hi(`${t.name} data:`,t.data),dt(this,rt,tE).call(this,{isDialogOpen:!0})}),ii(this,Uf,Wu()),this.attachShadow({mode:"open"}),dt(this,rt,z1).call(this),this.isConnected&&dt(this,rt,Zs).call(this)}static get NAME(){return k1}static get VERSION(){return x1}static get observedAttributes(){var i;return[...(i=_1.observedAttributes)!=null?i:[],...uN,...dN,...cN]}get mediaTheme(){var i;return(i=this.shadowRoot)==null?void 0:i.querySelector("media-theme")}get mediaController(){var i,e;return(e=(i=this.mediaTheme)==null?void 0:i.shadowRoot)==null?void 0:e.querySelector("media-controller")}connectedCallback(){dt(this,rt,Zs).call(this);let i=this.media;i&&(i.metadata=R1(this))}disconnectedCallback(){var i,e,t,s,r,n,a,o;(i=ve(this,Id))==null||i.disconnect(),(e=this.media)==null||e.removeEventListener("streamtypechange",ve(this,Hf)),(t=this.media)==null||t.removeEventListener("loadstart",ve(this,Gf)),this.removeEventListener("error",ve(this,Kf)),this.media&&(this.media.errorTranslator=void 0),(r=(s=this.media)==null?void 0:s.textTracks)==null||r.removeEventListener("addtrack",ve(this,_o)),(a=(n=this.media)==null?void 0:n.textTracks)==null||a.removeEventListener("removetrack",ve(this,_o)),(o=ve(this,Ld))==null||o.call(this),ii(this,Ld,void 0),ii(this,Sd,!1)}attributeChangedCallback(i,e,t){switch(dt(this,rt,Zs).call(this),super.attributeChangedCallback(i,e,t),i){case B.HOTKEYS:ve(this,Bf).value=t;break;case B.THUMBNAIL_TIME:{t!=null&&this.tokens.thumbnail&&Qs(te("Use of thumbnail-time with thumbnail-token is currently unsupported. Ignore thumbnail-time.").toString());break}case B.THUMBNAIL_TOKEN:{if(t){let s=dr(t);if(s){let{aud:r}=s,n=oa.THUMBNAIL;r!==n&&Qs(te("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.").format({aud:r,expectedAud:n,tokenNamePrefix:"thumbnail"}))}}break}case B.STORYBOARD_TOKEN:{if(t){let s=dr(t);if(s){let{aud:r}=s,n=oa.STORYBOARD;r!==n&&Qs(te("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.").format({aud:r,expectedAud:n,tokenNamePrefix:"storyboard"}))}}break}case B.DRM_TOKEN:{if(t){let s=dr(t);if(s){let{aud:r}=s,n=oa.DRM;r!==n&&Qs(te("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.").format({aud:r,expectedAud:n,tokenNamePrefix:"drm"}))}}break}case k.PLAYBACK_ID:{t!=null&&t.includes("?token")&&hi(te("The specificed playback ID {playbackId} contains a token which must be provided via the playback-token attribute.").format({playbackId:t}));break}case k.STREAM_TYPE:{t&&![we.LIVE,we.ON_DEMAND,we.UNKNOWN].includes(t)?["ll-live","live:dvr","ll-live:dvr"].includes(this.streamType)?this.targetLiveWindow=t.includes("dvr")?Number.POSITIVE_INFINITY:0:T1({file:"invalid-stream-type.md",message:te("Invalid stream-type value supplied: `{streamType}`. Please provide stream-type as either: `on-demand` or `live`").format({streamType:this.streamType})}):t===we.LIVE?this.getAttribute(B.TARGET_LIVE_WINDOW)==null&&(this.targetLiveWindow=0):this.targetLiveWindow=Number.NaN;break}case B.FULLSCREEN_ELEMENT:{if(t!=null||t!==e){let s=$f.getElementById(t),r=s==null?void 0:s.querySelector("mux-player");this.mediaController&&s&&r&&(this.mediaController.fullscreenElement=s)}break}case k.CAP_RENDITION_TO_PLAYER_SIZE:{(t==null||t!==e)&&(this.capRenditionToPlayerSize=t!=null?!0:void 0);break}}[k.PLAYBACK_ID,Xs.SRC,B.PLAYBACK_TOKEN].includes(i)&&e!==t&&ii(this,Ao,{...ve(this,Ao),...D1}),dt(this,rt,$n).call(this,{[k2(i)]:t})}async requestFullscreen(i){var e;if(!(!this.mediaController||this.mediaController.hasAttribute(_.MEDIA_IS_FULLSCREEN)))return(e=this.mediaController)==null||e.dispatchEvent(new Ss.CustomEvent(K.MEDIA_ENTER_FULLSCREEN_REQUEST,{composed:!0,bubbles:!0})),new Promise((t,s)=>{var r;(r=this.mediaController)==null||r.addEventListener(di.MEDIA_IS_FULLSCREEN,()=>t(),{once:!0})})}async exitFullscreen(){var i;if(!(!this.mediaController||!this.mediaController.hasAttribute(_.MEDIA_IS_FULLSCREEN)))return(i=this.mediaController)==null||i.dispatchEvent(new Ss.CustomEvent(K.MEDIA_EXIT_FULLSCREEN_REQUEST,{composed:!0,bubbles:!0})),new Promise((e,t)=>{var s;(s=this.mediaController)==null||s.addEventListener(di.MEDIA_IS_FULLSCREEN,()=>e(),{once:!0})})}get preferCmcd(){var i;return(i=this.getAttribute(k.PREFER_CMCD))!=null?i:void 0}set preferCmcd(i){i!==this.preferCmcd&&(i?la.includes(i)?this.setAttribute(k.PREFER_CMCD,i):Qs(`Invalid value for preferCmcd. Must be one of ${la.join()}`):this.removeAttribute(k.PREFER_CMCD))}get hasPlayed(){var i,e;return(e=(i=this.mediaController)==null?void 0:i.hasAttribute(_.MEDIA_HAS_PLAYED))!=null?e:!1}get inLiveWindow(){var i;return(i=this.mediaController)==null?void 0:i.hasAttribute(_.MEDIA_TIME_IS_LIVE)}get _hls(){var i;return(i=this.media)==null?void 0:i._hls}get mux(){var i;return(i=this.media)==null?void 0:i.mux}get theme(){var i;return(i=this.getAttribute(B.THEME))!=null?i:rN}set theme(i){this.setAttribute(B.THEME,`${i}`)}get themeProps(){let i=this.mediaTheme;if(!i)return;let e={};for(let t of i.getAttributeNames()){if(eE.includes(t))continue;let s=i.getAttribute(t);e[F1(t)]=s===""?!0:s}return e}set themeProps(i){var e,t;dt(this,rt,Zs).call(this);let s={...this.themeProps,...i};for(let r in s){if(eE.includes(r))continue;let n=i==null?void 0:i[r];typeof n=="boolean"||n==null?(e=this.mediaTheme)==null||e.toggleAttribute(Zv(r),!!n):(t=this.mediaTheme)==null||t.setAttribute(Zv(r),n)}}get playbackId(){var i;return(i=this.getAttribute(k.PLAYBACK_ID))!=null?i:void 0}set playbackId(i){i?this.setAttribute(k.PLAYBACK_ID,i):this.removeAttribute(k.PLAYBACK_ID)}get src(){var i,e;return this.playbackId?(i=As(this,Xs.SRC))!=null?i:void 0:(e=this.getAttribute(Xs.SRC))!=null?e:void 0}set src(i){i?this.setAttribute(Xs.SRC,i):this.removeAttribute(Xs.SRC)}get poster(){var i;let e=this.getAttribute(Xs.POSTER);if(e!=null)return e;let{tokens:t}=this;if(t.playback&&!t.thumbnail){Qs("Missing expected thumbnail token. No poster image will be shown");return}if(this.playbackId&&!this.audio)return L2(this.playbackId,{customDomain:this.customDomain,thumbnailTime:(i=this.thumbnailTime)!=null?i:this.startTime,programTime:this.programStartTime,token:t.thumbnail})}set poster(i){i||i===""?this.setAttribute(Xs.POSTER,i):this.removeAttribute(Xs.POSTER)}get storyboardSrc(){var i;return(i=this.getAttribute(B.STORYBOARD_SRC))!=null?i:void 0}set storyboardSrc(i){i?this.setAttribute(B.STORYBOARD_SRC,i):this.removeAttribute(B.STORYBOARD_SRC)}get storyboard(){let{tokens:i}=this;if(this.storyboardSrc&&!i.storyboard)return this.storyboardSrc;if(!(this.audio||!this.playbackId||!this.streamType||[we.LIVE,we.UNKNOWN].includes(this.streamType)||i.playback&&!i.storyboard))return R2(this.playbackId,{customDomain:this.customDomain,token:i.storyboard,programStartTime:this.programStartTime,programEndTime:this.programEndTime})}get audio(){return this.hasAttribute(B.AUDIO)}set audio(i){if(!i){this.removeAttribute(B.AUDIO);return}this.setAttribute(B.AUDIO,"")}get hotkeys(){return ve(this,Bf)}get nohotkeys(){return this.hasAttribute(B.NOHOTKEYS)}set nohotkeys(i){if(!i){this.removeAttribute(B.NOHOTKEYS);return}this.setAttribute(B.NOHOTKEYS,"")}get thumbnailTime(){return Ut(this.getAttribute(B.THUMBNAIL_TIME))}set thumbnailTime(i){this.setAttribute(B.THUMBNAIL_TIME,`${i}`)}get videoTitle(){var i,e;return(e=(i=this.getAttribute(B.VIDEO_TITLE))!=null?i:this.getAttribute(B.TITLE))!=null?e:""}set videoTitle(i){i!==this.videoTitle&&(i?this.setAttribute(B.VIDEO_TITLE,i):this.removeAttribute(B.VIDEO_TITLE))}get placeholder(){var i;return(i=As(this,B.PLACEHOLDER))!=null?i:""}set placeholder(i){this.setAttribute(B.PLACEHOLDER,`${i}`)}get primaryColor(){var i,e;let t=this.getAttribute(B.PRIMARY_COLOR);if(t!=null||this.mediaTheme&&(t=(e=(i=Ss.getComputedStyle(this.mediaTheme))==null?void 0:i.getPropertyValue("--_primary-color"))==null?void 0:e.trim(),t))return t}set primaryColor(i){this.setAttribute(B.PRIMARY_COLOR,`${i}`)}get secondaryColor(){var i,e;let t=this.getAttribute(B.SECONDARY_COLOR);if(t!=null||this.mediaTheme&&(t=(e=(i=Ss.getComputedStyle(this.mediaTheme))==null?void 0:i.getPropertyValue("--_secondary-color"))==null?void 0:e.trim(),t))return t}set secondaryColor(i){this.setAttribute(B.SECONDARY_COLOR,`${i}`)}get accentColor(){var i,e;let t=this.getAttribute(B.ACCENT_COLOR);if(t!=null||this.mediaTheme&&(t=(e=(i=Ss.getComputedStyle(this.mediaTheme))==null?void 0:i.getPropertyValue("--_accent-color"))==null?void 0:e.trim(),t))return t}set accentColor(i){this.setAttribute(B.ACCENT_COLOR,`${i}`)}get defaultShowRemainingTime(){return this.hasAttribute(B.DEFAULT_SHOW_REMAINING_TIME)}set defaultShowRemainingTime(i){i?this.setAttribute(B.DEFAULT_SHOW_REMAINING_TIME,""):this.removeAttribute(B.DEFAULT_SHOW_REMAINING_TIME)}get playbackRates(){if(this.hasAttribute(B.PLAYBACK_RATES))return this.getAttribute(B.PLAYBACK_RATES).trim().split(/\s*,?\s+/).map(i=>Number(i)).filter(i=>!Number.isNaN(i)).sort((i,e)=>i-e)}set playbackRates(i){if(!i){this.removeAttribute(B.PLAYBACK_RATES);return}this.setAttribute(B.PLAYBACK_RATES,i.join(" "))}get forwardSeekOffset(){var i;return(i=Ut(this.getAttribute(B.FORWARD_SEEK_OFFSET)))!=null?i:10}set forwardSeekOffset(i){this.setAttribute(B.FORWARD_SEEK_OFFSET,`${i}`)}get backwardSeekOffset(){var i;return(i=Ut(this.getAttribute(B.BACKWARD_SEEK_OFFSET)))!=null?i:10}set backwardSeekOffset(i){this.setAttribute(B.BACKWARD_SEEK_OFFSET,`${i}`)}get defaultHiddenCaptions(){return this.hasAttribute(B.DEFAULT_HIDDEN_CAPTIONS)}set defaultHiddenCaptions(i){i?this.setAttribute(B.DEFAULT_HIDDEN_CAPTIONS,""):this.removeAttribute(B.DEFAULT_HIDDEN_CAPTIONS)}get defaultDuration(){return Ut(this.getAttribute(B.DEFAULT_DURATION))}set defaultDuration(i){i==null?this.removeAttribute(B.DEFAULT_DURATION):this.setAttribute(B.DEFAULT_DURATION,`${i}`)}get playerInitTime(){return this.hasAttribute(k.PLAYER_INIT_TIME)?Ut(this.getAttribute(k.PLAYER_INIT_TIME)):ve(this,Uf)}set playerInitTime(i){i!=this.playerInitTime&&(i==null?this.removeAttribute(k.PLAYER_INIT_TIME):this.setAttribute(k.PLAYER_INIT_TIME,`${+i}`))}get playerSoftwareName(){var i;return(i=this.getAttribute(k.PLAYER_SOFTWARE_NAME))!=null?i:k1}get playerSoftwareVersion(){var i;return(i=this.getAttribute(k.PLAYER_SOFTWARE_VERSION))!=null?i:x1}get beaconCollectionDomain(){var i;return(i=this.getAttribute(k.BEACON_COLLECTION_DOMAIN))!=null?i:void 0}set beaconCollectionDomain(i){i!==this.beaconCollectionDomain&&(i?this.setAttribute(k.BEACON_COLLECTION_DOMAIN,i):this.removeAttribute(k.BEACON_COLLECTION_DOMAIN))}get maxResolution(){var i;return(i=this.getAttribute(k.MAX_RESOLUTION))!=null?i:void 0}set maxResolution(i){i!==this.maxResolution&&(i?this.setAttribute(k.MAX_RESOLUTION,i):this.removeAttribute(k.MAX_RESOLUTION))}get minResolution(){var i;return(i=this.getAttribute(k.MIN_RESOLUTION))!=null?i:void 0}set minResolution(i){i!==this.minResolution&&(i?this.setAttribute(k.MIN_RESOLUTION,i):this.removeAttribute(k.MIN_RESOLUTION))}get maxAutoResolution(){var i;return(i=this.getAttribute(k.MAX_AUTO_RESOLUTION))!=null?i:void 0}set maxAutoResolution(i){i==null?this.removeAttribute(k.MAX_AUTO_RESOLUTION):this.setAttribute(k.MAX_AUTO_RESOLUTION,i)}get renditionOrder(){var i;return(i=this.getAttribute(k.RENDITION_ORDER))!=null?i:void 0}set renditionOrder(i){i!==this.renditionOrder&&(i?this.setAttribute(k.RENDITION_ORDER,i):this.removeAttribute(k.RENDITION_ORDER))}get programStartTime(){return Ut(this.getAttribute(k.PROGRAM_START_TIME))}set programStartTime(i){i==null?this.removeAttribute(k.PROGRAM_START_TIME):this.setAttribute(k.PROGRAM_START_TIME,`${i}`)}get programEndTime(){return Ut(this.getAttribute(k.PROGRAM_END_TIME))}set programEndTime(i){i==null?this.removeAttribute(k.PROGRAM_END_TIME):this.setAttribute(k.PROGRAM_END_TIME,`${i}`)}get assetStartTime(){return Ut(this.getAttribute(k.ASSET_START_TIME))}set assetStartTime(i){i==null?this.removeAttribute(k.ASSET_START_TIME):this.setAttribute(k.ASSET_START_TIME,`${i}`)}get assetEndTime(){return Ut(this.getAttribute(k.ASSET_END_TIME))}set assetEndTime(i){i==null?this.removeAttribute(k.ASSET_END_TIME):this.setAttribute(k.ASSET_END_TIME,`${i}`)}get extraSourceParams(){return this.hasAttribute(B.EXTRA_SOURCE_PARAMS)?[...new URLSearchParams(this.getAttribute(B.EXTRA_SOURCE_PARAMS)).entries()].reduce((i,[e,t])=>(i[e]=t,i),{}):hN}set extraSourceParams(i){i==null?this.removeAttribute(B.EXTRA_SOURCE_PARAMS):this.setAttribute(B.EXTRA_SOURCE_PARAMS,new URLSearchParams(i).toString())}get customDomain(){var i;return(i=this.getAttribute(k.CUSTOM_DOMAIN))!=null?i:void 0}set customDomain(i){i!==this.customDomain&&(i?this.setAttribute(k.CUSTOM_DOMAIN,i):this.removeAttribute(k.CUSTOM_DOMAIN))}get envKey(){var i;return(i=As(this,k.ENV_KEY))!=null?i:void 0}set envKey(i){this.setAttribute(k.ENV_KEY,`${i}`)}get noVolumePref(){return this.hasAttribute(B.NO_VOLUME_PREF)}set noVolumePref(i){i?this.setAttribute(B.NO_VOLUME_PREF,""):this.removeAttribute(B.NO_VOLUME_PREF)}get noMutedPref(){return this.hasAttribute(B.NO_MUTED_PREF)}set noMutedPref(i){i?this.setAttribute(B.NO_MUTED_PREF,""):this.removeAttribute(B.NO_MUTED_PREF)}get debug(){return As(this,k.DEBUG)!=null}set debug(i){i?this.setAttribute(k.DEBUG,""):this.removeAttribute(k.DEBUG)}get disableTracking(){return As(this,k.DISABLE_TRACKING)!=null}set disableTracking(i){this.toggleAttribute(k.DISABLE_TRACKING,!!i)}get disableCookies(){return As(this,k.DISABLE_COOKIES)!=null}set disableCookies(i){i?this.setAttribute(k.DISABLE_COOKIES,""):this.removeAttribute(k.DISABLE_COOKIES)}get streamType(){var i,e,t;return(t=(e=this.getAttribute(k.STREAM_TYPE))!=null?e:(i=this.media)==null?void 0:i.streamType)!=null?t:we.UNKNOWN}set streamType(i){this.setAttribute(k.STREAM_TYPE,`${i}`)}get defaultStreamType(){var i,e,t;return(t=(e=this.getAttribute(B.DEFAULT_STREAM_TYPE))!=null?e:(i=this.mediaController)==null?void 0:i.getAttribute(B.DEFAULT_STREAM_TYPE))!=null?t:we.ON_DEMAND}set defaultStreamType(i){i?this.setAttribute(B.DEFAULT_STREAM_TYPE,i):this.removeAttribute(B.DEFAULT_STREAM_TYPE)}get targetLiveWindow(){var i,e;return this.hasAttribute(B.TARGET_LIVE_WINDOW)?+this.getAttribute(B.TARGET_LIVE_WINDOW):(e=(i=this.media)==null?void 0:i.targetLiveWindow)!=null?e:Number.NaN}set targetLiveWindow(i){i==this.targetLiveWindow||Number.isNaN(i)&&Number.isNaN(this.targetLiveWindow)||(i==null?this.removeAttribute(B.TARGET_LIVE_WINDOW):this.setAttribute(B.TARGET_LIVE_WINDOW,`${+i}`))}get liveEdgeStart(){var i;return(i=this.media)==null?void 0:i.liveEdgeStart}get startTime(){return Ut(As(this,k.START_TIME))}set startTime(i){this.setAttribute(k.START_TIME,`${i}`)}get initialBandwidthEstimateKbps(){return Ut(As(this,k.INITIAL_BANDWIDTH_ESTIMATE_KBPS))}set initialBandwidthEstimateKbps(i){i==null?this.removeAttribute(k.INITIAL_BANDWIDTH_ESTIMATE_KBPS):this.setAttribute(k.INITIAL_BANDWIDTH_ESTIMATE_KBPS,`${i}`)}get initialEstimateSegments(){return Ut(As(this,k.INITIAL_ESTIMATE_SEGMENTS))}set initialEstimateSegments(i){i==null?this.removeAttribute(k.INITIAL_ESTIMATE_SEGMENTS):this.setAttribute(k.INITIAL_ESTIMATE_SEGMENTS,`${i}`)}get minPreloadSegments(){return Ut(As(this,k.MIN_PRELOAD_SEGMENTS))}set minPreloadSegments(i){i==null?this.removeAttribute(k.MIN_PRELOAD_SEGMENTS):this.setAttribute(k.MIN_PRELOAD_SEGMENTS,`${i}`)}get preferPlayback(){let i=this.getAttribute(k.PREFER_PLAYBACK);if(i===gi.MSE||i===gi.NATIVE)return i}set preferPlayback(i){i!==this.preferPlayback&&(i===gi.MSE||i===gi.NATIVE?this.setAttribute(k.PREFER_PLAYBACK,i):this.removeAttribute(k.PREFER_PLAYBACK))}get metadata(){var i;return(i=this.media)==null?void 0:i.metadata}set metadata(i){if(dt(this,rt,Zs).call(this),!this.media){hi("underlying media element missing when trying to set metadata. metadata will not be set.");return}this.media.metadata={...R1(this),...i}}get _hlsConfig(){var i;return(i=this.media)==null?void 0:i._hlsConfig}set _hlsConfig(i){if(dt(this,rt,Zs).call(this),!this.media){hi("underlying media element missing when trying to set _hlsConfig. _hlsConfig will not be set.");return}this.media._hlsConfig=i}async addCuePoints(i){var e;if(dt(this,rt,Zs).call(this),!this.media){hi("underlying media element missing when trying to addCuePoints. cuePoints will not be added.");return}return(e=this.media)==null?void 0:e.addCuePoints(i)}get activeCuePoint(){var i;return(i=this.media)==null?void 0:i.activeCuePoint}get cuePoints(){var i,e;return(e=(i=this.media)==null?void 0:i.cuePoints)!=null?e:[]}addChapters(i){var e;if(dt(this,rt,Zs).call(this),!this.media){hi("underlying media element missing when trying to addChapters. chapters will not be added.");return}return(e=this.media)==null?void 0:e.addChapters(i)}get activeChapter(){var i;return(i=this.media)==null?void 0:i.activeChapter}get chapters(){var i,e;return(e=(i=this.media)==null?void 0:i.chapters)!=null?e:[]}getStartDate(){var i;return(i=this.media)==null?void 0:i.getStartDate()}get currentPdt(){var i;return(i=this.media)==null?void 0:i.currentPdt}get tokens(){let i=this.getAttribute(B.PLAYBACK_TOKEN),e=this.getAttribute(B.DRM_TOKEN),t=this.getAttribute(B.THUMBNAIL_TOKEN),s=this.getAttribute(B.STORYBOARD_TOKEN);return{...ve(this,Ff),...i!=null?{playback:i}:{},...e!=null?{drm:e}:{},...t!=null?{thumbnail:t}:{},...s!=null?{storyboard:s}:{}}}set tokens(i){ii(this,Ff,i!=null?i:{})}get playbackToken(){var i;return(i=this.getAttribute(B.PLAYBACK_TOKEN))!=null?i:void 0}set playbackToken(i){this.setAttribute(B.PLAYBACK_TOKEN,`${i}`)}get drmToken(){var i;return(i=this.getAttribute(B.DRM_TOKEN))!=null?i:void 0}set drmToken(i){this.setAttribute(B.DRM_TOKEN,`${i}`)}get thumbnailToken(){var i;return(i=this.getAttribute(B.THUMBNAIL_TOKEN))!=null?i:void 0}set thumbnailToken(i){this.setAttribute(B.THUMBNAIL_TOKEN,`${i}`)}get storyboardToken(){var i;return(i=this.getAttribute(B.STORYBOARD_TOKEN))!=null?i:void 0}set storyboardToken(i){this.setAttribute(B.STORYBOARD_TOKEN,`${i}`)}addTextTrack(i,e,t,s){var r;let n=(r=this.media)==null?void 0:r.nativeEl;if(n)return Vu(n,i,e,t,s)}removeTextTrack(i){var e;let t=(e=this.media)==null?void 0:e.nativeEl;if(t)return Cb(t,i)}get textTracks(){var i;return(i=this.media)==null?void 0:i.textTracks}get castReceiver(){var i;return(i=this.getAttribute(B.CAST_RECEIVER))!=null?i:void 0}set castReceiver(i){i!==this.castReceiver&&(i?this.setAttribute(B.CAST_RECEIVER,i):this.removeAttribute(B.CAST_RECEIVER))}get castCustomData(){var i;return(i=this.media)==null?void 0:i.castCustomData}set castCustomData(i){if(!this.media){hi("underlying media element missing when trying to set castCustomData. castCustomData will not be set.");return}this.media.castCustomData=i}get noTooltips(){return this.hasAttribute(B.NO_TOOLTIPS)}set noTooltips(i){if(!i){this.removeAttribute(B.NO_TOOLTIPS);return}this.setAttribute(B.NO_TOOLTIPS,"")}get proudlyDisplayMuxBadge(){return this.hasAttribute(B.PROUDLY_DISPLAY_MUX_BADGE)}set proudlyDisplayMuxBadge(i){i?this.setAttribute(B.PROUDLY_DISPLAY_MUX_BADGE,""):this.removeAttribute(B.PROUDLY_DISPLAY_MUX_BADGE)}get capRenditionToPlayerSize(){var i;return(i=this.media)==null?void 0:i.capRenditionToPlayerSize}set capRenditionToPlayerSize(i){if(!this.media){hi("underlying media element missing when trying to set capRenditionToPlayerSize");return}this.media.capRenditionToPlayerSize=i}};Uf=new WeakMap,Sd=new WeakMap,Ff=new WeakMap,Bn=new WeakMap,Bf=new WeakMap,Id=new WeakMap,Hf=new WeakMap,Gf=new WeakMap,_o=new WeakMap,Ld=new WeakMap,Ao=new WeakMap,Kf=new WeakMap,rt=new WeakSet,Zs=function(){var i,e,t,s;if(!ve(this,Sd)){ii(this,Sd,!0),dt(this,rt,$n).call(this);try{if(customElements.upgrade(this.mediaTheme),!(this.mediaTheme instanceof Ss.HTMLElement))throw""}catch{hi("<media-theme> failed to upgrade!")}try{customElements.upgrade(this.media)}catch{hi("underlying media element failed to upgrade!")}try{if(customElements.upgrade(this.mediaController),!(this.mediaController instanceof g0))throw""}catch{hi("<media-controller> failed to upgrade!")}dt(this,rt,C1).call(this),dt(this,rt,w1).call(this),dt(this,rt,M1).call(this),ii(this,Bn,(e=(i=this.mediaController)==null?void 0:i.hasAttribute(ae.USER_INACTIVE))!=null?e:!0),dt(this,rt,P1).call(this),(t=this.media)==null||t.addEventListener("streamtypechange",ve(this,Hf)),(s=this.media)==null||s.addEventListener("loadstart",ve(this,Gf))}},z1=function(){var i,e;try{(i=window==null?void 0:window.CSS)==null||i.registerProperty({name:"--media-primary-color",syntax:"<color>",inherits:!0}),(e=window==null?void 0:window.CSS)==null||e.registerProperty({name:"--media-secondary-color",syntax:"<color>",inherits:!0})}catch{}},tE=function(i){Object.assign(ve(this,Ao),i),dt(this,rt,$n).call(this)},$n=function(i={}){q2(j2(nN(this,{...ve(this,Ao),...i})),this.shadowRoot)},C1=function(){let i=e=>{var t,s;if(!(e!=null&&e.startsWith("theme-")))return;let r=e.replace(/^theme-/,"");if(eE.includes(r))return;let n=this.getAttribute(e);n!=null?(t=this.mediaTheme)==null||t.setAttribute(r,n):(s=this.mediaTheme)==null||s.removeAttribute(r)};ii(this,Id,new MutationObserver(e=>{for(let{attributeName:t}of e)i(t)})),ve(this,Id).observe(this,{attributes:!0}),this.getAttributeNames().forEach(i)},w1=function(){this.addEventListener("error",ve(this,Kf)),this.media&&(this.media.errorTranslator=(i={})=>{var e,t,s;if(!(((e=this.media)==null?void 0:e.error)instanceof z))return i;let r=Y1((t=this.media)==null?void 0:t.error,!1);return{player_error_code:(s=this.media)==null?void 0:s.error.code,player_error_message:r.message?String(r.message):i.player_error_message,player_error_context:r.context?String(r.context):i.player_error_context}})},M1=function(){var i,e,t,s;(e=(i=this.media)==null?void 0:i.textTracks)==null||e.addEventListener("addtrack",ve(this,_o)),(s=(t=this.media)==null?void 0:t.textTracks)==null||s.addEventListener("removetrack",ve(this,_o))},P1=function(){var i,e;if(!/Firefox/i.test(navigator.userAgent))return;let t,s=new WeakMap,r=()=>this.streamType===we.LIVE&&!this.secondaryColor&&this.offsetWidth>=800,n=(d,u,c=!1)=>{r()||Array.from(d&&d.activeCues||[]).forEach(h=>{if(!(!h.snapToLines||h.line<-5||h.line>=0&&h.line<10))if(!u||this.paused){let f=h.text.split(`
3398
+ `}return aN(i)};function oN(i){var e,t;let s=i.theme;if(s){let r=(t=(e=i.getRootNode())==null?void 0:e.getElementById)==null?void 0:t.call(e,s);if(r&&r instanceof HTMLTemplateElement)return r;s.startsWith("media-theme-")||(s=`media-theme-${s}`);let n=Ss.customElements.get(s);if(n!=null&&n.template)return n.template}}function lN(i){var e;let t=(e=i.mediaController)==null?void 0:e.querySelector("media-time-display");return t&&getComputedStyle(t).getPropertyValue("--media-duration-display-display").trim()==="none"}function R1(i){let e=i.videoTitle?{video_title:i.videoTitle}:{};return i.getAttributeNames().filter(t=>t.startsWith("metadata-")).reduce((t,s)=>{let r=i.getAttribute(s);return r!==null&&(t[s.replace(/^metadata-/,"").replace(/-/g,"_")]=r),t},e)}var dN=Object.values(k),uN=Object.values(Xs),cN=Object.values(B),x1=G1(),k1="mux-player",D1={isDialogOpen:!1},hN={redundant_streams:!0},Uf,Sd,Ff,Bn,Bf,Id,Hf,Gf,_o,Ld,Ao,Kf,rt,Zs,z1,tE,$n,C1,w1,M1,P1,fN=class extends _1{constructor(){super(),Ot(this,rt),Ot(this,Uf),Ot(this,Sd,!1),Ot(this,Ff,{}),Ot(this,Bn,!0),Ot(this,Bf,new D2(this,"hotkeys")),Ot(this,Id),Ot(this,Hf,()=>dt(this,rt,$n).call(this)),Ot(this,Gf,()=>dt(this,rt,$n).call(this)),Ot(this,_o,()=>dt(this,rt,$n).call(this)),Ot(this,Ld),Ot(this,Ao,{...D1,onCloseErrorDialog:i=>{var e;((e=i.composedPath()[0])==null?void 0:e.localName)==="media-error-dialog"&&dt(this,rt,tE).call(this,{isDialogOpen:!1})},onFocusInErrorDialog:i=>{var e;((e=i.composedPath()[0])==null?void 0:e.localName)==="media-error-dialog"&&($1(this,$f.activeElement)||i.preventDefault())}}),Ot(this,Kf,i=>{var e;let t=(e=this.media)==null?void 0:e.error;if(!(t instanceof z)){let{message:r,code:n}=t!=null?t:{};t=new z(r,n)}if(!(t!=null&&t.fatal)){Qs(t),t.data&&Qs(`${t.name} data:`,t.data);return}let s=Y1(t,!1);s.message&&b1(s),hi(t),t.data&&hi(`${t.name} data:`,t.data),dt(this,rt,tE).call(this,{isDialogOpen:!0})}),ii(this,Uf,Wu()),this.attachShadow({mode:"open"}),dt(this,rt,z1).call(this),this.isConnected&&dt(this,rt,Zs).call(this)}static get NAME(){return k1}static get VERSION(){return x1}static get observedAttributes(){var i;return[...(i=_1.observedAttributes)!=null?i:[],...uN,...dN,...cN]}get mediaTheme(){var i;return(i=this.shadowRoot)==null?void 0:i.querySelector("media-theme")}get mediaController(){var i,e;return(e=(i=this.mediaTheme)==null?void 0:i.shadowRoot)==null?void 0:e.querySelector("media-controller")}connectedCallback(){dt(this,rt,Zs).call(this);let i=this.media;i&&(i.metadata=R1(this))}disconnectedCallback(){var i,e,t,s,r,n,a,o;(i=ve(this,Id))==null||i.disconnect(),(e=this.media)==null||e.removeEventListener("streamtypechange",ve(this,Hf)),(t=this.media)==null||t.removeEventListener("loadstart",ve(this,Gf)),this.removeEventListener("error",ve(this,Kf)),this.media&&(this.media.errorTranslator=void 0),(r=(s=this.media)==null?void 0:s.textTracks)==null||r.removeEventListener("addtrack",ve(this,_o)),(a=(n=this.media)==null?void 0:n.textTracks)==null||a.removeEventListener("removetrack",ve(this,_o)),(o=ve(this,Ld))==null||o.call(this),ii(this,Ld,void 0),ii(this,Sd,!1)}attributeChangedCallback(i,e,t){switch(dt(this,rt,Zs).call(this),super.attributeChangedCallback(i,e,t),i){case B.HOTKEYS:ve(this,Bf).value=t;break;case B.THUMBNAIL_TIME:{t!=null&&this.tokens.thumbnail&&Qs(te("Use of thumbnail-time with thumbnail-token is currently unsupported. Ignore thumbnail-time.").toString());break}case B.THUMBNAIL_TOKEN:{if(t){let s=dr(t);if(s){let{aud:r}=s,n=oa.THUMBNAIL;r!==n&&Qs(te("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.").format({aud:r,expectedAud:n,tokenNamePrefix:"thumbnail"}))}}break}case B.STORYBOARD_TOKEN:{if(t){let s=dr(t);if(s){let{aud:r}=s,n=oa.STORYBOARD;r!==n&&Qs(te("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.").format({aud:r,expectedAud:n,tokenNamePrefix:"storyboard"}))}}break}case B.DRM_TOKEN:{if(t){let s=dr(t);if(s){let{aud:r}=s,n=oa.DRM;r!==n&&Qs(te("The {tokenNamePrefix}-token has an incorrect aud value: {aud}. aud value should be {expectedAud}.").format({aud:r,expectedAud:n,tokenNamePrefix:"drm"}))}}break}case k.PLAYBACK_ID:{t!=null&&t.includes("?token")&&hi(te("The specificed playback ID {playbackId} contains a token which must be provided via the playback-token attribute.").format({playbackId:t}));break}case k.STREAM_TYPE:{t&&![we.LIVE,we.ON_DEMAND,we.UNKNOWN].includes(t)?["ll-live","live:dvr","ll-live:dvr"].includes(this.streamType)?this.targetLiveWindow=t.includes("dvr")?Number.POSITIVE_INFINITY:0:b1({file:"invalid-stream-type.md",message:te("Invalid stream-type value supplied: `{streamType}`. Please provide stream-type as either: `on-demand` or `live`").format({streamType:this.streamType})}):t===we.LIVE?this.getAttribute(B.TARGET_LIVE_WINDOW)==null&&(this.targetLiveWindow=0):this.targetLiveWindow=Number.NaN;break}case B.FULLSCREEN_ELEMENT:{if(t!=null||t!==e){let s=$f.getElementById(t),r=s==null?void 0:s.querySelector("mux-player");this.mediaController&&s&&r&&(this.mediaController.fullscreenElement=s)}break}case k.CAP_RENDITION_TO_PLAYER_SIZE:{(t==null||t!==e)&&(this.capRenditionToPlayerSize=t!=null?!0:void 0);break}}[k.PLAYBACK_ID,Xs.SRC,B.PLAYBACK_TOKEN].includes(i)&&e!==t&&ii(this,Ao,{...ve(this,Ao),...D1}),dt(this,rt,$n).call(this,{[k2(i)]:t})}async requestFullscreen(i){var e;if(!(!this.mediaController||this.mediaController.hasAttribute(_.MEDIA_IS_FULLSCREEN)))return(e=this.mediaController)==null||e.dispatchEvent(new Ss.CustomEvent(K.MEDIA_ENTER_FULLSCREEN_REQUEST,{composed:!0,bubbles:!0})),new Promise((t,s)=>{var r;(r=this.mediaController)==null||r.addEventListener(di.MEDIA_IS_FULLSCREEN,()=>t(),{once:!0})})}async exitFullscreen(){var i;if(!(!this.mediaController||!this.mediaController.hasAttribute(_.MEDIA_IS_FULLSCREEN)))return(i=this.mediaController)==null||i.dispatchEvent(new Ss.CustomEvent(K.MEDIA_EXIT_FULLSCREEN_REQUEST,{composed:!0,bubbles:!0})),new Promise((e,t)=>{var s;(s=this.mediaController)==null||s.addEventListener(di.MEDIA_IS_FULLSCREEN,()=>e(),{once:!0})})}get preferCmcd(){var i;return(i=this.getAttribute(k.PREFER_CMCD))!=null?i:void 0}set preferCmcd(i){i!==this.preferCmcd&&(i?la.includes(i)?this.setAttribute(k.PREFER_CMCD,i):Qs(`Invalid value for preferCmcd. Must be one of ${la.join()}`):this.removeAttribute(k.PREFER_CMCD))}get hasPlayed(){var i,e;return(e=(i=this.mediaController)==null?void 0:i.hasAttribute(_.MEDIA_HAS_PLAYED))!=null?e:!1}get inLiveWindow(){var i;return(i=this.mediaController)==null?void 0:i.hasAttribute(_.MEDIA_TIME_IS_LIVE)}get _hls(){var i;return(i=this.media)==null?void 0:i._hls}get mux(){var i;return(i=this.media)==null?void 0:i.mux}get theme(){var i;return(i=this.getAttribute(B.THEME))!=null?i:rN}set theme(i){this.setAttribute(B.THEME,`${i}`)}get themeProps(){let i=this.mediaTheme;if(!i)return;let e={};for(let t of i.getAttributeNames()){if(eE.includes(t))continue;let s=i.getAttribute(t);e[F1(t)]=s===""?!0:s}return e}set themeProps(i){var e,t;dt(this,rt,Zs).call(this);let s={...this.themeProps,...i};for(let r in s){if(eE.includes(r))continue;let n=i==null?void 0:i[r];typeof n=="boolean"||n==null?(e=this.mediaTheme)==null||e.toggleAttribute(Zv(r),!!n):(t=this.mediaTheme)==null||t.setAttribute(Zv(r),n)}}get playbackId(){var i;return(i=this.getAttribute(k.PLAYBACK_ID))!=null?i:void 0}set playbackId(i){i?this.setAttribute(k.PLAYBACK_ID,i):this.removeAttribute(k.PLAYBACK_ID)}get src(){var i,e;return this.playbackId?(i=As(this,Xs.SRC))!=null?i:void 0:(e=this.getAttribute(Xs.SRC))!=null?e:void 0}set src(i){i?this.setAttribute(Xs.SRC,i):this.removeAttribute(Xs.SRC)}get poster(){var i;let e=this.getAttribute(Xs.POSTER);if(e!=null)return e;let{tokens:t}=this;if(t.playback&&!t.thumbnail){Qs("Missing expected thumbnail token. No poster image will be shown");return}if(this.playbackId&&!this.audio)return L2(this.playbackId,{customDomain:this.customDomain,thumbnailTime:(i=this.thumbnailTime)!=null?i:this.startTime,programTime:this.programStartTime,token:t.thumbnail})}set poster(i){i||i===""?this.setAttribute(Xs.POSTER,i):this.removeAttribute(Xs.POSTER)}get storyboardSrc(){var i;return(i=this.getAttribute(B.STORYBOARD_SRC))!=null?i:void 0}set storyboardSrc(i){i?this.setAttribute(B.STORYBOARD_SRC,i):this.removeAttribute(B.STORYBOARD_SRC)}get storyboard(){let{tokens:i}=this;if(this.storyboardSrc&&!i.storyboard)return this.storyboardSrc;if(!(this.audio||!this.playbackId||!this.streamType||[we.LIVE,we.UNKNOWN].includes(this.streamType)||i.playback&&!i.storyboard))return R2(this.playbackId,{customDomain:this.customDomain,token:i.storyboard,programStartTime:this.programStartTime,programEndTime:this.programEndTime})}get audio(){return this.hasAttribute(B.AUDIO)}set audio(i){if(!i){this.removeAttribute(B.AUDIO);return}this.setAttribute(B.AUDIO,"")}get hotkeys(){return ve(this,Bf)}get nohotkeys(){return this.hasAttribute(B.NOHOTKEYS)}set nohotkeys(i){if(!i){this.removeAttribute(B.NOHOTKEYS);return}this.setAttribute(B.NOHOTKEYS,"")}get thumbnailTime(){return Ut(this.getAttribute(B.THUMBNAIL_TIME))}set thumbnailTime(i){this.setAttribute(B.THUMBNAIL_TIME,`${i}`)}get videoTitle(){var i,e;return(e=(i=this.getAttribute(B.VIDEO_TITLE))!=null?i:this.getAttribute(B.TITLE))!=null?e:""}set videoTitle(i){i!==this.videoTitle&&(i?this.setAttribute(B.VIDEO_TITLE,i):this.removeAttribute(B.VIDEO_TITLE))}get placeholder(){var i;return(i=As(this,B.PLACEHOLDER))!=null?i:""}set placeholder(i){this.setAttribute(B.PLACEHOLDER,`${i}`)}get primaryColor(){var i,e;let t=this.getAttribute(B.PRIMARY_COLOR);if(t!=null||this.mediaTheme&&(t=(e=(i=Ss.getComputedStyle(this.mediaTheme))==null?void 0:i.getPropertyValue("--_primary-color"))==null?void 0:e.trim(),t))return t}set primaryColor(i){this.setAttribute(B.PRIMARY_COLOR,`${i}`)}get secondaryColor(){var i,e;let t=this.getAttribute(B.SECONDARY_COLOR);if(t!=null||this.mediaTheme&&(t=(e=(i=Ss.getComputedStyle(this.mediaTheme))==null?void 0:i.getPropertyValue("--_secondary-color"))==null?void 0:e.trim(),t))return t}set secondaryColor(i){this.setAttribute(B.SECONDARY_COLOR,`${i}`)}get accentColor(){var i,e;let t=this.getAttribute(B.ACCENT_COLOR);if(t!=null||this.mediaTheme&&(t=(e=(i=Ss.getComputedStyle(this.mediaTheme))==null?void 0:i.getPropertyValue("--_accent-color"))==null?void 0:e.trim(),t))return t}set accentColor(i){this.setAttribute(B.ACCENT_COLOR,`${i}`)}get defaultShowRemainingTime(){return this.hasAttribute(B.DEFAULT_SHOW_REMAINING_TIME)}set defaultShowRemainingTime(i){i?this.setAttribute(B.DEFAULT_SHOW_REMAINING_TIME,""):this.removeAttribute(B.DEFAULT_SHOW_REMAINING_TIME)}get playbackRates(){if(this.hasAttribute(B.PLAYBACK_RATES))return this.getAttribute(B.PLAYBACK_RATES).trim().split(/\s*,?\s+/).map(i=>Number(i)).filter(i=>!Number.isNaN(i)).sort((i,e)=>i-e)}set playbackRates(i){if(!i){this.removeAttribute(B.PLAYBACK_RATES);return}this.setAttribute(B.PLAYBACK_RATES,i.join(" "))}get forwardSeekOffset(){var i;return(i=Ut(this.getAttribute(B.FORWARD_SEEK_OFFSET)))!=null?i:10}set forwardSeekOffset(i){this.setAttribute(B.FORWARD_SEEK_OFFSET,`${i}`)}get backwardSeekOffset(){var i;return(i=Ut(this.getAttribute(B.BACKWARD_SEEK_OFFSET)))!=null?i:10}set backwardSeekOffset(i){this.setAttribute(B.BACKWARD_SEEK_OFFSET,`${i}`)}get defaultHiddenCaptions(){return this.hasAttribute(B.DEFAULT_HIDDEN_CAPTIONS)}set defaultHiddenCaptions(i){i?this.setAttribute(B.DEFAULT_HIDDEN_CAPTIONS,""):this.removeAttribute(B.DEFAULT_HIDDEN_CAPTIONS)}get defaultDuration(){return Ut(this.getAttribute(B.DEFAULT_DURATION))}set defaultDuration(i){i==null?this.removeAttribute(B.DEFAULT_DURATION):this.setAttribute(B.DEFAULT_DURATION,`${i}`)}get playerInitTime(){return this.hasAttribute(k.PLAYER_INIT_TIME)?Ut(this.getAttribute(k.PLAYER_INIT_TIME)):ve(this,Uf)}set playerInitTime(i){i!=this.playerInitTime&&(i==null?this.removeAttribute(k.PLAYER_INIT_TIME):this.setAttribute(k.PLAYER_INIT_TIME,`${+i}`))}get playerSoftwareName(){var i;return(i=this.getAttribute(k.PLAYER_SOFTWARE_NAME))!=null?i:k1}get playerSoftwareVersion(){var i;return(i=this.getAttribute(k.PLAYER_SOFTWARE_VERSION))!=null?i:x1}get beaconCollectionDomain(){var i;return(i=this.getAttribute(k.BEACON_COLLECTION_DOMAIN))!=null?i:void 0}set beaconCollectionDomain(i){i!==this.beaconCollectionDomain&&(i?this.setAttribute(k.BEACON_COLLECTION_DOMAIN,i):this.removeAttribute(k.BEACON_COLLECTION_DOMAIN))}get maxResolution(){var i;return(i=this.getAttribute(k.MAX_RESOLUTION))!=null?i:void 0}set maxResolution(i){i!==this.maxResolution&&(i?this.setAttribute(k.MAX_RESOLUTION,i):this.removeAttribute(k.MAX_RESOLUTION))}get minResolution(){var i;return(i=this.getAttribute(k.MIN_RESOLUTION))!=null?i:void 0}set minResolution(i){i!==this.minResolution&&(i?this.setAttribute(k.MIN_RESOLUTION,i):this.removeAttribute(k.MIN_RESOLUTION))}get maxAutoResolution(){var i;return(i=this.getAttribute(k.MAX_AUTO_RESOLUTION))!=null?i:void 0}set maxAutoResolution(i){i==null?this.removeAttribute(k.MAX_AUTO_RESOLUTION):this.setAttribute(k.MAX_AUTO_RESOLUTION,i)}get renditionOrder(){var i;return(i=this.getAttribute(k.RENDITION_ORDER))!=null?i:void 0}set renditionOrder(i){i!==this.renditionOrder&&(i?this.setAttribute(k.RENDITION_ORDER,i):this.removeAttribute(k.RENDITION_ORDER))}get programStartTime(){return Ut(this.getAttribute(k.PROGRAM_START_TIME))}set programStartTime(i){i==null?this.removeAttribute(k.PROGRAM_START_TIME):this.setAttribute(k.PROGRAM_START_TIME,`${i}`)}get programEndTime(){return Ut(this.getAttribute(k.PROGRAM_END_TIME))}set programEndTime(i){i==null?this.removeAttribute(k.PROGRAM_END_TIME):this.setAttribute(k.PROGRAM_END_TIME,`${i}`)}get assetStartTime(){return Ut(this.getAttribute(k.ASSET_START_TIME))}set assetStartTime(i){i==null?this.removeAttribute(k.ASSET_START_TIME):this.setAttribute(k.ASSET_START_TIME,`${i}`)}get assetEndTime(){return Ut(this.getAttribute(k.ASSET_END_TIME))}set assetEndTime(i){i==null?this.removeAttribute(k.ASSET_END_TIME):this.setAttribute(k.ASSET_END_TIME,`${i}`)}get extraSourceParams(){return this.hasAttribute(B.EXTRA_SOURCE_PARAMS)?[...new URLSearchParams(this.getAttribute(B.EXTRA_SOURCE_PARAMS)).entries()].reduce((i,[e,t])=>(i[e]=t,i),{}):hN}set extraSourceParams(i){i==null?this.removeAttribute(B.EXTRA_SOURCE_PARAMS):this.setAttribute(B.EXTRA_SOURCE_PARAMS,new URLSearchParams(i).toString())}get customDomain(){var i;return(i=this.getAttribute(k.CUSTOM_DOMAIN))!=null?i:void 0}set customDomain(i){i!==this.customDomain&&(i?this.setAttribute(k.CUSTOM_DOMAIN,i):this.removeAttribute(k.CUSTOM_DOMAIN))}get envKey(){var i;return(i=As(this,k.ENV_KEY))!=null?i:void 0}set envKey(i){this.setAttribute(k.ENV_KEY,`${i}`)}get noVolumePref(){return this.hasAttribute(B.NO_VOLUME_PREF)}set noVolumePref(i){i?this.setAttribute(B.NO_VOLUME_PREF,""):this.removeAttribute(B.NO_VOLUME_PREF)}get noMutedPref(){return this.hasAttribute(B.NO_MUTED_PREF)}set noMutedPref(i){i?this.setAttribute(B.NO_MUTED_PREF,""):this.removeAttribute(B.NO_MUTED_PREF)}get debug(){return As(this,k.DEBUG)!=null}set debug(i){i?this.setAttribute(k.DEBUG,""):this.removeAttribute(k.DEBUG)}get disableTracking(){return As(this,k.DISABLE_TRACKING)!=null}set disableTracking(i){this.toggleAttribute(k.DISABLE_TRACKING,!!i)}get disableCookies(){return As(this,k.DISABLE_COOKIES)!=null}set disableCookies(i){i?this.setAttribute(k.DISABLE_COOKIES,""):this.removeAttribute(k.DISABLE_COOKIES)}get streamType(){var i,e,t;return(t=(e=this.getAttribute(k.STREAM_TYPE))!=null?e:(i=this.media)==null?void 0:i.streamType)!=null?t:we.UNKNOWN}set streamType(i){this.setAttribute(k.STREAM_TYPE,`${i}`)}get defaultStreamType(){var i,e,t;return(t=(e=this.getAttribute(B.DEFAULT_STREAM_TYPE))!=null?e:(i=this.mediaController)==null?void 0:i.getAttribute(B.DEFAULT_STREAM_TYPE))!=null?t:we.ON_DEMAND}set defaultStreamType(i){i?this.setAttribute(B.DEFAULT_STREAM_TYPE,i):this.removeAttribute(B.DEFAULT_STREAM_TYPE)}get targetLiveWindow(){var i,e;return this.hasAttribute(B.TARGET_LIVE_WINDOW)?+this.getAttribute(B.TARGET_LIVE_WINDOW):(e=(i=this.media)==null?void 0:i.targetLiveWindow)!=null?e:Number.NaN}set targetLiveWindow(i){i==this.targetLiveWindow||Number.isNaN(i)&&Number.isNaN(this.targetLiveWindow)||(i==null?this.removeAttribute(B.TARGET_LIVE_WINDOW):this.setAttribute(B.TARGET_LIVE_WINDOW,`${+i}`))}get liveEdgeStart(){var i;return(i=this.media)==null?void 0:i.liveEdgeStart}get startTime(){return Ut(As(this,k.START_TIME))}set startTime(i){this.setAttribute(k.START_TIME,`${i}`)}get initialBandwidthEstimateKbps(){return Ut(As(this,k.INITIAL_BANDWIDTH_ESTIMATE_KBPS))}set initialBandwidthEstimateKbps(i){i==null?this.removeAttribute(k.INITIAL_BANDWIDTH_ESTIMATE_KBPS):this.setAttribute(k.INITIAL_BANDWIDTH_ESTIMATE_KBPS,`${i}`)}get initialEstimateSegments(){return Ut(As(this,k.INITIAL_ESTIMATE_SEGMENTS))}set initialEstimateSegments(i){i==null?this.removeAttribute(k.INITIAL_ESTIMATE_SEGMENTS):this.setAttribute(k.INITIAL_ESTIMATE_SEGMENTS,`${i}`)}get minPreloadSegments(){return Ut(As(this,k.MIN_PRELOAD_SEGMENTS))}set minPreloadSegments(i){i==null?this.removeAttribute(k.MIN_PRELOAD_SEGMENTS):this.setAttribute(k.MIN_PRELOAD_SEGMENTS,`${i}`)}get preferPlayback(){let i=this.getAttribute(k.PREFER_PLAYBACK);if(i===gi.MSE||i===gi.NATIVE)return i}set preferPlayback(i){i!==this.preferPlayback&&(i===gi.MSE||i===gi.NATIVE?this.setAttribute(k.PREFER_PLAYBACK,i):this.removeAttribute(k.PREFER_PLAYBACK))}get metadata(){var i;return(i=this.media)==null?void 0:i.metadata}set metadata(i){if(dt(this,rt,Zs).call(this),!this.media){hi("underlying media element missing when trying to set metadata. metadata will not be set.");return}this.media.metadata={...R1(this),...i}}get _hlsConfig(){var i;return(i=this.media)==null?void 0:i._hlsConfig}set _hlsConfig(i){if(dt(this,rt,Zs).call(this),!this.media){hi("underlying media element missing when trying to set _hlsConfig. _hlsConfig will not be set.");return}this.media._hlsConfig=i}async addCuePoints(i){var e;if(dt(this,rt,Zs).call(this),!this.media){hi("underlying media element missing when trying to addCuePoints. cuePoints will not be added.");return}return(e=this.media)==null?void 0:e.addCuePoints(i)}get activeCuePoint(){var i;return(i=this.media)==null?void 0:i.activeCuePoint}get cuePoints(){var i,e;return(e=(i=this.media)==null?void 0:i.cuePoints)!=null?e:[]}addChapters(i){var e;if(dt(this,rt,Zs).call(this),!this.media){hi("underlying media element missing when trying to addChapters. chapters will not be added.");return}return(e=this.media)==null?void 0:e.addChapters(i)}get activeChapter(){var i;return(i=this.media)==null?void 0:i.activeChapter}get chapters(){var i,e;return(e=(i=this.media)==null?void 0:i.chapters)!=null?e:[]}getStartDate(){var i;return(i=this.media)==null?void 0:i.getStartDate()}get currentPdt(){var i;return(i=this.media)==null?void 0:i.currentPdt}get tokens(){let i=this.getAttribute(B.PLAYBACK_TOKEN),e=this.getAttribute(B.DRM_TOKEN),t=this.getAttribute(B.THUMBNAIL_TOKEN),s=this.getAttribute(B.STORYBOARD_TOKEN);return{...ve(this,Ff),...i!=null?{playback:i}:{},...e!=null?{drm:e}:{},...t!=null?{thumbnail:t}:{},...s!=null?{storyboard:s}:{}}}set tokens(i){ii(this,Ff,i!=null?i:{})}get playbackToken(){var i;return(i=this.getAttribute(B.PLAYBACK_TOKEN))!=null?i:void 0}set playbackToken(i){this.setAttribute(B.PLAYBACK_TOKEN,`${i}`)}get drmToken(){var i;return(i=this.getAttribute(B.DRM_TOKEN))!=null?i:void 0}set drmToken(i){this.setAttribute(B.DRM_TOKEN,`${i}`)}get thumbnailToken(){var i;return(i=this.getAttribute(B.THUMBNAIL_TOKEN))!=null?i:void 0}set thumbnailToken(i){this.setAttribute(B.THUMBNAIL_TOKEN,`${i}`)}get storyboardToken(){var i;return(i=this.getAttribute(B.STORYBOARD_TOKEN))!=null?i:void 0}set storyboardToken(i){this.setAttribute(B.STORYBOARD_TOKEN,`${i}`)}addTextTrack(i,e,t,s){var r;let n=(r=this.media)==null?void 0:r.nativeEl;if(n)return Vu(n,i,e,t,s)}removeTextTrack(i){var e;let t=(e=this.media)==null?void 0:e.nativeEl;if(t)return CT(t,i)}get textTracks(){var i;return(i=this.media)==null?void 0:i.textTracks}get castReceiver(){var i;return(i=this.getAttribute(B.CAST_RECEIVER))!=null?i:void 0}set castReceiver(i){i!==this.castReceiver&&(i?this.setAttribute(B.CAST_RECEIVER,i):this.removeAttribute(B.CAST_RECEIVER))}get castCustomData(){var i;return(i=this.media)==null?void 0:i.castCustomData}set castCustomData(i){if(!this.media){hi("underlying media element missing when trying to set castCustomData. castCustomData will not be set.");return}this.media.castCustomData=i}get noTooltips(){return this.hasAttribute(B.NO_TOOLTIPS)}set noTooltips(i){if(!i){this.removeAttribute(B.NO_TOOLTIPS);return}this.setAttribute(B.NO_TOOLTIPS,"")}get proudlyDisplayMuxBadge(){return this.hasAttribute(B.PROUDLY_DISPLAY_MUX_BADGE)}set proudlyDisplayMuxBadge(i){i?this.setAttribute(B.PROUDLY_DISPLAY_MUX_BADGE,""):this.removeAttribute(B.PROUDLY_DISPLAY_MUX_BADGE)}get capRenditionToPlayerSize(){var i;return(i=this.media)==null?void 0:i.capRenditionToPlayerSize}set capRenditionToPlayerSize(i){if(!this.media){hi("underlying media element missing when trying to set capRenditionToPlayerSize");return}this.media.capRenditionToPlayerSize=i}};Uf=new WeakMap,Sd=new WeakMap,Ff=new WeakMap,Bn=new WeakMap,Bf=new WeakMap,Id=new WeakMap,Hf=new WeakMap,Gf=new WeakMap,_o=new WeakMap,Ld=new WeakMap,Ao=new WeakMap,Kf=new WeakMap,rt=new WeakSet,Zs=function(){var i,e,t,s;if(!ve(this,Sd)){ii(this,Sd,!0),dt(this,rt,$n).call(this);try{if(customElements.upgrade(this.mediaTheme),!(this.mediaTheme instanceof Ss.HTMLElement))throw""}catch{hi("<media-theme> failed to upgrade!")}try{customElements.upgrade(this.media)}catch{hi("underlying media element failed to upgrade!")}try{if(customElements.upgrade(this.mediaController),!(this.mediaController instanceof g0))throw""}catch{hi("<media-controller> failed to upgrade!")}dt(this,rt,C1).call(this),dt(this,rt,w1).call(this),dt(this,rt,M1).call(this),ii(this,Bn,(e=(i=this.mediaController)==null?void 0:i.hasAttribute(ae.USER_INACTIVE))!=null?e:!0),dt(this,rt,P1).call(this),(t=this.media)==null||t.addEventListener("streamtypechange",ve(this,Hf)),(s=this.media)==null||s.addEventListener("loadstart",ve(this,Gf))}},z1=function(){var i,e;try{(i=window==null?void 0:window.CSS)==null||i.registerProperty({name:"--media-primary-color",syntax:"<color>",inherits:!0}),(e=window==null?void 0:window.CSS)==null||e.registerProperty({name:"--media-secondary-color",syntax:"<color>",inherits:!0})}catch{}},tE=function(i){Object.assign(ve(this,Ao),i),dt(this,rt,$n).call(this)},$n=function(i={}){q2(j2(nN(this,{...ve(this,Ao),...i})),this.shadowRoot)},C1=function(){let i=e=>{var t,s;if(!(e!=null&&e.startsWith("theme-")))return;let r=e.replace(/^theme-/,"");if(eE.includes(r))return;let n=this.getAttribute(e);n!=null?(t=this.mediaTheme)==null||t.setAttribute(r,n):(s=this.mediaTheme)==null||s.removeAttribute(r)};ii(this,Id,new MutationObserver(e=>{for(let{attributeName:t}of e)i(t)})),ve(this,Id).observe(this,{attributes:!0}),this.getAttributeNames().forEach(i)},w1=function(){this.addEventListener("error",ve(this,Kf)),this.media&&(this.media.errorTranslator=(i={})=>{var e,t,s;if(!(((e=this.media)==null?void 0:e.error)instanceof z))return i;let r=Y1((t=this.media)==null?void 0:t.error,!1);return{player_error_code:(s=this.media)==null?void 0:s.error.code,player_error_message:r.message?String(r.message):i.player_error_message,player_error_context:r.context?String(r.context):i.player_error_context}})},M1=function(){var i,e,t,s;(e=(i=this.media)==null?void 0:i.textTracks)==null||e.addEventListener("addtrack",ve(this,_o)),(s=(t=this.media)==null?void 0:t.textTracks)==null||s.addEventListener("removetrack",ve(this,_o))},P1=function(){var i,e;if(!/Firefox/i.test(navigator.userAgent))return;let t,s=new WeakMap,r=()=>this.streamType===we.LIVE&&!this.secondaryColor&&this.offsetWidth>=800,n=(d,u,c=!1)=>{r()||Array.from(d&&d.activeCues||[]).forEach(h=>{if(!(!h.snapToLines||h.line<-5||h.line>=0&&h.line<10))if(!u||this.paused){let f=h.text.split(`
3399
3399
  `).length,m=-3;this.streamType===we.LIVE&&(m=-2);let p=m-f;if(h.line===p&&!c)return;s.has(h)||s.set(h,h.line),h.line=p}else setTimeout(()=>{h.line=s.get(h)||"auto"},500)})},a=()=>{var d,u;n(t,(u=(d=this.mediaController)==null?void 0:d.hasAttribute(ae.USER_INACTIVE))!=null?u:!1)},o=()=>{var d,u;let c=Array.from(((u=(d=this.mediaController)==null?void 0:d.media)==null?void 0:u.textTracks)||[]).filter(h=>["subtitles","captions"].includes(h.kind)&&h.mode==="showing")[0];c!==t&&(t==null||t.removeEventListener("cuechange",a)),t=c,t==null||t.addEventListener("cuechange",a),n(t,ve(this,Bn))};o(),(i=this.textTracks)==null||i.addEventListener("change",o),(e=this.textTracks)==null||e.addEventListener("addtrack",o);let l=()=>{var d,u;let c=(u=(d=this.mediaController)==null?void 0:d.hasAttribute(ae.USER_INACTIVE))!=null?u:!0;ve(this,Bn)!==c&&(ii(this,Bn,c),n(t,ve(this,Bn)))};this.addEventListener("userinactivechange",l),ii(this,Ld,()=>{var d,u;t==null||t.removeEventListener("cuechange",a),(d=this.textTracks)==null||d.removeEventListener("change",o),(u=this.textTracks)==null||u.removeEventListener("addtrack",o),this.removeEventListener("userinactivechange",l)})};function As(i,e){return i.media?i.media.getAttribute(e):i.getAttribute(e)}var Wf=fN;Md.customElements.get("mux-player")||(Md.customElements.define("mux-player",Wf),Md.MuxPlayerElement=Wf);var E9=Wf;})();
3400
3400
  /*! Bundled license information:
3401
3401