@clappr/hlsjs-playback 1.7.4 → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/hlsjs-playback.esm.js +5 -0
- package/dist/hlsjs-playback.external.js +5 -0
- package/dist/hlsjs-playback.external.min.js +1 -1
- package/dist/hlsjs-playback.external.min.js.map +1 -1
- package/dist/hlsjs-playback.js +5 -0
- package/dist/hlsjs-playback.min.js +1 -1
- package/dist/hlsjs-playback.min.js.map +1 -1
- package/package.json +2 -2
- package/src/hls.js +4 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var HlsjsPlayback=function(){"use strict";function t(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,r=Array(e);i<e;i++)r[i]=t[i];return r}function e(t,e,i){return e=s(e),function(t,e){if(e&&("object"==typeof e||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}(t,a()?Reflect.construct(e,i||[],s(t).constructor):e.apply(t,i))}function i(t,e){for(var i=0;i<e.length;i++){var r=e[i];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,d(r.key),r)}}function r(t,e,i){return(e=d(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function n(){return n="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(t,e,i){var r=function(t,e){for(;!{}.hasOwnProperty.call(t,e)&&null!==(t=s(t)););return t}(t,e);if(r){var n=Object.getOwnPropertyDescriptor(r,e);return n.get?n.get.call(arguments.length<3?t:i):n.value}},n.apply(null,arguments)}function s(t){return s=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},s(t)}function a(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(t){}return(a=function(){return!!t})()}function o(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),i.push.apply(i,r)}return i}function l(t){for(var e=1;e<arguments.length;e++){var i=null!=arguments[e]?arguments[e]:{};e%2?o(Object(i),!0).forEach((function(e){r(t,e,i[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):o(Object(i)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))}))}return t}function c(t,e){return c=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},c(t,e)}function h(t,e,i,r){var a=n(s(1&r?t.prototype:t),e,i);return 2&r&&"function"==typeof a?function(t){return a.apply(i,t)}:a}function u(e){return function(e){if(Array.isArray(e))return t(e)}(e)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(e)||function(e,i){if(e){if("string"==typeof e)return t(e,i);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?t(e,i):void 0}}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function d(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var r=i.call(t,e||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}function f(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,r=Array(e);i<e;i++)r[i]=t[i];return r}function g(t,e,i){return e=T(e),function(t,e){if(e&&("object"==typeof e||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}(t,b()?Reflect.construct(e,i||[],T(t).constructor):e.apply(t,i))}function p(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function m(t,e){for(var i=0;i<e.length;i++){var r=e[i];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,w(r.key),r)}}function y(t,e,i){return e&&m(t.prototype,e),i&&m(t,i),Object.defineProperty(t,"prototype",{writable:!1}),t}function v(t,e){var i="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!i){if(Array.isArray(t)||(i=P(t))||e){i&&(t=i);var r=0,n=function(){};return{s:n,n:function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:n}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,a=!0,o=!1;return{s:function(){i=i.call(t)},n:function(){var t=i.next();return a=t.done,t},e:function(t){o=!0,s=t},f:function(){try{a||null==i.return||i.return()}finally{if(o)throw s}}}}function A(t,e,i){return(e=w(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function E(){return E="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(t,e,i){var r=function(t,e){for(;!{}.hasOwnProperty.call(t,e)&&null!==(t=T(t)););return t}(t,e);if(r){var n=Object.getOwnPropertyDescriptor(r,e);return n.get?n.get.call(arguments.length<3?t:i):n.value}},E.apply(null,arguments)}function T(t){return T=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},T(t)}function S(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&L(t,e)}function b(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(t){}return(b=function(){return!!t})()}function k(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),i.push.apply(i,r)}return i}function _(t){for(var e=1;e<arguments.length;e++){var i=null!=arguments[e]?arguments[e]:{};e%2?k(Object(i),!0).forEach((function(e){A(t,e,i[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):k(Object(i)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))}))}return t}function L(t,e){return L=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},L(t,e)}function R(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var i=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=i){var r,n,s,a,o=[],l=!0,c=!1;try{if(s=(i=i.call(t)).next,0===e){if(Object(i)!==i)return;l=!1}else for(;!(l=(r=s.call(i)).done)&&(o.push(r.value),o.length!==e);l=!0);}catch(t){c=!0,n=t}finally{try{if(!l&&null!=i.return&&(a=i.return(),Object(a)!==a))return}finally{if(c)throw n}}return o}}(t,e)||P(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function C(t,e,i,r){var n=E(T(t.prototype),e,i);return"function"==typeof n?function(t){return n.apply(i,t)}:n}function D(t){return function(t){if(Array.isArray(t))return f(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||P(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function w(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var r=i.call(t,e);if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t,"string");return"symbol"==typeof e?e:e+""}function I(t){return I="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},I(t)}function P(t,e){if(t){if("string"==typeof t)return f(t,e);var i={}.toString.call(t).slice(8,-1);return"Object"===i&&t.constructor&&(i=t.constructor.name),"Map"===i||"Set"===i?Array.from(t):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?f(t,e):void 0}}function O(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var x=function(){var t,e,i,r,n,s,a=[],o=a.concat,l=a.filter,c=a.slice,h=window.document,u={},d={},f={"column-count":1,columns:1,"font-weight":1,"line-height":1,opacity:1,"z-index":1,zoom:1},g=/^\s*<(\w+|!)[^>]*>/,p=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,m=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,y=/^(?:body|html)$/i,v=/([A-Z])/g,A=["val","css","html","text","data","width","height","offset"],E=h.createElement("table"),T=h.createElement("tr"),S={tr:h.createElement("tbody"),tbody:E,thead:E,tfoot:E,td:T,th:T,"*":h.createElement("div")},b=/complete|loaded|interactive/,k=/^[\w-]*$/,_={},L=_.toString,R={},C=h.createElement("div"),D={tabindex:"tabIndex",readonly:"readOnly",for:"htmlFor",class:"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},w=Array.isArray||function(t){return t instanceof Array};function I(t){return null==t?String(t):_[L.call(t)]||"object"}function P(t){return"function"==I(t)}function O(t){return null!=t&&t==t.window}function x(t){return null!=t&&t.nodeType==t.DOCUMENT_NODE}function M(t){return"object"==I(t)}function F(t){return M(t)&&!O(t)&&Object.getPrototypeOf(t)==Object.prototype}function N(t){var e=!!t&&"length"in t&&t.length,r=i.type(t);return"function"!=r&&!O(t)&&("array"==r||0===e||"number"==typeof e&&e>0&&e-1 in t)}function U(t){return t.replace(/::/g,"/").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/_/g,"-").toLowerCase()}function B(t){return t in d?d[t]:d[t]=new RegExp("(^|\\s)"+t+"(\\s|$)")}function $(t,e){return"number"!=typeof e||f[U(t)]?e:e+"px"}function G(t){return"children"in t?c.call(t.children):i.map(t.childNodes,(function(t){if(1==t.nodeType)return t}))}function K(t,e){var i,r=t?t.length:0;for(i=0;i<r;i++)this[i]=t[i];this.length=r,this.selector=e||""}function H(i,r,n){for(e in r)n&&(F(r[e])||w(r[e]))?(F(r[e])&&!F(i[e])&&(i[e]={}),w(r[e])&&!w(i[e])&&(i[e]=[]),H(i[e],r[e],n)):r[e]!==t&&(i[e]=r[e])}function V(t,e){return null==e?i(t):i(t).filter(e)}function Y(t,e,i,r){return P(e)?e.call(t,i,r):e}function j(t,e,i){null==i?t.removeAttribute(e):t.setAttribute(e,i)}function W(e,i){var r=e.className||"",n=r&&r.baseVal!==t;if(i===t)return n?r.baseVal:r;n?r.baseVal=i:e.className=i}function z(t){try{return t?"true"==t||"false"!=t&&("null"==t?null:+t+""==t?+t:/^[\[\{]/.test(t)?i.parseJSON(t):t):t}catch(e){return t}}function q(t,e){e(t);for(var i=0,r=t.childNodes.length;i<r;i++)q(t.childNodes[i],e)}return R.matches=function(t,e){if(!e||!t||1!==t.nodeType)return!1;var i=t.matches||t.webkitMatchesSelector||t.mozMatchesSelector||t.oMatchesSelector||t.matchesSelector;if(i)return i.call(t,e);var r,n=t.parentNode,s=!n;return s&&(n=C).appendChild(t),r=~R.qsa(n,e).indexOf(t),s&&C.removeChild(t),r},n=function(t){return t.replace(/-+(.)?/g,(function(t,e){return e?e.toUpperCase():""}))},s=function(t){return l.call(t,(function(e,i){return t.indexOf(e)==i}))},R.fragment=function(e,r,n){var s,a,o;return p.test(e)&&(s=i(h.createElement(RegExp.$1))),s||(e.replace&&(e=e.replace(m,"<$1></$2>")),r===t&&(r=g.test(e)&&RegExp.$1),r in S||(r="*"),(o=S[r]).innerHTML=""+e,s=i.each(c.call(o.childNodes),(function(){o.removeChild(this)}))),F(n)&&(a=i(s),i.each(n,(function(t,e){A.indexOf(t)>-1?a[t](e):a.attr(t,e)}))),s},R.Z=function(t,e){return new K(t,e)},R.isZ=function(t){return t instanceof R.Z},R.init=function(e,r){var n,s;if(!e)return R.Z();if("string"==typeof e)if("<"==(e=e.trim())[0]&&g.test(e))n=R.fragment(e,RegExp.$1,r),e=null;else{if(r!==t)return i(r).find(e);n=R.qsa(h,e)}else{if(P(e))return i(h).ready(e);if(R.isZ(e))return e;if(w(e))s=e,n=l.call(s,(function(t){return null!=t}));else if(M(e))n=[e],e=null;else if(g.test(e))n=R.fragment(e.trim(),RegExp.$1,r),e=null;else{if(r!==t)return i(r).find(e);n=R.qsa(h,e)}}return R.Z(n,e)},(i=function(t,e){return R.init(t,e)}).extend=function(t){var e,i=c.call(arguments,1);return"boolean"==typeof t&&(e=t,t=i.shift()),i.forEach((function(i){H(t,i,e)})),t},R.qsa=function(t,e){var i,r="#"==e[0],n=!r&&"."==e[0],s=r||n?e.slice(1):e,a=k.test(s);return t.getElementById&&a&&r?(i=t.getElementById(s))?[i]:[]:1!==t.nodeType&&9!==t.nodeType&&11!==t.nodeType?[]:c.call(a&&!r&&t.getElementsByClassName?n?t.getElementsByClassName(s):t.getElementsByTagName(e):t.querySelectorAll(e))},i.contains=h.documentElement.contains?function(t,e){return t!==e&&t.contains(e)}:function(t,e){for(;e&&(e=e.parentNode);)if(e===t)return!0;return!1},i.type=I,i.isFunction=P,i.isWindow=O,i.isArray=w,i.isPlainObject=F,i.isEmptyObject=function(t){var e;for(e in t)return!1;return!0},i.isNumeric=function(t){var e=Number(t),i=typeof t;return null!=t&&"boolean"!=i&&("string"!=i||t.length)&&!isNaN(e)&&isFinite(e)||!1},i.inArray=function(t,e,i){return a.indexOf.call(e,t,i)},i.camelCase=n,i.trim=function(t){return null==t?"":String.prototype.trim.call(t)},i.uuid=0,i.support={},i.expr={},i.noop=function(){},i.map=function(t,e){var r,n,s,a,o=[];if(N(t))for(n=0;n<t.length;n++)null!=(r=e(t[n],n))&&o.push(r);else for(s in t)null!=(r=e(t[s],s))&&o.push(r);return(a=o).length>0?i.fn.concat.apply([],a):a},i.each=function(t,e){var i,r;if(N(t)){for(i=0;i<t.length;i++)if(!1===e.call(t[i],i,t[i]))return t}else for(r in t)if(!1===e.call(t[r],r,t[r]))return t;return t},i.grep=function(t,e){return l.call(t,e)},window.JSON&&(i.parseJSON=JSON.parse),i.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),(function(t,e){_["[object "+e+"]"]=e.toLowerCase()})),i.fn={constructor:R.Z,length:0,forEach:a.forEach,reduce:a.reduce,push:a.push,sort:a.sort,splice:a.splice,indexOf:a.indexOf,concat:function(){var t,e,i=[];for(t=0;t<arguments.length;t++)e=arguments[t],i[t]=R.isZ(e)?e.toArray():e;return o.apply(R.isZ(this)?this.toArray():this,i)},map:function(t){return i(i.map(this,(function(e,i){return t.call(e,i,e)})))},slice:function(){return i(c.apply(this,arguments))},ready:function(t){return b.test(h.readyState)&&h.body?t(i):h.addEventListener("DOMContentLoaded",(function(){t(i)}),!1),this},get:function(e){return e===t?c.call(this):this[e>=0?e:e+this.length]},toArray:function(){return this.get()},size:function(){return this.length},remove:function(){return this.each((function(){null!=this.parentNode&&this.parentNode.removeChild(this)}))},each:function(t){return a.every.call(this,(function(e,i){return!1!==t.call(e,i,e)})),this},filter:function(t){return P(t)?this.not(this.not(t)):i(l.call(this,(function(e){return R.matches(e,t)})))},add:function(t,e){return i(s(this.concat(i(t,e))))},is:function(t){return this.length>0&&R.matches(this[0],t)},not:function(e){var r=[];if(P(e)&&e.call!==t)this.each((function(t){e.call(this,t)||r.push(this)}));else{var n="string"==typeof e?this.filter(e):N(e)&&P(e.item)?c.call(e):i(e);this.forEach((function(t){n.indexOf(t)<0&&r.push(t)}))}return i(r)},has:function(t){return this.filter((function(){return M(t)?i.contains(this,t):i(this).find(t).size()}))},eq:function(t){return-1===t?this.slice(t):this.slice(t,+t+1)},first:function(){var t=this[0];return t&&!M(t)?t:i(t)},last:function(){var t=this[this.length-1];return t&&!M(t)?t:i(t)},find:function(t){var e=this;return t?"object"==typeof t?i(t).filter((function(){var t=this;return a.some.call(e,(function(e){return i.contains(e,t)}))})):1==this.length?i(R.qsa(this[0],t)):this.map((function(){return R.qsa(this,t)})):i()},closest:function(t,e){var r=[],n="object"==typeof t&&i(t);return this.each((function(i,s){for(;s&&!(n?n.indexOf(s)>=0:R.matches(s,t));)s=s!==e&&!x(s)&&s.parentNode;s&&r.indexOf(s)<0&&r.push(s)})),i(r)},parents:function(t){for(var e=[],r=this;r.length>0;)r=i.map(r,(function(t){if((t=t.parentNode)&&!x(t)&&e.indexOf(t)<0)return e.push(t),t}));return V(e,t)},parent:function(t){return V(s(this.pluck("parentNode")),t)},children:function(t){return V(this.map((function(){return G(this)})),t)},contents:function(){return this.map((function(){return this.contentDocument||c.call(this.childNodes)}))},siblings:function(t){return V(this.map((function(t,e){return l.call(G(e.parentNode),(function(t){return t!==e}))})),t)},empty:function(){return this.each((function(){this.innerHTML=""}))},pluck:function(t){return i.map(this,(function(e){return e[t]}))},show:function(){return this.each((function(){var t,e,i;"none"==this.style.display&&(this.style.display=""),"none"==getComputedStyle(this,"").getPropertyValue("display")&&(this.style.display=(t=this.nodeName,u[t]||(e=h.createElement(t),h.body.appendChild(e),i=getComputedStyle(e,"").getPropertyValue("display"),e.parentNode.removeChild(e),"none"==i&&(i="block"),u[t]=i),u[t]))}))},replaceWith:function(t){return this.before(t).remove()},wrap:function(t){var e=P(t);if(this[0]&&!e)var r=i(t).get(0),n=r.parentNode||this.length>1;return this.each((function(s){i(this).wrapAll(e?t.call(this,s):n?r.cloneNode(!0):r)}))},wrapAll:function(t){if(this[0]){var e;for(i(this[0]).before(t=i(t));(e=t.children()).length;)t=e.first();i(t).append(this)}return this},wrapInner:function(t){var e=P(t);return this.each((function(r){var n=i(this),s=n.contents(),a=e?t.call(this,r):t;s.length?s.wrapAll(a):n.append(a)}))},unwrap:function(){return this.parent().each((function(){i(this).replaceWith(i(this).children())})),this},clone:function(){return this.map((function(){return this.cloneNode(!0)}))},hide:function(){return this.css("display","none")},toggle:function(e){return this.each((function(){var r=i(this);(e===t?"none"==r.css("display"):e)?r.show():r.hide()}))},prev:function(t){return i(this.pluck("previousElementSibling")).filter(t||"*")},next:function(t){return i(this.pluck("nextElementSibling")).filter(t||"*")},html:function(t){return 0 in arguments?this.each((function(e){var r=this.innerHTML;i(this).empty().append(Y(this,t,e,r))})):0 in this?this[0].innerHTML:null},text:function(t){return 0 in arguments?this.each((function(e){var i=Y(this,t,e,this.textContent);this.textContent=null==i?"":""+i})):0 in this?this.pluck("textContent").join(""):null},attr:function(i,r){var n;return"string"!=typeof i||1 in arguments?this.each((function(t){if(1===this.nodeType)if(M(i))for(e in i)j(this,e,i[e]);else j(this,i,Y(this,r,t,this.getAttribute(i)))})):0 in this&&1==this[0].nodeType&&null!=(n=this[0].getAttribute(i))?n:t},removeAttr:function(t){return this.each((function(){1===this.nodeType&&t.split(" ").forEach((function(t){j(this,t)}),this)}))},prop:function(t,e){return t=D[t]||t,1 in arguments?this.each((function(i){this[t]=Y(this,e,i,this[t])})):this[0]&&this[0][t]},removeProp:function(t){return t=D[t]||t,this.each((function(){delete this[t]}))},data:function(e,i){var r="data-"+e.replace(v,"-$1").toLowerCase(),n=1 in arguments?this.attr(r,i):this.attr(r);return null!==n?z(n):t},val:function(t){return 0 in arguments?(null==t&&(t=""),this.each((function(e){this.value=Y(this,t,e,this.value)}))):this[0]&&(this[0].multiple?i(this[0]).find("option").filter((function(){return this.selected})).pluck("value"):this[0].value)},offset:function(t){if(t)return this.each((function(e){var r=i(this),n=Y(this,t,e,r.offset()),s=r.offsetParent().offset(),a={top:n.top-s.top,left:n.left-s.left};"static"==r.css("position")&&(a.position="relative"),r.css(a)}));if(!this.length)return null;if(h.documentElement!==this[0]&&!i.contains(h.documentElement,this[0]))return{top:0,left:0};var e=this[0].getBoundingClientRect();return{left:e.left+window.pageXOffset,top:e.top+window.pageYOffset,width:Math.round(e.width),height:Math.round(e.height)}},css:function(t,r){if(arguments.length<2){var s=this[0];if("string"==typeof t){if(!s)return;return s.style[n(t)]||getComputedStyle(s,"").getPropertyValue(t)}if(w(t)){if(!s)return;var a={},o=getComputedStyle(s,"");return i.each(t,(function(t,e){a[e]=s.style[n(e)]||o.getPropertyValue(e)})),a}}var l="";if("string"==I(t))r||0===r?l=U(t)+":"+$(t,r):this.each((function(){this.style.removeProperty(U(t))}));else for(e in t)t[e]||0===t[e]?l+=U(e)+":"+$(e,t[e])+";":this.each((function(){this.style.removeProperty(U(e))}));return this.each((function(){this.style.cssText+=";"+l}))},index:function(t){return t?this.indexOf(i(t)[0]):this.parent().children().indexOf(this[0])},hasClass:function(t){return!!t&&a.some.call(this,(function(t){return this.test(W(t))}),B(t))},addClass:function(t){return t?this.each((function(e){if("className"in this){r=[];var n=W(this);Y(this,t,e,n).split(/\s+/g).forEach((function(t){i(this).hasClass(t)||r.push(t)}),this),r.length&&W(this,n+(n?" ":"")+r.join(" "))}})):this},removeClass:function(e){return this.each((function(i){if("className"in this){if(e===t)return W(this,"");r=W(this),Y(this,e,i,r).split(/\s+/g).forEach((function(t){r=r.replace(B(t)," ")})),W(this,r.trim())}}))},toggleClass:function(e,r){return e?this.each((function(n){var s=i(this);Y(this,e,n,W(this)).split(/\s+/g).forEach((function(e){(r===t?!s.hasClass(e):r)?s.addClass(e):s.removeClass(e)}))})):this},scrollTop:function(e){if(this.length){var i="scrollTop"in this[0];return e===t?i?this[0].scrollTop:this[0].pageYOffset:this.each(i?function(){this.scrollTop=e}:function(){this.scrollTo(this.scrollX,e)})}},scrollLeft:function(e){if(this.length){var i="scrollLeft"in this[0];return e===t?i?this[0].scrollLeft:this[0].pageXOffset:this.each(i?function(){this.scrollLeft=e}:function(){this.scrollTo(e,this.scrollY)})}},position:function(){if(this.length){var t=this[0],e=this.offsetParent(),r=this.offset(),n=y.test(e[0].nodeName)?{top:0,left:0}:e.offset();return r.top-=parseFloat(i(t).css("margin-top"))||0,r.left-=parseFloat(i(t).css("margin-left"))||0,n.top+=parseFloat(i(e[0]).css("border-top-width"))||0,n.left+=parseFloat(i(e[0]).css("border-left-width"))||0,{top:r.top-n.top,left:r.left-n.left}}},offsetParent:function(){return this.map((function(){for(var t=this.offsetParent||h.body;t&&!y.test(t.nodeName)&&"static"==i(t).css("position");)t=t.offsetParent;return t}))}},i.fn.detach=i.fn.remove,["width","height"].forEach((function(e){var r=e.replace(/./,(function(t){return t[0].toUpperCase()}));i.fn[e]=function(n){var s,a=this[0];return n===t?O(a)?a["inner"+r]:x(a)?a.documentElement["scroll"+r]:(s=this.offset())&&s[e]:this.each((function(t){(a=i(this)).css(e,Y(this,n,t,a[e]()))}))}})),["after","prepend","before","append"].forEach((function(e,r){var n=r%2;i.fn[e]=function(){var e,s,a=i.map(arguments,(function(r){var n=[];return"array"==(e=I(r))?(r.forEach((function(e){return e.nodeType!==t?n.push(e):i.zepto.isZ(e)?n=n.concat(e.get()):void(n=n.concat(R.fragment(e)))})),n):"object"==e||null==r?r:R.fragment(r)})),o=this.length>1;return a.length<1?this:this.each((function(t,e){s=n?e:e.parentNode,e=0==r?e.nextSibling:1==r?e.firstChild:2==r?e:null;var l=i.contains(h.documentElement,s);a.forEach((function(t){if(o)t=t.cloneNode(!0);else if(!s)return i(t).remove();s.insertBefore(t,e),l&&q(t,(function(t){if(!(null==t.nodeName||"SCRIPT"!==t.nodeName.toUpperCase()||t.type&&"text/javascript"!==t.type||t.src)){var e=t.ownerDocument?t.ownerDocument.defaultView:window;e.eval.call(e,t.innerHTML)}}))}))}))},i.fn[n?e+"To":"insert"+(r?"Before":"After")]=function(t){return i(t)[e](this),this}})),R.Z.prototype=K.prototype=i.fn,R.uniq=s,R.deserializeValue=z,i.zepto=R,i}();window.Zepto=x,void 0===window.$&&(window.$=x),function(t){var e,i,r=+new Date,n=window.document,s=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,a=/^(?:text|application)\/javascript/i,o=/^(?:text|application)\/xml/i,l="application/json",c="text/html",h=/^\s*$/,u=n.createElement("a");function d(e,i,r,s){if(e.global)return function(e,i,r){var n=t.Event(i);return t(e).trigger(n,r),!n.isDefaultPrevented()}(i||n,r,s)}function f(t,e){var i=e.context;if(!1===e.beforeSend.call(i,t,e)||!1===d(e,i,"ajaxBeforeSend",[t,e]))return!1;d(e,i,"ajaxSend",[t,e])}function g(t,e,i,r){var n=i.context,s="success";i.success.call(n,t,s,e),r&&r.resolveWith(n,[t,s,e]),d(i,n,"ajaxSuccess",[e,i,t]),m(s,e,i)}function p(t,e,i,r,n){var s=r.context;r.error.call(s,i,e,t),n&&n.rejectWith(s,[i,e,t]),d(r,s,"ajaxError",[i,r,t||e]),m(e,i,r)}function m(e,i,r){var n=r.context;r.complete.call(n,i,e),d(r,n,"ajaxComplete",[i,r]),function(e){e.global&&! --t.active&&d(e,null,"ajaxStop")}(r)}function y(){}function v(t,e){return""==e?t:(t+"&"+e).replace(/[&?]{1,2}/,"?")}function A(e,i,r,n){return t.isFunction(i)&&(n=r,r=i,i=void 0),t.isFunction(r)||(n=r,r=void 0),{url:e,data:i,success:r,dataType:n}}u.href=window.location.href,t.active=0,t.ajaxJSONP=function(e,i){if(!("type"in e))return t.ajax(e);var s,a,o=e.jsonpCallback,l=(t.isFunction(o)?o():o)||"Zepto"+r++,c=n.createElement("script"),h=window[l],u=function(e){t(c).triggerHandler("error",e||"abort")},d={abort:u};return i&&i.promise(d),t(c).on("load error",(function(r,n){clearTimeout(a),t(c).off().remove(),"error"!=r.type&&s?g(s[0],d,e,i):p(null,n||"error",d,e,i),window[l]=h,s&&t.isFunction(h)&&h(s[0]),h=s=void 0})),!1===f(d,e)?(u("abort"),d):(window[l]=function(){s=arguments},c.src=e.url.replace(/\?(.+)=\?/,"?$1="+l),n.head.appendChild(c),e.timeout>0&&(a=setTimeout((function(){u("timeout")}),e.timeout)),d)},t.ajaxSettings={type:"GET",beforeSend:y,success:y,error:y,complete:y,context:null,global:!0,xhr:function(){return new window.XMLHttpRequest},accepts:{script:"text/javascript, application/javascript, application/x-javascript",json:l,xml:"application/xml, text/xml",html:c,text:"text/plain"},crossDomain:!1,timeout:0,processData:!0,cache:!0,dataFilter:y},t.ajax=function(r){var s,m,A=t.extend({},r||{}),E=t.Deferred&&t.Deferred();for(e in t.ajaxSettings)void 0===A[e]&&(A[e]=t.ajaxSettings[e]);!function(e){e.global&&0==t.active++&&d(e,null,"ajaxStart")}(A),A.crossDomain||((s=n.createElement("a")).href=A.url,s.href=s.href,A.crossDomain=u.protocol+"//"+u.host!=s.protocol+"//"+s.host),A.url||(A.url=window.location.toString()),(m=A.url.indexOf("#"))>-1&&(A.url=A.url.slice(0,m)),function(e){e.processData&&e.data&&"string"!=t.type(e.data)&&(e.data=t.param(e.data,e.traditional)),!e.data||e.type&&"GET"!=e.type.toUpperCase()&&"jsonp"!=e.dataType||(e.url=v(e.url,e.data),e.data=void 0)}(A);var T=A.dataType,S=/\?.+=\?/.test(A.url);if(S&&(T="jsonp"),!1!==A.cache&&(r&&!0===r.cache||"script"!=T&&"jsonp"!=T)||(A.url=v(A.url,"_="+Date.now())),"jsonp"==T)return S||(A.url=v(A.url,A.jsonp?A.jsonp+"=?":!1===A.jsonp?"":"callback=?")),t.ajaxJSONP(A,E);var b,k=A.accepts[T],_={},L=function(t,e){_[t.toLowerCase()]=[t,e]},R=/^([\w-]+:)\/\//.test(A.url)?RegExp.$1:window.location.protocol,C=A.xhr(),D=C.setRequestHeader;if(E&&E.promise(C),A.crossDomain||L("X-Requested-With","XMLHttpRequest"),L("Accept",k||"*/*"),(k=A.mimeType||k)&&(k.indexOf(",")>-1&&(k=k.split(",",2)[0]),C.overrideMimeType&&C.overrideMimeType(k)),(A.contentType||!1!==A.contentType&&A.data&&"GET"!=A.type.toUpperCase())&&L("Content-Type",A.contentType||"application/x-www-form-urlencoded"),A.headers)for(i in A.headers)L(i,A.headers[i]);if(C.setRequestHeader=L,C.onreadystatechange=function(){if(4==C.readyState){C.onreadystatechange=y,clearTimeout(b);var e,i=!1;if(C.status>=200&&C.status<300||304==C.status||0==C.status&&"file:"==R){if(T=T||function(t){return t&&(t=t.split(";",2)[0]),t&&(t==c?"html":t==l?"json":a.test(t)?"script":o.test(t)&&"xml")||"text"}(A.mimeType||C.getResponseHeader("content-type")),"arraybuffer"==C.responseType||"blob"==C.responseType)e=C.response;else{e=C.responseText;try{e=function(t,e,i){if(i.dataFilter==y)return t;var r=i.context;return i.dataFilter.call(r,t,e)}(e,T,A),"script"==T?(0,eval)(e):"xml"==T?e=C.responseXML:"json"==T&&(e=h.test(e)?null:t.parseJSON(e))}catch(t){i=t}if(i)return p(i,"parsererror",C,A,E)}g(e,C,A,E)}else p(C.statusText||null,C.status?"error":"abort",C,A,E)}},!1===f(C,A))return C.abort(),p(null,"abort",C,A,E),C;var w=!("async"in A)||A.async;if(C.open(A.type,A.url,w,A.username,A.password),A.xhrFields)for(i in A.xhrFields)C[i]=A.xhrFields[i];for(i in _)D.apply(C,_[i]);return A.timeout>0&&(b=setTimeout((function(){C.onreadystatechange=y,C.abort(),p(null,"timeout",C,A,E)}),A.timeout)),C.send(A.data?A.data:null),C},t.get=function(){return t.ajax(A.apply(null,arguments))},t.post=function(){var e=A.apply(null,arguments);return e.type="POST",t.ajax(e)},t.getJSON=function(){var e=A.apply(null,arguments);return e.dataType="json",t.ajax(e)},t.fn.load=function(e,i,r){if(!this.length)return this;var n,a=this,o=e.split(/\s/),l=A(e,i,r),c=l.success;return o.length>1&&(l.url=o[0],n=o[1]),l.success=function(e){a.html(n?t("<div>").html(e.replace(s,"")).find(n):e),c&&c.apply(a,arguments)},t.ajax(l),this};var E=encodeURIComponent;function T(e,i,r,n){var s,a=t.isArray(i),o=t.isPlainObject(i);t.each(i,(function(i,l){s=t.type(l),n&&(i=r?n:n+"["+(o||"object"==s||"array"==s?i:"")+"]"),!n&&a?e.add(l.name,l.value):"array"==s||!r&&"object"==s?T(e,l,r,i):e.add(i,l)}))}t.param=function(e,i){var r=[];return r.add=function(e,i){t.isFunction(i)&&(i=i()),null==i&&(i=""),this.push(E(e)+"="+E(i))},T(r,e,i),r.join("&").replace(/%20/g,"+")}}(x),function(t){t.Callbacks=function(e){e=t.extend({},e);var i,r,n,s,a,o,l=[],c=!e.once&&[],h=function(t){for(i=e.memory&&t,r=!0,o=s||0,s=0,a=l.length,n=!0;l&&o<a;++o)if(!1===l[o].apply(t[0],t[1])&&e.stopOnFalse){i=!1;break}n=!1,l&&(c?c.length&&h(c.shift()):i?l.length=0:u.disable())},u={add:function(){if(l){var r=l.length,o=function(i){t.each(i,(function(t,i){"function"==typeof i?e.unique&&u.has(i)||l.push(i):i&&i.length&&"string"!=typeof i&&o(i)}))};o(arguments),n?a=l.length:i&&(s=r,h(i))}return this},remove:function(){return l&&t.each(arguments,(function(e,i){for(var r;(r=t.inArray(i,l,r))>-1;)l.splice(r,1),n&&(r<=a&&--a,r<=o&&--o)})),this},has:function(e){return!(!l||!(e?t.inArray(e,l)>-1:l.length))},empty:function(){return a=l.length=0,this},disable:function(){return l=c=i=void 0,this},disabled:function(){return!l},lock:function(){return c=void 0,i||u.disable(),this},locked:function(){return!c},fireWith:function(t,e){return!l||r&&!c||(e=[t,(e=e||[]).slice?e.slice():e],n?c.push(e):h(e)),this},fire:function(){return u.fireWith(this,arguments)},fired:function(){return!!r}};return u}}(x),function(t){var e=Array.prototype.slice;function i(e){var r=[["resolve","done",t.Callbacks({once:1,memory:1}),"resolved"],["reject","fail",t.Callbacks({once:1,memory:1}),"rejected"],["notify","progress",t.Callbacks({memory:1})]],n="pending",s={state:function(){return n},always:function(){return a.done(arguments).fail(arguments),this},then:function(){var e=arguments;return i((function(i){t.each(r,(function(r,n){var o=t.isFunction(e[r])&&e[r];a[n[1]]((function(){var e=o&&o.apply(this,arguments);if(e&&t.isFunction(e.promise))e.promise().done(i.resolve).fail(i.reject).progress(i.notify);else{var r=this===s?i.promise():this,a=o?[e]:arguments;i[n[0]+"With"](r,a)}}))})),e=null})).promise()},promise:function(e){return null!=e?t.extend(e,s):s}},a={};return t.each(r,(function(t,e){var i=e[2],o=e[3];s[e[1]]=i.add,o&&i.add((function(){n=o}),r[1^t][2].disable,r[2][2].lock),a[e[0]]=function(){return a[e[0]+"With"](this===a?s:this,arguments),this},a[e[0]+"With"]=i.fireWith})),s.promise(a),e&&e.call(a,a),a}t.when=function(r){var n,s,a,o=e.call(arguments),l=o.length,c=0,h=1!==l||r&&t.isFunction(r.promise)?l:0,u=1===h?r:i(),d=function(t,i,r){return function(s){i[t]=this,r[t]=arguments.length>1?e.call(arguments):s,r===n?u.notifyWith(i,r):--h||u.resolveWith(i,r)}};if(l>1)for(n=new Array(l),s=new Array(l),a=new Array(l);c<l;++c)o[c]&&t.isFunction(o[c].promise)?o[c].promise().done(d(c,a,o)).fail(u.reject).progress(d(c,s,n)):--h;return h||u.resolveWith(a,o),u.promise()},t.Deferred=i}(x),function(t){var e,i=1,r=Array.prototype.slice,n=t.isFunction,s=function(t){return"string"==typeof t},a={},o={},l="onfocusin"in window,c={focus:"focusin",blur:"focusout"},h={mouseenter:"mouseover",mouseleave:"mouseout"};function u(t){return t._zid||(t._zid=i++)}function d(t,e,i,r){if((e=f(e)).ns)var n=(s=e.ns,new RegExp("(?:^| )"+s.replace(" "," .* ?")+"(?: |$)"));var s;return(a[u(t)]||[]).filter((function(t){return t&&(!e.e||t.e==e.e)&&(!e.ns||n.test(t.ns))&&(!i||u(t.fn)===u(i))&&(!r||t.sel==r)}))}function f(t){var e=(""+t).split(".");return{e:e[0],ns:e.slice(1).sort().join(" ")}}function g(t,e){return t.del&&!l&&t.e in c||!!e}function p(t){return h[t]||l&&c[t]||t}function m(i,r,n,s,o,l,c){var d=u(i),m=a[d]||(a[d]=[]);r.split(/\s/).forEach((function(r){if("ready"==r)return t(document).ready(n);var a=f(r);a.fn=n,a.sel=o,a.e in h&&(n=function(e){var i=e.relatedTarget;if(!i||i!==this&&!t.contains(this,i))return a.fn.apply(this,arguments)}),a.del=l;var u=l||n;a.proxy=function(t){if(!(t=S(t)).isImmediatePropagationStopped()){t.data=s;var r=u.apply(i,t._args==e?[t]:[t].concat(t._args));return!1===r&&(t.preventDefault(),t.stopPropagation()),r}},a.i=m.length,m.push(a),"addEventListener"in i&&i.addEventListener(p(a.e),a.proxy,g(a,c))}))}function y(t,e,i,r,n){var s=u(t);(e||"").split(/\s/).forEach((function(e){d(t,e,i,r).forEach((function(e){delete a[s][e.i],"removeEventListener"in t&&t.removeEventListener(p(e.e),e.proxy,g(e,n))}))}))}o.click=o.mousedown=o.mouseup=o.mousemove="MouseEvents",t.event={add:m,remove:y},t.proxy=function(e,i){var a=2 in arguments&&r.call(arguments,2);if(n(e)){var o=function(){return e.apply(i,a?a.concat(r.call(arguments)):arguments)};return o._zid=u(e),o}if(s(i))return a?(a.unshift(e[i],e),t.proxy.apply(null,a)):t.proxy(e[i],e);throw new TypeError("expected function")},t.fn.bind=function(t,e,i){return this.on(t,e,i)},t.fn.unbind=function(t,e){return this.off(t,e)},t.fn.one=function(t,e,i,r){return this.on(t,e,i,r,1)};var v=function(){return!0},A=function(){return!1},E=/^([A-Z]|returnValue$|layer[XY]$|webkitMovement[XY]$)/,T={preventDefault:"isDefaultPrevented",stopImmediatePropagation:"isImmediatePropagationStopped",stopPropagation:"isPropagationStopped"};function S(i,r){return!r&&i.isDefaultPrevented||(r||(r=i),t.each(T,(function(t,e){var n=r[t];i[t]=function(){return this[e]=v,n&&n.apply(r,arguments)},i[e]=A})),i.timeStamp||(i.timeStamp=Date.now()),(r.defaultPrevented!==e?r.defaultPrevented:"returnValue"in r?!1===r.returnValue:r.getPreventDefault&&r.getPreventDefault())&&(i.isDefaultPrevented=v)),i}function b(t){var i,r={originalEvent:t};for(i in t)E.test(i)||t[i]===e||(r[i]=t[i]);return S(r,t)}t.fn.delegate=function(t,e,i){return this.on(e,t,i)},t.fn.undelegate=function(t,e,i){return this.off(e,t,i)},t.fn.live=function(e,i){return t(document.body).delegate(this.selector,e,i),this},t.fn.die=function(e,i){return t(document.body).undelegate(this.selector,e,i),this},t.fn.on=function(i,a,o,l,c){var h,u,d=this;return i&&!s(i)?(t.each(i,(function(t,e){d.on(t,a,o,e,c)})),d):(s(a)||n(l)||!1===l||(l=o,o=a,a=e),l!==e&&!1!==o||(l=o,o=e),!1===l&&(l=A),d.each((function(e,n){c&&(h=function(t){return y(n,t.type,l),l.apply(this,arguments)}),a&&(u=function(e){var i,s=t(e.target).closest(a,n).get(0);if(s&&s!==n)return i=t.extend(b(e),{currentTarget:s,liveFired:n}),(h||l).apply(s,[i].concat(r.call(arguments,1)))}),m(n,i,l,o,a,u||h)})))},t.fn.off=function(i,r,a){var o=this;return i&&!s(i)?(t.each(i,(function(t,e){o.off(t,r,e)})),o):(s(r)||n(a)||!1===a||(a=r,r=e),!1===a&&(a=A),o.each((function(){y(this,i,a,r)})))},t.fn.trigger=function(e,i){return(e=s(e)||t.isPlainObject(e)?t.Event(e):S(e))._args=i,this.each((function(){e.type in c&&"function"==typeof this[e.type]?this[e.type]():"dispatchEvent"in this?this.dispatchEvent(e):t(this).triggerHandler(e,i)}))},t.fn.triggerHandler=function(e,i){var r,n;return this.each((function(a,o){(r=b(s(e)?t.Event(e):e))._args=i,r.target=o,t.each(d(o,e.type||e),(function(t,e){if(n=e.proxy(r),r.isImmediatePropagationStopped())return!1}))})),n},"focusin focusout focus blur load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select keydown keypress keyup error".split(" ").forEach((function(e){t.fn[e]=function(t){return 0 in arguments?this.bind(e,t):this.trigger(e)}})),t.Event=function(t,e){s(t)||(t=(e=t).type);var i=document.createEvent(o[t]||"Events"),r=!0;if(e)for(var n in e)"bubbles"==n?r=!!e[n]:i[n]=e[n];return i.initEvent(t,r,!0),S(i)}}(x),function(){try{getComputedStyle(void 0)}catch(e){var t=getComputedStyle;window.getComputedStyle=function(e,i){try{return t(e,i)}catch(t){return null}}}}(),function(t){var e=t.zepto,i=e.qsa,r=e.matches;function n(e){return!(!(e=t(e)).width()&&!e.height())&&"none"!==e.css("display")}var s=t.expr[":"]={visible:function(){if(n(this))return this},hidden:function(){if(!n(this))return this},selected:function(){if(this.selected)return this},checked:function(){if(this.checked)return this},parent:function(){return this.parentNode},first:function(t){if(0===t)return this},last:function(t,e){if(t===e.length-1)return this},eq:function(t,e,i){if(t===i)return this},contains:function(e,i,r){if(t(this).text().indexOf(r)>-1)return this},has:function(t,i,r){if(e.qsa(this,r).length)return this}},a=new RegExp("(.*):(\\w+)(?:\\(([^)]+)\\))?$\\s*"),o=/^\s*>/,l="Zepto"+ +new Date;function c(t,e){t=t.replace(/=#\]/g,'="#"]');var i,r,n=a.exec(t);if(n&&n[2]in s&&(i=s[n[2]],r=n[3],t=n[1],r)){var o=Number(r);r=isNaN(o)?r.replace(/^["']|["']$/g,""):o}return e(t,i,r)}e.qsa=function(r,n){return c(n,(function(s,a,c){try{var h;!s&&a?s="*":o.test(s)&&(h=t(r).addClass(l),s="."+l+" "+s);var u=i(r,s)}catch(t){throw console.error("error performing selector: %o",n),t}finally{h&&h.removeClass(l)}return a?e.uniq(t.map(u,(function(t,e){return a.call(t,e,u,c)}))):u}))},e.matches=function(t,e){return c(e,(function(e,i,n){return(!e||r(t,e))&&(!i||i.call(t,null,n)===t)}))}}(x);var M=O(x);Array.prototype.find||Object.defineProperty(Array.prototype,"find",{value:function(t){if(null==this)throw new TypeError('"this" is null or not defined');var e=Object(this),i=e.length>>>0;if("function"!=typeof t)throw new TypeError("predicate must be a function");for(var r=arguments[1],n=0;n<i;){var s=e[n];if(t.call(r,s,n,e))return s;n++}}}),Object.entries||(Object.entries=function(t){for(var e=Object.keys(t),i=e.length,r=new Array(i);i--;)r[i]=[e[i],t[e[i]]];return r}),Object.values||(Object.values=function(t){for(var e=Object.keys(t),i=e.length,r=new Array(i);i--;)r[i]=t[e[i]];return r}),"function"!=typeof Object.assign&&Object.defineProperty(Object,"assign",{value:function(t,e){if(null==t)throw new TypeError("Cannot convert undefined or null to object");for(var i=Object(t),r=1;r<arguments.length;r++){var n=arguments[r];if(null!=n)for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[s]=n[s])}return i},writable:!0,configurable:!0}),Array.prototype.findIndex||Object.defineProperty(Array.prototype,"findIndex",{value:function(t){if(null==this)throw new TypeError('"this" is null or not defined');var e=Object(this),i=e.length>>>0;if("function"!=typeof t)throw new TypeError("predicate must be a function");for(var r=arguments[1],n=0;n<i;){var s=e[n];if(t.call(r,s,n,e))return n;n++}return-1},configurable:!0,writable:!0});var F,N,U,B={mp4:"data:video/mp4;base64,AAAAHGZ0eXBpc29tAAACAGlzb21pc28ybXA0MQAAAAhmcmVlAAAC721kYXQhEAUgpBv/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA3pwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcCEQBSCkG//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADengAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcAAAAsJtb292AAAAbG12aGQAAAAAAAAAAAAAAAAAAAPoAAAALwABAAABAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAB7HRyYWsAAABcdGtoZAAAAAMAAAAAAAAAAAAAAAIAAAAAAAAALwAAAAAAAAAAAAAAAQEAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAACRlZHRzAAAAHGVsc3QAAAAAAAAAAQAAAC8AAAAAAAEAAAAAAWRtZGlhAAAAIG1kaGQAAAAAAAAAAAAAAAAAAKxEAAAIAFXEAAAAAAAtaGRscgAAAAAAAAAAc291bgAAAAAAAAAAAAAAAFNvdW5kSGFuZGxlcgAAAAEPbWluZgAAABBzbWhkAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAADTc3RibAAAAGdzdHNkAAAAAAAAAAEAAABXbXA0YQAAAAAAAAABAAAAAAAAAAAAAgAQAAAAAKxEAAAAAAAzZXNkcwAAAAADgICAIgACAASAgIAUQBUAAAAAAfQAAAHz+QWAgIACEhAGgICAAQIAAAAYc3R0cwAAAAAAAAABAAAAAgAABAAAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAIAAAABAAAAHHN0c3oAAAAAAAAAAAAAAAIAAAFzAAABdAAAABRzdGNvAAAAAAAAAAEAAAAsAAAAYnVkdGEAAABabWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWRpcmFwcGwAAAAAAAAAAAAAAAAtaWxzdAAAACWpdG9vAAAAHWRhdGEAAAABAAAAAExhdmY1Ni40MC4xMDE="},$=[{name:"Chromium",group:"Chrome",identifier:"Chromium/([0-9.]*)"},{name:"Chrome Mobile",group:"Chrome",identifier:"Chrome/([0-9.]*) Mobile",versionIdentifier:"Chrome/([0-9.]*)"},{name:"Chrome",group:"Chrome",identifier:"Chrome/([0-9.]*)"},{name:"Chrome for iOS",group:"Chrome",identifier:"CriOS/([0-9.]*)"},{name:"Android Browser",group:"Chrome",identifier:"CrMo/([0-9.]*)"},{name:"Firefox",group:"Firefox",identifier:"Firefox/([0-9.]*)"},{name:"Opera Mini",group:"Opera",identifier:"Opera Mini/([0-9.]*)"},{name:"Opera",group:"Opera",identifier:"Opera ([0-9.]*)"},{name:"Opera",group:"Opera",identifier:"Opera/([0-9.]*)",versionIdentifier:"Version/([0-9.]*)"},{name:"IEMobile",group:"Explorer",identifier:"IEMobile/([0-9.]*)"},{name:"Internet Explorer",group:"Explorer",identifier:"MSIE ([a-zA-Z0-9.]*)"},{name:"Internet Explorer",group:"Explorer",identifier:"Trident/([0-9.]*)",versionIdentifier:"rv:([0-9.]*)"},{name:"Spartan",group:"Spartan",identifier:"Edge/([0-9.]*)",versionIdentifier:"Edge/([0-9.]*)"},{name:"Safari",group:"Safari",identifier:"Safari/([0-9.]*)",versionIdentifier:"Version/([0-9.]*)"}],G=[{name:"Windows 2000",group:"Windows",identifier:"Windows NT 5.0",version:"5.0"},{name:"Windows XP",group:"Windows",identifier:"Windows NT 5.1",version:"5.1"},{name:"Windows Vista",group:"Windows",identifier:"Windows NT 6.0",version:"6.0"},{name:"Windows 7",group:"Windows",identifier:"Windows NT 6.1",version:"7.0"},{name:"Windows 8",group:"Windows",identifier:"Windows NT 6.2",version:"8.0"},{name:"Windows 8.1",group:"Windows",identifier:"Windows NT 6.3",version:"8.1"},{name:"Windows 10",group:"Windows",identifier:"Windows NT 10.0",version:"10.0"},{name:"Windows Phone",group:"Windows Phone",identifier:"Windows Phone ([0-9.]*)"},{name:"Windows Phone",group:"Windows Phone",identifier:"Windows Phone OS ([0-9.]*)"},{name:"Windows",group:"Windows",identifier:"Windows"},{name:"Chrome OS",group:"Chrome OS",identifier:"CrOS"},{name:"Android",group:"Android",identifier:"Android",versionIdentifier:"Android ([a-zA-Z0-9.-]*)"},{name:"iPad",group:"iOS",identifier:"iPad",versionIdentifier:"OS ([0-9_]*)",versionSeparator:"[_|.]"},{name:"iPod",group:"iOS",identifier:"iPod",versionIdentifier:"OS ([0-9_]*)",versionSeparator:"[_|.]"},{name:"iPhone",group:"iOS",identifier:"iPhone OS",versionIdentifier:"OS ([0-9_]*)",versionSeparator:"[_|.]"},{name:"Mac OS X High Sierra",group:"Mac OS",identifier:"Mac OS X (10([_|.])13([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Sierra",group:"Mac OS",identifier:"Mac OS X (10([_|.])12([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X El Capitan",group:"Mac OS",identifier:"Mac OS X (10([_|.])11([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Yosemite",group:"Mac OS",identifier:"Mac OS X (10([_|.])10([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Mavericks",group:"Mac OS",identifier:"Mac OS X (10([_|.])9([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Mountain Lion",group:"Mac OS",identifier:"Mac OS X (10([_|.])8([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Lion",group:"Mac OS",identifier:"Mac OS X (10([_|.])7([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Snow Leopard",group:"Mac OS",identifier:"Mac OS X (10([_|.])6([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Leopard",group:"Mac OS",identifier:"Mac OS X (10([_|.])5([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Tiger",group:"Mac OS",identifier:"Mac OS X (10([_|.])4([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Panther",group:"Mac OS",identifier:"Mac OS X (10([_|.])3([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Jaguar",group:"Mac OS",identifier:"Mac OS X (10([_|.])2([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Puma",group:"Mac OS",identifier:"Mac OS X (10([_|.])1([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Cheetah",group:"Mac OS",identifier:"Mac OS X (10([_|.])0([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS",group:"Mac OS",identifier:"Mac OS"},{name:"Ubuntu",group:"Linux",identifier:"Ubuntu",versionIdentifier:"Ubuntu/([0-9.]*)"},{name:"Debian",group:"Linux",identifier:"Debian"},{name:"Gentoo",group:"Linux",identifier:"Gentoo"},{name:"Linux",group:"Linux",identifier:"Linux"},{name:"BlackBerry",group:"BlackBerry",identifier:"BlackBerry"}],K={},H=function(t,e){var i=t.split(".",2);e.fullVersion=t,i[0]&&(e.majorVersion=parseInt(i[0])),i[1]&&(e.minorVersion=parseInt(i[1]))},V=function(t,e,i){var r="["==e.substr(0,1)?new RegExp(e,"g"):e,n=t.split(r,2);"."!=e&&(t=t.replace(new RegExp(e,"g"),".")),i.fullVersion=t,n&&n[0]&&(i.majorVersion=parseInt(n[0])),n&&n[1]&&(i.minorVersion=parseInt(n[1]))},Y=function(t){var e,i=t.match(/\b(playstation 4|nx|opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];if(/trident/i.test(i[1]))return e=/\brv[ :]+(\d+)/g.exec(t)||[],{name:"IE",version:parseInt(e[1]||"")};if("Chrome"===i[1]){if(null!=(e=t.match(/\bOPR\/(\d+)/)))return{name:"Opera",version:parseInt(e[1])};if(null!=(e=t.match(/\bEdge\/(\d+)/)))return{name:"Edge",version:parseInt(e[1])}}else/android/i.test(t)&&(e=t.match(/version\/(\d+)/i))&&(i.splice(1,1,"Android WebView"),i.splice(2,1,e[1]));return{name:(i=i[2]?[i[1],i[2]]:[navigator.appName,navigator.appVersion,"-?"])[0],version:parseInt(i[1])}}(navigator.userAgent);K.isEdge=/Edg|EdgiOS|EdgA/i.test(navigator.userAgent),K.isChrome=/Chrome|CriOS/i.test(navigator.userAgent)&&!K.isEdge,K.isSafari=/Safari/i.test(navigator.userAgent)&&!K.isChrome&&!K.isEdge,K.isFirefox=/Firefox/i.test(navigator.userAgent),K.isLegacyIE=!!window.ActiveXObject,K.isIE=K.isLegacyIE||/trident.*rv:1\d/i.test(navigator.userAgent),K.isIE11=/trident.*rv:11/i.test(navigator.userAgent),K.isChromecast=K.isChrome&&/CrKey/i.test(navigator.userAgent),K.isMobile=/Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone|IEMobile|Mobile Safari|Opera Mini/i.test(navigator.userAgent),K.isiOS=/iPad|iPhone|iPod/i.test(navigator.userAgent),K.isAndroid=/Android/i.test(navigator.userAgent),K.isWindowsPhone=/Windows Phone/i.test(navigator.userAgent),K.isWin8App=/MSAppHost/i.test(navigator.userAgent),K.isWiiU=/WiiU/i.test(navigator.userAgent),K.isPS4=/PlayStation 4/i.test(navigator.userAgent),K.hasLocalstorage=function(){try{return localStorage.setItem("clappr","clappr"),localStorage.removeItem("clappr"),!0}catch(t){return!1}}(),K.hasFlash=function(){try{return!!new ActiveXObject("ShockwaveFlash.ShockwaveFlash")}catch(t){return!(!navigator.mimeTypes||void 0===navigator.mimeTypes["application/x-shockwave-flash"]||!navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin)}}(),K.name=Y.name,K.version=Y.version,K.userAgent=navigator.userAgent,K.data=function(){var t,e={},i=K.userAgent.toLowerCase(),r=v($);try{for(r.s();!(t=r.n()).done;){var n=t.value,s=new RegExp(n.identifier.toLowerCase()).exec(i);if(null!=s&&s[1]){if(e.name=n.name,e.group=n.group,n.versionIdentifier){var a=new RegExp(n.versionIdentifier.toLowerCase()).exec(i);null!=a&&a[1]&&H(a[1],e)}else H(s[1],e);break}}}catch(t){r.e(t)}finally{r.f()}return e}(),K.os=function(){var t,e={},i=K.userAgent.toLowerCase(),r=v(G);try{for(r.s();!(t=r.n()).done;){var n=t.value,s=new RegExp(n.identifier.toLowerCase()).exec(i);if(null!=s){if(e.name=n.name,e.group=n.group,n.version)V(n.version,n.versionSeparator?n.versionSeparator:".",e);else if(s[1])V(s[1],n.versionSeparator?n.versionSeparator:".",e);else if(n.versionIdentifier){var a=new RegExp(n.versionIdentifier.toLowerCase()).exec(i);null!=a&&a[1]&&V(a[1],n.versionSeparator?n.versionSeparator:".",e)}break}}}catch(t){r.e(t)}finally{r.f()}return e}(),K.isWindows=/^Windows$/i.test(K.os.group),K.isMacOS=/^Mac OS$/i.test(K.os.group),K.isLinux=/^Linux$/i.test(K.os.group),K.viewport=((F={}).width=M(window).width(),F.height=M(window).height(),F),K.device=(N=K.userAgent,(U=/\((iP(?:hone|ad|od))?(?:[^;]*; ){0,2}([^)]+(?=\)))/.exec(N))&&(U[1]||U[2])||""),void 0!==window.orientation&&function(){switch(window.orientation){case-90:case 90:K.viewport.orientation="landscape";break;default:K.viewport.orientation="portrait"}}();var j={},W=[],z=(window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||function(t){window.setTimeout(t,1e3/60)}).bind(window),q=(window.cancelAnimationFrame||window.mozCancelAnimationFrame||window.webkitCancelAnimationFrame||window.clearTimeout).bind(window);function X(t,e){if(e)for(var i in e){var r=Object.getOwnPropertyDescriptor(e,i);r?Object.defineProperty(t,i,r):t[i]=e[i]}return t}function Q(t,e){var i=function(t){function i(){var t;p(this,i);for(var r=arguments.length,n=new Array(r),s=0;s<r;s++)n[s]=arguments[s];return t=g(this,i,[].concat(n)),e.initialize&&e.initialize.apply(t,n),t}return S(i,t),y(i)}(t);return X(i.prototype,e),i}var Z={fullscreenElement:function(){return document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement},requestFullscreen:function(t){if(t.requestFullscreen)return t.requestFullscreen();if(t.webkitRequestFullscreen){if("function"==typeof t.then)return t.webkitRequestFullscreen();t.webkitRequestFullscreen()}else{if(t.mozRequestFullScreen)return t.mozRequestFullScreen();if(t.msRequestFullscreen)return t.msRequestFullscreen();t.querySelector&&t.querySelector("video")&&t.querySelector("video").webkitEnterFullScreen?t.querySelector("video").webkitEnterFullScreen():t.webkitEnterFullScreen&&t.webkitEnterFullScreen()}},cancelFullscreen:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:document;t.exitFullscreen?t.exitFullscreen():t.webkitCancelFullScreen?t.webkitCancelFullScreen():t.webkitExitFullscreen?t.webkitExitFullscreen():t.mozCancelFullScreen?t.mozCancelFullScreen():t.msExitFullscreen&&t.msExitFullscreen()},fullscreenEnabled:function(){return!!(document.fullscreenEnabled||document.webkitFullscreenEnabled||document.mozFullScreenEnabled||document.msFullscreenEnabled)}},J=function(){return y((function t(){p(this,t)}),null,[{key:"params",get:function(){var t=window.location.search.substring(1);return t!==this.query&&(this._urlParams=this.parse(t),this.query=t),this._urlParams}},{key:"hashParams",get:function(){var t=window.location.hash.substring(1);return t!==this.hash&&(this._hashParams=this.parse(t),this.hash=t),this._hashParams}},{key:"parse",value:function(t){for(var e,i=/\+/g,r=/([^&=]+)=?([^&]*)/g,n=function(t){return decodeURIComponent(t.replace(i," "))},s={};e=r.exec(t);)s[n(e[1]).toLowerCase()]=n(e[2]);return s}}])}();function tt(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"t",e=0,i=J.params[t]||J.hashParams[t]||"",r=i.match(/[0-9]+[hms]+/g)||[];if(r.length>0){var n={h:3600,m:60,s:1};r.forEach((function(t){if(t){var i=t[t.length-1],r=parseInt(t.slice(0,t.length-1),10);e+=r*n[i]}}))}else i&&(e=parseInt(i,10));return e}function et(t){return j[t]||(j[t]=0),t+ ++j[t]}function it(t){return t-parseFloat(t)+1>=0}function rt(){var t=document.getElementsByTagName("script");return t.length?t[t.length-1].src:""}function nt(){return window.navigator&&window.navigator.language}function st(t,e){var i=(e=Object.assign({inline:!1,muted:!1,timeout:250,type:"video",source:B.mp4,element:null},e)).element?e.element:document.createElement(e.type);i.muted=e.muted,!0===e.muted&&i.setAttribute("muted","muted"),!0===e.inline&&i.setAttribute("playsinline","playsinline"),i.src=e.source;var r=i.play(),n=setTimeout((function(){s(!1,new Error("Timeout ".concat(e.timeout," ms has been reached")))}),e.timeout),s=function(e){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;clearTimeout(n),t(e,i)};void 0!==r?r.then((function(){return s(!0)})).catch((function(t){return s(!1,t)})):s(!0)}var at=function(){return y((function t(){p(this,t)}),null,[{key:"configure",value:function(t){this.options=M.extend(!0,this.options,t)}},{key:"create",value:function(t){return this.options.recycleVideo&&"video"===t&&W.length>0?W.shift():document.createElement(t)}},{key:"garbage",value:function(t){this.options.recycleVideo&&"VIDEO"===t.tagName.toUpperCase()&&(M(t).children().remove(),Object.values(t.attributes).forEach((function(e){return t.removeAttribute(e.name)})),W.push(t))}}])}();at.options={recycleVideo:!1};var ot=function(){return y((function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:500;p(this,t),this.delay=e,this.lastTime=0}),[{key:"handle",value:function(t,e){var i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],r=(new Date).getTime(),n=r-this.lastTime;n<this.delay&&n>0&&(e(),i&&t.preventDefault()),this.lastTime=r}}])}(),lt=function(){return window.performance&&window.performance.now?performance.now():Date.now()},ct=function(t,e){return void 0!==t&&void 0!==e&&void 0!==e.find((function(e){return t.toLowerCase()===e.toLowerCase()}))},ht="font-weight: bold; font-size: 13px;",ut="color: #ff8000;"+ht,dt="color: #ff0000;"+ht,ft=["color: #0000ff;"+ht,"color: #006600;"+ht,ut,dt,dt],gt=["debug","info","warn","error","disabled"],pt=function(){return y((function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:3;p(this,t),this.EXCLUDE_LIST=["timeupdate","playback:timeupdate","playback:progress","container:hover","container:timeupdate","container:progress","core:mousemove"],this.level=e,this.previousLevel=this.level,this.offLevel=i}),[{key:"level",get:function(){return this._level},set:function(t){this._level=t}},{key:"debug",value:function(t){this.log(t,0,Array.prototype.slice.call(arguments,1))}},{key:"info",value:function(t){this.log(t,1,Array.prototype.slice.call(arguments,1))}},{key:"warn",value:function(t){this.log(t,2,Array.prototype.slice.call(arguments,1))}},{key:"error",value:function(t){this.log(t,3,Array.prototype.slice.call(arguments,1))}},{key:"onOff",value:function(){this.level===this.offLevel?this.level=this.previousLevel:(this.previousLevel=this.level,this.level=this.offLevel),window.console&&window.console.log&&window.console.log("%c[Clappr.Log] set log level to "+gt[this.level],ut)}},{key:"log",value:function(t,e,i){if(!(e<this.level||this.EXCLUDE_LIST.indexOf(i[0])>=0)){i||(i=t,t=null);var r=ft[e],n="";t&&(n="["+t+"]"),window.console&&window.console.log&&window.console.log.apply(console,["%c["+gt[e]+"]"+n,r].concat(i))}}}])}();pt.LEVEL_DEBUG=0,pt.LEVEL_INFO=1,pt.LEVEL_WARN=2,pt.LEVEL_ERROR=3,pt.getInstance=function(){return void 0===this._instance&&(this._instance=new this),this._instance},pt.setLevel=function(t){this.getInstance().level=t},pt.debug=function(){this.getInstance().debug.apply(this.getInstance(),arguments)},pt.info=function(){this.getInstance().info.apply(this.getInstance(),arguments)},pt.warn=function(){this.getInstance().warn.apply(this.getInstance(),arguments)},pt.error=function(){this.getInstance().error.apply(this.getInstance(),arguments)};var mt=Array.prototype.slice,yt=/\s+/,vt=function(t,e,i,r){if(!i)return!0;if("object"===I(i)){for(var n in i)t[e].apply(t,[n,i[n]].concat(r));return!1}if(yt.test(i)){for(var s=i.split(yt),a=0,o=s.length;a<o;a++)t[e].apply(t,[s[a]].concat(r));return!1}return!0},At=function(t,e,i,r){var n,s=-1,a=t.length,o=e[0],l=e[1],c=e[2];!function h(){try{switch(e.length){case 0:for(;++s<a;)(n=t[s]).callback.call(n.ctx);return;case 1:for(;++s<a;)(n=t[s]).callback.call(n.ctx,o);return;case 2:for(;++s<a;)(n=t[s]).callback.call(n.ctx,o,l);return;case 3:for(;++s<a;)(n=t[s]).callback.call(n.ctx,o,l,c);return;default:for(;++s<a;)(n=t[s]).callback.apply(n.ctx,e);return}}catch(t){pt.error.apply(pt,[i,"error on event",r,"trigger","-",t]),h()}}()},Et=function(){function t(){p(this,t)}return y(t,[{key:"on",value:function(t,e,i){return vt(this,"on",t,[e,i])&&e?(this._events||(this._events={}),(this._events[t]||(this._events[t]=[])).push({callback:e,context:i,ctx:i||this}),this):this}},{key:"once",value:function(t,e,i){var r,n=this;if(!vt(this,"once",t,[e,i])||!e)return this;return r=function(){n.off(t,r),e.apply(this,arguments)},r._callback=e,this.on(t,r,i)}},{key:"off",value:function(t,e,i){var r,n,s,a,o,l,c,h;if(!this._events||!vt(this,"off",t,[e,i]))return this;if(!t&&!e&&!i)return this._events=void 0,this;for(o=0,l=(a=t?[t]:Object.keys(this._events)).length;o<l;o++)if(t=a[o],s=this._events[t]){if(this._events[t]=r=[],e||i)for(c=0,h=s.length;c<h;c++)n=s[c],(e&&e!==n.callback&&e!==n.callback._callback||i&&i!==n.context)&&r.push(n);r.length||delete this._events[t]}return this}},{key:"trigger",value:function(t){var e=this.name||this.constructor.name;if(pt.debug.apply(pt,[e].concat(Array.prototype.slice.call(arguments))),!this._events)return this;var i=mt.call(arguments,1);if(!vt(this,"trigger",t,i))return this;var r=this._events[t],n=this._events.all;return r&&At(r,i,e,t),n&&At(n,arguments,e,t),this}},{key:"stopListening",value:function(t,e,i){var r=this._listeningTo;if(!r)return this;var n=!e&&!i;for(var s in i||"object"!==I(e)||(i=this),t&&((r={})[t._listenId]=t),r)(t=r[s]).off(e,i,this),(n||0===Object.keys(t._events).length)&&delete this._listeningTo[s];return this}}],[{key:"register",value:function(e){t.Custom||(t.Custom={});var i="string"==typeof e&&e.toUpperCase().trim();i&&!t.Custom[i]?t.Custom[i]=i.toLowerCase().split("_").map((function(t,e){return 0===e?t:t=t[0].toUpperCase()+t.slice(1)})).join(""):pt.error("Events","Error when register event: "+e)}},{key:"listAvailableCustomEvents",value:function(){return t.Custom||(t.Custom={}),Object.keys(t.Custom).filter((function(e){return"string"==typeof t.Custom[e]}))}}])}();Et.prototype.listenTo=function(t,e,i){return(this._listeningTo||(this._listeningTo={}))[t._listenId||(t._listenId=et("l"))]=t,i||"object"!==I(e)||(i=this),t.on(e,i,this),this},Et.prototype.listenToOnce=function(t,e,i){return(this._listeningTo||(this._listeningTo={}))[t._listenId||(t._listenId=et("l"))]=t,i||"object"!==I(e)||(i=this),t.once(e,i,this),this},Et.PLAYER_READY="ready",Et.PLAYER_RESIZE="resize",Et.PLAYER_FULLSCREEN="fullscreen",Et.PLAYER_PLAY="play",Et.PLAYER_PAUSE="pause",Et.PLAYER_STOP="stop",Et.PLAYER_ENDED="ended",Et.PLAYER_SEEK="seek",Et.PLAYER_ERROR="playererror",Et.ERROR="error",Et.PLAYER_TIMEUPDATE="timeupdate",Et.PLAYER_VOLUMEUPDATE="volumeupdate",Et.PLAYER_SUBTITLE_AVAILABLE="subtitleavailable",Et.PLAYBACK_PIP_ENTER="playback:picture-in-picture:enter",Et.PLAYBACK_PIP_EXIT="playback:picture-in-picture:exit",Et.PLAYBACK_PROGRESS="playback:progress",Et.PLAYBACK_TIMEUPDATE="playback:timeupdate",Et.PLAYBACK_READY="playback:ready",Et.PLAYBACK_BUFFERING="playback:buffering",Et.PLAYBACK_BUFFERFULL="playback:bufferfull",Et.PLAYBACK_SETTINGSUPDATE="playback:settingsupdate",Et.PLAYBACK_LOADEDMETADATA="playback:loadedmetadata",Et.PLAYBACK_HIGHDEFINITIONUPDATE="playback:highdefinitionupdate",Et.PLAYBACK_BITRATE="playback:bitrate",Et.PLAYBACK_LEVELS_AVAILABLE="playback:levels:available",Et.PLAYBACK_LEVEL_SWITCH_START="playback:levels:switch:start",Et.PLAYBACK_LEVEL_SWITCH_END="playback:levels:switch:end",Et.PLAYBACK_PLAYBACKSTATE="playback:playbackstate",Et.PLAYBACK_DVR="playback:dvr",Et.PLAYBACK_MEDIACONTROL_DISABLE="playback:mediacontrol:disable",Et.PLAYBACK_MEDIACONTROL_ENABLE="playback:mediacontrol:enable",Et.PLAYBACK_ENDED="playback:ended",Et.PLAYBACK_PLAY_INTENT="playback:play:intent",Et.PLAYBACK_PLAY="playback:play",Et.PLAYBACK_PAUSE="playback:pause",Et.PLAYBACK_SEEK="playback:seek",Et.PLAYBACK_SEEKED="playback:seeked",Et.PLAYBACK_STOP="playback:stop",Et.PLAYBACK_ERROR="playback:error",Et.PLAYBACK_STATS_ADD="playback:stats:add",Et.PLAYBACK_FRAGMENT_LOADED="playback:fragment:loaded",Et.PLAYBACK_FRAGMENT_BUFFERED="playback:fragment:buffered",Et.PLAYBACK_LEVEL_SWITCH="playback:level:switch",Et.PLAYBACK_SUBTITLE_AVAILABLE="playback:subtitle:available",Et.PLAYBACK_SUBTITLE_CHANGED="playback:subtitle:changed",Et.PLAYBACK_AUDIO_AVAILABLE="playback:audio:available",Et.PLAYBACK_AUDIO_CHANGED="playback:audio:changed",Et.PLAYBACK_RESIZE="playback:resize",Et.CORE_CONTAINERS_CREATED="core:containers:created",Et.CORE_ACTIVE_CONTAINER_CHANGED="core:active:container:changed",Et.CORE_OPTIONS_CHANGE="core:options:change",Et.CORE_READY="core:ready",Et.CORE_FULLSCREEN="core:fullscreen",Et.CORE_RESIZE="core:resize",Et.CORE_SCREEN_ORIENTATION_CHANGED="core:screen:orientation:changed",Et.CORE_MOUSE_MOVE="core:mousemove",Et.CORE_MOUSE_LEAVE="core:mouseleave",Et.CONTAINER_PLAYBACKSTATE="container:playbackstate",Et.CONTAINER_PLAYBACKDVRSTATECHANGED="container:dvr",Et.CONTAINER_BITRATE="container:bitrate",Et.CONTAINER_STATS_REPORT="container:stats:report",Et.CONTAINER_DESTROYED="container:destroyed",Et.CONTAINER_READY="container:ready",Et.CONTAINER_RESIZE="container:resize",Et.CONTAINER_ERROR="container:error",Et.CONTAINER_LOADEDMETADATA="container:loadedmetadata",Et.CONTAINER_SUBTITLE_AVAILABLE="container:subtitle:available",Et.CONTAINER_SUBTITLE_CHANGED="container:subtitle:changed",Et.CONTAINER_AUDIO_AVAILABLE="container:audio:available",Et.CONTAINER_AUDIO_CHANGED="container:audio:changed",Et.CONTAINER_TIMEUPDATE="container:timeupdate",Et.CONTAINER_PROGRESS="container:progress",Et.CONTAINER_PLAY="container:play",Et.CONTAINER_STOP="container:stop",Et.CONTAINER_PAUSE="container:pause",Et.CONTAINER_ENDED="container:ended",Et.CONTAINER_CLICK="container:click",Et.CONTAINER_DBLCLICK="container:dblclick",Et.CONTAINER_CONTEXTMENU="container:contextmenu",Et.CONTAINER_MOUSE_ENTER="container:mouseenter",Et.CONTAINER_MOUSE_LEAVE="container:mouseleave",Et.CONTAINER_MOUSE_UP="container:mouseup",Et.CONTAINER_MOUSE_DOWN="container:mousedown",Et.CONTAINER_PIP_ENTER="container:picture-in-picture:enter",Et.CONTAINER_PIP_EXIT="container:picture-in-picture:exit",Et.CONTAINER_SEEK="container:seek",Et.CONTAINER_SEEKED="container:seeked",Et.CONTAINER_VOLUME="container:volume",Et.CONTAINER_FULLSCREEN="container:fullscreen",Et.CONTAINER_STATE_BUFFERING="container:state:buffering",Et.CONTAINER_STATE_BUFFERFULL="container:state:bufferfull",Et.CONTAINER_SETTINGSUPDATE="container:settingsupdate",Et.CONTAINER_HIGHDEFINITIONUPDATE="container:highdefinitionupdate",Et.CONTAINER_MEDIACONTROL_SHOW="container:mediacontrol:show",Et.CONTAINER_MEDIACONTROL_HIDE="container:mediacontrol:hide",Et.CONTAINER_MEDIACONTROL_DISABLE="container:mediacontrol:disable",Et.CONTAINER_MEDIACONTROL_ENABLE="container:mediacontrol:enable",Et.CONTAINER_STATS_ADD="container:stats:add",Et.CONTAINER_OPTIONS_CHANGE="container:options:change",Et.MEDIACONTROL_RENDERED="mediacontrol:rendered",Et.MEDIACONTROL_FULLSCREEN="mediacontrol:fullscreen",Et.MEDIACONTROL_SHOW="mediacontrol:show",Et.MEDIACONTROL_HIDE="mediacontrol:hide",Et.MEDIACONTROL_MOUSEMOVE_SEEKBAR="mediacontrol:mousemove:seekbar",Et.MEDIACONTROL_MOUSELEAVE_SEEKBAR="mediacontrol:mouseleave:seekbar",Et.MEDIACONTROL_PLAYING="mediacontrol:playing",Et.MEDIACONTROL_NOTPLAYING="mediacontrol:notplaying",Et.MEDIACONTROL_CONTAINERCHANGED="mediacontrol:containerchanged",Et.MEDIACONTROL_OPTIONS_CHANGE="mediacontrol:options:change";var Tt=function(t){function e(){var t,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return p(this,e),(t=g(this,e,[i]))._options=i,t.uniqueId=et("o"),t}return S(e,t),y(e,[{key:"options",get:function(){return this._options}}])}(Et),St={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g},bt=/(.)^/,kt={"'":"'","\\":"\\","\r":"r","\n":"n","\t":"t","\u2028":"u2028","\u2029":"u2029"},_t=/\\|'|\r|\n|\t|\u2028|\u2029/g,Lt={"&":"&","<":"<",">":">",'"':""","'":"'"},Rt=new RegExp("[&<>\"']","g"),Ct=function(t){return null===t?"":(""+t).replace(Rt,(function(t){return Lt[t]}))},Dt=0,wt=function(t,e){var i,r=new RegExp([(St.escape||bt).source,(St.interpolate||bt).source,(St.evaluate||bt).source].join("|")+"|$","g"),n=0,s="__p+='";t.replace(r,(function(e,i,r,a,o){return s+=t.slice(n,o).replace(_t,(function(t){return"\\"+kt[t]})),i&&(s+="'+\n((__t=("+i+"))==null?'':escapeExpr(__t))+\n'"),r&&(s+="'+\n((__t=("+r+"))==null?'':__t)+\n'"),a&&(s+="';\n"+a+"\n__p+='"),n=o+e.length,e})),s+="';\n",St.variable||(s="with(obj||{}){\n"+s+"}\n"),s="var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};\n"+s+"return __p;\n//# sourceURL=/microtemplates/source["+Dt+++"]";try{i=new Function(St.variable||"obj","escapeExpr",s)}catch(t){throw t.source=s,t}if(e)return i(e,Ct);var a=function(t){return i.call(this,t,Ct)};return a.source="function("+(St.variable||"obj")+"){\n"+s+"}",a};wt.settings=St;var It=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{baseUrl:""};return M('<style class="clappr-style"></style>').html(wt(t.toString())(e))},Pt=/^(\S+)\s*(.*)$/,Ot=function(t){function e(t){var i;return p(this,e),(i=g(this,e,[t])).cid=et("c"),i._ensureElement(),i.delegateEvents(),i}return S(e,t),y(e,[{key:"tagName",get:function(){return"div"}},{key:"events",get:function(){return{}}},{key:"attributes",get:function(){return{}}},{key:"$",value:function(t){return this.$el.find(t)}},{key:"render",value:function(){return this}},{key:"destroy",value:function(){return this.$el.remove(),this.stopListening(),this.undelegateEvents(),this}},{key:"setElement",value:function(t,e){return this.$el&&this.undelegateEvents(),this.$el=M.zepto.isZ(t)?t:M(t),this.el=this.$el[0],!1!==e&&this.delegateEvents(),this}},{key:"delegateEvents",value:function(t){for(var e in t||(t=this.events),this.undelegateEvents(),t){var i=t[e];if(i&&i.constructor!==Function&&(i=this[t[e]]),i){var r=e.match(Pt),n=r[1],s=r[2];n+=".delegateEvents"+this.cid,""===s?this.$el.on(n,i.bind(this)):this.$el.on(n,s,i.bind(this))}}return this}},{key:"undelegateEvents",value:function(){return this.$el.off(".delegateEvents"+this.cid),this}},{key:"_ensureElement",value:function(){if(this.el)this.setElement(this.el,!1);else{var t=M.extend(!0,{},this.attributes);this.id&&(t.id=this.id),this.className&&(t.class=this.className);var e=M(at.create(this.tagName)).attr(t);this.setElement(e,!1)}}},{key:"onResize",value:function(){return this}},{key:"resize",value:function(t){var e=it(t.width)?"".concat(t.width,"px"):"".concat(t.width),i=it(t.height)?"".concat(t.height,"px"):"".concat(t.height);return this.el.style.width=e,this.el.style.height=i,this.onResize(t),this}}])}(Tt),xt=function(t){function e(){var t,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=arguments.length>1?arguments[1]:void 0;return p(this,e),(t=g(this,e,[i])).core=r,t}return S(e,t),y(e,[{key:"name",get:function(){return"error"}},{key:"createError",value:function(t){this.core?this.core.trigger(Et.ERROR,t):pt.warn(this.name,"Core is not set. Error: ",t)}}],[{key:"Levels",get:function(){return{FATAL:"FATAL",WARN:"WARN",INFO:"INFO"}}}])}(Tt),Mt={createError:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{useCodePrefix:!0},i=this.constructor&&this.constructor.type||"",r=this.name||i,n=this.i18n||this.core&&this.core.i18n||this.container&&this.container.i18n,s="".concat(r,":").concat(t&&t.code||"unknown"),a={description:"",level:xt.Levels.FATAL,origin:r,scope:i,raw:{}},o=Object.assign({},a,t,{code:e.useCodePrefix?s:t.code});if(n&&o.level==xt.Levels.FATAL&&!o.UI){var l={title:n.t("default_error_title"),message:n.t("default_error_message")};o.UI=l}return this.playerError?this.playerError.createError(o):pt.warn(r,"PlayerError is not defined. Error: ",o),o}},Ft=function(t){function e(t){var i;return p(this,e),(i=g(this,e,[t.options])).core=t,i.enabled=!0,i.bindEvents(),i.render(),i}return S(e,t),y(e,[{key:"playerError",get:function(){return this.core.playerError}},{key:"bindEvents",value:function(){}},{key:"getExternalInterface",value:function(){return{}}},{key:"enable",value:function(){this.enabled||(this.bindEvents(),this.$el.show(),this.enabled=!0)}},{key:"disable",value:function(){this.stopListening(),this.$el.hide(),this.enabled=!1}},{key:"render",value:function(){return this}}])}(Ot);Object.assign(Ft.prototype,Mt),Ft.extend=function(t){return Q(Ft,t)},Ft.type="core";var Nt=function(t){function e(t,i,r){var n;return p(this,e),(n=g(this,e,[t]))._i18n=i,n.currentTime=0,n.volume=100,n.playback=t.playback,n.playerError=r,n.settings=M.extend(!0,{},n.playback.settings),n.isReady=!1,n.mediaControlDisabled=!1,n.plugins=[n.playback],n.dblTapHandler=new ot(500),n.clickTimer=null,n.clickDelay=200,n.actionsMetadata={},n.bindEvents(),n}return S(e,t),y(e,[{key:"name",get:function(){return"Container"}},{key:"attributes",get:function(){return{class:"container","data-container":""}}},{key:"events",get:function(){return{click:"clicked",dblclick:"dblClicked",touchend:"dblTap",contextmenu:"onContextMenu",mouseenter:"mouseEnter",mouseleave:"mouseLeave",mouseup:"onMouseUp",mousedown:"onMouseDown"}}},{key:"ended",get:function(){return this.playback.ended}},{key:"buffering",get:function(){return this.playback.buffering}},{key:"i18n",get:function(){return this._i18n}},{key:"hasClosedCaptionsTracks",get:function(){return this.playback.hasClosedCaptionsTracks}},{key:"closedCaptionsTracks",get:function(){return this.playback.closedCaptionsTracks}},{key:"closedCaptionsTrackId",get:function(){return this.playback.closedCaptionsTrackId},set:function(t){this.playback.closedCaptionsTrackId=t}},{key:"audioTracks",get:function(){return this.playback.audioTracks}},{key:"currentAudioTrack",get:function(){return this.playback.currentAudioTrack}},{key:"isPiPActive",get:function(){return this.playback.isPiPActive}},{key:"bindEvents",value:function(){this.listenTo(this.playback,Et.PLAYBACK_PROGRESS,this.onProgress),this.listenTo(this.playback,Et.PLAYBACK_TIMEUPDATE,this.timeUpdated),this.listenTo(this.playback,Et.PLAYBACK_READY,this.ready),this.listenTo(this.playback,Et.PLAYBACK_BUFFERING,this.onBuffering),this.listenTo(this.playback,Et.PLAYBACK_BUFFERFULL,this.bufferfull),this.listenTo(this.playback,Et.PLAYBACK_SETTINGSUPDATE,this.settingsUpdate),this.listenTo(this.playback,Et.PLAYBACK_LOADEDMETADATA,this.loadedMetadata),this.listenTo(this.playback,Et.PLAYBACK_HIGHDEFINITIONUPDATE,this.highDefinitionUpdate),this.listenTo(this.playback,Et.PLAYBACK_BITRATE,this.updateBitrate),this.listenTo(this.playback,Et.PLAYBACK_PLAYBACKSTATE,this.playbackStateChanged),this.listenTo(this.playback,Et.PLAYBACK_DVR,this.playbackDvrStateChanged),this.listenTo(this.playback,Et.PLAYBACK_MEDIACONTROL_DISABLE,this.disableMediaControl),this.listenTo(this.playback,Et.PLAYBACK_MEDIACONTROL_ENABLE,this.enableMediaControl),this.listenTo(this.playback,Et.PLAYBACK_SEEK,this.onSeek),this.listenTo(this.playback,Et.PLAYBACK_SEEKED,this.onSeeked),this.listenTo(this.playback,Et.PLAYBACK_ENDED,this.onEnded),this.listenTo(this.playback,Et.PLAYBACK_PLAY,this.playing),this.listenTo(this.playback,Et.PLAYBACK_PAUSE,this.paused),this.listenTo(this.playback,Et.PLAYBACK_STOP,this.stopped),this.listenTo(this.playback,Et.PLAYBACK_ERROR,this.error),this.listenTo(this.playback,Et.PLAYBACK_SUBTITLE_AVAILABLE,this.subtitleAvailable),this.listenTo(this.playback,Et.PLAYBACK_SUBTITLE_CHANGED,this.subtitleChanged),this.listenTo(this.playback,Et.PLAYBACK_AUDIO_AVAILABLE,this.audioAvailable),this.listenTo(this.playback,Et.PLAYBACK_AUDIO_CHANGED,this.audioChanged),this.listenTo(this.playback,Et.PLAYBACK_PIP_ENTER,this.onEnterPiP),this.listenTo(this.playback,Et.PLAYBACK_PIP_EXIT,this.onExitPiP)}},{key:"subtitleAvailable",value:function(){this.trigger(Et.CONTAINER_SUBTITLE_AVAILABLE)}},{key:"subtitleChanged",value:function(t){this.trigger(Et.CONTAINER_SUBTITLE_CHANGED,t)}},{key:"audioAvailable",value:function(t){this.trigger(Et.CONTAINER_AUDIO_AVAILABLE,t)}},{key:"audioChanged",value:function(t){this.trigger(Et.CONTAINER_AUDIO_CHANGED,t)}},{key:"playbackStateChanged",value:function(t){this.trigger(Et.CONTAINER_PLAYBACKSTATE,t)}},{key:"playbackDvrStateChanged",value:function(t){this.settings=this.playback.settings,this.dvrInUse=t,this.trigger(Et.CONTAINER_PLAYBACKDVRSTATECHANGED,t)}},{key:"updateBitrate",value:function(t){this.trigger(Et.CONTAINER_BITRATE,t)}},{key:"statsReport",value:function(t){this.trigger(Et.CONTAINER_STATS_REPORT,t)}},{key:"getPlaybackType",value:function(){return this.playback.getPlaybackType()}},{key:"isDvrEnabled",value:function(){return!!this.playback.dvrEnabled}},{key:"isDvrInUse",value:function(){return!!this.dvrInUse}},{key:"destroy",value:function(){this.disableResizeObserver(),this.trigger(Et.CONTAINER_DESTROYED,this,this.name),this.stopListening(),this.plugins.forEach((function(t){return t.destroy()})),this.$el.remove(),this.undelegateEvents()}},{key:"setStyle",value:function(t){this.$el.css(t)}},{key:"ready",value:function(){this.isReady=!0,this.trigger(Et.CONTAINER_READY,this.name)}},{key:"isPlaying",value:function(){return this.playback.isPlaying()}},{key:"getStartTimeOffset",value:function(){return this.playback.getStartTimeOffset()}},{key:"getCurrentTime",value:function(){return this.currentTime}},{key:"getDuration",value:function(){return this.playback.getDuration()}},{key:"error",value:function(t){this.isReady||this.ready(),this.trigger(Et.CONTAINER_ERROR,t,this.name)}},{key:"loadedMetadata",value:function(t){this.trigger(Et.CONTAINER_LOADEDMETADATA,t)}},{key:"timeUpdated",value:function(t){this.currentTime=t.current,this.trigger(Et.CONTAINER_TIMEUPDATE,t,this.name)}},{key:"onProgress",value:function(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];this.trigger.apply(this,[Et.CONTAINER_PROGRESS].concat(e,[this.name]))}},{key:"playing",value:function(){this.trigger(Et.CONTAINER_PLAY,this.name,this.actionsMetadata.playEvent||{}),this.actionsMetadata.playEvent={}}},{key:"paused",value:function(){this.trigger(Et.CONTAINER_PAUSE,this.name,this.actionsMetadata.pauseEvent||{}),this.actionsMetadata.pauseEvent={}}},{key:"stopped",value:function(){this.trigger(Et.CONTAINER_STOP,this.actionsMetadata.stopEvent||{}),this.actionsMetadata.stopEvent={}}},{key:"play",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.actionsMetadata.playEvent=t,this.playback.play(t)}},{key:"stop",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.actionsMetadata.stopEvent=t,this.playback.stop(t),this.currentTime=0}},{key:"switchAudioTrack",value:function(t){this.playback.switchAudioTrack(t)}},{key:"pause",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.actionsMetadata.pauseEvent=t,this.playback.pause(t)}},{key:"onEnded",value:function(){this.trigger(Et.CONTAINER_ENDED,this,this.name),this.currentTime=0}},{key:"clicked",value:function(){var t=this;this.options.chromeless&&!this.options.allowUserInteraction||(this.clickTimer=setTimeout((function(){t.clickTimer&&t.trigger(Et.CONTAINER_CLICK,t,t.name)}),this.clickDelay))}},{key:"cancelClicked",value:function(){clearTimeout(this.clickTimer),this.clickTimer=null}},{key:"dblClicked",value:function(){this.options.chromeless&&!this.options.allowUserInteraction||(this.cancelClicked(),this.trigger(Et.CONTAINER_DBLCLICK,this,this.name))}},{key:"dblTap",value:function(t){var e=this;this.options.chromeless&&!this.options.allowUserInteraction||this.dblTapHandler.handle(t,(function(){e.cancelClicked(),e.trigger(Et.CONTAINER_DBLCLICK,e,e.name)}))}},{key:"onContextMenu",value:function(t){this.options.chromeless&&!this.options.allowUserInteraction||this.trigger(Et.CONTAINER_CONTEXTMENU,t,this.name)}},{key:"seek",value:function(t){this.playback.seek(t)}},{key:"onSeek",value:function(t){this.trigger(Et.CONTAINER_SEEK,t,this.name)}},{key:"onSeeked",value:function(){this.trigger(Et.CONTAINER_SEEKED,this.name)}},{key:"seekPercentage",value:function(t){var e=this.getDuration();if(t>=0&&t<=100){var i=e*(t/100);this.seek(i)}}},{key:"setVolume",value:function(t){this.volume=parseFloat(t),this.trigger(Et.CONTAINER_VOLUME,this.volume,this.name),this.playback.volume(this.volume)}},{key:"fullscreen",value:function(){this.trigger(Et.CONTAINER_FULLSCREEN,this.name)}},{key:"onBuffering",value:function(){this.trigger(Et.CONTAINER_STATE_BUFFERING,this.name)}},{key:"bufferfull",value:function(){this.trigger(Et.CONTAINER_STATE_BUFFERFULL,this.name)}},{key:"onEnterPiP",value:function(){this.trigger(Et.CONTAINER_PIP_ENTER,this.name)}},{key:"onExitPiP",value:function(){this.trigger(Et.CONTAINER_PIP_EXIT,this.name)}},{key:"addPlugin",value:function(t){this.plugins.push(t)}},{key:"hasPlugin",value:function(t){return!!this.getPlugin(t)}},{key:"getPlugin",value:function(t){return this.plugins.filter((function(e){return e.name===t}))[0]}},{key:"mouseEnter",value:function(){this.options.chromeless&&!this.options.allowUserInteraction||this.trigger(Et.CONTAINER_MOUSE_ENTER)}},{key:"mouseLeave",value:function(){this.options.chromeless&&!this.options.allowUserInteraction||this.trigger(Et.CONTAINER_MOUSE_LEAVE)}},{key:"mouseUp",value:function(){this.options.chromeless&&!this.options.allowUserInteraction||this.trigger(Et.CONTAINER_MOUSE_UP)}},{key:"mouseDown",value:function(){this.options.chromeless&&!this.options.allowUserInteraction||this.trigger(Et.CONTAINER_MOUSE_DOWN)}},{key:"enterPiP",value:function(){this.playback.enterPiP()}},{key:"exitPiP",value:function(){this.playback.exitPiP()}},{key:"settingsUpdate",value:function(){this.settings=this.playback.settings,this.trigger(Et.CONTAINER_SETTINGSUPDATE)}},{key:"highDefinitionUpdate",value:function(t){this.trigger(Et.CONTAINER_HIGHDEFINITIONUPDATE,t)}},{key:"isHighDefinitionInUse",value:function(){return this.playback.isHighDefinitionInUse()}},{key:"disableMediaControl",value:function(){this.mediaControlDisabled||(this.mediaControlDisabled=!0,this.trigger(Et.CONTAINER_MEDIACONTROL_DISABLE))}},{key:"enableMediaControl",value:function(){this.mediaControlDisabled&&(this.mediaControlDisabled=!1,this.trigger(Et.CONTAINER_MEDIACONTROL_ENABLE))}},{key:"updateStyle",value:function(){!this.options.chromeless||this.options.allowUserInteraction?this.$el.removeClass("chromeless"):this.$el.addClass("chromeless")}},{key:"enableResizeObserver",value:function(){var t=this;this.disableResizeObserver(),this.resizeObserverInterval=setInterval((function(){return t.checkResize()}),500)}},{key:"disableResizeObserver",value:function(){this.resizeObserverInterval&&clearInterval(this.resizeObserverInterval)}},{key:"checkResize",value:function(){var t={width:this.el.clientWidth,height:this.el.clientHeight},e=this.currentSize||{},i=e.width;(e.height!==t.height||i!==t.width)&&(this.currentSize=t,this.trigger(Et.CONTAINER_RESIZE,t))}},{key:"onResize",value:function(t){return this.playback.resize(t),this}},{key:"configure",value:function(t){this._options=M.extend(!0,this._options,t),this.updateStyle(),this.playback.configure(this.options),this.trigger(Et.CONTAINER_OPTIONS_CHANGE)}},{key:"render",value:function(){var t=It(".container[data-container] {\n position: absolute;\n background-color: black;\n height: 100%;\n width: 100%;\n max-width: 100%; }\n .container[data-container] .chromeless {\n cursor: default; }\n\n[data-player]:not(.nocursor) .container[data-container]:not(.chromeless).pointer-enabled {\n cursor: pointer; }\n".toString(),{baseUrl:this.options.baseUrl});return this.$el.append(t[0]),this.$el.append(this.playback.render().el),this.updateStyle(),this.checkResize(),this.enableResizeObserver(),this}}])}(Ot);Object.assign(Nt.prototype,Mt);var Ut=function(t){function e(t,i,r){var n;return p(this,e),(n=g(this,e,[t])).settings={},n._i18n=i,n.playerError=r,n._consented=!1,n}return S(e,t),y(e,[{key:"isAudioOnly",get:function(){return!1}},{key:"isAdaptive",get:function(){return!1}},{key:"ended",get:function(){return!1}},{key:"i18n",get:function(){return this._i18n}},{key:"buffering",get:function(){return!1}},{key:"latency",get:function(){return null}},{key:"currentProgramDateTime",get:function(){return null}},{key:"isPiPActive",get:function(){return!1}},{key:"consent",value:function(t){"function"==typeof t&&t()}},{key:"play",value:function(){}},{key:"pause",value:function(){}},{key:"stop",value:function(){}},{key:"enterPiP",value:function(){}},{key:"exitPiP",value:function(){}},{key:"seek",value:function(t){}},{key:"seekPercentage",value:function(t){}},{key:"getStartTimeOffset",value:function(){return 0}},{key:"getDuration",value:function(){return 0}},{key:"isPlaying",value:function(){return!1}},{key:"isReady",get:function(){return!1}},{key:"hasClosedCaptionsTracks",get:function(){return this.closedCaptionsTracks.length>0}},{key:"closedCaptionsTracks",get:function(){return[]}},{key:"closedCaptionsTrackId",get:function(){return-1},set:function(t){}},{key:"audioTracks",get:function(){return[]}},{key:"currentAudioTrack",get:function(){return null}},{key:"switchAudioTrack",value:function(t){}},{key:"getPlaybackType",value:function(){return e.NO_OP}},{key:"isHighDefinitionInUse",value:function(){return!1}},{key:"mute",value:function(){}},{key:"unmute",value:function(){}},{key:"volume",value:function(t){}},{key:"configure",value:function(t){this._options=M.extend(!0,this._options,t)}},{key:"attemptAutoPlay",value:function(){var t=this;this.canAutoPlay((function(e,i){e&&t.play()}))}},{key:"canAutoPlay",value:function(t){t(!0,null)}},{key:"onResize",value:function(t){return this.trigger(Et.PLAYBACK_RESIZE,t),this}}])}(Ot);Object.assign(Ut.prototype,Mt),Ut.extend=function(t){return Q(Ut,t)},Ut.canPlay=function(t,e){return!1},Ut.VOD="vod",Ut.AOD="aod",Ut.LIVE="live",Ut.NO_OP="no_op",Ut.type="playback";var Bt=function(t){function e(t,i,r,n){var s;return p(this,e),(s=g(this,e,[t]))._i18n=r,s.loader=i,s.playerError=n,s}return S(e,t),y(e,[{key:"options",get:function(){return this._options},set:function(t){this._options=t}},{key:"createContainers",value:function(){var t=this;return M.Deferred((function(e){e.resolve(t.options.sources.map((function(e){return t.createContainer(e)})))}))}},{key:"findPlaybackPlugin",value:function(t,e){return this.loader.playbackPlugins.filter((function(i){return i.canPlay(t,e)}))[0]}},{key:"createContainer",value:function(t){var e=null,i=this.options.mimeType;"object"===I(t)?(e=t.source.toString(),t.mimeType&&(i=t.mimeType)):e=t.toString(),e.match(/^\/\//)&&(e=window.location.protocol+e);var r=_(_({},this.options),{},{src:e,mimeType:i}),n=this.findPlaybackPlugin(e,i),s=n?new n(r,this._i18n,this.playerError):new Ut;r=_(_({},r),{},{playback:s});var a=new Nt(r,this._i18n,this.playerError),o=M.Deferred();return o.promise(a),this.addContainerPlugins(a),this.listenToOnce(a,Et.CONTAINER_READY,(function(){return o.resolve(a)})),a}},{key:"addContainerPlugins",value:function(t){this.loader.containerPlugins.forEach((function(e){t.addPlugin(new e(t))}))}}])}(Tt),$t=function(t){function e(t){var i;return p(this,e),(i=g(this,e,[t])).playerError=new xt(t,i),i.configureDomRecycler(),i.firstResize=!0,i.styleRendered=!1,i.plugins=[],i.containers=[],i._boundFullscreenHandler=function(){return i.handleFullscreenChange()},i._boundHandleWindowResize=function(t){return i.handleWindowResize(t)},M(document).bind("fullscreenchange",i._boundFullscreenHandler),M(document).bind("MSFullscreenChange",i._boundFullscreenHandler),M(document).bind("mozfullscreenchange",i._boundFullscreenHandler),K.isMobile&&M(window).bind("resize",i._boundHandleWindowResize),i}return S(e,t),y(e,[{key:"events",get:function(){return{webkitfullscreenchange:"handleFullscreenChange",mousemove:"onMouseMove",mouseleave:"onMouseLeave"}}},{key:"attributes",get:function(){return{"data-player":"",tabindex:9999}}},{key:"isReady",get:function(){return!!this.ready}},{key:"i18n",get:function(){return this.getPlugin("strings")||{t:function(t){return t}}}},{key:"mediaControl",get:function(){return this._mediaControl||(this._mediaControl=this.getPlugin("media_control"))||this.dummyMediaControl}},{key:"dummyMediaControl",get:function(){return this._dummyMediaControl||(this._dummyMediaControl=new Ft(this)),this._dummyMediaControl}},{key:"activeContainer",get:function(){return this._activeContainer},set:function(t){this._activeContainer=t,this.trigger(Et.CORE_ACTIVE_CONTAINER_CHANGED,this._activeContainer)}},{key:"activePlayback",get:function(){return this.activeContainer&&this.activeContainer.playback}},{key:"activePlaybackEl",get:function(){if(this.activePlayback)return this.activePlayback.$el&&this.activePlayback.$el.find("video")[0]||this.activePlayback.el}},{key:"configureDomRecycler",value:function(){var t=this.options&&this.options.playback&&this.options.playback.recycleVideo;at.configure({recycleVideo:t})}},{key:"createContainers",value:function(t){this.defer=M.Deferred(),this.defer.promise(this),this.containerFactory=new Bt(t,t.loader,this.i18n,this.playerError),this.prepareContainers()}},{key:"prepareContainers",value:function(){var t=this;this.containerFactory.createContainers().then((function(e){return t.setupContainers(e)})).then((function(e){return t.resolveOnContainersReady(e)}))}},{key:"updateSize",value:function(){this.isFullscreen()?this.setFullscreen():this.setPlayerSize()}},{key:"setFullscreen",value:function(){K.isiOS||(this.$el.addClass("fullscreen"),this.$el.removeAttr("style"),this.previousSize={width:this.options.width,height:this.options.height},this.currentSize={width:M(window).width(),height:M(window).height()})}},{key:"setPlayerSize",value:function(){this.$el.removeClass("fullscreen"),this.currentSize=this.previousSize,this.previousSize={width:M(window).width(),height:M(window).height()},this.resize(this.currentSize)}},{key:"onResize",value:function(t){return this.previousSize={width:this.options.width,height:this.options.height},this.options.width=t.width,this.options.height=t.height,this.currentSize=t,this.triggerResize(this.currentSize),this}},{key:"enableResizeObserver",value:function(){var t=this;this.disableResizeObserver();this.resizeObserverInterval=setInterval((function(){t.triggerResize({width:t.el.clientWidth,height:t.el.clientHeight})}),500)}},{key:"triggerResize",value:function(t){(this.firstResize||this.oldHeight!==t.height||this.oldWidth!==t.width)&&(this.oldHeight=t.height,this.oldWidth=t.width,this.computedSize=t,this.firstResize=!1,this.trigger(Et.CORE_RESIZE,t))}},{key:"disableResizeObserver",value:function(){this.resizeObserverInterval&&clearInterval(this.resizeObserverInterval),this.resizeObserverInterval=null}},{key:"resolveOnContainersReady",value:function(t){var e=this;M.when.apply(M,t).done((function(){e.defer.resolve(e),e.ready=!0,e.trigger(Et.CORE_READY)}))}},{key:"addPlugin",value:function(t){this.plugins.push(t)}},{key:"hasPlugin",value:function(t){return!!this.getPlugin(t)}},{key:"getPlugin",value:function(t){return this.plugins.filter((function(e){return e.name===t}))[0]}},{key:"load",value:function(t,e){this.options.mimeType=e,t=t&&t.constructor===Array?t:[t],this.options.sources=t,this.containers.forEach((function(t){return t.destroy()})),this.containerFactory.options=M.extend(!0,this.options,{sources:t}),this.prepareContainers()}},{key:"destroy",value:function(){this.disableResizeObserver(),this.containers.forEach((function(t){return t.destroy()})),this.plugins.forEach((function(t){return t.destroy()})),this.$el.remove(),M(document).unbind("fullscreenchange",this._boundFullscreenHandler),M(document).unbind("MSFullscreenChange",this._boundFullscreenHandler),M(document).unbind("mozfullscreenchange",this._boundFullscreenHandler),K.isMobile&&M(window).unbind("resize",this._boundHandleWindowResize),this.stopListening(),this.undelegateEvents()}},{key:"handleFullscreenChange",value:function(){this.trigger(Et.CORE_FULLSCREEN,this.isFullscreen()),this.updateSize()}},{key:"handleWindowResize",value:function(t){var e=window.innerWidth>window.innerHeight?"landscape":"portrait";this._screenOrientation!==e&&(this._screenOrientation=e,this.triggerResize({width:this.el.clientWidth,height:this.el.clientHeight}),this.trigger(Et.CORE_SCREEN_ORIENTATION_CHANGED,{event:t,orientation:this._screenOrientation}))}},{key:"removeContainer",value:function(t){this.stopListening(t),this.containerFactory.stopListening(t),this.containers=this.containers.filter((function(e){return e!==t}))}},{key:"setupContainer",value:function(t){this.listenTo(t,Et.CONTAINER_DESTROYED,this.removeContainer),this.containers.push(t)}},{key:"setupContainers",value:function(t){return t.forEach(this.setupContainer.bind(this)),this.trigger(Et.CORE_CONTAINERS_CREATED),this.renderContainers(),this.activeContainer=t[0],this.render(),this.appendToParent(),this.containers}},{key:"renderContainers",value:function(){var t=this;this.containers.forEach((function(e){return t.el.appendChild(e.render().el)}))}},{key:"createContainer",value:function(t,e){var i=this.containerFactory.createContainer(t,e);return this.setupContainer(i),this.el.appendChild(i.render().el),i}},{key:"getCurrentContainer",value:function(){return this.activeContainer}},{key:"getCurrentPlayback",value:function(){return this.activePlayback}},{key:"getPlaybackType",value:function(){return this.activeContainer&&this.activeContainer.getPlaybackType()}},{key:"isFullscreen",value:function(){var t=Z.fullscreenElement();return t&&t===this.el||t&&t===this.activePlaybackEl||this.activePlaybackEl&&this.activePlaybackEl.webkitDisplayingFullscreen||!1}},{key:"toggleFullscreen",value:function(){var t=this;if(this.isFullscreen()){var e=K.isiOS?this.activePlaybackEl:document;Z.cancelFullscreen(e),!K.isiOS&&this.$el.removeClass("fullscreen nocursor")}else{var i=K.isiOS?this.activePlaybackEl:this.el;if(!i)return;K.isSafari||K.isiOS?Z.requestFullscreen(i):Z.requestFullscreen(i).then((function(t){return t}),(function(e){return setTimeout((function(){if(!t.isFullscreen())throw new ReferenceError(e)}),600)})),!K.isiOS&&this.$el.addClass("fullscreen")}}},{key:"onMouseMove",value:function(t){this.trigger(Et.CORE_MOUSE_MOVE,t)}},{key:"onMouseLeave",value:function(t){this.trigger(Et.CORE_MOUSE_LEAVE,t)}},{key:"configure",value:function(t){var e=this;this._options=M.extend(!0,this._options,t),this.configureDomRecycler();var i=t.source||t.sources;i&&this.load(i,t.mimeType||this.options.mimeType),this.trigger(Et.CORE_OPTIONS_CHANGE,t),this.containers.forEach((function(t){return t.configure(e.options)}))}},{key:"appendToParent",value:function(){!(this.$el.parent()&&this.$el.parent().length)&&this.$el.appendTo(this.options.parentElement)}},{key:"appendStyles",value:function(){if(!this.styleRendered){var t=It('[data-player] {\n -webkit-touch-callout: none;\n -webkit-user-select: none;\n -moz-user-select: none;\n -o-user-select: none;\n user-select: none;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n transform: translate3d(0, 0, 0);\n position: relative;\n margin: 0;\n padding: 0;\n border: 0;\n font-style: normal;\n font-weight: normal;\n text-align: center;\n overflow: hidden;\n font-size: 100%;\n font-family: "Roboto", "Open Sans", Arial, sans-serif;\n text-shadow: 0 0 0;\n box-sizing: border-box; }\n [data-player]:focus {\n outline: 0; }\n [data-player] * {\n box-sizing: inherit; }\n [data-player] > * {\n float: none;\n max-width: none; }\n [data-player] > div {\n display: block; }\n [data-player].fullscreen {\n width: 100% !important;\n height: 100% !important;\n top: 0;\n left: 0; }\n [data-player].nocursor {\n cursor: none; }\n\n.clappr-style {\n display: none !important; }\n'.toString(),{baseUrl:this.options.baseUrl});if(this.$el.append(t[0]),this.options.includeResetStyle){var e=It('[data-player] div, [data-player] span, [data-player] applet, [data-player] object, [data-player] iframe,\n[data-player] h1, [data-player] h2, [data-player] h3, [data-player] h4, [data-player] h5, [data-player] h6, [data-player] p, [data-player] blockquote, [data-player] pre,\n[data-player] a, [data-player] abbr, [data-player] acronym, [data-player] address, [data-player] big, [data-player] cite, [data-player] code,\n[data-player] del, [data-player] dfn, [data-player] em, [data-player] img, [data-player] ins, [data-player] kbd, [data-player] q, [data-player] s, [data-player] samp,\n[data-player] small, [data-player] strike, [data-player] strong, [data-player] sub, [data-player] sup, [data-player] tt, [data-player] var,\n[data-player] b, [data-player] u, [data-player] i, [data-player] center,\n[data-player] dl, [data-player] dt, [data-player] dd, [data-player] ol, [data-player] ul, [data-player] li,\n[data-player] fieldset, [data-player] form, [data-player] label, [data-player] legend,\n[data-player] table, [data-player] caption, [data-player] tbody, [data-player] tfoot, [data-player] thead, [data-player] tr, [data-player] th, [data-player] td,\n[data-player] article, [data-player] aside, [data-player] canvas, [data-player] details, [data-player] embed,\n[data-player] figure, [data-player] figcaption, [data-player] footer, [data-player] header, [data-player] hgroup,\n[data-player] menu, [data-player] nav, [data-player] output, [data-player] ruby, [data-player] section, [data-player] summary,\n[data-player] time, [data-player] mark, [data-player] audio, [data-player] video {\n margin: 0;\n padding: 0;\n border: 0;\n font: inherit;\n font-size: 100%;\n vertical-align: baseline; }\n\n[data-player] table {\n border-collapse: collapse;\n border-spacing: 0; }\n\n[data-player] caption, [data-player] th, [data-player] td {\n text-align: left;\n font-weight: normal;\n vertical-align: middle; }\n\n[data-player] q, [data-player] blockquote {\n quotes: none; }\n [data-player] q:before, [data-player] q:after, [data-player] blockquote:before, [data-player] blockquote:after {\n content: "";\n content: none; }\n\n[data-player] a img {\n border: none; }\n'.toString(),{baseUrl:this.options.baseUrl});this.$el.append(e[0])}this.styleRendered=!0}}},{key:"render",value:function(){this.appendStyles(),this.options.width=this.options.width||this.$el.width(),this.options.height=this.options.height||this.$el.height();var t={width:this.options.width,height:this.options.height};return this.previousSize=this.currentSize=this.computedSize=t,this.updateSize(),this.enableResizeObserver(),this}}])}(Ot);Object.assign($t.prototype,Mt);var Gt,Kt,Ht=function(t){function e(t){var i;return p(this,e),(i=g(this,e,[t.options])).player=t,i}return S(e,t),y(e,[{key:"loader",get:function(){return this.player.loader}},{key:"create",value:function(){return this.options.loader=this.loader,this.core=new $t(this.options),this.addCorePlugins(),this.core.createContainers(this.options),this.core}},{key:"addCorePlugins",value:function(){var t=this;return this.loader.corePlugins.forEach((function(e){var i=new e(t.core);t.core.addPlugin(i),t.setupExternalInterface(i)})),this.core}},{key:"setupExternalInterface",value:function(t){var e=t.getExternalInterface();for(var i in e)this.player[i]=e[i].bind(t)}}])}(Tt),Vt=/(\d+)(?:\.(\d+))?(?:\.(\d+))?/,Yt=function(){function t(e,i,r){p(this,t),this.major=parseInt(e||0,10),this.minor=parseInt(i||0,10),this.patch=parseInt(r||0,10)}return y(t,[{key:"compare",value:function(t){var e=this.major-t.major;return e=(e=e||this.minor-t.minor)||this.patch-t.patch}},{key:"inc",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"patch";return void 0!==this[t]&&(this[t]+=1),this}},{key:"satisfies",value:function(t,e){return this.compare(t)>=0&&(!e||this.compare(e)<0)}},{key:"toString",value:function(){return"".concat(this.major,".").concat(this.minor,".").concat(this.patch)}}],[{key:"parse",value:function(){var e=R((arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").match(Vt)||[],4),i=e[1],r=e[2],n=e[3];return void 0===i?null:new t(i,r,n)}}])}(),jt=function(t,e){return t&&e?Object.entries(t).filter((function(t){return R(t,2)[1].type===e})).reduce((function(t,e){var i=R(e,2),r=i[0],n=i[1];return t[r]=n,t}),{}):{}},Wt=(Gt={plugins:{},playbacks:[]},Kt="0.11.4",function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;p(this,t),this.playerId=i,this.playbackPlugins=D(Gt.playbacks);var r=t.registeredPlugins,n=r.core,s=r.container;this.containerPlugins=Object.values(s),this.corePlugins=Object.values(n),Array.isArray(e)||this.validateExternalPluginsType(e),this.addExternalPlugins(e)}return y(t,[{key:"groupPluginsByType",value:function(t){return Array.isArray(t)&&(t=t.reduce((function(t,e){return t[e.type]||(t[e.type]=[]),t[e.type].push(e),t}),{})),t}},{key:"removeDups",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]&&arguments[1],i=t.reduceRight((function(t,i){return t[i.prototype.name]&&e||(t[i.prototype.name]&&delete t[i.prototype.name],t[i.prototype.name]=i),t}),Object.create(null)),r=[];for(var n in i)r.unshift(i[n]);return r}},{key:"addExternalPlugins",value:function(e){var i="boolean"!=typeof e.loadExternalPluginsFirst||e.loadExternalPluginsFirst,r="boolean"!=typeof e.loadExternalPlaybacksFirst||e.loadExternalPlaybacksFirst;if((e=this.groupPluginsByType(e)).playback){var n=e.playback.filter((function(e){return t.checkVersionSupport(e),!0}));this.playbackPlugins=r?this.removeDups(n.concat(this.playbackPlugins)):this.removeDups(this.playbackPlugins.concat(n),!0)}if(e.container){var s=e.container.filter((function(e){return t.checkVersionSupport(e),!0}));this.containerPlugins=i?this.removeDups(s.concat(this.containerPlugins)):this.removeDups(this.containerPlugins.concat(s),!0)}if(e.core){var a=e.core.filter((function(e){return t.checkVersionSupport(e),!0}));this.corePlugins=i?this.removeDups(a.concat(this.corePlugins)):this.removeDups(this.corePlugins.concat(a),!0)}}},{key:"validateExternalPluginsType",value:function(t){["playback","container","core"].forEach((function(e){(t[e]||[]).forEach((function(t){var i="external "+t.type+" plugin on "+e+" array";if(t.type!==e)throw new ReferenceError(i)}))}))}}],[{key:"registeredPlaybacks",get:function(){return D(Gt.playbacks)}},{key:"registeredPlugins",get:function(){var t=Gt.plugins;return{core:jt(t,"core"),container:jt(t,"container")}}},{key:"checkVersionSupport",value:function(t){var e=t.prototype,i=e.supportedVersion,r=e.name;if(!i||!i.min)return pt.warn("Loader","missing version information for ".concat(r)),!1;var n=i.max?Yt.parse(i.max):Yt.parse(i.min).inc("minor"),s=Yt.parse(i.min);return!!Yt.parse(Kt).satisfies(s,n)||(pt.warn("Loader","unsupported plugin ".concat(r,": Clappr version ").concat(Kt," does not match required range [").concat(s,",").concat(n,")")),!1)}},{key:"registerPlugin",value:function(e){if(!e||!e.prototype.name)return pt.warn("Loader","missing information to register plugin: ".concat(e)),!1;t.checkVersionSupport(e);var i=Gt.plugins;if(!i)return!1;var r=i[e.prototype.name];return r&&pt.warn("Loader","overriding plugin entry: ".concat(e.prototype.name," - ").concat(r)),i[e.prototype.name]=e,!0}},{key:"registerPlayback",value:function(e){if(!e||!e.prototype.name)return!1;t.checkVersionSupport(e);var i=Gt.playbacks,r=i.findIndex((function(t){return t.prototype.name===e.prototype.name}));if(r>=0){var n=i[r];i.splice(r,1),pt.warn("Loader","overriding playback entry: ".concat(n.name," - ").concat(n))}return Gt.playbacks=[e].concat(D(i)),!0}},{key:"unregisterPlugin",value:function(t){if(!t)return!1;var e=Gt.plugins;return!!e[t]&&(delete e[t],!0)}},{key:"unregisterPlayback",value:function(t){if(!t)return!1;var e=Gt.playbacks,i=e.findIndex((function(e){return e.prototype.name===t}));return!(i<0||(e.splice(i,1),Gt.playbacks=e,0))}},{key:"clearPlugins",value:function(){Gt.plugins={}}},{key:"clearPlaybacks",value:function(){Gt.playbacks=[]}}])}()),zt=rt().replace(/\/[^/]+$/,""),qt=function(t){function e(t){var i;p(this,e),i=g(this,e,[t]);var r={playerId:et(""),persistConfig:!0,width:640,height:360,baseUrl:zt,allowUserInteraction:K.isMobile,includeResetStyle:!0,playback:{recycleVideo:!0}};i._options=M.extend(!0,r,t),i.options.sources=i._normalizeSources(t),i.options.chromeless||(i.options.allowUserInteraction=!0),i.options.allowUserInteraction||(i.options.disableKeyboardShortcuts=!0),i._registerOptionEventListeners(i.options.events),i._coreFactory=new Ht(i);var n=i._getParentElement(i.options);return n&&i.attachTo(n),i}return S(e,t),y(e,[{key:"loader",get:function(){return this._loader||(this._loader=new Wt(this.options.plugins||{},this.options.playerId)),this._loader},set:function(t){this._loader=t}},{key:"ended",get:function(){return this.core.activeContainer.ended}},{key:"buffering",get:function(){return this.core.activeContainer.buffering}},{key:"isReady",get:function(){return!!this._ready}},{key:"eventsMapping",get:function(){return{onReady:Et.PLAYER_READY,onResize:Et.PLAYER_RESIZE,onPlay:Et.PLAYER_PLAY,onPause:Et.PLAYER_PAUSE,onStop:Et.PLAYER_STOP,onEnded:Et.PLAYER_ENDED,onSeek:Et.PLAYER_SEEK,onError:Et.PLAYER_ERROR,onTimeUpdate:Et.PLAYER_TIMEUPDATE,onVolumeUpdate:Et.PLAYER_VOLUMEUPDATE,onSubtitleAvailable:Et.PLAYER_SUBTITLE_AVAILABLE}}},{key:"_getParentElement",value:function(t){var e=t.parentId,i=t.parent;return e?document.querySelector(e):i}},{key:"attachTo",value:function(t){return this.options.parentElement=t,this.core=this._coreFactory.create(),this._addEventListeners(),this}},{key:"_addEventListeners",value:function(){return this.core.isReady?this._onReady():this.listenToOnce(this.core,Et.CORE_READY,this._onReady),this.listenTo(this.core,Et.CORE_ACTIVE_CONTAINER_CHANGED,this._containerChanged),this.listenTo(this.core,Et.CORE_FULLSCREEN,this._onFullscreenChange),this.listenTo(this.core,Et.CORE_RESIZE,this._onResize),this}},{key:"_addContainerEventListeners",value:function(){var t=this.core.activeContainer;return t&&(this.listenTo(t,Et.CONTAINER_PLAY,this._onPlay),this.listenTo(t,Et.CONTAINER_PAUSE,this._onPause),this.listenTo(t,Et.CONTAINER_STOP,this._onStop),this.listenTo(t,Et.CONTAINER_ENDED,this._onEnded),this.listenTo(t,Et.CONTAINER_SEEK,this._onSeek),this.listenTo(t,Et.CONTAINER_ERROR,this._onError),this.listenTo(t,Et.CONTAINER_TIMEUPDATE,this._onTimeUpdate),this.listenTo(t,Et.CONTAINER_VOLUME,this._onVolumeUpdate),this.listenTo(t,Et.CONTAINER_SUBTITLE_AVAILABLE,this._onSubtitleAvailable)),this}},{key:"_registerOptionEventListeners",value:function(){var t=this,e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return Object.keys(e).length>0&&Object.keys(i).forEach((function(e){var r=t.eventsMapping[e];r&&t.off(r,i[e])})),Object.keys(e).forEach((function(i){var r=t.eventsMapping[i];if(r){var n=e[i];(n="function"==typeof n&&n)&&t.on(r,n)}})),this}},{key:"_containerChanged",value:function(){this.stopListening(),this._addEventListeners()}},{key:"_onReady",value:function(){this._ready=!0,this._addContainerEventListeners(),this.trigger(Et.PLAYER_READY)}},{key:"_onFullscreenChange",value:function(t){this.trigger(Et.PLAYER_FULLSCREEN,t)}},{key:"_onVolumeUpdate",value:function(t){this.trigger(Et.PLAYER_VOLUMEUPDATE,t)}},{key:"_onSubtitleAvailable",value:function(){this.trigger(Et.PLAYER_SUBTITLE_AVAILABLE)}},{key:"_onResize",value:function(t){this.trigger(Et.PLAYER_RESIZE,t)}},{key:"_onPlay",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.trigger(Et.PLAYER_PLAY,e)}},{key:"_onPause",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.trigger(Et.PLAYER_PAUSE,e)}},{key:"_onStop",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.trigger(Et.PLAYER_STOP,this.getCurrentTime(),t)}},{key:"_onEnded",value:function(){this.trigger(Et.PLAYER_ENDED)}},{key:"_onSeek",value:function(t){this.trigger(Et.PLAYER_SEEK,t)}},{key:"_onTimeUpdate",value:function(t){this.trigger(Et.PLAYER_TIMEUPDATE,t)}},{key:"_onError",value:function(t){this.trigger(Et.PLAYER_ERROR,t)}},{key:"_normalizeSources",value:function(t){var e=t.sources||(void 0!==t.source?[t.source]:[]);return 0===e.length?[{source:"",mimeType:""}]:e}},{key:"resize",value:function(t){return this.core.resize(t),this}},{key:"load",value:function(t,e,i){return void 0!==i&&this.configure({autoPlay:!!i}),this.core.load(t,e),this}},{key:"destroy",value:function(){return this.stopListening(),this.core.destroy(),this}},{key:"consent",value:function(t){this.core.getCurrentPlayback().consent(t)}},{key:"play",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.core.activeContainer.play(t),this}},{key:"pause",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.core.activeContainer.pause(t),this}},{key:"stop",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.core.activeContainer.stop(t),this}},{key:"seek",value:function(t){return this.core.activeContainer.seek(t),this}},{key:"seekPercentage",value:function(t){return this.core.activeContainer.seekPercentage(t),this}},{key:"mute",value:function(){return this.core.activePlayback.mute(),this}},{key:"unmute",value:function(){return this.core.activePlayback.unmute(),this}},{key:"isPlaying",value:function(){return this.core.activeContainer.isPlaying()}},{key:"isDvrEnabled",value:function(){return this.core.activeContainer.isDvrEnabled()}},{key:"isDvrInUse",value:function(){return this.core.activeContainer.isDvrInUse()}},{key:"configure",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this._registerOptionEventListeners(t.events,this.options.events),this.core.configure(t),this}},{key:"getPlugin",value:function(t){return this.core.plugins.concat(this.core.activeContainer.plugins).filter((function(e){return e.name===t}))[0]}},{key:"getCurrentTime",value:function(){return this.core.activeContainer.getCurrentTime()}},{key:"getStartTimeOffset",value:function(){return this.core.activeContainer.getStartTimeOffset()}},{key:"getDuration",value:function(){return this.core.activeContainer.getDuration()}}])}(Tt);Object.assign(qt.prototype,Mt);var Xt=function(t){function e(t){var i;return p(this,e),(i=g(this,e,[t.options])).container=t,i.enabled=!0,i.bindEvents(),i}return S(e,t),y(e,[{key:"playerError",get:function(){return this.container.playerError}},{key:"enable",value:function(){this.enabled||(this.bindEvents(),this.enabled=!0)}},{key:"disable",value:function(){this.enabled&&(this.stopListening(),this.enabled=!1)}},{key:"bindEvents",value:function(){}},{key:"destroy",value:function(){this.stopListening()}}])}(Tt);Object.assign(Xt.prototype,Mt),Xt.extend=function(t){return Q(Xt,t)},Xt.type="container";var Qt=function(t){function e(t){var i;return p(this,e),(i=g(this,e,[t.options])).core=t,i.enabled=!0,i.bindEvents(),i}return S(e,t),y(e,[{key:"playerError",get:function(){return this.core.playerError}},{key:"bindEvents",value:function(){}},{key:"enable",value:function(){this.enabled||(this.bindEvents(),this.enabled=!0)}},{key:"disable",value:function(){this.enabled&&(this.stopListening(),this.enabled=!1)}},{key:"getExternalInterface",value:function(){return{}}},{key:"destroy",value:function(){this.stopListening()}}])}(Tt);Object.assign(Qt.prototype,Mt),Qt.extend=function(t){return Q(Qt,t)},Qt.type="core";var Zt=function(t){function e(t){var i;return p(this,e),(i=g(this,e,[t.options])).container=t,i.enabled=!0,i.bindEvents(),i}return S(e,t),y(e,[{key:"playerError",get:function(){return this.container.playerError}},{key:"enable",value:function(){this.enabled||(this.bindEvents(),this.$el.show(),this.enabled=!0)}},{key:"disable",value:function(){this.stopListening(),this.$el.hide(),this.enabled=!1}},{key:"bindEvents",value:function(){}}])}(Ot);Object.assign(Zt.prototype,Mt),Zt.extend=function(t){return Q(Zt,t)},Zt.type="container";var Jt={mp4:["avc1.42E01E","avc1.58A01E","avc1.4D401E","avc1.64001E","mp4v.20.8","mp4v.20.240","mp4a.40.2"].map((function(t){return'video/mp4; codecs="'+t+', mp4a.40.2"'})),ogg:['video/ogg; codecs="theora, vorbis"','video/ogg; codecs="dirac"','video/ogg; codecs="theora, speex"'],"3gpp":['video/3gpp; codecs="mp4v.20.8, samr"'],webm:['video/webm; codecs="vp8, vorbis"'],mkv:['video/x-matroska; codecs="theora, vorbis"'],m3u8:["application/x-mpegurl"]};Jt.ogv=Jt.ogg,Jt["3gp"]=Jt["3gpp"];var te={wav:["audio/wav"],mp3:["audio/mp3",'audio/mpeg;codecs="mp3"'],aac:['audio/mp4;codecs="mp4a.40.5"'],oga:["audio/ogg"]},ee=Object.keys(te).reduce((function(t,e){return[].concat(D(t),D(te[e]))}),[]),ie={code:"unknown",message:"unknown"},re=function(t){function e(){var t;p(this,e);for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];(t=g(this,e,[].concat(r)))._destroyed=!1,t._loadStarted=!1,t._isBuffering=!1,t._playheadMoving=!1,t._playheadMovingTimer=null,t._stopped=!1,t._ccTrackId=-1,t._playheadMovingCheckEnabled=!t.options.disablePlayheadMovingCheck,t._setupSrc(t.options.src),t._playheadMovingCheckInterval=t.options.playheadMovingCheckInterval||500,t.options.playback||(t.options.playback=t.options||{}),t.options.playback.disableContextMenu=t.options.playback.disableContextMenu||t.options.disableVideoTagContextMenu,t._minDvrSize=t.isValidMinimumDVRSizeConfig?t.minimumDVRSizeConfig:60;var s,a=t.options.playback,o=a.preload||(K.isSafari?"auto":t.options.preload);return t.options.poster&&("string"==typeof t.options.poster?s=t.options.poster:"string"==typeof t.options.poster.url&&(s=t.options.poster.url)),M.extend(!0,t.el,{muted:t.options.mute,defaultMuted:t.options.mute,loop:t.options.loop,poster:s,preload:o||"metadata",crossOrigin:a.crossOrigin,"x-webkit-playsinline":a.playInline}),(a.controls||t.options.useVideoTagDefaultControls)&&t.$el.attr("controls",""),a.playInline&&t.$el.attr({playsinline:"playsinline"}),a.crossOrigin&&t.$el.attr({crossorigin:a.crossOrigin}),t.settings={default:["seekbar"]},t.settings.left=["playpause","position","duration"],t.settings.right=["fullscreen","volume","hd-indicator"],a.externalTracks&&t._setupExternalTracks(a.externalTracks),t.options.autoPlay&&t.attemptAutoPlay(),t}return S(e,t),y(e,[{key:"name",get:function(){return"html5_video"}},{key:"supportedVersion",get:function(){return{min:"0.11.4"}}},{key:"tagName",get:function(){return this.isAudioOnly?"audio":"video"}},{key:"isAudioOnly",get:function(){var t=this.options.src,i=e._mimeTypesForUrl(t,te,this.options.mimeType);return this.options.playback&&this.options.playback.audioOnly||this.options.audioOnly||ee.indexOf(i[0])>=0}},{key:"attributes",get:function(){return{"data-html5-video":""}}},{key:"events",get:function(){return{canplay:"_onCanPlay",canplaythrough:"_handleBufferingEvents",durationchange:"_onDurationChange",ended:"_onEnded",error:"_onError",loadeddata:"_onLoadedData",loadedmetadata:"_onLoadedMetadata",pause:"_onPause",playing:"_onPlaying",progress:"_onProgress",seeking:"_onSeeking",seeked:"_onSeeked",stalled:"_handleBufferingEvents",timeupdate:"_onTimeUpdate",waiting:"_onWaiting",enterpictureinpicture:"_onEnterPiP",leavepictureinpicture:"_onExitPiP"}}},{key:"ended",get:function(){return this.el.ended}},{key:"buffering",get:function(){return this._isBuffering}},{key:"isPiPActive",get:function(){return this.el===document.pictureInPictureElement}},{key:"isLive",get:function(){return this.getPlaybackType()===Ut.LIVE}},{key:"dvrEnabled",get:function(){return this.getDuration()>=this._minDvrSize&&this.isLive}},{key:"minimumDVRSizeConfig",get:function(){return this.options.playback&&this.options.playback.minimumDvrSize}},{key:"isValidMinimumDVRSizeConfig",get:function(){return void 0!==this.minimumDVRSizeConfig&&"number"==typeof this.minimumDVRSizeConfig}},{key:"sourceMedia",get:function(){return this._src}},{key:"configure",value:function(t){C(e,"configure",this)([t]),this.el.loop=!!t.loop}},{key:"attemptAutoPlay",value:function(){var t=this;this.canAutoPlay((function(e,i){i&&pt.warn(t.name,"autoplay error.",{result:e,error:i}),e&&setTimeout((function(){return!t._destroyed&&t.play()}),0)}))}},{key:"canAutoPlay",value:function(t){if(this.options.disableCanAutoPlay)t(!0,null);else{var e={timeout:this.options.autoPlayTimeout||500,inline:this.options.playback.playInline||!1,muted:this.options.mute||!1};K.isMobile&&at.options.recycleVideo&&(e.element=this.el),st(t,e)}}},{key:"_setupExternalTracks",value:function(t){this._externalTracks=t.map((function(t){return{kind:t.kind||"subtitles",label:t.label,lang:t.lang,src:t.src}}))}},{key:"load",value:function(t){this._setupSrc(t)}},{key:"_setupSrc",value:function(t){this.el.src!==t&&(this._ccIsSetup=!1,this.el.src=t,this._src=this.el.src)}},{key:"_onLoadedMetadata",value:function(t){this._handleBufferingEvents(),this.trigger(Et.PLAYBACK_LOADEDMETADATA,{duration:t.target.duration,data:t}),this._updateSettings();var e=void 0===this._options.autoSeekFromUrl||this._options.autoSeekFromUrl;this.getPlaybackType()!==Ut.LIVE&&e&&this._checkInitialSeek()}},{key:"_onDurationChange",value:function(){this._updateSettings(),this._onTimeUpdate(),this._onProgress()}},{key:"_updateSettings",value:function(){this.getPlaybackType()===Ut.VOD||this.getPlaybackType()===Ut.AOD?this.settings.left=["playpause","position","duration"]:this.settings.left=["playstop"],this.settings.seekEnabled=this.isSeekEnabled(),this.trigger(Et.PLAYBACK_SETTINGSUPDATE)}},{key:"isSeekEnabled",value:function(){return isFinite(this.getDuration())}},{key:"getPlaybackType",value:function(){var t="audio"===this.tagName?Ut.AOD:Ut.VOD;return[0,void 0,1/0].indexOf(this.el.duration)>=0?Ut.LIVE:t}},{key:"isHighDefinitionInUse",value:function(){return!1}},{key:"consent",value:function(t){var i=this;if(this.isPlaying()||this.el._consented)C(e,"consent",this)([t]);else{var r=function(){i.el.removeEventListener("loadedmetadata",r,!1),i.el.removeEventListener("error",r,!1),i.el._consented=!0,C(e,"consent",i)([t])};this.el.addEventListener("loadedmetadata",r,!1),this.el.addEventListener("error",r,!1),this.el.load()}}},{key:"play",value:function(){var t=this;this.trigger(Et.PLAYBACK_PLAY_INTENT),this._stopped=!1,this._setupSrc(this._src),this._handleBufferingEvents();var e=this.el.play();return e&&e.catch&&e.catch((function(e){return pt.warn(t.name,"HTML5 play failed",e)})),e}},{key:"pause",value:function(){this.el.pause()}},{key:"stop",value:function(){this.pause(),this._stopped=!0,this.el.removeAttribute("src"),this.el.load(),this._stopPlayheadMovingChecks(),this._handleBufferingEvents(),this.trigger(Et.PLAYBACK_STOP)}},{key:"volume",value:function(t){0===t?(this.$el.attr({muted:"true"}),this.el.muted=!0):(this.$el.attr({muted:null}),this.el.muted=!1,this.el.volume=t/100)}},{key:"mute",value:function(){this.el.muted=!0}},{key:"unmute",value:function(){this.el.muted=!1}},{key:"isMuted",value:function(){return!0===this.el.muted||0===this.el.volume}},{key:"isPlaying",value:function(){return!this.el.paused&&!this.el.ended}},{key:"isReady",get:function(){return this._isReadyState}},{key:"_startPlayheadMovingChecks",value:function(){null===this._playheadMovingTimer&&this._playheadMovingCheckEnabled&&(this._playheadMovingTimeOnCheck=null,this._determineIfPlayheadMoving(),this._playheadMovingTimer=setInterval(this._determineIfPlayheadMoving.bind(this),this._playheadMovingCheckInterval))}},{key:"_stopPlayheadMovingChecks",value:function(){null!==this._playheadMovingTimer&&(clearInterval(this._playheadMovingTimer),this._playheadMovingTimer=null,this._playheadMoving=!1)}},{key:"_determineIfPlayheadMoving",value:function(){var t=this._playheadMovingTimeOnCheck,e=this.el.currentTime;this._playheadMoving=t!==e,this._playheadMovingTimeOnCheck=e,this._handleBufferingEvents()}},{key:"_onWaiting",value:function(){this._loadStarted=!0,this._handleBufferingEvents()}},{key:"_onLoadedData",value:function(){this._loadStarted=!0,this._handleBufferingEvents()}},{key:"_onCanPlay",value:function(){this._handleBufferingEvents()}},{key:"_onPlaying",value:function(){this._checkForClosedCaptions(),this._startPlayheadMovingChecks(),this._handleBufferingEvents(),this.trigger(Et.PLAYBACK_PLAY)}},{key:"_onPause",value:function(){this.dvrEnabled&&this._updateDvr(!0),this._stopPlayheadMovingChecks(),this._handleBufferingEvents(),this.trigger(Et.PLAYBACK_PAUSE)}},{key:"_onSeeking",value:function(){var t=this.getCurrentTime();this.dvrEnabled&&this._updateDvr(t<this.getDuration()-3),this.trigger(Et.PLAYBACK_SEEK,t),this._handleBufferingEvents()}},{key:"_onSeeked",value:function(){this._handleBufferingEvents(),this.trigger(Et.PLAYBACK_SEEKED)}},{key:"_onEnded",value:function(){this._handleBufferingEvents(),this.trigger(Et.PLAYBACK_ENDED,this.name)}},{key:"_onEnterPiP",value:function(){this.trigger(Et.PLAYBACK_PIP_ENTER,this.name)}},{key:"_onExitPiP",value:function(){this.trigger(Et.PLAYBACK_PIP_EXIT,this.name)}},{key:"enterPiP",value:function(){var t=this;this.el.requestPictureInPicture().then((function(){pt.info(t.name,"enter PIP success")})).catch((function(e){pt.warn(t.name,"enter PIP failed",e)}))}},{key:"exitPiP",value:function(){var t=this;document.exitPictureInPicture().then((function(){pt.info(t.name,"exit PIP success")})).catch((function(e){pt.warn(t.name,"exit PIP failed",e)}))}},{key:"_handleBufferingEvents",value:function(){var t=this._loadStarted&&!this.el.ended&&!this._stopped,e=this.el.readyState<this.el.HAVE_FUTURE_DATA,i=!this.el.ended&&!this.el.paused&&!this._playheadMoving,r=t&&e;this._playheadMovingCheckEnabled&&(r=r||t&&i),this._isBuffering!==r&&(this._isBuffering=r,r?this.trigger(Et.PLAYBACK_BUFFERING,this.name):this.trigger(Et.PLAYBACK_BUFFERFULL,this.name))}},{key:"_onError",value:function(){var t=this.el.error||ie,e=t.code,i=t.message,r=e===ie.code,n=this.createError({code:e,description:i,raw:this.el.error,level:r?xt.Levels.WARN:xt.Levels.FATAL});r?pt.warn(this.name,"HTML5 unknown error: ",n):this.trigger(Et.PLAYBACK_ERROR,n)}},{key:"destroy",value:function(){this._destroyed=!0,this._stopPlayheadMovingChecks(),this.handleTextTrackChange&&this.el.textTracks.removeEventListener("change",this.handleTextTrackChange),this.$el.off("contextmenu"),C(e,"destroy",this)([]),this.el.removeAttribute("src"),this.el.load(),this._src=null,at.garbage(this.el)}},{key:"_updateDvr",value:function(t){this.trigger(Et.PLAYBACK_DVR,t),this.trigger(Et.PLAYBACK_STATS_ADD,{dvr:t})}},{key:"seek",value:function(t){t<0&&(pt.warn("Attempt to seek to a negative time. Resetting to live point. Use seekToLivePoint() to seek to the live point."),t=this.getDuration()),t+=this.el.seekable.start(0),this.el.currentTime=t}},{key:"seekPercentage",value:function(t){var e=this.el.duration*(t/100);this.seek(e)}},{key:"_checkInitialSeek",value:function(){var t=tt();0!==t&&this.seek(t)}},{key:"getCurrentTime",value:function(){return this.el.currentTime}},{key:"getDuration",value:function(){if(this.isLive){if(this.el.seekable.length>0)return this.el.seekable.end(0)-this.el.seekable.start(0);this._scheduleUpdateSettingsCheck()}return this.el.duration}},{key:"_scheduleUpdateSettingsCheck",value:function(){var t=this;this._updateSettingsCheckInFlight||(this._updateSettingsCheckInFlight=setTimeout((function(){t._updateSettings(),t._updateSettingsCheckInFlight=null}),1e3))}},{key:"_onTimeUpdate",value:function(){var t=this.isLive?this.getDuration():this.el.duration;this.trigger(Et.PLAYBACK_TIMEUPDATE,{current:this.el.currentTime,total:t},this.name)}},{key:"_onProgress",value:function(){if(this.el.buffered.length){for(var t=[],e=0,i=0;i<this.el.buffered.length;i++)t=[].concat(D(t),[{start:this.el.buffered.start(i),end:this.el.buffered.end(i)}]),this.el.currentTime>=t[i].start&&this.el.currentTime<=t[i].end&&(e=i);var r={start:t[e].start,current:t[e].end,total:this.el.duration};this.trigger(Et.PLAYBACK_PROGRESS,r,t)}}},{key:"_typeFor",value:function(t){var i=e._mimeTypesForUrl(t,Jt,this.options.mimeType);return 0===i.length&&(i=e._mimeTypesForUrl(t,te,this.options.mimeType)),(i[0]||"").split(";")[0]}},{key:"_ready",value:function(){this._isReadyState||(this._isReadyState=!0,this.trigger(Et.PLAYBACK_READY,this.name))}},{key:"_checkForClosedCaptions",value:function(){if(this.isHTML5Video&&!this._ccIsSetup){if(this.hasClosedCaptionsTracks){this.trigger(Et.PLAYBACK_SUBTITLE_AVAILABLE);var t=this.closedCaptionsTrackId;this.closedCaptionsTrackId=t,this.handleTextTrackChange=this._handleTextTrackChange.bind(this),this.el.textTracks.addEventListener("change",this.handleTextTrackChange)}this._ccIsSetup=!0}}},{key:"_handleTextTrackChange",value:function(){var t=this.closedCaptionsTracks.find((function(t){return"showing"===t.track.mode}))||{id:-1};this._ccTrackId!==t.id&&(this._ccTrackId=t.id,this.trigger(Et.PLAYBACK_SUBTITLE_CHANGED,{id:t.id}))}},{key:"isHTML5Video",get:function(){return this.name===e.prototype.name}},{key:"closedCaptionsTracks",get:function(){var t=0;return(this.el.textTracks?Array.from(this.el.textTracks):[]).filter((function(t){return"subtitles"===t.kind||"captions"===t.kind})).map((function(e){return{id:t++,name:e.label,track:e}}))}},{key:"closedCaptionsTrackId",get:function(){return this._ccTrackId},set:function(t){if(it(t)){var e,i=this.closedCaptionsTracks;if(-1!==t){if(!(e=i.find((function(e){return e.id===t}))))return;if("showing"===e.track.mode)return}i.filter((function(t){return"hidden"!==t.track.mode})).forEach((function(t){return t.track.mode="hidden"})),e&&(e.track.mode="showing"),this._ccTrackId=t,this.trigger(Et.PLAYBACK_SUBTITLE_CHANGED,{id:t})}}},{key:"template",get:function(){return wt('<% for (var i = 0; i < tracks.length; i++) { %>\n <track data-html5-video-track="<%= i %>" kind="<%= tracks[i].kind %>" label="<%= tracks[i].label %>" srclang="<%= tracks[i].lang %>" src="<%= tracks[i].src %>">\n<% }; %>\n')}},{key:"render",value:function(){this.options.playback.disableContextMenu&&this.$el.on("contextmenu",(function(){return!1})),this._externalTracks&&this._externalTracks.length>0&&this.$el.html(this.template({tracks:this._externalTracks})),this._ready();var t=It("[data-html5-video] {\n position: absolute;\n height: 100%;\n width: 100%;\n display: block; }\n".toString(),{baseUrl:this.options.baseUrl});return this.$el.append(t[0]),this}}])}(Ut);re._mimeTypesForUrl=function(){var t=arguments.length>1?arguments[1]:void 0,e=arguments.length>2?arguments[2]:void 0,i=((arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").split("?")[0].match(/.*\.(.*)$/)||[])[1],r=e||i&&t[i.toLowerCase()]||[];return r.constructor===Array?r:[r]},re._canPlay=function(t,e,i,r){var n=re._mimeTypesForUrl(i,e,r),s=document.createElement(t);return!!n.filter((function(t){return!!s.canPlayType(t).replace(/no/,"")}))[0]},re.canPlay=function(t,e){return re._canPlay("audio",te,t,e)||re._canPlay("video",Jt,t,e)};var ne=function(t){function e(){return p(this,e),g(this,e,arguments)}return S(e,t),y(e,[{key:"name",get:function(){return"html5_audio"}},{key:"supportedVersion",get:function(){return{min:"0.11.4"}}},{key:"tagName",get:function(){return"audio"}},{key:"isAudioOnly",get:function(){return!0}},{key:"updateSettings",value:function(){this.settings.left=["playpause","position","duration"],this.settings.seekEnabled=this.isSeekEnabled(),this.trigger(Et.PLAYBACK_SETTINGSUPDATE)}},{key:"getPlaybackType",value:function(){return Ut.AOD}}])}(re);ne.canPlay=function(t,e){return re._canPlay("audio",{wav:["audio/wav"],mp3:["audio/mp3",'audio/mpeg;codecs="mp3"'],aac:['audio/mp4;codecs="mp4a.40.5"'],oga:["audio/ogg"]},t,e)};var se=function(t){function e(t){var i;return p(this,e),(i=g(this,e,[t])).el.src=t.src,i}return S(e,t),y(e,[{key:"name",get:function(){return"html_img"}},{key:"supportedVersion",get:function(){return{min:"0.11.4"}}},{key:"tagName",get:function(){return"img"}},{key:"attributes",get:function(){return{"data-html-img":""}}},{key:"events",get:function(){return{load:"_onLoad",abort:"_onError",error:"_onError"}}},{key:"getPlaybackType",value:function(){return Ut.NO_OP}},{key:"render",value:function(){var t=It("[data-html-img] {\n max-width: 100%;\n max-height: 100%; }\n".toString(),{baseUrl:this.options.baseUrl});return this.$el.append(t[0]),this.trigger(Et.PLAYBACK_READY,this.name),this}},{key:"_onLoad",value:function(){this.trigger(Et.PLAYBACK_ENDED,this.name)}},{key:"_onError",value:function(t){var e="error"===t.type?"load error":"loading aborted";this.trigger(Et.PLAYBACK_ERROR,{message:e},this.name)}}])}(Ut);se.canPlay=function(t){return/\.(png|jpg|jpeg|gif|bmp|tiff|pgm|pnm|webp)(|\?.*)$/i.test(t)};var ae=function(t){function e(){var t;p(this,e);for(var i=arguments.length,r=new Array(i),n=0;n<i;n++)r[n]=arguments[n];return(t=g(this,e,[].concat(r)))._noiseFrameNum=-1,t}return S(e,t),y(e,[{key:"name",get:function(){return"no_op"}},{key:"supportedVersion",get:function(){return{min:"0.11.4"}}},{key:"template",get:function(){return wt("<canvas data-no-op-canvas></canvas>\n<p data-no-op-msg><%=message%></p><p>\n</p>")}},{key:"attributes",get:function(){return{"data-no-op":""}}},{key:"render",value:function(){var t=this.options.playbackNotSupportedMessage||this.i18n.t("playback_not_supported"),e=It("[data-no-op] {\n position: absolute;\n height: 100%;\n width: 100%;\n text-align: center; }\n\n[data-no-op] p[data-no-op-msg] {\n position: absolute;\n text-align: center;\n font-size: 25px;\n left: 0;\n right: 0;\n color: white;\n padding: 10px;\n /* center vertically */\n top: 50%;\n transform: translateY(-50%);\n max-height: 100%;\n overflow: auto; }\n\n[data-no-op] canvas[data-no-op-canvas] {\n background-color: #777;\n height: 100%;\n width: 100%; }\n".toString(),{baseUrl:this.options.baseUrl});this.$el.append(e[0]),this.$el.html(this.template({message:t})),this.trigger(Et.PLAYBACK_READY,this.name);var i=!(!this.options.poster||!this.options.poster.showForNoOp);return!this.options.autoPlay&&i||this._animate(),this}},{key:"_noise",value:function(){if(this._noiseFrameNum=(this._noiseFrameNum+1)%5,!this._noiseFrameNum){var t,e=this.context.createImageData(this.context.canvas.width,this.context.canvas.height);try{t=new Uint32Array(e.data.buffer)}catch(n){t=new Uint32Array(this.context.canvas.width*this.context.canvas.height*4);for(var i=e.data,r=0;r<i.length;r++)t[r]=i[r]}for(var n=t.length,s=6*Math.random()+4,a=0,o=0,l=0;l<n;){if(a<0)a=s*Math.random(),o=255*Math.pow(Math.random(),.4)<<24;a-=1,t[l++]=o}this.context.putImageData(e,0,0)}}},{key:"_loop",value:function(){var t=this;this._stop||(this._noise(),this._animationHandle=z((function(){return t._loop()})))}},{key:"destroy",value:function(){this._animationHandle&&(q(this._animationHandle),this._stop=!0)}},{key:"_animate",value:function(){this.canvas=this.$el.find("canvas[data-no-op-canvas]")[0],this.context=this.canvas.getContext("2d"),this._loop()}}])}(Ut);ae.canPlay=function(t){return!0};var oe=function(t){function e(t){var i;return p(this,e),(i=g(this,e,[t]))._initializeMessages(),i}return S(e,t),y(e,[{key:"name",get:function(){return"strings"}},{key:"supportedVersion",get:function(){return{min:"0.11.4"}}},{key:"t",value:function(t){var e=this._language(),i=this._messages.en;return(e&&this._messages[e]||i)[t]||i[t]||t}},{key:"_language",value:function(){return this.core.options.language||nt()}},{key:"_initializeMessages",value:function(){this._messages=M.extend(!0,{en:{live:"live",back_to_live:"back to live",disabled:"Disabled",playback_not_supported:"Your browser does not support the playback of this video. Please try using a different browser.",default_error_title:"Could not play video.",default_error_message:"There was a problem trying to load the video."},de:{live:"Live",back_to_live:"Zurück zum Live-Video",disabled:"Deaktiviert",playback_not_supported:"Ihr Browser unterstützt das Playback Verfahren nicht. Bitte vesuchen Sie es mit einem anderen Browser.",default_error_title:"Video kann nicht abgespielt werden",default_error_message:"Es gab ein Problem beim Laden des Videos"},pt:{live:"ao vivo",back_to_live:"voltar para o ao vivo",disabled:"Desativado",playback_not_supported:"Seu navegador não suporta a reprodução deste video. Por favor, tente usar um navegador diferente.",default_error_title:"Não foi possível reproduzir o vídeo.",default_error_message:"Ocorreu um problema ao tentar carregar o vídeo."},es_am:{live:"vivo",back_to_live:"volver en vivo",disabled:"No disponible",playback_not_supported:"Su navegador no soporta la reproducción de este video. Por favor, utilice un navegador diferente.",default_error_title:"No se puede reproducir el video.",default_error_message:"Se ha producido un error al cargar el video."},es:{live:"en directo",back_to_live:"volver al directo",disabled:"No disponible",playback_not_supported:"Este navegador no es compatible para reproducir este vídeo. Utilice un navegador diferente.",default_error_title:"No se puede reproducir el vídeo.",default_error_message:"Se ha producido un problema al cargar el vídeo."},ru:{live:"прямой эфир",back_to_live:"к прямому эфиру",disabled:"Отключено",playback_not_supported:"Ваш браузер не поддерживает воспроизведение этого видео. Пожалуйста, попробуйте другой браузер."},bg:{live:"на живо",back_to_live:"Върни на живо",disabled:"Изключено",playback_not_supported:"Вашият браузър не поддържа възпроизвеждането на това видео. Моля, пробвайте с друг браузър.",default_error_title:"Видеото не може да се възпроизведе.",default_error_message:"Възникна проблем при зареждането на видеото."},fr:{live:"en direct",back_to_live:"retour au direct",disabled:"Désactivé",playback_not_supported:"Votre navigateur ne supporte pas la lecture de cette vidéo. Merci de tenter sur un autre navigateur.",default_error_title:"Impossible de lire la vidéo.",default_error_message:"Un problème est survenu lors du chargement de la vidéo."},tr:{live:"canlı",back_to_live:"canlı yayına dön",disabled:"Engelli",playback_not_supported:"Tarayıcınız bu videoyu oynatma desteğine sahip değil. Lütfen farklı bir tarayıcı ile deneyin."},et:{live:"Otseülekanne",back_to_live:"Tagasi otseülekande juurde",disabled:"Keelatud",playback_not_supported:"Teie brauser ei toeta selle video taasesitust. Proovige kasutada muud brauserit."},ar:{live:"مباشر",back_to_live:"الرجوع إلى المباشر",disabled:"معطّل",playback_not_supported:"المتصفح الذي تستخدمه لا يدعم تشغيل هذا الفيديو. الرجاء إستخدام متصفح آخر.",default_error_title:"غير قادر الى التشغيل.",default_error_message:"حدثت مشكلة أثناء تحميل الفيديو."},zh:{live:"直播",back_to_live:"返回直播",disabled:"已禁用",playback_not_supported:"您的浏览器不支持该视频的播放。请尝试使用另一个浏览器。",default_error_title:"无法播放视频。",default_error_message:"在尝试加载视频时出现了问题。"}},this.core.options.strings||{}),this._messages["de-DE"]=this._messages.de,this._messages["pt-BR"]=this._messages.pt,this._messages["en-US"]=this._messages.en,this._messages["bg-BG"]=this._messages.bg,this._messages["es-419"]=this._messages.es_am,this._messages["es-ES"]=this._messages.es,this._messages["fr-FR"]=this._messages.fr,this._messages["tr-TR"]=this._messages.tr,this._messages["et-EE"]=this._messages.et,this._messages["ar-IQ"]=this._messages.ar,this._messages["zh-CN"]=this._messages.zh}}])}(Qt),le=function(t){function e(){return p(this,e),g(this,e,arguments)}return S(e,t),y(e,[{key:"name",get:function(){return"sources"}},{key:"supportedVersion",get:function(){return{min:"0.11.4"}}},{key:"bindEvents",value:function(){this.listenTo(this.core,Et.CORE_CONTAINERS_CREATED,this.onContainersCreated)}},{key:"onContainersCreated",value:function(){var t=this.core.containers.filter((function(t){return"no_op"!==t.playback.name}))[0]||this.core.containers[0];t&&this.core.containers.forEach((function(e){e!==t&&e.destroy()}))}}])}(Qt);function ce(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}Wt.registerPlugin(oe),Wt.registerPlugin(le),Wt.registerPlayback(ae),Wt.registerPlayback(se),Wt.registerPlayback(ne),Wt.registerPlayback(re);var he,ue,de,fe,ge,pe={exports:{}};he=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,ue=/^(?=([^\/?#]*))\1([^]*)$/,de=/(?:\/|^)\.(?=\/)/g,fe=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,pe.exports=ge={buildAbsoluteURL:function(t,e,i){if(i=i||{},t=t.trim(),!(e=e.trim())){if(!i.alwaysNormalize)return t;var r=ge.parseURL(t);if(!r)throw new Error("Error trying to parse base URL.");return r.path=ge.normalizePath(r.path),ge.buildURLFromParts(r)}var n=ge.parseURL(e);if(!n)throw new Error("Error trying to parse relative URL.");if(n.scheme)return i.alwaysNormalize?(n.path=ge.normalizePath(n.path),ge.buildURLFromParts(n)):e;var s=ge.parseURL(t);if(!s)throw new Error("Error trying to parse base URL.");if(!s.netLoc&&s.path&&"/"!==s.path[0]){var a=ue.exec(s.path);s.netLoc=a[1],s.path=a[2]}s.netLoc&&!s.path&&(s.path="/");var o={scheme:s.scheme,netLoc:n.netLoc,path:null,params:n.params,query:n.query,fragment:n.fragment};if(!n.netLoc&&(o.netLoc=s.netLoc,"/"!==n.path[0]))if(n.path){var l=s.path,c=l.substring(0,l.lastIndexOf("/")+1)+n.path;o.path=ge.normalizePath(c)}else o.path=s.path,n.params||(o.params=s.params,n.query||(o.query=s.query));return null===o.path&&(o.path=i.alwaysNormalize?ge.normalizePath(n.path):n.path),ge.buildURLFromParts(o)},parseURL:function(t){var e=he.exec(t);return e?{scheme:e[1]||"",netLoc:e[2]||"",path:e[3]||"",params:e[4]||"",query:e[5]||"",fragment:e[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(de,"");t.length!==(t=t.replace(fe,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}};var me=pe.exports;function ye(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),i.push.apply(i,r)}return i}function ve(t){for(var e=1;e<arguments.length;e++){var i=null!=arguments[e]?arguments[e]:{};e%2?ye(Object(i),!0).forEach((function(e){Ee(t,e,i[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):ye(Object(i)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))}))}return t}function Ae(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var r=i.call(t,e||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}function Ee(t,e,i){return(e=Ae(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function Te(){return Te=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var r in i)Object.prototype.hasOwnProperty.call(i,r)&&(t[r]=i[r])}return t},Te.apply(this,arguments)}const Se=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},be=Number.isSafeInteger||function(t){return"number"==typeof t&&Math.abs(t)<=ke},ke=Number.MAX_SAFE_INTEGER||9007199254740991;let _e=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached",t.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",t}({}),Le=function(t){return t.NETWORK_ERROR="networkError",t.MEDIA_ERROR="mediaError",t.KEY_SYSTEM_ERROR="keySystemError",t.MUX_ERROR="muxError",t.OTHER_ERROR="otherError",t}({}),Re=function(t){return t.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",t.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",t.KEY_SYSTEM_NO_SESSION="keySystemNoSession",t.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",t.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",t.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",t.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",t.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",t.MANIFEST_LOAD_ERROR="manifestLoadError",t.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",t.MANIFEST_PARSING_ERROR="manifestParsingError",t.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",t.LEVEL_EMPTY_ERROR="levelEmptyError",t.LEVEL_LOAD_ERROR="levelLoadError",t.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",t.LEVEL_PARSING_ERROR="levelParsingError",t.LEVEL_SWITCH_ERROR="levelSwitchError",t.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",t.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",t.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",t.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",t.FRAG_LOAD_ERROR="fragLoadError",t.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",t.FRAG_DECRYPT_ERROR="fragDecryptError",t.FRAG_PARSING_ERROR="fragParsingError",t.FRAG_GAP="fragGap",t.REMUX_ALLOC_ERROR="remuxAllocError",t.KEY_LOAD_ERROR="keyLoadError",t.KEY_LOAD_TIMEOUT="keyLoadTimeOut",t.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",t.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",t.BUFFER_APPEND_ERROR="bufferAppendError",t.BUFFER_APPENDING_ERROR="bufferAppendingError",t.BUFFER_STALLED_ERROR="bufferStalledError",t.BUFFER_FULL_ERROR="bufferFullError",t.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",t.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.UNKNOWN="unknown",t}({});const Ce=function(){},De={trace:Ce,debug:Ce,log:Ce,warn:Ce,info:Ce,error:Ce};let we=De;function Ie(t,...e){e.forEach((function(e){we[e]=t[e]?t[e].bind(t):function(t){const e=self.console[t];return e?e.bind(self.console,`[${t}] >`):Ce}(e)}))}const Pe=we,Oe=/^(\d+)x(\d+)$/,xe=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Me{constructor(t){"string"==typeof t&&(t=Me.parseAttrList(t)),Te(this,t)}get clientAttrs(){return Object.keys(this).filter((t=>"X-"===t.substring(0,2)))}decimalInteger(t){const e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e}hexadecimalInteger(t){if(this[t]){let e=(this[t]||"0x").slice(2);e=(1&e.length?"0":"")+e;const i=new Uint8Array(e.length/2);for(let t=0;t<e.length/2;t++)i[t]=parseInt(e.slice(2*t,2*t+2),16);return i}return null}hexadecimalIntegerAsNumber(t){const e=parseInt(this[t],16);return e>Number.MAX_SAFE_INTEGER?1/0:e}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,e){const i=this[t];return i?parseFloat(i):e}enumeratedString(t){return this[t]}bool(t){return"YES"===this[t]}decimalResolution(t){const e=Oe.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t){let e;const i={};for(xe.lastIndex=0;null!==(e=xe.exec(t));){let t=e[2];0===t.indexOf('"')&&t.lastIndexOf('"')===t.length-1&&(t=t.slice(1,-1));i[e[1].trim()]=t}return i}}function Fe(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t}class Ne{constructor(t,e){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,e){const i=e.attr;for(const e in i)if(Object.prototype.hasOwnProperty.call(t,e)&&t[e]!==i[e]){Pe.warn(`DATERANGE tag attribute: "${e}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=e;break}t=Te(new Me({}),i,t)}if(this.attr=t,this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){const t=new Date(this.attr["END-DATE"]);Se(t.getTime())&&(this._endDate=t)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get startDate(){return this._startDate}get endDate(){if(this._endDate)return this._endDate;const t=this.duration;return null!==t?new Date(this._startDate.getTime()+1e3*t):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(Se(t))return t}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isValid(){return!!this.id&&!this._badValueForSameId&&Se(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class Ue{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var Be="audio",$e="video",Ge="audiovideo";class Ke{constructor(t){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[Be]:null,[$e]:null,[Ge]:null},this.baseurl=t}setByteRange(t,e){const i=t.split("@",2);let r;r=1===i.length?(null==e?void 0:e.byteRangeEndOffset)||0:parseInt(i[1]),this._byteRange=[r,parseInt(i[0])+r]}get byteRange(){return this._byteRange?this._byteRange:[]}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=me.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}}class He extends Ke{constructor(t,e){super(e),this._decryptdata=null,this.rawProgramDateTime=null,this.programDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.stats=new Ue,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=t}get decryptdata(){const{levelkeys:t}=this;if(!t&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const t=this.levelkeys.identity;if(t)this._decryptdata=t.getDecryptData(this.sn);else{const t=Object.keys(this.levelkeys);if(1===t.length)return this._decryptdata=this.levelkeys[t[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;if(!Se(this.programDateTime))return null;const t=Se(this.duration)?this.duration:0;return this.programDateTime+1e3*t}get encrypted(){var t;if(null!=(t=this._decryptdata)&&t.encrypted)return!0;if(this.levelkeys){const t=Object.keys(this.levelkeys),e=t.length;if(e>1||1===e&&this.levelkeys[t[0]].encrypted)return!0}return!1}setKeyFormat(t){if(this.levelkeys){const e=this.levelkeys[t];e&&!this._decryptdata&&(this._decryptdata=e.getDecryptData(this.sn))}}abortRequests(){var t,e;null==(t=this.loader)||t.abort(),null==(e=this.keyLoader)||e.abort()}setElementaryStreamInfo(t,e,i,r,n,s=!1){const{elementaryStreams:a}=this,o=a[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,i),o.startDTS=Math.min(o.startDTS,r),o.endDTS=Math.max(o.endDTS,n)):a[t]={startPTS:e,endPTS:i,startDTS:r,endDTS:n,partial:s}}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[Be]=null,t[$e]=null,t[Ge]=null}}class Ve extends Ke{constructor(t,e,i,r,n){super(i),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.stats=new Ue,this.duration=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=e,this.index=r;const s=t.enumeratedString("BYTERANGE");s&&this.setByteRange(s,n),n&&(this.fragOffset=n.fragOffset+n.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:t}=this;return!!(t.audio||t.video||t.audiovideo)}}class Ye{constructor(t){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t}reloaded(t){if(!t)return this.advanced=!0,void(this.updated=!0);const e=this.lastPartSn-t.lastPartSn,i=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!i||!!e||!this.live,this.advanced=this.endSN>t.endSN||e>0||0===e&&i>0,this.updated||this.advanced?this.misses=Math.floor(.6*t.misses):this.misses=t.misses+1,this.availabilityDelay=t.availabilityDelay}get hasProgramDateTime(){return!!this.fragments.length&&Se(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const t=this.driftEndTime-this.driftStartTime;if(t>0){return 1e3*(this.driftEnd-this.driftStart)/t}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var t;return null!=(t=this.fragments)&&t.length?this.fragments[this.fragments.length-1].end:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].index:-1}get lastPartSn(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}function je(t){return Uint8Array.from(atob(t),(t=>t.charCodeAt(0)))}function We(t){const e=t.split(":");let i=null;if("data"===e[0]&&2===e.length){const t=e[1].split(";"),r=t[t.length-1].split(",");if(2===r.length){const e="base64"===r[0],n=r[1];e?(t.splice(-1,1),i=je(n)):i=function(t){const e=ze(t).subarray(0,16),i=new Uint8Array(16);return i.set(e,16-e.length),i}(n)}}return i}function ze(t){return Uint8Array.from(unescape(encodeURIComponent(t)),(t=>t.charCodeAt(0)))}const qe="undefined"!=typeof self?self:void 0;var Xe={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Qe="org.w3.clearkey",Ze="com.apple.streamingkeydelivery",Je="com.microsoft.playready",ti="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function ei(t){switch(t){case Ze:return Xe.FAIRPLAY;case Je:return Xe.PLAYREADY;case ti:return Xe.WIDEVINE;case Qe:return Xe.CLEARKEY}}var ii="edef8ba979d64acea3c827dcd51d21ed";function ri(t){switch(t){case Xe.FAIRPLAY:return Ze;case Xe.PLAYREADY:return Je;case Xe.WIDEVINE:return ti;case Xe.CLEARKEY:return Qe}}function ni(t){const{drmSystems:e,widevineLicenseUrl:i}=t,r=e?[Xe.FAIRPLAY,Xe.WIDEVINE,Xe.PLAYREADY,Xe.CLEARKEY].filter((t=>!!e[t])):[];return!r[Xe.WIDEVINE]&&i&&r.push(Xe.WIDEVINE),r}const si=null!=qe&&null!=(ai=qe.navigator)&&ai.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var ai;function oi(t,e,i){return Uint8Array.prototype.slice?t.slice(e,i):new Uint8Array(Array.prototype.slice.call(t,e,i))}const li=(t,e)=>e+10<=t.length&&73===t[e]&&68===t[e+1]&&51===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128,ci=(t,e)=>e+10<=t.length&&51===t[e]&&68===t[e+1]&&73===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128,hi=(t,e)=>{const i=e;let r=0;for(;li(t,e);){r+=10;r+=ui(t,e+6),ci(t,e+10)&&(r+=10),e+=r}if(r>0)return t.subarray(i,i+r)},ui=(t,e)=>{let i=0;return i=(127&t[e])<<21,i|=(127&t[e+1])<<14,i|=(127&t[e+2])<<7,i|=127&t[e+3],i},di=(t,e)=>li(t,e)&&ui(t,e+6)+10<=t.length-e,fi=t=>{const e=mi(t);for(let t=0;t<e.length;t++){const i=e[t];if(gi(i))return Ti(i)}},gi=t=>t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info,pi=t=>{const e=String.fromCharCode(t[0],t[1],t[2],t[3]),i=ui(t,4);return{type:e,size:i,data:t.subarray(10,10+i)}},mi=t=>{let e=0;const i=[];for(;li(t,e);){const r=ui(t,e+6);e+=10;const n=e+r;for(;e+8<n;){const r=pi(t.subarray(e)),n=yi(r);n&&i.push(n),e+=r.size+10}ci(t,e)&&(e+=10)}return i},yi=t=>"PRIV"===t.type?vi(t):"W"===t.type[0]?Ei(t):Ai(t),vi=t=>{if(t.size<2)return;const e=Si(t.data,!0),i=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:i.buffer}},Ai=t=>{if(t.size<2)return;if("TXXX"===t.type){let e=1;const i=Si(t.data.subarray(e),!0);e+=i.length+1;const r=Si(t.data.subarray(e));return{key:t.type,info:i,data:r}}const e=Si(t.data.subarray(1));return{key:t.type,data:e}},Ei=t=>{if("WXXX"===t.type){if(t.size<2)return;let e=1;const i=Si(t.data.subarray(e),!0);e+=i.length+1;const r=Si(t.data.subarray(e));return{key:t.type,info:i,data:r}}const e=Si(t.data);return{key:t.type,data:e}},Ti=t=>{if(8===t.data.byteLength){const e=new Uint8Array(t.data),i=1&e[3];let r=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return r/=45,i&&(r+=47721858.84),Math.round(r)}},Si=(t,e=!1)=>{const i=ki();if(i){const r=i.decode(t);if(e){const t=r.indexOf("\0");return-1!==t?r.substring(0,t):r}return r.replace(/\0/g,"")}const r=t.length;let n,s,a,o="",l=0;for(;l<r;){if(n=t[l++],0===n&&e)return o;if(0!==n&&3!==n)switch(n>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(n);break;case 12:case 13:s=t[l++],o+=String.fromCharCode((31&n)<<6|63&s);break;case 14:s=t[l++],a=t[l++],o+=String.fromCharCode((15&n)<<12|(63&s)<<6|63&a)}}return o};let bi;function ki(){if(!navigator.userAgent.includes("PlayStation 4"))return bi||void 0===self.TextDecoder||(bi=new self.TextDecoder("utf-8")),bi}const _i=function(t){let e="";for(let i=0;i<t.length;i++){let r=t[i].toString(16);r.length<2&&(r="0"+r),e+=r}return e},Li=Math.pow(2,32)-1,Ri=[].push,Ci={video:1,audio:2,id3:3,text:4};function Di(t){return String.fromCharCode.apply(null,t)}function wi(t,e){const i=t[e]<<8|t[e+1];return i<0?65536+i:i}function Ii(t,e){const i=Oi(t,e);return i<0?4294967296+i:i}function Pi(t,e){let i=Ii(t,e);return i*=Math.pow(2,32),i+=Ii(t,e+4),i}function Oi(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function xi(t,e,i){t[e]=i>>24,t[e+1]=i>>16&255,t[e+2]=i>>8&255,t[e+3]=255&i}function Mi(t,e){const i=[];if(!e.length)return i;const r=t.byteLength;for(let n=0;n<r;){const s=Ii(t,n),a=s>1?n+s:r;if(Di(t.subarray(n+4,n+8))===e[0])if(1===e.length)i.push(t.subarray(n+8,a));else{const r=Mi(t.subarray(n+8,a),e.slice(1));r.length&&Ri.apply(i,r)}n=a}return i}function Fi(t){const e=[],i=t[0];let r=8;const n=Ii(t,r);r+=4;let s=0,a=0;0===i?(s=Ii(t,r),a=Ii(t,r+4),r+=8):(s=Pi(t,r),a=Pi(t,r+8),r+=16),r+=2;let o=t.length+a;const l=wi(t,r);r+=2;for(let i=0;i<l;i++){let i=r;const s=Ii(t,i);i+=4;const a=2147483647&s;if(1===(2147483648&s)>>>31)return Pe.warn("SIDX has hierarchical references (not supported)"),null;const l=Ii(t,i);i+=4,e.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/n,start:o,end:o+a-1}}),o+=a,i+=4,r=i}return{earliestPresentationTime:s,timescale:n,version:i,referencesCount:l,references:e}}function Ni(t){const e=[],i=Mi(t,["moov","trak"]);for(let t=0;t<i.length;t++){const r=i[t],n=Mi(r,["tkhd"])[0];if(n){let t=n[0];const i=Ii(n,0===t?12:20),s=Mi(r,["mdia","mdhd"])[0];if(s){t=s[0];const n=Ii(s,0===t?12:20),a=Mi(r,["mdia","hdlr"])[0];if(a){const t=Di(a.subarray(8,12)),s={soun:Be,vide:$e}[t];if(s){const t=Ui(Mi(r,["mdia","minf","stbl","stsd"])[0]);e[i]={timescale:n,type:s},e[s]=ve({timescale:n,id:i},t)}}}}}return Mi(t,["moov","mvex","trex"]).forEach((t=>{const i=Ii(t,4),r=e[i];r&&(r.default={duration:Ii(t,12),flags:Ii(t,20)})})),e}function Ui(t){const e=t.subarray(8),i=e.subarray(86),r=Di(e.subarray(4,8));let n=r;const s="enca"===r||"encv"===r;if(s){const t=Mi(e,[r])[0];Mi(t.subarray("enca"===r?28:78),["sinf"]).forEach((t=>{const e=Mi(t,["schm"])[0];if(e){const i=Di(e.subarray(4,8));if("cbcs"===i||"cenc"===i){const e=Mi(t,["frma"])[0];e&&(n=Di(e))}}}))}switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const t=Mi(i,["avcC"])[0];n+="."+$i(t[1])+$i(t[2])+$i(t[3]);break}case"mp4a":{const t=Mi(e,[r])[0],i=Mi(t.subarray(28),["esds"])[0];if(i&&i.length>12){let t=4;if(3!==i[t++])break;t=Bi(i,t),t+=2;const e=i[t++];if(128&e&&(t+=2),64&e&&(t+=i[t++]),4!==i[t++])break;t=Bi(i,t);const r=i[t++];if(64!==r)break;if(n+="."+$i(r),t+=12,5!==i[t++])break;t=Bi(i,t);const s=i[t++];let a=(248&s)>>3;31===a&&(a+=1+((7&s)<<3)+((224&i[t])>>5)),n+="."+a}break}case"hvc1":case"hev1":{const t=Mi(i,["hvcC"])[0],e=t[1],r=["","A","B","C"][e>>6],s=31&e,a=Ii(t,2),o=(32&e)>>5?"H":"L",l=t[12],c=t.subarray(6,12);n+="."+r+s,n+="."+a.toString(16).toUpperCase(),n+="."+o+l;let h="";for(let t=c.length;t--;){const e=c[t];if(e||h){h="."+e.toString(16).toUpperCase()+h}}n+=h;break}case"dvh1":case"dvhe":{const t=Mi(i,["dvcC"])[0],e=t[2]>>1&127,r=t[2]<<5&32|t[3]>>3&31;n+="."+Gi(e)+"."+Gi(r);break}case"vp09":{const t=Mi(i,["vpcC"])[0],e=t[4],r=t[5],s=t[6]>>4&15;n+="."+Gi(e)+"."+Gi(r)+"."+Gi(s);break}case"av01":{const t=Mi(i,["av1C"])[0],e=t[1]>>>5,r=31&t[1],s=t[2]>>>7?"H":"M",a=(64&t[2])>>6,o=(32&t[2])>>5,l=2===e&&a?o?12:10:a?10:8,c=(16&t[2])>>4,h=(8&t[2])>>3,u=(4&t[2])>>2,d=3&t[2],f=1,g=1,p=1,m=0;n+="."+e+"."+Gi(r)+s+"."+Gi(l)+"."+c+"."+h+u+d+"."+Gi(f)+"."+Gi(g)+"."+Gi(p)+"."+m;break}}return{codec:n,encrypted:s}}function Bi(t,e){const i=e+5;for(;128&t[e++]&&e<i;);return e}function $i(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function Gi(t){return(t<10?"0":"")+t}function Ki(t){const e=Mi(t,["schm"])[0];if(e){const i=Di(e.subarray(4,8));if("cbcs"===i||"cenc"===i)return Mi(t,["schi","tenc"])[0]}return Pe.error("[eme] missing 'schm' box"),null}function Hi(t){const e=Ii(t,0);let i=8;1&e&&(i+=4),4&e&&(i+=4);let r=0;const n=Ii(t,4);for(let s=0;s<n;s++){if(256&e){r+=Ii(t,i),i+=4}512&e&&(i+=4),1024&e&&(i+=4),2048&e&&(i+=4)}return r}function Vi(t,e){const i=new Uint8Array(t.length+e.length);return i.set(t),i.set(e,t.length),i}function Yi(t,e){const i=[],r=e.samples,n=e.timescale,s=e.id;let a=!1;return Mi(r,["moof"]).map((o=>{const l=o.byteOffset-8;Mi(o,["traf"]).map((o=>{const c=Mi(o,["tfdt"]).map((t=>{const e=t[0];let i=Ii(t,4);return 1===e&&(i*=Math.pow(2,32),i+=Ii(t,8)),i/n}))[0];return void 0!==c&&(t=c),Mi(o,["tfhd"]).map((c=>{const h=Ii(c,4),u=16777215&Ii(c,0);let d=0;const f=!!(16&u);let g=0;const p=!!(32&u);let m=8;h===s&&(!!(1&u)&&(m+=8),!!(2&u)&&(m+=4),!!(8&u)&&(d=Ii(c,m),m+=4),f&&(g=Ii(c,m),m+=4),p&&(m+=4),"video"===e.type&&(a=function(t){if(!t)return!1;const e=t.indexOf("."),i=e<0?t:t.substring(0,e);return"hvc1"===i||"hev1"===i||"dvh1"===i||"dvhe"===i}(e.codec)),Mi(o,["trun"]).map((s=>{const o=s[0],c=16777215&Ii(s,0),h=!!(1&c);let u=0;const f=!!(4&c),p=!!(256&c);let m=0;const y=!!(512&c);let v=0;const A=!!(1024&c),E=!!(2048&c);let T=0;const S=Ii(s,4);let b=8;h&&(u=Ii(s,b),b+=4),f&&(b+=4);let k=u+l;for(let l=0;l<S;l++){if(p?(m=Ii(s,b),b+=4):m=d,y?(v=Ii(s,b),b+=4):v=g,A&&(b+=4),E&&(T=0===o?Ii(s,b):Oi(s,b),b+=4),e.type===$e){let e=0;for(;e<v;){const s=Ii(r,k);if(k+=4,ji(a,r[k])){Wi(r.subarray(k,k+s),a?2:1,t+T/n,i)}k+=s,e+=s+4}}t+=m/n}})))}))}))})),i}function ji(t,e){if(t){const t=e>>1&63;return 39===t||40===t}return 6===(31&e)}function Wi(t,e,i,r){const n=zi(t);let s=0;s+=e;let a=0,o=0,l=0;for(;s<n.length;){a=0;do{if(s>=n.length)break;l=n[s++],a+=l}while(255===l);o=0;do{if(s>=n.length)break;l=n[s++],o+=l}while(255===l);const t=n.length-s;let e=s;if(o<t)s+=o;else if(o>t){Pe.error(`Malformed SEI payload. ${o} is too small, only ${t} bytes left to parse.`);break}if(4===a){if(181===n[e++]){const t=wi(n,e);if(e+=2,49===t){const t=Ii(n,e);if(e+=4,1195456820===t){const t=n[e++];if(3===t){const s=n[e++],o=64&s,l=o?2+3*(31&s):0,c=new Uint8Array(l);if(o){c[0]=s;for(let t=1;t<l;t++)c[t]=n[e++]}r.push({type:t,payloadType:a,pts:i,bytes:c})}}}}}else if(5===a&&o>16){const t=[];for(let i=0;i<16;i++){const r=n[e++].toString(16);t.push(1==r.length?"0"+r:r),3!==i&&5!==i&&7!==i&&9!==i||t.push("-")}const s=o-16,l=new Uint8Array(s);for(let t=0;t<s;t++)l[t]=n[e++];r.push({payloadType:a,pts:i,uuid:t.join(""),userData:Si(l),userDataBytes:l})}}}function zi(t){const e=t.byteLength,i=[];let r=1;for(;r<e-2;)0===t[r]&&0===t[r+1]&&3===t[r+2]?(i.push(r+2),r+=2):r++;if(0===i.length)return t;const n=e-i.length,s=new Uint8Array(n);let a=0;for(r=0;r<n;a++,r++)a===i[0]&&(a++,i.shift()),s[r]=t[a];return s}function qi(t,e,i){if(16!==t.byteLength)throw new RangeError("Invalid system id");let r,n,s;if(e){r=1,n=new Uint8Array(16*e.length);for(let t=0;t<e.length;t++){const i=e[t];if(16!==i.byteLength)throw new RangeError("Invalid key");n.set(i,16*t)}}else r=0,n=new Uint8Array;r>0?(s=new Uint8Array(4),e.length>0&&new DataView(s.buffer).setUint32(0,e.length,!1)):s=new Uint8Array;const a=new Uint8Array(4);return i&&i.byteLength>0&&new DataView(a.buffer).setUint32(0,i.byteLength,!1),function(t,...e){const i=e.length;let r=8,n=i;for(;n--;)r+=e[n].byteLength;const s=new Uint8Array(r);for(s[0]=r>>24&255,s[1]=r>>16&255,s[2]=r>>8&255,s[3]=255&r,s.set(t,4),n=0,r=8;n<i;n++)s.set(e[n],r),r+=e[n].byteLength;return s}([112,115,115,104],new Uint8Array([r,0,0,0]),t,s,n,a,i||new Uint8Array)}let Xi={};class Qi{static clearKeyUriToKeyIdMap(){Xi={}}constructor(t,e,i,r=[1],n=null){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=t,this.uri=e,this.keyFormat=i,this.keyFormatVersions=r,this.iv=n,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&"AES-128"!==t}isSupported(){if(this.method){if("AES-128"===this.method||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case Ze:case ti:case Je:case Qe:return-1!==["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(t){if(!this.encrypted||!this.uri)return null;if("AES-128"===this.method&&this.uri&&!this.iv){"number"!=typeof t&&("AES-128"!==this.method||this.iv||Pe.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0);const e=function(t){const e=new Uint8Array(16);for(let i=12;i<16;i++)e[i]=t>>8*(15-i)&255;return e}(t);return new Qi(this.method,this.uri,"identity",this.keyFormatVersions,e)}const e=We(this.uri);if(e)switch(this.keyFormat){case ti:this.pssh=e,e.length>=22&&(this.keyId=e.subarray(e.length-22,e.length-6));break;case Je:{const t=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=qi(t,null,e);const i=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),r=String.fromCharCode.apply(null,Array.from(i)),n=r.substring(r.indexOf("<"),r.length),s=(new DOMParser).parseFromString(n,"text/xml").getElementsByTagName("KID")[0];if(s){const t=s.childNodes[0]?s.childNodes[0].nodeValue:s.getAttribute("VALUE");if(t){const e=je(t).subarray(0,16);!function(t){const e=function(t,e,i){const r=t[e];t[e]=t[i],t[i]=r};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}(e),this.keyId=e}}break}default:{let t=e.subarray(0,16);if(16!==t.length){const e=new Uint8Array(16);e.set(t,16-t.length),t=e}this.keyId=t;break}}if(!this.keyId||16!==this.keyId.byteLength){let t=Xi[this.uri];if(!t){const e=Object.keys(Xi).length%Number.MAX_SAFE_INTEGER;t=new Uint8Array(16);new DataView(t.buffer,12,4).setUint32(0,e),Xi[this.uri]=t}this.keyId=t}return this}}const Zi=/\{\$([a-zA-Z0-9-_]+)\}/g;function Ji(t){return Zi.test(t)}function tr(t,e,i){if(null!==t.variableList||t.hasVariableRefs)for(let r=i.length;r--;){const n=i[r],s=e[n];s&&(e[n]=er(t,s))}}function er(t,e){if(null!==t.variableList||t.hasVariableRefs){const i=t.variableList;return e.replace(Zi,(e=>{const r=e.substring(2,e.length-1),n=null==i?void 0:i[r];return void 0===n?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),e):n}))}return e}function ir(t,e,i){let r,n,s=t.variableList;if(s||(t.variableList=s={}),"QUERYPARAM"in e){r=e.QUERYPARAM;try{const t=new self.URL(i).searchParams;if(!t.has(r))throw new Error(`"${r}" does not match any query parameter in URI: "${i}"`);n=t.get(r)}catch(e){t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${e.message}`))}}else r=e.NAME,n=e.VALUE;r in s?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):s[r]=n||""}function rr(t,e,i){const r=e.IMPORT;if(i&&r in i){let e=t.variableList;e||(t.variableList=e={}),e[r]=i[r]}else t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`))}function nr(t=!0){if("undefined"==typeof self)return;return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}const sr={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function ar(t,e,i=!0){return!t.split(",").some((t=>!or(t,e,i)))}function or(t,e,i=!0){var r;const n=nr(i);return null!=(r=null==n?void 0:n.isTypeSupported(lr(t,e)))&&r}function lr(t,e){return`${e}/mp4;codecs="${t}"`}function cr(t){if(t){const e=t.substring(0,4);return sr.video[e]}return 2}function hr(t){return t.split(",").reduce(((t,e)=>{const i=sr.video[e];return i?(2*i+t)/(t?3:2):(sr.audio[e]+t)/(t?2:1)}),0)}const ur={};const dr=/flac|opus/i;function fr(t,e=!0){return t.replace(dr,(t=>function(t,e=!0){if(ur[t])return ur[t];const i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[t];for(let r=0;r<i.length;r++)if(or(i[r],"audio",e))return ur[t]=i[r],i[r];return t}(t.toLowerCase(),e)))}function gr(t,e){return t&&"mp4a"!==t?t:e?e.split(",")[0]:e}const pr=/#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,mr=/#EXT-X-MEDIA:(.*)/g,yr=/^#EXT(?:INF|-X-TARGETDURATION):/m,vr=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),Ar=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class Er{static findGroup(t,e){for(let i=0;i<t.length;i++){const r=t[i];if(r.id===e)return r}}static resolve(t,e){return me.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return yr.test(t)}static parseMasterPlaylist(t,e){const i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:Ji(t)},r=[];let n;for(pr.lastIndex=0;null!=(n=pr.exec(t));)if(n[1]){var s;const t=new Me(n[1]);tr(i,t,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const a=er(i,n[2]),o={attrs:t,bitrate:t.decimalInteger("BANDWIDTH")||t.decimalInteger("AVERAGE-BANDWIDTH"),name:t.NAME,url:Er.resolve(a,e)},l=t.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),br(t.CODECS,o),null!=(s=o.unknownCodecs)&&s.length||r.push(o),i.levels.push(o)}else if(n[3]){const t=n[3],r=n[4];switch(t){case"SESSION-DATA":{const t=new Me(r);tr(i,t,["DATA-ID","LANGUAGE","VALUE","URI"]);const e=t["DATA-ID"];e&&(null===i.sessionData&&(i.sessionData={}),i.sessionData[e]=t);break}case"SESSION-KEY":{const t=Tr(r,e,i);t.encrypted&&t.isSupported()?(null===i.sessionKeys&&(i.sessionKeys=[]),i.sessionKeys.push(t)):Pe.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${r}"`);break}case"DEFINE":{const t=new Me(r);tr(i,t,["NAME","VALUE","QUERYPARAM"]),ir(i,t,e)}break;case"CONTENT-STEERING":{const t=new Me(r);tr(i,t,["SERVER-URI","PATHWAY-ID"]),i.contentSteering={uri:Er.resolve(t["SERVER-URI"],e),pathwayId:t["PATHWAY-ID"]||"."};break}case"START":i.startTimeOffset=Sr(r)}}const a=r.length>0&&r.length<i.levels.length;return i.levels=a?r:i.levels,0===i.levels.length&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(t,e,i){let r;const n={},s=i.levels,a={AUDIO:s.map((t=>({id:t.attrs.AUDIO,audioCodec:t.audioCodec}))),SUBTITLES:s.map((t=>({id:t.attrs.SUBTITLES,textCodec:t.textCodec}))),"CLOSED-CAPTIONS":[]};let o=0;for(mr.lastIndex=0;null!==(r=mr.exec(t));){const t=new Me(r[1]),s=t.TYPE;if(s){const r=a[s],l=n[s]||[];n[s]=l,tr(i,t,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const c=t.LANGUAGE,h=t["ASSOC-LANGUAGE"],u=t.CHANNELS,d=t.CHARACTERISTICS,f=t["INSTREAM-ID"],g={attrs:t,bitrate:0,id:o++,groupId:t["GROUP-ID"]||"",name:t.NAME||c||"",type:s,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:c,url:t.URI?Er.resolve(t.URI,e):""};if(h&&(g.assocLang=h),u&&(g.channels=u),d&&(g.characteristics=d),f&&(g.instreamId=f),null!=r&&r.length){const t=Er.findGroup(r,g.groupId)||r[0];kr(g,t,"audioCodec"),kr(g,t,"textCodec")}l.push(g)}}return n}static parseLevelPlaylist(t,e,i,r,n,s){const a=new Ye(e),o=a.fragments;let l,c,h,u=null,d=0,f=0,g=0,p=0,m=null,y=new He(r,e),v=-1,A=!1,E=null;for(vr.lastIndex=0,a.m3u8=t,a.hasVariableRefs=Ji(t);null!==(l=vr.exec(t));){A&&(A=!1,y=new He(r,e),y.start=g,y.sn=d,y.cc=p,y.level=i,u&&(y.initSegment=u,y.rawProgramDateTime=u.rawProgramDateTime,u.rawProgramDateTime=null,E&&(y.setByteRange(E),E=null)));const t=l[1];if(t){y.duration=parseFloat(t);const e=(" "+l[2]).slice(1);y.title=e||null,y.tagList.push(e?["INF",t,e]:["INF",t])}else if(l[3]){if(Se(y.duration)){y.start=g,h&&Rr(y,h,a),y.sn=d,y.level=i,y.cc=p,o.push(y);const t=(" "+l[3]).slice(1);y.relurl=er(a,t),_r(y,m),m=y,g+=y.duration,d++,f=0,A=!0}}else if(l[4]){const t=(" "+l[4]).slice(1);m?y.setByteRange(t,m):y.setByteRange(t)}else if(l[5])y.rawProgramDateTime=(" "+l[5]).slice(1),y.tagList.push(["PROGRAM-DATE-TIME",y.rawProgramDateTime]),-1===v&&(v=o.length);else{if(l=l[0].match(Ar),!l){Pe.warn("No matches on slow regex match for level playlist!");continue}for(c=1;c<l.length&&void 0===l[c];c++);const t=(" "+l[c]).slice(1),n=(" "+l[c+1]).slice(1),g=l[c+2]?(" "+l[c+2]).slice(1):"";switch(t){case"PLAYLIST-TYPE":a.type=n.toUpperCase();break;case"MEDIA-SEQUENCE":d=a.startSN=parseInt(n);break;case"SKIP":{const t=new Me(n);tr(a,t,["RECENTLY-REMOVED-DATERANGES"]);const e=t.decimalInteger("SKIPPED-SEGMENTS");if(Se(e)){a.skippedSegments=e;for(let t=e;t--;)o.unshift(null);d+=e}const i=t.enumeratedString("RECENTLY-REMOVED-DATERANGES");i&&(a.recentlyRemovedDateranges=i.split("\t"));break}case"TARGETDURATION":a.targetduration=Math.max(parseInt(n),1);break;case"VERSION":a.version=parseInt(n);break;case"INDEPENDENT-SEGMENTS":case"EXTM3U":break;case"ENDLIST":a.live=!1;break;case"#":(n||g)&&y.tagList.push(g?[n,g]:[n]);break;case"DISCONTINUITY":p++,y.tagList.push(["DIS"]);break;case"GAP":y.gap=!0,y.tagList.push([t]);break;case"BITRATE":y.tagList.push([t,n]);break;case"DATERANGE":{const t=new Me(n);tr(a,t,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),tr(a,t,t.clientAttrs);const e=new Ne(t,a.dateRanges[t.ID]);e.isValid||a.skippedSegments?a.dateRanges[e.id]=e:Pe.warn(`Ignoring invalid DATERANGE tag: "${n}"`),y.tagList.push(["EXT-X-DATERANGE",n]);break}case"DEFINE":{const t=new Me(n);tr(a,t,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in t?rr(a,t,s):ir(a,t,e)}break;case"DISCONTINUITY-SEQUENCE":p=parseInt(n);break;case"KEY":{const t=Tr(n,e,a);if(t.isSupported()){if("NONE"===t.method){h=void 0;break}h||(h={}),h[t.keyFormat]&&(h=Te({},h)),h[t.keyFormat]=t}else Pe.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${n}"`);break}case"START":a.startTimeOffset=Sr(n);break;case"MAP":{const t=new Me(n);if(tr(a,t,["BYTERANGE","URI"]),y.duration){const n=new He(r,e);Lr(n,t,i,h),u=n,y.initSegment=u,u.rawProgramDateTime&&!y.rawProgramDateTime&&(y.rawProgramDateTime=u.rawProgramDateTime)}else{const e=y.byteRangeEndOffset;if(e){const t=y.byteRangeStartOffset;E=`${e-t}@${t}`}else E=null;Lr(y,t,i,h),u=y,A=!0}break}case"SERVER-CONTROL":{const t=new Me(n);a.canBlockReload=t.bool("CAN-BLOCK-RELOAD"),a.canSkipUntil=t.optionalFloat("CAN-SKIP-UNTIL",0),a.canSkipDateRanges=a.canSkipUntil>0&&t.bool("CAN-SKIP-DATERANGES"),a.partHoldBack=t.optionalFloat("PART-HOLD-BACK",0),a.holdBack=t.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const t=new Me(n);a.partTarget=t.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=a.partList;t||(t=a.partList=[]);const i=f>0?t[t.length-1]:void 0,r=f++,s=new Me(n);tr(a,s,["BYTERANGE","URI"]);const o=new Ve(s,y,e,r,i);t.push(o),y.duration+=o.duration;break}case"PRELOAD-HINT":{const t=new Me(n);tr(a,t,["URI"]),a.preloadHint=t;break}case"RENDITION-REPORT":{const t=new Me(n);tr(a,t,["URI"]),a.renditionReports=a.renditionReports||[],a.renditionReports.push(t);break}default:Pe.warn(`line parsed but not handled: ${l}`)}}}m&&!m.relurl?(o.pop(),g-=m.duration,a.partList&&(a.fragmentHint=m)):a.partList&&(_r(y,m),y.cc=p,a.fragmentHint=y,h&&Rr(y,h,a));const T=o.length,S=o[0],b=o[T-1];if(g+=a.skippedSegments*a.targetduration,g>0&&T&&b){a.averagetargetduration=g/T;const t=b.sn;a.endSN="initSegment"!==t?t:0,a.live||(b.endList=!0),S&&(a.startCC=S.cc)}else a.endSN=0,a.startCC=0;return a.fragmentHint&&(g+=a.fragmentHint.duration),a.totalduration=g,a.endCC=p,v>0&&function(t,e){let i=t[e];for(let r=e;r--;){const e=t[r];if(!e)return;e.programDateTime=i.programDateTime-1e3*e.duration,i=e}}(o,v),a}}function Tr(t,e,i){var r,n;const s=new Me(t);tr(i,s,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const a=null!=(r=s.METHOD)?r:"",o=s.URI,l=s.hexadecimalInteger("IV"),c=s.KEYFORMATVERSIONS,h=null!=(n=s.KEYFORMAT)?n:"identity";o&&s.IV&&!l&&Pe.error(`Invalid IV: ${s.IV}`);const u=o?Er.resolve(o,e):"",d=(c||"1").split("/").map(Number).filter(Number.isFinite);return new Qi(a,u,h,d,l)}function Sr(t){const e=new Me(t).decimalFloatingPoint("TIME-OFFSET");return Se(e)?e:null}function br(t,e){let i=(t||"").split(/[ ,]+/).filter((t=>t));["video","audio","text"].forEach((t=>{const r=i.filter((e=>function(t,e){const i=sr[e];return!!i&&!!i[t.slice(0,4)]}(e,t)));r.length&&(e[`${t}Codec`]=r.join(","),i=i.filter((t=>-1===r.indexOf(t))))})),e.unknownCodecs=i}function kr(t,e,i){const r=e[i];r&&(t[i]=r)}function _r(t,e){t.rawProgramDateTime?t.programDateTime=Date.parse(t.rawProgramDateTime):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime),Se(t.programDateTime)||(t.programDateTime=null,t.rawProgramDateTime=null)}function Lr(t,e,i,r){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=i,t.sn="initSegment",r&&(t.levelkeys=r),t.initSegment=null}function Rr(t,e,i){t.levelkeys=e;const{encryptedFragments:r}=i;r.length&&r[r.length-1].levelkeys===e||!Object.keys(e).some((t=>e[t].isCommonEncryption))||r.push(t)}var Cr="manifest",Dr="level",wr="audioTrack",Ir="subtitleTrack",Pr="main",Or="audio",xr="subtitle";function Mr(t){const{type:e}=t;switch(e){case wr:return Or;case Ir:return xr;default:return Pr}}function Fr(t,e){let i=t.url;return void 0!==i&&0!==i.indexOf("data:")||(i=e.url),i}class Nr{constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=t,this.registerListeners()}startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:t}=this;t.on(_e.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_e.LEVEL_LOADING,this.onLevelLoading,this),t.on(_e.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(_e.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:t}=this;t.off(_e.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_e.LEVEL_LOADING,this.onLevelLoading,this),t.off(_e.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(_e.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(t){const e=this.hls.config,i=e.pLoader,r=e.loader,n=new(i||r)(e);return this.loaders[t.type]=n,n}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}destroyInternalLoaders(){for(const t in this.loaders){const e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,e){const{url:i}=e;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Cr,url:i,deliveryDirectives:null})}onLevelLoading(t,e){const{id:i,level:r,pathwayId:n,url:s,deliveryDirectives:a}=e;this.load({id:i,level:r,pathwayId:n,responseType:"text",type:Dr,url:s,deliveryDirectives:a})}onAudioTrackLoading(t,e){const{id:i,groupId:r,url:n,deliveryDirectives:s}=e;this.load({id:i,groupId:r,level:null,responseType:"text",type:wr,url:n,deliveryDirectives:s})}onSubtitleTrackLoading(t,e){const{id:i,groupId:r,url:n,deliveryDirectives:s}=e;this.load({id:i,groupId:r,level:null,responseType:"text",type:Ir,url:n,deliveryDirectives:s})}load(t){var e;const i=this.hls.config;let r,n=this.getInternalLoader(t);if(n){const e=n.context;if(e&&e.url===t.url&&e.level===t.level)return void Pe.trace("[playlist-loader]: playlist request ongoing");Pe.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),n.abort()}if(r=t.type===Cr?i.manifestLoadPolicy.default:Te({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(t),Se(null==(e=t.deliveryDirectives)?void 0:e.part)){let e;if(t.type===Dr&&null!==t.level?e=this.hls.levels[t.level].details:t.type===wr&&null!==t.id?e=this.hls.audioTracks[t.id].details:t.type===Ir&&null!==t.id&&(e=this.hls.subtitleTracks[t.id].details),e){const t=e.partTarget,i=e.targetduration;if(t&&i){const e=1e3*Math.max(3*t,.8*i);r=Te({},r,{maxTimeToFirstByteMs:Math.min(e,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(e,r.maxTimeToFirstByteMs)})}}}const s=r.errorRetry||r.timeoutRetry||{},a={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:s.maxNumRetry||0,retryDelay:s.retryDelayMs||0,maxRetryDelay:s.maxRetryDelayMs||0},o={onSuccess:(t,e,i,r)=>{const n=this.getInternalLoader(i);this.resetInternalLoader(i.type);const s=t.data;0===s.indexOf("#EXTM3U")?(e.parsing.start=performance.now(),Er.isMediaPlaylist(s)?this.handleTrackOrLevelPlaylist(t,e,i,r||null,n):this.handleMasterPlaylist(t,e,i,r)):this.handleManifestParsingError(t,i,new Error("no EXTM3U delimiter"),r||null,e)},onError:(t,e,i,r)=>{this.handleNetworkError(e,i,!1,t,r)},onTimeout:(t,e,i)=>{this.handleNetworkError(e,i,!0,void 0,t)}};n.load(t,a,o)}handleMasterPlaylist(t,e,i,r){const n=this.hls,s=t.data,a=Fr(t,i),o=Er.parseMasterPlaylist(s,a);if(o.playlistParsingError)return void this.handleManifestParsingError(t,i,o.playlistParsingError,r,e);const{contentSteering:l,levels:c,sessionData:h,sessionKeys:u,startTimeOffset:d,variableList:f}=o;this.variableList=f;const{AUDIO:g=[],SUBTITLES:p,"CLOSED-CAPTIONS":m}=Er.parseMasterPlaylistMedia(s,a,o);if(g.length){g.some((t=>!t.url))||!c[0].audioCodec||c[0].attrs.AUDIO||(Pe.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Me({}),bitrate:0,url:""}))}n.trigger(_e.MANIFEST_LOADED,{levels:c,audioTracks:g,subtitles:p,captions:m,contentSteering:l,url:a,stats:e,networkDetails:r,sessionData:h,sessionKeys:u,startTimeOffset:d,variableList:f})}handleTrackOrLevelPlaylist(t,e,i,r,n){const s=this.hls,{id:a,level:o,type:l}=i,c=Fr(t,i),h=Se(o)?o:Se(a)?a:0,u=Mr(i),d=Er.parseLevelPlaylist(t.data,c,h,u,0,this.variableList);if(l===Cr){const t={attrs:new Me({}),bitrate:0,details:d,name:"",url:c};s.trigger(_e.MANIFEST_LOADED,{levels:[t],audioTracks:[],url:c,stats:e,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),i.levelDetails=d,this.handlePlaylistLoaded(d,t,e,i,r,n)}handleManifestParsingError(t,e,i,r,n){this.hls.trigger(_e.ERROR,{type:Le.NETWORK_ERROR,details:Re.MANIFEST_PARSING_ERROR,fatal:e.type===Cr,url:t.url,err:i,error:i,reason:i.message,response:t,context:e,networkDetails:r,stats:n})}handleNetworkError(t,e,i=!1,r,n){let s=`A network ${i?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${t.type}`;t.type===Dr?s+=`: ${t.level} id: ${t.id}`:t.type!==wr&&t.type!==Ir||(s+=` id: ${t.id} group-id: "${t.groupId}"`);const a=new Error(s);Pe.warn(`[playlist-loader]: ${s}`);let o=Re.UNKNOWN,l=!1;const c=this.getInternalLoader(t);switch(t.type){case Cr:o=i?Re.MANIFEST_LOAD_TIMEOUT:Re.MANIFEST_LOAD_ERROR,l=!0;break;case Dr:o=i?Re.LEVEL_LOAD_TIMEOUT:Re.LEVEL_LOAD_ERROR,l=!1;break;case wr:o=i?Re.AUDIO_TRACK_LOAD_TIMEOUT:Re.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case Ir:o=i?Re.SUBTITLE_TRACK_LOAD_TIMEOUT:Re.SUBTITLE_LOAD_ERROR,l=!1}c&&this.resetInternalLoader(t.type);const h={type:Le.NETWORK_ERROR,details:o,fatal:l,url:t.url,loader:c,context:t,error:a,networkDetails:e,stats:n};if(r){const i=(null==e?void 0:e.url)||t.url;h.response=ve({url:i,data:void 0},r)}this.hls.trigger(_e.ERROR,h)}handlePlaylistLoaded(t,e,i,r,n,s){const a=this.hls,{type:o,level:l,id:c,groupId:h,deliveryDirectives:u}=r,d=Fr(e,r),f=Mr(r),g="number"==typeof r.level&&f===Pr?l:void 0;if(!t.fragments.length){const t=new Error("No Segments found in Playlist");return void a.trigger(_e.ERROR,{type:Le.NETWORK_ERROR,details:Re.LEVEL_EMPTY_ERROR,fatal:!1,url:d,error:t,reason:t.message,response:e,context:r,level:g,parent:f,networkDetails:n,stats:i})}t.targetduration||(t.playlistParsingError=new Error("Missing Target Duration"));const p=t.playlistParsingError;if(p)a.trigger(_e.ERROR,{type:Le.NETWORK_ERROR,details:Re.LEVEL_PARSING_ERROR,fatal:!1,url:d,error:p,reason:p.message,response:e,context:r,level:g,parent:f,networkDetails:n,stats:i});else switch(t.live&&s&&(s.getCacheAge&&(t.ageHeader=s.getCacheAge()||0),s.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),o){case Cr:case Dr:a.trigger(_e.LEVEL_LOADED,{details:t,level:g||0,id:c||0,stats:i,networkDetails:n,deliveryDirectives:u});break;case wr:a.trigger(_e.AUDIO_TRACK_LOADED,{details:t,id:c||0,groupId:h||"",stats:i,networkDetails:n,deliveryDirectives:u});break;case Ir:a.trigger(_e.SUBTITLE_TRACK_LOADED,{details:t,id:c||0,groupId:h||"",stats:i,networkDetails:n,deliveryDirectives:u})}}}function Ur(t,e){let i;try{i=new Event("addtrack")}catch(t){i=document.createEvent("Event"),i.initEvent("addtrack",!1,!1)}i.track=t,e.dispatchEvent(i)}function Br(t,e){const i=t.mode;if("disabled"===i&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(e.id))try{if(t.addCue(e),!t.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){Pe.debug(`[texttrack-utils]: ${i}`);try{const i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,t.addCue(i)}catch(t){Pe.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${t}`)}}"disabled"===i&&(t.mode=i)}function $r(t){const e=t.mode;if("disabled"===e&&(t.mode="hidden"),t.cues)for(let e=t.cues.length;e--;)t.removeCue(t.cues[e]);"disabled"===e&&(t.mode=e)}function Gr(t,e,i,r){const n=t.mode;if("disabled"===n&&(t.mode="hidden"),t.cues&&t.cues.length>0){const n=function(t,e,i){const r=[],n=function(t,e){if(e<t[0].startTime)return 0;const i=t.length-1;if(e>t[i].endTime)return-1;let r=0,n=i;for(;r<=n;){const s=Math.floor((n+r)/2);if(e<t[s].startTime)n=s-1;else{if(!(e>t[s].startTime&&r<i))return s;r=s+1}}return t[r].startTime-e<e-t[n].startTime?r:n}(t,e);if(n>-1)for(let s=n,a=t.length;s<a;s++){const n=t[s];if(n.startTime>=e&&n.endTime<=i)r.push(n);else if(n.startTime>i)return r}return r}(t.cues,e,i);for(let e=0;e<n.length;e++)r&&!r(n[e])||t.removeCue(n[e])}"disabled"===n&&(t.mode=n)}function Kr(t){const e=[];for(let i=0;i<t.length;i++){const r=t[i];"subtitles"!==r.kind&&"captions"!==r.kind||!r.label||e.push(t[i])}return e}var Hr="org.id3",Vr="com.apple.quicktime.HLS",Yr="https://aomedia.org/emsg/ID3";function jr(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function Wr(t,e,i,r,n){let s=new t(e,i,"");try{s.value=r,n&&(s.type=n)}catch(a){s=new t(e,i,JSON.stringify(n?ve({type:n},r):r))}return s}const zr=(()=>{const t=jr();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function qr(t,e){return t.getTime()/1e3-e}class Xr{constructor(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){const{hls:t}=this;t.on(_e.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(_e.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(_e.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_e.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(_e.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(_e.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:t}=this;t.off(_e.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(_e.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(_e.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_e.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(_e.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(_e.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(t,e){this.media=e.media}onMediaDetaching(){this.id3Track&&($r(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){const e=this.getID3Track(t.textTracks);return e.mode="hidden",e}getID3Track(t){if(this.media){for(let e=0;e<t.length;e++){const i=t[e];if("metadata"===i.kind&&"id3"===i.label)return Ur(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(t,e){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:i,enableID3MetadataCues:r}}}=this;if(!i&&!r)return;const{samples:n}=e;this.id3Track||(this.id3Track=this.createTrack(this.media));const s=jr();if(s)for(let t=0;t<n.length;t++){const e=n[t].type;if(e===Yr&&!i||!r)continue;const a=mi(n[t].data);if(a){const i=n[t].pts;let r=i+n[t].duration;r>zr&&(r=zr);r-i<=0&&(r=i+.25);for(let t=0;t<a.length;t++){const n=a[t];if(!gi(n)){this.updateId3CueEnds(i,e);const t=Wr(s,i,r,n,e);t&&this.id3Track.addCue(t)}}}}}updateId3CueEnds(t,e){var i;const r=null==(i=this.id3Track)?void 0:i.cues;if(r)for(let i=r.length;i--;){const n=r[i];n.type===e&&n.startTime<t&&n.endTime===zr&&(n.endTime=t)}}onBufferFlushing(t,{startOffset:e,endOffset:i,type:r}){const{id3Track:n,hls:s}=this;if(!s)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=s;if(n&&(a||o)){let t;t="audio"===r?t=>t.type===Hr&&o:"video"===r?t=>t.type===Yr&&a:t=>t.type===Hr&&o||t.type===Yr&&a,Gr(n,e,i,t)}}onLevelUpdated(t,{details:e}){if(!this.media||!e.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:i,id3Track:r}=this,{dateRanges:n}=e,s=Object.keys(n);if(r){const t=Object.keys(i).filter((t=>!s.includes(t)));for(let e=t.length;e--;){const n=t[e];Object.keys(i[n].cues).forEach((t=>{r.removeCue(i[n].cues[t])})),delete i[n]}}const a=e.fragments[e.fragments.length-1];if(0===s.length||!Se(null==a?void 0:a.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const o=a.programDateTime/1e3-a.start,l=jr();for(let t=0;t<s.length;t++){const e=s[t],r=n[e],a=qr(r.startDate,o),u=i[e],d=(null==u?void 0:u.cues)||{};let f=(null==u?void 0:u.durationKnown)||!1,g=zr;const p=r.endDate;if(p)g=qr(p,o),f=!0;else if(r.endOnNext&&!f){const t=s.reduce(((t,e)=>{if(e!==r.id){const i=n[e];if(i.class===r.class&&i.startDate>r.startDate&&(!t||r.startDate<t.startDate))return i}return t}),null);t&&(g=qr(t.startDate,o),f=!0)}const m=Object.keys(r.attr);for(let t=0;t<m.length;t++){const i=m[t];if("ID"===(h=i)||"CLASS"===h||"START-DATE"===h||"DURATION"===h||"END-DATE"===h||"END-ON-NEXT"===h)continue;const n=d[i];if(n)f&&!u.durationKnown&&(n.endTime=g);else if(l){let t=r.attr[i];Fe(i)&&(c=t,t=Uint8Array.from(c.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer);const n=Wr(l,a,g,{key:i,data:t},Vr);n&&(n.id=e,this.id3Track.addCue(n),d[i]=n)}}i[e]={cues:d,dateRange:r,durationKnown:f}}var c,h}}class Qr{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.levelDetails=null,this.currentTime=0,this.stallCount=0,this._latency=null,this.timeupdateHandler=()=>this.timeupdate(),this.hls=t,this.config=t.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:t,levelDetails:e}=this;return void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:e?t.liveMaxLatencyDurationCount*e.targetduration:0}get targetLatency(){const{levelDetails:t}=this;if(null===t)return null;const{holdBack:e,partHoldBack:i,targetduration:r}=t,{liveSyncDuration:n,liveSyncDurationCount:s,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&i||e;(o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==n?n:s*r);const c=r;return l+Math.min(1*this.stallCount,c)}get liveSyncPosition(){const t=this.estimateLiveEdge(),e=this.targetLatency,i=this.levelDetails;if(null===t||null===e||null===i)return null;const r=i.edge,n=t-e-this.edgeStalled,s=r-i.totalduration,a=r-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(s,n),a)}get drift(){const{levelDetails:t}=this;return null===t?1:t.drift}get edgeStalled(){const{levelDetails:t}=this;if(null===t)return 0;const e=3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}get forwardBufferLength(){const{media:t,levelDetails:e}=this;if(!t||!e)return 0;const i=t.buffered.length;return(i?t.buffered.end(i-1):e.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(_e.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(_e.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(_e.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(_e.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(_e.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(_e.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(_e.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(_e.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(_e.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(_e.ERROR,this.onError,this)}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}onLevelUpdated(t,{details:e}){this.levelDetails=e,e.advanced&&this.timeupdate(),!e.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(t,e){var i;e.details===Re.BUFFER_STALLED_ERROR&&(this.stallCount++,null!=(i=this.levelDetails)&&i.live&&Pe.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:t,levelDetails:e}=this;if(!t||!e)return;this.currentTime=t.currentTime;const i=this.computeLatency();if(null===i)return;this._latency=i;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:n}=this.config;if(!r||1===n||!e.live)return;const s=this.targetLatency;if(null===s)return;const a=i-s;if(a<Math.min(this.maxLatency,s+e.targetduration)&&a>.05&&this.forwardBufferLength>1){const e=Math.min(2,Math.max(1,n)),i=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20;t.playbackRate=Math.min(e,Math.max(1,i))}else 1!==t.playbackRate&&0!==t.playbackRate&&(t.playbackRate=1)}estimateLiveEdge(){const{levelDetails:t}=this;return null===t?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return null===t?null:t-this.currentTime}}const Zr=["NONE","TYPE-0","TYPE-1",null];const Jr=["SDR","PQ","HLG"];var tn="",en="YES",rn="v2";function nn(t){const{canSkipUntil:e,canSkipDateRanges:i,age:r}=t;return e&&r<e/2?i?rn:en:tn}class sn{constructor(t,e,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=e,this.skip=i}addDirectives(t){const e=new self.URL(t);return void 0!==this.msn&&e.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&e.searchParams.set("_HLS_part",this.part.toString()),this.skip&&e.searchParams.set("_HLS_skip",this.skip),e.href}}class an{constructor(t){this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[t.url],this._attrs=[t.attrs],this.bitrate=t.bitrate,t.details&&(this.details=t.details),this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.frameRate=t.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=t.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,this.codecSet=[t.videoCodec,t.audioCodec].filter((t=>!!t)).map((t=>t.substring(0,4))).join(","),this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.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(t){return on(this._audioGroups,t)}hasSubtitleGroup(t){return on(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,e){if(e)if("audio"===t){let t=this._audioGroups;t||(t=this._audioGroups=[]),-1===t.indexOf(e)&&t.push(e)}else if("text"===t){let t=this._subtitleGroups;t||(t=this._subtitleGroups=[]),-1===t.indexOf(e)&&t.push(e)}}get urlId(){return 0}set urlId(t){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var t;return null==(t=this.audioGroups)?void 0:t[0]}get textGroupId(){var t;return null==(t=this.subtitleGroups)?void 0:t[0]}addFallback(){}}function on(t,e){return!(!e||!t)&&-1!==t.indexOf(e)}function ln(t,e){const i=e.startPTS;if(Se(i)){let r,n=0;e.sn>t.sn?(n=i-t.start,r=t):(n=t.start-i,r=e),r.duration!==n&&(r.duration=n)}else if(e.sn>t.sn){t.cc===e.cc&&t.minEndPTS?e.start=t.start+(t.minEndPTS-t.start):e.start=t.start+t.duration}else e.start=Math.max(t.start-e.duration,0)}function cn(t,e,i,r,n,s){r-i<=0&&(Pe.warn("Fragment should have a positive duration",e),r=i+e.duration,s=n+e.duration);let a=i,o=r;const l=e.startPTS,c=e.endPTS;if(Se(l)){const t=Math.abs(l-i);Se(e.deltaPTS)?e.deltaPTS=Math.max(t,e.deltaPTS):e.deltaPTS=t,a=Math.max(i,l),i=Math.min(i,l),n=Math.min(n,e.startDTS),o=Math.min(r,c),r=Math.max(r,c),s=Math.max(s,e.endDTS)}const h=i-e.start;0!==e.start&&(e.start=i),e.duration=r-e.start,e.startPTS=i,e.maxStartPTS=a,e.startDTS=n,e.endPTS=r,e.minEndPTS=o,e.endDTS=s;const u=e.sn;if(!t||u<t.startSN||u>t.endSN)return 0;let d;const f=u-t.startSN,g=t.fragments;for(g[f]=e,d=f;d>0;d--)ln(g[d],g[d-1]);for(d=f;d<g.length-1;d++)ln(g[d],g[d+1]);return t.fragmentHint&&ln(g[g.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,h}function hn(t,e){let i=null;const r=t.fragments;for(let t=r.length-1;t>=0;t--){const e=r[t].initSegment;if(e){i=e;break}}t.fragmentHint&&delete t.fragmentHint.endPTS;let n,s=0;if(function(t,e,i){const r=e.skippedSegments,n=Math.max(t.startSN,e.startSN)-e.startSN,s=(t.fragmentHint?1:0)+(r?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,a=e.startSN-t.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments;for(let t=n;t<=s;t++){const n=l[a+t];let s=o[t];r&&!s&&t<r&&(s=e.fragments[t]=n),n&&s&&i(n,s)}}(t,e,((t,r)=>{t.relurl&&(s=t.cc-r.cc),Se(t.startPTS)&&Se(t.endPTS)&&(r.start=r.startPTS=t.startPTS,r.startDTS=t.startDTS,r.maxStartPTS=t.maxStartPTS,r.endPTS=t.endPTS,r.endDTS=t.endDTS,r.minEndPTS=t.minEndPTS,r.duration=t.endPTS-t.startPTS,r.duration&&(n=r),e.PTSKnown=e.alignedSliding=!0),r.elementaryStreams=t.elementaryStreams,r.loader=t.loader,r.stats=t.stats,t.initSegment&&(r.initSegment=t.initSegment,i=t.initSegment)})),i){(e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments).forEach((t=>{var e;!t||t.initSegment&&t.initSegment.relurl!==(null==(e=i)?void 0:e.relurl)||(t.initSegment=i)}))}if(e.skippedSegments)if(e.deltaUpdateFailed=e.fragments.some((t=>!t)),e.deltaUpdateFailed){Pe.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let t=e.skippedSegments;t--;)e.fragments.shift();e.startSN=e.fragments[0].sn,e.startCC=e.fragments[0].cc}else e.canSkipDateRanges&&(e.dateRanges=function(t,e,i){const r=Te({},t);i&&i.forEach((t=>{delete r[t]}));return Object.keys(e).forEach((t=>{const i=new Ne(e[t].attr,r[t]);i.isValid?r[t]=i:Pe.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(e[t].attr)}"`)})),r}(t.dateRanges,e.dateRanges,e.recentlyRemovedDateranges));const a=e.fragments;if(s){Pe.warn("discontinuity sliding from playlist, take drift into account");for(let t=0;t<a.length;t++)a[t].cc+=s}e.skippedSegments&&(e.startCC=e.fragments[0].cc),function(t,e,i){if(t&&e){let r=0;for(let n=0,s=t.length;n<=s;n++){const s=t[n],a=e[n+r];s&&a&&s.index===a.index&&s.fragment.sn===a.fragment.sn?i(s,a):r--}}}(t.partList,e.partList,((t,e)=>{e.elementaryStreams=t.elementaryStreams,e.stats=t.stats})),n?cn(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS):un(t,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;const o=e.advancedDateTime;if(e.advanced&&o){const t=e.edge;e.driftStart||(e.driftStartTime=o,e.driftStart=t),e.driftEndTime=o,e.driftEnd=t}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime}function un(t,e){const i=e.startSN+e.skippedSegments-t.startSN,r=t.fragments;i<0||i>=r.length||dn(e,r[i].start)}function dn(t,e){if(e){const i=t.fragments;for(let r=t.skippedSegments;r<i.length;r++)i[r].start+=e;t.fragmentHint&&(t.fragmentHint.start+=e)}}function fn(t,e,i){var r;return null!=t&&t.details?gn(null==(r=t.details)?void 0:r.partList,e,i):null}function gn(t,e,i){if(t)for(let r=t.length;r--;){const n=t[r];if(n.index===i&&n.fragment.sn===e)return n}return null}function pn(t){t.forEach(((t,e)=>{const{details:i}=t;null!=i&&i.fragments&&i.fragments.forEach((t=>{t.level=e}))}))}function mn(t){switch(t.details){case Re.FRAG_LOAD_TIMEOUT:case Re.KEY_LOAD_TIMEOUT:case Re.LEVEL_LOAD_TIMEOUT:case Re.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function yn(t,e){const i=mn(e);return t.default[(i?"timeout":"error")+"Retry"]}function vn(t,e){const i="linear"===t.backoff?1:Math.pow(2,e);return Math.min(i*t.retryDelayMs,t.maxRetryDelayMs)}function An(t){return ve(ve({},t),{errorRetry:null,timeoutRetry:null})}function En(t,e,i,r){if(!t)return!1;const n=null==r?void 0:r.code,s=e<t.maxNumRetry&&(function(t){return 0===t&&!1===navigator.onLine||!!t&&(t<400||t>499)}(n)||!!i);return t.shouldRetry?t.shouldRetry(t,e,i,r,s):s}const Tn=function(t,e){let i=0,r=t.length-1,n=null,s=null;for(;i<=r;){n=(i+r)/2|0,s=t[n];const a=e(s);if(a>0)i=n+1;else{if(!(a<0))return s;r=n-1}}return null};function Sn(t,e,i=0,r=0,n=.005){let s=null;if(t){s=e[t.sn-e[0].sn+1]||null;const r=t.endDTS-i;r>0&&r<15e-7&&(i+=15e-7)}else 0===i&&0===e[0].start&&(s=e[0]);if(s&&((!t||t.level===s.level)&&0===bn(i,r,s)||function(t,e,i){if(e&&0===e.start&&e.level<t.level&&(e.endPTS||0)>0){const r=e.tagList.reduce(((t,e)=>("INF"===e[0]&&(t+=parseFloat(e[1])),t)),i);return t.start<=r}return!1}(s,t,Math.min(n,r))))return s;const a=Tn(e,bn.bind(null,i,r));return!a||a===t&&s?s:a}function bn(t=0,e=0,i){if(i.start<=t&&i.start+i.duration>t)return 0;const r=Math.min(e,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-r<=t?1:i.start-r>t&&i.start?-1:0}function kn(t,e,i){const r=1e3*Math.min(e,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-r>t}var _n=0,Ln=2,Rn=3,Cn=5,Dn=0,wn=1,In=2;class Pn{constructor(t,e){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=Pe.log.bind(Pe,`${e}:`),this.warn=Pe.warn.bind(Pe,`${e}:`),this.hls=t}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,e,i){const r=null==e?void 0:e.renditionReports;if(r){let n=-1;for(let i=0;i<r.length;i++){const s=r[i];let a;try{a=new self.URL(s.URI,e.url).href}catch(t){Pe.warn(`Could not construct new URL for Rendition Report: ${t}`),a=s.URI||""}if(a===t){n=i;break}a===t.substring(0,a.length)&&(n=i)}if(-1!==n){const t=r[n],s=parseInt(t["LAST-MSN"])||(null==e?void 0:e.lastPartSn);let a=parseInt(t["LAST-PART"])||(null==e?void 0:e.lastPartIndex);if(this.hls.config.lowLatencyMode){const t=Math.min(e.age-e.partTarget,e.targetduration);a>=0&&t>e.partTarget&&(a+=1)}const o=i&&nn(i);return new sn(s,a>=0?a:void 0,o)}}}loadPlaylist(t){-1===this.requestScheduled&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}shouldReloadPlaylist(t){return-1===this.timer&&-1===this.requestScheduled&&this.shouldLoadPlaylist(t)}playlistLoaded(t,e,i){const{details:r,stats:n}=e,s=self.performance.now(),a=n.loading.first?Math.max(0,s-n.loading.first):0;if(r.advancedDateTime=Date.now()-a,r.live||null!=i&&i.live){if(r.reloaded(i),i&&this.log(`live playlist ${t} ${r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED"}`),i&&r.fragments.length>0&&hn(i,r),!this.canLoad||!r.live)return;let a,o,l;if(r.canBlockReload&&r.endSN&&r.advanced){const t=this.hls.config.lowLatencyMode,n=r.lastPartSn,s=r.endSN,c=r.lastPartIndex,h=n===s;-1!==c?(o=h?s+1:n,l=h?t?0:c:c+1):o=s+1;const u=r.age,d=u+r.ageHeader;let f=Math.min(d-r.partTarget,1.5*r.targetduration);if(f>0){if(i&&f>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${f} with playlist age: ${r.age}`),f=0;else{const t=Math.floor(f/r.targetduration);if(o+=t,void 0!==l){l+=Math.round(f%r.targetduration/r.partTarget)}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${u.toFixed(2)}s goal: ${f} skip sn ${t} to part ${l}`)}r.tuneInGoal=f}if(a=this.getDeliveryDirectives(r,e.deliveryDirectives,o,l),t||!h)return void this.loadPlaylist(a)}else(r.canBlockReload||r.canSkipUntil)&&(a=this.getDeliveryDirectives(r,e.deliveryDirectives,o,l));const c=this.hls.mainForwardBufferInfo,h=c?c.end-c.len:0,u=function(t,e=1/0){let i=1e3*t.targetduration;if(t.updated){const r=t.fragments,n=4;if(r.length&&i*n>e){const t=1e3*r[r.length-1].duration;t<i&&(i=t)}}else i/=2;return Math.round(i)}(r,1e3*(r.edge-h));r.updated&&s>this.requestScheduled+u&&(this.requestScheduled=n.loading.start),void 0!==o&&r.canBlockReload?this.requestScheduled=n.loading.first+u-(1e3*r.partTarget||1e3):-1===this.requestScheduled||this.requestScheduled+u<s?this.requestScheduled=s:this.requestScheduled-s<=0&&(this.requestScheduled+=u);let d=this.requestScheduled-s;d=Math.max(0,d),this.log(`reload live playlist ${t} in ${Math.round(d)} ms`),this.timer=self.setTimeout((()=>this.loadPlaylist(a)),d)}else this.clearTimer()}getDeliveryDirectives(t,e,i,r){let n=nn(t);return null!=e&&e.skip&&t.deltaUpdateFailed&&(i=e.msn,r=e.part,n=tn),new sn(i,r,n)}checkRetry(t){const e=t.details,i=mn(t),r=t.errorAction,{action:n,retryCount:s=0,retryConfig:a}=r||{},o=!!r&&!!a&&(n===Cn||!r.resolved&&n===Ln);if(o){var l;if(this.requestScheduled=-1,s>=a.maxNumRetry)return!1;if(i&&null!=(l=t.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${s+1}/${a.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{const t=vn(a,s);this.timer=self.setTimeout((()=>this.loadPlaylist()),t),this.warn(`Retrying playlist loading ${s+1}/${a.maxNumRetry} after "${e}" in ${t}ms`)}t.levelRetry=!0,r.resolved=!0}return o}}class On{constructor(t,e=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=i}sample(t,e){const i=Math.pow(this.alpha_,t);this.estimate_=e*(1-i)+i*this.estimate_,this.totalWeight_+=t}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}}class xn{constructor(t,e,i,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new On(t),this.fast_=new On(e),this.defaultTTFB_=r,this.ttfb_=new On(t)}update(t,e){const{slow_:i,fast_:r,ttfb_:n}=this;i.halfLife!==t&&(this.slow_=new On(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.fast_=new On(e,r.getEstimate(),r.getTotalWeight())),n.halfLife!==t&&(this.ttfb_=new On(t,n.getEstimate(),n.getTotalWeight()))}sample(t,e){const i=(t=Math.max(t,this.minDelayMs_))/1e3,r=8*e/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}sampleTTFB(t){const e=t/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(i,Math.max(t,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}destroy(){}}const Mn={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},Fn={};function Nn(t,e,i,r,n,s){const a=t.audioCodec?t.audioGroups:null,o=null==s?void 0:s.audioCodec,l=null==s?void 0:s.channels,c=l?parseInt(l):o?1/0:2;let h=null;if(null!=a&&a.length)try{h=1===a.length&&a[0]?e.groups[a[0]].channels:a.reduce(((t,i)=>{if(i){const r=e.groups[i];if(!r)throw new Error(`Audio track group ${i} not found`);Object.keys(r.channels).forEach((e=>{t[e]=(t[e]||0)+r.channels[e]}))}return t}),{2:0})}catch(t){return!0}return void 0!==t.videoCodec&&(t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(r,30)||"SDR"!==t.videoRange&&t.videoRange!==i||t.bitrate>Math.max(n,8e6))||!!h&&Se(c)&&Object.keys(h).some((t=>parseInt(t)>c))}function Un(t,e,i){const r=t.videoCodec,n=t.audioCodec;if(!r||!n||!i)return Promise.resolve(Mn);const s={width:t.width,height:t.height,bitrate:Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)),framerate:t.frameRate||30},a=t.videoRange;"SDR"!==a&&(s.transferFunction=a.toLowerCase());const o=r.split(",").map((t=>({type:"media-source",video:ve(ve({},s),{},{contentType:lr(t,"video")})})));return n&&t.audioGroups&&t.audioGroups.forEach((t=>{var i;t&&(null==(i=e.groups[t])||i.tracks.forEach((e=>{if(e.groupId===t){const t=e.channels||"",i=parseFloat(t);Se(i)&&i>2&&o.push.apply(o,n.split(",").map((t=>({type:"media-source",audio:{contentType:lr(t,"audio"),channels:""+i}}))))}})))})),Promise.all(o.map((t=>{const e=function(t){const{audio:e,video:i}=t,r=i||e;if(r){const t=r.contentType.split('"')[1];if(i)return`r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${t}_${Math.ceil(i.bitrate/1e5)}`;if(e)return`c${e.channels}${e.spatialRendering?"s":"n"}_${t}`}return""}(t);return Fn[e]||(Fn[e]=i.decodingInfo(t))}))).then((t=>({supported:!t.some((t=>!t.supported)),configurations:o,decodingInfoResults:t}))).catch((t=>({supported:!1,configurations:o,decodingInfoResults:[],error:t})))}function Bn(t,e){let i=!1,r=[];return t&&(i="SDR"!==t,r=[t]),e&&(r=e.allowedVideoRanges||Jr.slice(0),i=void 0!==e.preferHDR?e.preferHDR:function(){if("function"==typeof matchMedia){const t=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(t.media!==e.media)return!0===t.matches}return!1}(),r=i?r.filter((t=>"SDR"!==t)):["SDR"]),{preferHDR:i,allowedVideoRanges:r}}function $n(t,e){Pe.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function Gn(t,e,i){if("attrs"in t){const i=e.indexOf(t);if(-1!==i)return i}for(let r=0;r<e.length;r++){if(Kn(t,e[r],i))return r}return-1}function Kn(t,e,i){const{groupId:r,name:n,lang:s,assocLang:a,characteristics:o,default:l}=t,c=t.forced;return(void 0===r||e.groupId===r)&&(void 0===n||e.name===n)&&(void 0===s||e.lang===s)&&(void 0===s||e.assocLang===a)&&(void 0===l||e.default===l)&&(void 0===c||e.forced===c)&&(void 0===o||function(t,e=""){const i=t.split(","),r=e.split(",");return i.length===r.length&&!i.some((t=>-1===r.indexOf(t)))}(o,e.characteristics))&&(void 0===i||i(t,e))}function Hn(t,e){const{audioCodec:i,channels:r}=t;return!(void 0!==i&&(e.audioCodec||"").substring(0,4)!==i.substring(0,4)||void 0!==r&&r!==(e.channels||"2"))}function Vn(t,e,i){for(let r=e;r;r--)if(i(t[r]))return r;for(let r=e+1;r<t.length;r++)if(i(t[r]))return r;return-1}class Yn{constructor(){this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(t){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}var jn="NOT_LOADED",Wn="APPENDING",zn="PARTIAL",qn="OK";class Xn{constructor(t){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=t,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(_e.BUFFER_APPENDED,this.onBufferAppended,this),t.on(_e.FRAG_BUFFERED,this.onFragBuffered,this),t.on(_e.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:t}=this;t.off(_e.BUFFER_APPENDED,this.onBufferAppended,this),t.off(_e.FRAG_BUFFERED,this.onFragBuffered,this),t.off(_e.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(t,e){const i=this.activePartLists[e];if(i)for(let e=i.length;e--;){const r=i[e];if(!r)break;const n=r.end;if(r.start<=t&&null!==n&&t<=n)return r}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){const{fragments:i}=this,r=Object.keys(i);for(let n=r.length;n--;){const s=i[r[n]];if((null==s?void 0:s.body.type)===e&&s.buffered){const e=s.body;if(e.start<=t&&t<=e.end)return e}}return null}detectEvictedFragments(t,e,i,r){this.timeRanges&&(this.timeRanges[t]=e);const n=(null==r?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach((r=>{const s=this.fragments[r];if(!s)return;if(n>=s.body.sn)return;if(!s.buffered&&!s.loaded)return void(s.body.type===i&&this.removeFragment(s.body));const a=s.range[t];a&&a.time.some((t=>{const i=!this.isTimeBuffered(t.startPTS,t.endPTS,e);return i&&this.removeFragment(s.body),i}))}))}detectPartialFragments(t){const e=this.timeRanges,{frag:i,part:r}=t;if(!e||"initSegment"===i.sn)return;const n=Zn(i),s=this.fragments[n];if(!s||s.buffered&&i.gap)return;const a=!i.relurl;if(Object.keys(e).forEach((t=>{const n=i.elementaryStreams[t];if(!n)return;const o=e[t],l=a||!0===n.partial;s.range[t]=this.getBufferedTimes(i,r,l,o)})),s.loaded=null,Object.keys(s.range).length){s.buffered=!0;(s.body.endList=i.endList||s.body.endList)&&(this.endListFragments[s.body.type]=s),Qn(s)||this.removeParts(i.sn-1,i.type)}else this.removeFragment(s.body)}removeParts(t,e){const i=this.activePartLists[e];i&&(this.activePartLists[e]=i.filter((e=>e.fragment.sn>=t)))}fragBuffered(t,e){const i=Zn(t);let r=this.fragments[i];!r&&e&&(r=this.fragments[i]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,r.buffered=!0)}getBufferedTimes(t,e,i,r){const n={time:[],partial:i},s=t.start,a=t.end,o=t.minEndPTS||a,l=t.maxStartPTS||s;for(let t=0;t<r.length;t++){const e=r.start(t)-this.bufferPadding,i=r.end(t)+this.bufferPadding;if(l>=e&&o<=i){n.time.push({startPTS:Math.max(s,r.start(t)),endPTS:Math.min(a,r.end(t))});break}if(s<i&&a>e){const e=Math.max(s,r.start(t)),i=Math.min(a,r.end(t));i>e&&(n.partial=!0,n.time.push({startPTS:e,endPTS:i}))}else if(a<=e)break}return n}getPartialFragment(t){let e,i,r,n=null,s=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach((l=>{const c=o[l];c&&Qn(c)&&(i=c.body.start-a,r=c.body.end+a,t>=i&&t<=r&&(e=Math.min(t-i,r-t),s<=e&&(n=c.body,s=e)))})),n}isEndListAppended(t){const e=this.endListFragments[t];return void 0!==e&&(e.buffered||Qn(e))}getState(t){const e=Zn(t),i=this.fragments[e];return i?i.buffered?Qn(i)?zn:qn:Wn:jn}isTimeBuffered(t,e,i){let r,n;for(let s=0;s<i.length;s++){if(r=i.start(s)-this.bufferPadding,n=i.end(s)+this.bufferPadding,t>=r&&e<=n)return!0;if(e<=r)return!1}return!1}onFragLoaded(t,e){const{frag:i,part:r}=e;if("initSegment"===i.sn||i.bitrateTest)return;const n=r?null:e,s=Zn(i);this.fragments[s]={body:i,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:i,part:r,timeRanges:n}=e;if("initSegment"===i.sn)return;const s=i.type;if(r){let t=this.activePartLists[s];t||(this.activePartLists[s]=t=[]),t.push(r)}this.timeRanges=n,Object.keys(n).forEach((t=>{const e=n[t];this.detectEvictedFragments(t,e,s,r)}))}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=Zn(t);return!!this.fragments[e]}hasParts(t){var e;return!(null==(e=this.activePartLists[t])||!e.length)}removeFragmentsInRange(t,e,i,r,n){r&&!this.hasGaps||Object.keys(this.fragments).forEach((s=>{const a=this.fragments[s];if(!a)return;const o=a.body;o.type!==i||r&&!o.gap||o.start<e&&o.end>t&&(a.buffered||n)&&this.removeFragment(o)}))}removeFragment(t){const e=Zn(t);t.stats.loaded=0,t.clearElementaryStreamInfo();const i=this.activePartLists[t.type];if(i){const e=t.sn;this.activePartLists[t.type]=i.filter((t=>t.fragment.sn!==e))}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}}function Qn(t){var e,i,r;return t.buffered&&(t.body.gap||(null==(e=t.range.video)?void 0:e.partial)||(null==(i=t.range.audio)?void 0:i.partial)||(null==(r=t.range.audiovideo)?void 0:r.partial))}function Zn(t){return`${t.type}_${t.level}_${t.sn}`}const Jn={length:0,start:()=>0,end:()=>0};class ts{static isBuffered(t,e){try{if(t){const i=ts.getBuffered(t);for(let t=0;t<i.length;t++)if(e>=i.start(t)&&e<=i.end(t))return!0}}catch(t){}return!1}static bufferInfo(t,e,i){try{if(t){const r=ts.getBuffered(t),n=[];let s;for(s=0;s<r.length;s++)n.push({start:r.start(s),end:r.end(s)});return this.bufferedInfo(n,e,i)}}catch(t){}return{len:0,start:e,end:e,nextStart:void 0}}static bufferedInfo(t,e,i){e=Math.max(0,e),t.sort((function(t,e){const i=t.start-e.start;return i||e.end-t.end}));let r=[];if(i)for(let e=0;e<t.length;e++){const n=r.length;if(n){const s=r[n-1].end;t[e].start-s<i?t[e].end>s&&(r[n-1].end=t[e].end):r.push(t[e])}else r.push(t[e])}else r=t;let n,s=0,a=e,o=e;for(let t=0;t<r.length;t++){const l=r[t].start,c=r[t].end;if(e+i>=l&&e<c)a=l,o=c,s=o-e;else if(e+i<l){n=l;break}}return{len:s,start:a||0,end:o||0,nextStart:n}}static getBuffered(t){try{return t.buffered}catch(t){return Pe.log("failed to get media.buffered",t),Jn}}}class es{constructor(t,e,i,r=0,n=-1,s=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=t,this.sn=e,this.id=i,this.size=r,this.part=n,this.partial=s}}function is(t,e){for(let r=0,n=t.length;r<n;r++){var i;if((null==(i=t[r])?void 0:i.cc)===e)return t[r]}return null}function rs(t,e){if(t){const i=t.start+e;t.start=t.startPTS=i,t.endPTS=i+t.duration}}function ns(t,e){const i=e.fragments;for(let e=0,r=i.length;e<r;e++)rs(i[e],t);e.fragmentHint&&rs(e.fragmentHint,t),e.alignedSliding=!0}function ss(t,e,i){e&&(!function(t,e,i){if(function(t,e,i){return!(!e||!(i.endCC>i.startCC||t&&t.cc<i.startCC))}(t,i,e)){const t=function(t,e){const i=t.fragments,r=e.fragments;if(!r.length||!i.length)return void Pe.log("No fragments to align");const n=is(i,r[0].cc);if(n&&(!n||n.startPTS))return n;Pe.log("No frag in previous level to align on")}(i,e);t&&Se(t.start)&&(Pe.log(`Adjusting PTS using last level due to CC increase within current level ${e.url}`),ns(t.start,e))}}(t,i,e),!i.alignedSliding&&e&&as(i,e),i.alignedSliding||!e||i.skippedSegments||un(e,i))}function as(t,e){if(!t.hasProgramDateTime||!e.hasProgramDateTime)return;const i=t.fragments,r=e.fragments;if(!i.length||!r.length)return;let n,s;const a=Math.min(e.endCC,t.endCC);e.startCC<a&&t.startCC<a&&(n=is(r,a),s=is(i,a)),n&&s||(n=r[Math.floor(r.length/2)],s=is(i,n.cc)||i[Math.floor(i.length/2)]);const o=n.programDateTime,l=s.programDateTime;if(!o||!l)return;ns((l-o)/1e3-(s.start-n.start),t)}const os=Math.pow(2,17);class ls{constructor(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(t,e){const i=t.url;if(!i)return Promise.reject(new us({type:Le.NETWORK_ERROR,details:Re.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error("Fragment does not have a "+(i?"part list":"url")),networkDetails:null}));this.abort();const r=this.config,n=r.fLoader,s=r.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),t.gap){if(t.tagList.some((t=>"GAP"===t[0])))return void o(hs(t));t.gap=!1}const l=this.loader=t.loader=n?new n(r):new s(r),c=cs(t),h=An(r.fragLoadPolicy.default),u={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:os};t.stats=l.stats,l.load(c,u,{onSuccess:(e,i,r,n)=>{this.resetLoader(t,l);let s=e.data;r.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(s.slice(0,16)),s=s.slice(16)),a({frag:t,part:null,payload:s,networkDetails:n})},onError:(e,r,n,s)=>{this.resetLoader(t,l),o(new us({type:Le.NETWORK_ERROR,details:Re.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:ve({url:i,data:void 0},e),error:new Error(`HTTP Error ${e.code} ${e.text}`),networkDetails:n,stats:s}))},onAbort:(e,i,r)=>{this.resetLoader(t,l),o(new us({type:Le.NETWORK_ERROR,details:Re.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:r,stats:e}))},onTimeout:(e,i,r)=>{this.resetLoader(t,l),o(new us({type:Le.NETWORK_ERROR,details:Re.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:r,stats:e}))},onProgress:(i,r,n,s)=>{e&&e({frag:t,part:null,payload:n,networkDetails:s})}})}))}loadPart(t,e,i){this.abort();const r=this.config,n=r.fLoader,s=r.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap)return void o(hs(t,e));const l=this.loader=t.loader=n?new n(r):new s(r),c=cs(t,e),h=An(r.fragLoadPolicy.default),u={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:os};e.stats=l.stats,l.load(c,u,{onSuccess:(r,n,s,o)=>{this.resetLoader(t,l),this.updateStatsFromPart(t,e);const c={frag:t,part:e,payload:r.data,networkDetails:o};i(c),a(c)},onError:(i,r,n,s)=>{this.resetLoader(t,l),o(new us({type:Le.NETWORK_ERROR,details:Re.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:ve({url:c.url,data:void 0},i),error:new Error(`HTTP Error ${i.code} ${i.text}`),networkDetails:n,stats:s}))},onAbort:(i,r,n)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,l),o(new us({type:Le.NETWORK_ERROR,details:Re.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:n,stats:i}))},onTimeout:(i,r,n)=>{this.resetLoader(t,l),o(new us({type:Le.NETWORK_ERROR,details:Re.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:n,stats:i}))}})}))}updateStatsFromPart(t,e){const i=t.stats,r=e.stats,n=r.total;if(i.loaded+=r.loaded,n){const r=Math.round(t.duration/e.duration),s=Math.min(Math.round(i.loaded/n),r),a=(r-s)*Math.round(i.loaded/s);i.total=i.loaded+a}else i.total=Math.max(i.loaded,i.total);const s=i.loading,a=r.loading;s.start?s.first+=a.first-a.start:(s.start=a.start,s.first=a.first),s.end=a.end}resetLoader(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()}}function cs(t,e=null){const i=e||t,r={frag:t,part:e,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},n=i.byteRangeStartOffset,s=i.byteRangeEndOffset;if(Se(n)&&Se(s)){var a;let e=n,i=s;if("initSegment"===t.sn&&"AES-128"===(null==(a=t.decryptdata)?void 0:a.method)){const t=s-n;t%16&&(i=s+(16-t%16)),0!==n&&(r.resetIV=!0,e=n-16)}r.rangeStart=e,r.rangeEnd=i}return r}function hs(t,e){const i=new Error(`GAP ${t.gap?"tag":"attribute"} found`),r={type:Le.MEDIA_ERROR,details:Re.FRAG_GAP,fatal:!1,frag:t,error:i,networkDetails:null};return e&&(r.part=e),(e||t).stats.aborted=!0,new us(r)}class us extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class ds{constructor(t,e){this.subtle=void 0,this.aesIV=void 0,this.subtle=t,this.aesIV=e}decrypt(t,e){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t)}}class fs{constructor(t,e){this.subtle=void 0,this.key=void 0,this.subtle=t,this.key=e}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}class gs{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(t){const e=new DataView(t),i=new Uint32Array(4);for(let t=0;t<4;t++)i[t]=e.getUint32(4*t);return i}initTable(){const t=this.sBox,e=this.invSBox,i=this.subMix,r=i[0],n=i[1],s=i[2],a=i[3],o=this.invSubMix,l=o[0],c=o[1],h=o[2],u=o[3],d=new Uint32Array(256);let f=0,g=0,p=0;for(p=0;p<256;p++)d[p]=p<128?p<<1:p<<1^283;for(p=0;p<256;p++){let i=g^g<<1^g<<2^g<<3^g<<4;i=i>>>8^255&i^99,t[f]=i,e[i]=f;const o=d[f],p=d[o],m=d[p];let y=257*d[i]^16843008*i;r[f]=y<<24|y>>>8,n[f]=y<<16|y>>>16,s[f]=y<<8|y>>>24,a[f]=y,y=16843009*m^65537*p^257*o^16843008*f,l[i]=y<<24|y>>>8,c[i]=y<<16|y>>>16,h[i]=y<<8|y>>>24,u[i]=y,f?(f=o^d[d[d[m^o]]],g^=d[d[g]]):f=g=1}}expandKey(t){const e=this.uint8ArrayToUint32Array_(t);let i=!0,r=0;for(;r<e.length&&i;)i=e[r]===this.key[r],r++;if(i)return;this.key=e;const n=this.keySize=e.length;if(4!==n&&6!==n&&8!==n)throw new Error("Invalid aes key size="+n);const s=this.ksRows=4*(n+6+1);let a,o;const l=this.keySchedule=new Uint32Array(s),c=this.invKeySchedule=new Uint32Array(s),h=this.sBox,u=this.rcon,d=this.invSubMix,f=d[0],g=d[1],p=d[2],m=d[3];let y,v;for(a=0;a<s;a++)a<n?y=l[a]=e[a]:(v=y,a%n==0?(v=v<<8|v>>>24,v=h[v>>>24]<<24|h[v>>>16&255]<<16|h[v>>>8&255]<<8|h[255&v],v^=u[a/n|0]<<24):n>6&&a%n==4&&(v=h[v>>>24]<<24|h[v>>>16&255]<<16|h[v>>>8&255]<<8|h[255&v]),l[a]=y=(l[a-n]^v)>>>0);for(o=0;o<s;o++)a=s-o,v=3&o?l[a]:l[a-4],c[o]=o<4||a<=4?v:f[h[v>>>24]]^g[h[v>>>16&255]]^p[h[v>>>8&255]]^m[h[255&v]],c[o]=c[o]>>>0}networkToHostOrderSwap(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24}decrypt(t,e,i){const r=this.keySize+6,n=this.invKeySchedule,s=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],c=a[2],h=a[3],u=this.uint8ArrayToUint32Array_(i);let d=u[0],f=u[1],g=u[2],p=u[3];const m=new Int32Array(t),y=new Int32Array(m.length);let v,A,E,T,S,b,k,_,L,R,C,D,w,I;const P=this.networkToHostOrderSwap;for(;e<m.length;){for(L=P(m[e]),R=P(m[e+1]),C=P(m[e+2]),D=P(m[e+3]),S=L^n[0],b=D^n[1],k=C^n[2],_=R^n[3],w=4,I=1;I<r;I++)v=o[S>>>24]^l[b>>16&255]^c[k>>8&255]^h[255&_]^n[w],A=o[b>>>24]^l[k>>16&255]^c[_>>8&255]^h[255&S]^n[w+1],E=o[k>>>24]^l[_>>16&255]^c[S>>8&255]^h[255&b]^n[w+2],T=o[_>>>24]^l[S>>16&255]^c[b>>8&255]^h[255&k]^n[w+3],S=v,b=A,k=E,_=T,w+=4;v=s[S>>>24]<<24^s[b>>16&255]<<16^s[k>>8&255]<<8^s[255&_]^n[w],A=s[b>>>24]<<24^s[k>>16&255]<<16^s[_>>8&255]<<8^s[255&S]^n[w+1],E=s[k>>>24]<<24^s[_>>16&255]<<16^s[S>>8&255]<<8^s[255&b]^n[w+2],T=s[_>>>24]<<24^s[S>>16&255]<<16^s[b>>8&255]<<8^s[255&k]^n[w+3],y[e]=P(v^d),y[e+1]=P(T^f),y[e+2]=P(E^g),y[e+3]=P(A^p),d=L,f=R,g=C,p=D,e+=4}return y.buffer}}class ps{constructor(t,{removePKCS7Padding:e=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.useSoftware=t.enableSoftwareAES,this.removePKCS7Padding=e,e)try{const t=self.crypto;t&&(this.subtle=t.subtle||t.webkitSubtle)}catch(t){}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(){const{currentResult:t,remainderData:e}=this;if(!t||e)return this.reset(),null;const i=new Uint8Array(t);return this.reset(),this.removePKCS7Padding?function(t){const e=t.byteLength,i=e&&new DataView(t.buffer).getUint8(e-1);return i?oi(t,0,e-i):t}(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,e,i){return this.useSoftware?new Promise(((r,n)=>{this.softwareDecrypt(new Uint8Array(t),e,i);const s=this.flush();s?r(s.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(t),e,i)}softwareDecrypt(t,e,i){const{currentIV:r,currentResult:n,remainderData:s}=this;this.logOnce("JS AES decrypt"),s&&(t=Vi(s,t),this.remainderData=null);const a=this.getValidChunk(t);if(!a.length)return null;r&&(i=r);let o=this.softwareDecrypter;o||(o=this.softwareDecrypter=new gs),o.expandKey(e);const l=n;return this.currentResult=o.decrypt(a.buffer,0,i),this.currentIV=oi(a,-16).buffer,l||null}webCryptoDecrypt(t,e,i){if(this.key!==e||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,e,i));this.key=e,this.fastAesKey=new fs(this.subtle,e)}return this.fastAesKey.expandKey().then((e=>{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new ds(this.subtle,new Uint8Array(i)).decrypt(t.buffer,e)})).catch((r=>(Pe.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(t,e,i))))}onWebCryptoError(t,e,i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,i);const r=this.flush();if(r)return r.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(t){let e=t;const i=t.length-t.length%16;return i!==t.length&&(e=oi(t,0,i),this.remainderData=oi(t,i)),e}logOnce(t){this.logEnabled&&(Pe.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const ms=function(t){let e="";const i=t.length;for(let r=0;r<i;r++)e+=`[${t.start(r).toFixed(3)}-${t.end(r).toFixed(3)}]`;return e},ys="STOPPED",vs="IDLE",As="KEY_LOADING",Es="FRAG_LOADING",Ts="FRAG_LOADING_WAITING_RETRY",Ss="WAITING_TRACK",bs="PARSING",ks="PARSED",_s="ENDED",Ls="ERROR",Rs="WAITING_INIT_PTS",Cs="WAITING_LEVEL";class Ds extends Yn{constructor(t,e,i,r,n){super(),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=ys,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.loadedmetadata=!1,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.onvseeking=null,this.onvended=null,this.logPrefix="",this.log=void 0,this.warn=void 0,this.playlistType=n,this.logPrefix=r,this.log=Pe.log.bind(Pe,`${r}:`),this.warn=Pe.warn.bind(Pe,`${r}:`),this.hls=t,this.fragmentLoader=new ls(t.config),this.keyLoader=i,this.fragmentTracker=e,this.config=t.config,this.decrypter=new ps(t.config),t.on(_e.MANIFEST_LOADED,this.onManifestLoaded,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const t=this.fragCurrent;null!=t&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=ys}_streamEnded(t,e){if(e.live||t.nextStart||!t.end||!this.media)return!1;const i=e.partList;if(null!=i&&i.length){const t=i[i.length-1];return ts.isBuffered(this.media,t.start+t.duration/2)}const r=e.fragments[e.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(r)}getLevelDetails(){var t;if(this.levels&&null!==this.levelLastLoaded)return null==(t=this.levelLastLoaded)?void 0:t.details}onMediaAttached(t,e){const i=this.media=this.mediaBuffer=e.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),i.addEventListener("seeking",this.onvseeking),i.addEventListener("ended",this.onvended);const r=this.config;this.levels&&r.autoStartLoad&&this.state===ys&&this.startLoad(r.startPosition)}onMediaDetaching(){const t=this.media;null!=t&&t.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),t&&this.onvseeking&&this.onvended&&(t.removeEventListener("seeking",this.onvseeking),t.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.keyLoader&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}onMediaSeeking(){const{config:t,fragCurrent:e,media:i,mediaBuffer:r,state:n}=this,s=i?i.currentTime:0,a=ts.bufferInfo(r||i,s,t.maxBufferHole);if(this.log(`media seeking to ${Se(s)?s.toFixed(3):s}, state: ${n}`),this.state===_s)this.resetLoadingState();else if(e){const i=t.maxFragLookUpTolerance,r=e.start-i,n=e.start+e.duration+i;if(!a.len||n<a.start||r>a.end){const t=s>n;(s<r||t)&&(t&&e.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),e.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}i&&(this.fragmentTracker.removeFragmentsInRange(s,1/0,this.playlistType,!0),this.lastCurrentTime=s),this.loadedmetadata||a.len||(this.nextLoadPosition=this.startPosition=s),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(t,e){this.startTimeOffset=e.startTimeOffset,this.initPTS=[]}onHandlerDestroying(){this.hls.off(_e.MANIFEST_LOADED,this.onManifestLoaded,this),this.stopLoad(),super.onHandlerDestroying(),this.hls=null}onHandlerDestroyed(){this.state=ys,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(t,e,i){this._loadFragForPlayback(t,e,i)}_loadFragForPlayback(t,e,i){this._doFragLoad(t,e,i,(e=>{if(this.fragContextChanged(t))return this.warn(`Fragment ${t.sn}${e.part?" p: "+e.part.index:""} of level ${t.level} was dropped during download.`),void this.fragmentTracker.removeFragment(t);t.stats.chunkCount++,this._handleFragmentLoadProgress(e)})).then((e=>{if(!e)return;const i=this.state;this.fragContextChanged(t)?(i===Es||!this.fragCurrent&&i===bs)&&(this.fragmentTracker.removeFragment(t),this.state=vs):("payload"in e&&(this.log(`Loaded fragment ${t.sn} of level ${t.level}`),this.hls.trigger(_e.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e))})).catch((e=>{this.state!==ys&&this.state!==Ls&&(this.warn(`Frag error: ${(null==e?void 0:e.message)||e}`),this.resetFragmentLoading(t))}))}clearTrackerIfNeeded(t){var e;const{fragmentTracker:i}=this;if(i.getState(t)===Wn){const e=t.type,r=this.getFwdBufferInfo(this.mediaBuffer,e),n=Math.max(t.duration,r?r.len:this.config.maxBufferLength),s=this.backtrackFragment;(1===(s?t.sn-s.sn:0)||this.reduceMaxBufferLength(n,t.duration))&&i.removeFragment(t)}else 0===(null==(e=this.mediaBuffer)?void 0:e.buffered.length)?i.removeAllFragments():i.hasParts(t.type)&&(i.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),i.getState(t)===zn&&i.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const e=t.fragments[t.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}flushMainBuffer(t,e,i=null){if(!(t-e))return;const r={startOffset:t,endOffset:e,type:i};this.hls.trigger(_e.BUFFER_FLUSHING,r)}_loadInitSegment(t,e){this._doFragLoad(t,e).then((e=>{if(!e||this.fragContextChanged(t)||!this.levels)throw new Error("init load aborted");return e})).then((e=>{const{hls:i}=this,{payload:r}=e,n=t.decryptdata;if(r&&r.byteLength>0&&null!=n&&n.key&&n.iv&&"AES-128"===n.method){const s=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),n.key.buffer,n.iv.buffer).catch((e=>{throw i.trigger(_e.ERROR,{type:Le.MEDIA_ERROR,details:Re.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e})).then((r=>{const n=self.performance.now();return i.trigger(_e.FRAG_DECRYPTED,{frag:t,payload:r,stats:{tstart:s,tdecrypt:n}}),e.payload=r,this.completeInitSegmentLoad(e)}))}return this.completeInitSegmentLoad(e)})).catch((e=>{this.state!==ys&&this.state!==Ls&&(this.warn(e),this.resetFragmentLoading(t))}))}completeInitSegmentLoad(t){const{levels:e}=this;if(!e)throw new Error("init load aborted, missing levels");const i=t.frag.stats;this.state=vs,t.frag.data=new Uint8Array(t.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}fragContextChanged(t){const{fragCurrent:e}=this;return!t||!e||t.sn!==e.sn||t.level!==e.level}fragBufferedComplete(t,e){var i,r,n,s;const a=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.playlistType===Pr?"level":"track"} ${t.level} (frag:[${(null!=(i=t.startPTS)?i:NaN).toFixed(3)}-${(null!=(r=t.endPTS)?r:NaN).toFixed(3)}] > buffer:${a?ms(ts.getBuffered(a)):"(detached)"})`),"initSegment"!==t.sn){var o;if(t.type!==xr){const e=t.elementaryStreams;if(!Object.keys(e).some((t=>!!e[t])))return void(this.state=vs)}const e=null==(o=this.levels)?void 0:o[t.level];null!=e&&e.fragmentError&&(this.log(`Resetting level fragment error count of ${e.fragmentError} on frag buffered`),e.fragmentError=0)}this.state=vs,a&&(!this.loadedmetadata&&t.type==Pr&&a.buffered.length&&(null==(n=this.fragCurrent)?void 0:n.sn)===(null==(s=this.fragPrevious)?void 0:s.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const{frag:i,part:r,partsLoaded:n}=t,s=!n||0===n.length||n.some((t=>!t)),a=new es(i.level,i.sn,i.stats.chunkCount+1,0,r?r.index:-1,!s);e.flush(a)}_handleFragmentLoadProgress(t){}_doFragLoad(t,e,i=null,r){var n;const s=null==e?void 0:e.details;if(!this.levels||!s)throw new Error(`frag load aborted, missing level${s?"":" detail"}s`);let a=null;if(!t.encrypted||null!=(n=t.decryptdata)&&n.key?!t.encrypted&&s.encryptedFragments.length&&this.keyLoader.loadClear(t,s.encryptedFragments):(this.log(`Loading key for ${t.sn} of [${s.startSN}-${s.endSN}], ${"[stream-controller]"===this.logPrefix?"level":"track"} ${t.level}`),this.state=As,this.fragCurrent=t,a=this.keyLoader.load(t).then((t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(_e.KEY_LOADED,t),this.state===As&&(this.state=vs),t})),this.hls.trigger(_e.KEY_LOADING,{frag:t}),null===this.fragCurrent&&(a=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))),i=Math.max(t.start,i||0),this.config.lowLatencyMode&&"initSegment"!==t.sn){const n=s.partList;if(n&&r){i>t.end&&s.fragmentHint&&(t=s.fragmentHint);const o=this.getNextPart(n,t,i);if(o>-1){const l=n[o];let c;return this.log(`Loading part sn: ${t.sn} p: ${l.index} cc: ${t.cc} of playlist [${s.startSN}-${s.endSN}] parts [0-${o}-${n.length-1}] ${"[stream-controller]"===this.logPrefix?"level":"track"}: ${t.level}, target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=Es,c=a?a.then((i=>!i||this.fragContextChanged(i.frag)?null:this.doFragPartsLoad(t,l,e,r))).catch((t=>this.handleFragLoadError(t))):this.doFragPartsLoad(t,l,e,r).catch((t=>this.handleFragLoadError(t))),this.hls.trigger(_e.FRAG_LOADING,{frag:t,part:l,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):c}if(!t.url||this.loadedEndOfParts(n,i))return Promise.resolve(null)}}this.log(`Loading fragment ${t.sn} cc: ${t.cc} ${s?"of ["+s.startSN+"-"+s.endSN+"] ":""}${"[stream-controller]"===this.logPrefix?"level":"track"}: ${t.level}, target: ${parseFloat(i.toFixed(3))}`),Se(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=Es;const o=this.config.progressive;let l;return l=o&&a?a.then((e=>!e||this.fragContextChanged(null==e?void 0:e.frag)?null:this.fragmentLoader.load(t,r))).catch((t=>this.handleFragLoadError(t))):Promise.all([this.fragmentLoader.load(t,o?r:void 0),a]).then((([t])=>(!o&&t&&r&&r(t),t))).catch((t=>this.handleFragLoadError(t))),this.hls.trigger(_e.FRAG_LOADING,{frag:t,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):l}doFragPartsLoad(t,e,i,r){return new Promise(((n,s)=>{var a;const o=[],l=null==(a=i.details)?void 0:a.partList,c=e=>{this.fragmentLoader.loadPart(t,e,r).then((r=>{o[e.index]=r;const s=r.part;this.hls.trigger(_e.FRAG_LOADED,r);const a=fn(i,t.sn,e.index+1)||gn(l,t.sn,e.index+1);if(!a)return n({frag:t,part:s,partsLoaded:o});c(a)})).catch(s)};c(e)}))}handleFragLoadError(t){if("data"in t){const e=t.data;t.data&&e.details===Re.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):this.hls.trigger(_e.ERROR,e)}else this.hls.trigger(_e.ERROR,{type:Le.OTHER_ERROR,details:Re.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==bs)return void(this.fragCurrent||this.state===ys||this.state===Ls||(this.state=vs));const{frag:i,part:r,level:n}=e,s=self.performance.now();i.stats.parsing.end=s,r&&(r.stats.parsing.end=s),this.updateLevelTiming(i,r,n,t.partial)}getCurrentContext(t){const{levels:e,fragCurrent:i}=this,{level:r,sn:n,part:s}=t;if(null==e||!e[r])return this.warn(`Levels object was unset while buffering fragment ${n} of level ${r}. The current chunk will not be buffered.`),null;const a=e[r],o=s>-1?fn(a,n,s):null,l=o?o.fragment:function(t,e,i){if(null==t||!t.details)return null;const r=t.details;let n=r.fragments[e-r.startSN];return n||(n=r.fragmentHint,n&&n.sn===e?n:e<r.startSN&&i&&i.sn===e?i:null)}(a,n,i);return l?(i&&i!==l&&(l.stats=i.stats),{frag:l,part:o,level:a}):null}bufferFragmentData(t,e,i,r,n){var s;if(!t||this.state!==bs)return;const{data1:a,data2:o}=t;let l=a;if(a&&o&&(l=Vi(a,o)),null==(s=l)||!s.length)return;const c={type:t.type,frag:e,part:i,chunkMeta:r,parent:e.type,data:l};if(this.hls.trigger(_e.BUFFER_APPENDING,c),t.dropped&&t.independent&&!i){if(n)return;this.flushBufferGap(e)}}flushBufferGap(t){const e=this.media;if(!e)return;if(!ts.isBuffered(e,e.currentTime))return void this.flushMainBuffer(0,t.start);const i=e.currentTime,r=ts.bufferInfo(e,i,0),n=t.duration,s=Math.min(2*this.config.maxFragLookUpTolerance,.25*n),a=Math.max(Math.min(t.start-s,r.end-s),i+s);t.start-a>s&&this.flushMainBuffer(a,t.start)}getFwdBufferInfo(t,e){const i=this.getLoadPosition();return Se(i)?this.getFwdBufferInfoAtPos(t,i,e):null}getFwdBufferInfoAtPos(t,e,i){const{config:{maxBufferHole:r}}=this,n=ts.bufferInfo(t,e,r);if(0===n.len&&void 0!==n.nextStart){const s=this.fragmentTracker.getBufferedFrag(e,i);if(s&&n.nextStart<s.end)return ts.bufferInfo(t,e,Math.max(n.nextStart,r))}return n}getMaxBufferLength(t){const{config:e}=this;let i;return i=t?Math.max(8*e.maxBufferSize/t,e.maxBufferLength):e.maxBufferLength,Math.min(i,e.maxMaxBufferLength)}reduceMaxBufferLength(t,e){const i=this.config,r=Math.max(Math.min(t-e,i.maxBufferLength),e),n=Math.max(t-3*e,i.maxMaxBufferLength/2,r);return n>=r&&(i.maxMaxBufferLength=n,this.warn(`Reduce max buffer length to ${n}s`),!0)}getAppendedFrag(t,e=Pr){const i=this.fragmentTracker.getAppendedFrag(t,Pr);return i&&"fragment"in i?i.fragment:i}getNextFragment(t,e){const i=e.fragments,r=i.length;if(!r)return null;const{config:n}=this,s=i[0].start;let a;if(e.live){const o=n.initialLiveManifestSize;if(r<o)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${o})`),null;(!e.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||t<s)&&(a=this.getInitialLiveFragment(e,i),this.startPosition=this.nextLoadPosition=a?this.hls.liveSyncPosition||a.start:t)}else t<=s&&(a=i[0]);if(!a){const i=n.lowLatencyMode?e.partEnd:e.fragmentEnd;a=this.getFragmentAtPosition(t,i,e)}return this.mapToInitFragWhenRequired(a)}isLoopLoading(t,e){const i=this.fragmentTracker.getState(t);return(i===qn||i===zn&&!!t.gap)&&this.nextLoadPosition>e}getNextFragmentLoopLoading(t,e,i,r,n){const s=t.gap,a=this.getNextFragment(this.nextLoadPosition,e);if(null===a)return a;if(t=a,s&&t&&!t.gap&&i.nextStart){const e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,r);if(null!==e&&i.len+e.len>=n)return this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${t.sn}`),null}return t}mapToInitFragWhenRequired(t){return null==t||!t.initSegment||null!=t&&t.initSegment.data||this.bitrateTest?t:t.initSegment}getNextPart(t,e,i){let r=-1,n=!1,s=!0;for(let a=0,o=t.length;a<o;a++){const o=t[a];if(s=s&&!o.independent,r>-1&&i<o.start)break;const l=o.loaded;l?r=-1:(n||o.independent||s)&&o.fragment===e&&(r=a),n=l}return r}loadedEndOfParts(t,e){const i=t[t.length-1];return i&&e>i.start&&i.loaded}getInitialLiveFragment(t,e){const i=this.fragPrevious;let r=null;if(i){if(t.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),r=function(t,e,i){if(null===e||!Array.isArray(t)||!t.length||!Se(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;i=i||0;for(let r=0;r<t.length;++r){const n=t[r];if(kn(e,i,n))return n}return null}(e,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){const n=i.sn+1;if(n>=t.startSN&&n<=t.endSN){const s=e[n-t.startSN];i.cc===s.cc&&(r=s,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=function(t,e){return Tn(t,(t=>t.cc<e?1:t.cc>e?-1:0))}(e,i.cc),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{const e=this.hls.liveSyncPosition;null!==e&&(r=this.getFragmentAtPosition(e,this.bitrateTest?t.fragmentEnd:t.edge,t))}return r}getFragmentAtPosition(t,e,i){const{config:r}=this;let{fragPrevious:n}=this,{fragments:s,endSN:a}=i;const{fragmentHint:o}=i,{maxFragLookUpTolerance:l}=r,c=i.partList,h=!!(r.lowLatencyMode&&null!=c&&c.length&&o);let u;if(h&&o&&!this.bitrateTest&&(s=s.concat(o),a=o.sn),t<e){u=Sn(n,s,t,t>e-l?0:l)}else u=s[s.length-1];if(u){const t=u.sn-i.startSN,e=this.fragmentTracker.getState(u);if((e===qn||e===zn&&u.gap)&&(n=u),n&&u.sn===n.sn&&(!h||c[0].fragment.sn>u.sn)){if(n&&u.level===n.level){const e=s[t+1];u=u.sn<a&&this.fragmentTracker.getState(e)!==qn?e:null}}}return u}synchronizeToLiveEdge(t){const{config:e,media:i}=this;if(!i)return;const r=this.hls.liveSyncPosition,n=i.currentTime,s=t.fragments[0].start,a=t.edge,o=n>=s-e.maxFragLookUpTolerance&&n<=a;if(null!==r&&i.duration>r&&(n<r||!o)){const s=void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;(!o&&i.readyState<4||n<a-s)&&(this.loadedmetadata||(this.nextLoadPosition=r),i.readyState&&(this.warn(`Playback: ${n.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${r.toFixed(3)}`),i.currentTime=r))}}alignPlaylists(t,e,i){const r=t.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;const n=t.fragments[0].start,s=!e,a=t.alignedSliding&&Se(n);if(s||!a&&!n){const{fragPrevious:n}=this;ss(n,i,t);const s=t.fragments[0].start;return this.log(`Live playlist sliding: ${s.toFixed(2)} start-sn: ${e?e.startSN:"na"}->${t.startSN} prev-sn: ${n?n.sn:"na"} fragments: ${r}`),s}return n}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)}setStartPosition(t,e){let i=this.startPosition;if(i<e&&(i=-1),-1===i||-1===this.lastCurrentTime){const r=null!==this.startTimeOffset,n=r?this.startTimeOffset:t.startTimeOffset;null!==n&&Se(n)?(i=e+n,n<0&&(i+=t.totalduration),i=Math.min(Math.max(e,i),e+t.totalduration),this.log(`Start time offset ${n} found in ${r?"multivariant":"media"} playlist, adjust startPosition to ${i}`),this.startPosition=i):t.live?i=this.hls.liveSyncPosition||e:this.startPosition=i=0,this.lastCurrentTime=i}this.nextLoadPosition=i}getLoadPosition(){const{media:t}=this;let e=0;return this.loadedmetadata&&t?e=t.currentTime:this.nextLoadPosition&&(e=this.nextLoadPosition),e}handleFragLoadAborted(t,e){this.transmuxer&&"initSegment"!==t.sn&&t.stats.aborted&&(this.warn(`Fragment ${t.sn}${e?" part "+e.index:""} of level ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){this.fragCurrent&&(this.fragContextChanged(t)||this.state===Ts)||(this.state=vs)}onFragmentOrKeyLoadError(t,e){if(e.chunkMeta&&!e.frag){const t=this.getCurrentContext(e.chunkMeta);t&&(e.frag=t.frag)}const i=e.frag;if(!i||i.type!==t||!this.levels)return;var r;if(this.fragContextChanged(i))return void this.warn(`Frag load error must match current frag to retry ${i.url} > ${null==(r=this.fragCurrent)?void 0:r.url}`);const n=e.details===Re.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);const s=e.errorAction,{action:a,retryCount:o=0,retryConfig:l}=s||{};if(s&&a===Cn&&l){this.resetStartWhenNotLoaded(this.levelLastLoaded);const r=vn(l,o);this.warn(`Fragment ${i.sn} of ${t} ${i.level} errored with ${e.details}, retrying loading ${o+1}/${l.maxNumRetry} in ${r}ms`),s.resolved=!0,this.retryDate=self.performance.now()+r,this.state=Ts}else if(l&&s){if(this.resetFragmentErrors(t),!(o<l.maxNumRetry))return void Pe.warn(`${e.details} reached or exceeded max retry (${o})`);n||a===Rn||(s.resolved=!0)}else(null==s?void 0:s.action)===Ln?this.state=Cs:this.state=Ls;this.tickImmediate()}reduceLengthAndFlushBuffer(t){if(this.state===bs||this.state===ks){const e=t.frag,i=t.parent,r=this.getFwdBufferInfo(this.mediaBuffer,i),n=r&&r.len>.5;n&&this.reduceMaxBufferLength(r.len,(null==e?void 0:e.duration)||10);const s=!n;return s&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${i} buffer`),e&&(this.fragmentTracker.removeFragment(e),this.nextLoadPosition=e.start),this.resetLoadingState(),s}return!1}resetFragmentErrors(t){t===Or&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==ys&&(this.state=vs)}afterBufferFlushed(t,e,i){if(!t)return;const r=ts.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,r,i),this.state===_s&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=vs}resetStartWhenNotLoaded(t){if(!this.loadedmetadata){this.startFragRequested=!1;const e=t?t.details:null;null!=e&&e.live?(this.startPosition=-1,this.setStartPosition(e,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.warn(`The loading context changed while buffering fragment ${t.sn} of level ${t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,e,i,r){var n;const s=i.details;if(!s)return void this.warn("level.details undefined");if(!Object.keys(t.elementaryStreams).reduce(((e,n)=>{const a=t.elementaryStreams[n];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${t.sn} ${n} duration reliably (${o})`),e||!1;const l=r?0:cn(s,t,a.startPTS,a.endPTS,a.startDTS,a.endDTS);return this.hls.trigger(_e.LEVEL_PTS_UPDATED,{details:s,level:i,drift:l,type:n,frag:t,start:a.startPTS,end:a.endPTS}),!0}return e}),!1)&&null===(null==(n=this.transmuxer)?void 0:n.error)){const e=new Error(`Found no media in fragment ${t.sn} of level ${t.level} resetting transmuxer to fallback to playlist timing`);if(0===i.fragmentError&&(i.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)),this.warn(e.message),this.hls.trigger(_e.ERROR,{type:Le.MEDIA_ERROR,details:Re.FRAG_PARSING_ERROR,fatal:!1,error:e,frag:t,reason:`Found no media in msn ${t.sn} of level "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=ks,this.hls.trigger(_e.FRAG_PARSED,{frag:t,part:e})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(t){"demuxerWorker"===t.event&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`))}get state(){return this._state}}class ws{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:e}=this;let i;return t.length?(i=1===t.length?t[0]:function(t,e){const i=new Uint8Array(e);let r=0;for(let e=0;e<t.length;e++){const n=t[e];i.set(n,r),r+=n.length}return i}(t,e),this.reset(),i):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}function Is(t="",e=9e4){return{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Ps{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(t,e,i,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(t){this.initPTS=t,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(t,e){return!1}appendFrame(t,e,i){}demux(t,e){this.cachedData&&(t=Vi(this.cachedData,t),this.cachedData=null);let i,r=hi(t,0),n=r?r.length:0;const s=this._audioTrack,a=this._id3Track,o=r?fi(r):void 0,l=t.length;for((null===this.basePTS||0===this.frameIndex&&Se(o))&&(this.basePTS=Os(o,e,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),r&&r.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Hr,duration:Number.POSITIVE_INFINITY});n<l;){if(this.canParse(t,n)){const e=this.appendFrame(s,t,n);e?(this.frameIndex++,this.lastPTS=e.sample.pts,n+=e.length,i=n):n=l}else di(t,n)?(r=hi(t,n),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Hr,duration:Number.POSITIVE_INFINITY}),n+=r.length,i=n):n++;if(n===l&&i!==l){const e=oi(t,i);this.cachedData?this.cachedData=Vi(this.cachedData,e):this.cachedData=e}}return{audioTrack:s,videoTrack:Is(),id3Track:a,textTrack:Is()}}demuxSampleAes(t,e,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(t){const e=this.cachedData;return e&&(this.cachedData=null,this.demux(e,0)),{audioTrack:this._audioTrack,videoTrack:Is(),id3Track:this._id3Track,textTrack:Is()}}destroy(){}}const Os=(t,e,i)=>{if(Se(t))return 90*t;return 9e4*e+(i?9e4*i.baseTime/i.timescale:0)};function xs(t,e){return 255===t[e]&&240==(246&t[e+1])}function Ms(t,e){return 1&t[e+1]?7:9}function Fs(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function Ns(t,e){return e+1<t.length&&xs(t,e)}function Us(t,e){if(Ns(t,e)){const i=Ms(t,e);if(e+i>=t.length)return!1;const r=Fs(t,e);if(r<=i)return!1;const n=e+r;return n===t.length||Ns(t,n)}return!1}function Bs(t,e,i,r,n){if(!t.samplerate){const s=function(t,e,i,r){let n,s,a,o;const l=navigator.userAgent.toLowerCase(),c=r,h=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];n=1+((192&e[i+2])>>>6);const u=(60&e[i+2])>>>2;if(!(u>h.length-1))return a=(1&e[i+2])<<2,a|=(192&e[i+3])>>>6,Pe.log(`manifest codec:${r}, ADTS type:${n}, samplingIndex:${u}`),/firefox/i.test(l)?u>=6?(n=5,o=new Array(4),s=u-3):(n=2,o=new Array(2),s=u):-1!==l.indexOf("android")?(n=2,o=new Array(2),s=u):(n=5,o=new Array(4),r&&(-1!==r.indexOf("mp4a.40.29")||-1!==r.indexOf("mp4a.40.5"))||!r&&u>=6?s=u-3:((r&&-1!==r.indexOf("mp4a.40.2")&&(u>=6&&1===a||/vivaldi/i.test(l))||!r&&1===a)&&(n=2,o=new Array(2)),s=u)),o[0]=n<<3,o[0]|=(14&u)>>1,o[1]|=(1&u)<<7,o[1]|=a<<3,5===n&&(o[1]|=(14&s)>>1,o[2]=(1&s)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:h[u],channelCount:a,codec:"mp4a.40."+n,manifestCodec:c};{const e=new Error(`invalid ADTS sampling index:${u}`);t.emit(_e.ERROR,_e.ERROR,{type:Le.MEDIA_ERROR,details:Re.FRAG_PARSING_ERROR,fatal:!0,error:e,reason:e.message})}}(e,i,r,n);if(!s)return;t.config=s.config,t.samplerate=s.samplerate,t.channelCount=s.channelCount,t.codec=s.codec,t.manifestCodec=s.manifestCodec,Pe.log(`parsed codec:${t.codec}, rate:${s.samplerate}, channels:${s.channelCount}`)}}function $s(t){return 9216e4/t}function Gs(t,e,i,r,n){const s=r+n*$s(t.samplerate),a=function(t,e){const i=Ms(t,e);if(e+i<=t.length){const r=Fs(t,e)-i;if(r>0)return{headerLength:i,frameLength:r}}}(e,i);let o;if(a){const{frameLength:r,headerLength:n}=a,l=n+r,c=Math.max(0,i+l-e.length);c?(o=new Uint8Array(l-n),o.set(e.subarray(i+n,e.length),0)):o=e.subarray(i+n,i+l);const h={unit:o,pts:s};return c||t.samples.push(h),{sample:h,length:l,missing:c}}const l=e.length-i;o=new Uint8Array(l),o.set(e.subarray(i,e.length),0);return{sample:{unit:o,pts:s},length:l,missing:-1}}let Ks=null;const Hs=[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],Vs=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Ys=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],js=[0,1,1,4];function Ws(t,e,i,r,n){if(i+24>e.length)return;const s=zs(e,i);if(s&&i+s.frameLength<=e.length){const a=r+n*(9e4*s.samplesPerFrame/s.sampleRate),o={unit:e.subarray(i,i+s.frameLength),pts:a,dts:a};return t.config=[],t.channelCount=s.channelCount,t.samplerate=s.sampleRate,t.samples.push(o),{sample:o,length:s.frameLength,missing:0}}}function zs(t,e){const i=t[e+1]>>3&3,r=t[e+1]>>1&3,n=t[e+2]>>4&15,s=t[e+2]>>2&3;if(1!==i&&0!==n&&15!==n&&3!==s){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*Hs[14*(3===i?3-r:3===r?3:4)+n-1],c=Vs[3*(3===i?0:2===i?1:2)+s],h=3===o?1:2,u=Ys[i][r],d=js[r],f=8*u*d,g=Math.floor(u*l/c+a)*d;if(null===Ks){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ks=t?parseInt(t[1]):0}return!!Ks&&Ks<=87&&2===r&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:c,channelCount:h,frameLength:g,samplesPerFrame:f}}}function qs(t,e){return!(255!==t[e]||224&~t[e+1]||!(6&t[e+1]))}function Xs(t,e){return e+1<t.length&&qs(t,e)}function Qs(t,e){if(e+1<t.length&&qs(t,e)){const i=4,r=zs(t,e);let n=i;null!=r&&r.frameLength&&(n=r.frameLength);const s=e+n;return s===t.length||Xs(t,s)}return!1}const Zs=/\/emsg[-/]ID3/i;const Js=(t,e)=>{let i=0,r=5;e+=r;const n=new Uint32Array(1),s=new Uint32Array(1),a=new Uint8Array(1);for(;r>0;){a[0]=t[e];const o=Math.min(r,8),l=8-o;s[0]=4278190080>>>24+l<<l,n[0]=(a[0]&s[0])>>l,i=i?i<<o|n[0]:n[0],e+=1,r-=o}return i};class ta extends Ps{constructor(t){super(),this.observer=void 0,this.observer=t}resetInitSegment(t,e,i,r){super.resetInitSegment(t,e,i,r),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:e,duration:r,inputTimeScale:9e4,dropped:0}}canParse(t,e){return e+64<t.length}appendFrame(t,e,i){const r=ea(t,e,i,this.basePTS,this.frameIndex);if(-1!==r){return{sample:t.samples[t.samples.length-1],length:r,missing:0}}}static probe(t){if(!t)return!1;const e=hi(t,0);if(!e)return!1;const i=e.length;return 11===t[i]&&119===t[i+1]&&void 0!==fi(e)&&Js(t,i)<16}}function ea(t,e,i,r,n){if(i+8>e.length)return-1;if(11!==e[i]||119!==e[i+1])return-1;const s=e[i+4]>>6;if(s>=3)return-1;const a=[48e3,44100,32e3][s],o=63&e[i+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+s];if(i+l>e.length)return-1;const c=e[i+6]>>5;let h=0;2===c?h+=2:(1&c&&1!==c&&(h+=2),4&c&&(h+=2));const u=(e[i+6]<<8|e[i+7])>>12-h&1,d=[2,1,2,3,3,4,4,5][c]+u,f=e[i+5]>>3,g=7&e[i+5],p=new Uint8Array([s<<6|f<<1|g>>2,(3&g)<<6|c<<3|u<<2|o>>4,o<<4&224]),m=r+n*(1536/a*9e4),y=e.subarray(i,i+l);return t.config=p,t.channelCount=d,t.samplerate=a,t.samples.push({unit:y,pts:m}),l}class ia{constructor(){this.VideoSample=null}createVideoSample(t,e,i,r){return{key:t,frame:!1,pts:e,dts:i,units:[],debug:r,length:0}}getLastNalUnit(t){var e;let i,r=this.VideoSample;if(r&&0!==r.units.length||(r=t[t.length-1]),null!=(e=r)&&e.units){const t=r.units;i=t[t.length-1]}return i}pushAccessUnit(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){const i=e.samples,r=i.length;if(!r)return void e.dropped++;{const e=i[r-1];t.pts=e.pts,t.dts=e.dts}}e.samples.push(t)}t.debug.length&&Pe.log(t.pts+"/"+t.dts+":"+t.debug)}}class ra{constructor(t){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const t=this.data,e=this.bytesAvailable,i=t.byteLength-e,r=new Uint8Array(4),n=Math.min(4,e);if(0===n)throw new Error("no bytes available");r.set(t.subarray(i,i+n)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=8*n,this.bytesAvailable-=n}skipBits(t){let e;t=Math.min(t,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(e=(t-=this.bitsAvailable)>>3,t-=e<<3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)}readBits(t){let e=Math.min(this.bitsAvailable,t);const i=this.word>>>32-e;if(t>32&&Pe.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0)this.word<<=e;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return e=t-e,e>0&&this.bitsAvailable?i<<e|this.readBits(e):i}skipLZ(){let t;for(t=0;t<this.bitsAvailable;++t)if(this.word&2147483648>>>t)return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const t=this.skipLZ();return this.readBits(t+1)-1}readEG(){const t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}skipScalingList(t){let e,i=8,r=8;for(let n=0;n<t;n++)0!==r&&(e=this.readEG(),r=(i+e+256)%256),i=0===r?i:r}readSPS(){let t,e,i,r=0,n=0,s=0,a=0;const o=this.readUByte.bind(this),l=this.readBits.bind(this),c=this.readUEG.bind(this),h=this.readBoolean.bind(this),u=this.skipBits.bind(this),d=this.skipEG.bind(this),f=this.skipUEG.bind(this),g=this.skipScalingList.bind(this);o();const p=o();if(l(5),u(3),o(),f(),100===p||110===p||122===p||244===p||44===p||83===p||86===p||118===p||128===p){const t=c();if(3===t&&u(1),f(),f(),u(1),h())for(e=3!==t?8:12,i=0;i<e;i++)h()&&g(i<6?16:64)}f();const m=c();if(0===m)c();else if(1===m)for(u(1),d(),d(),t=c(),i=0;i<t;i++)d();f(),u(1);const y=c(),v=c(),A=l(1);0===A&&u(1),u(1),h()&&(r=c(),n=c(),s=c(),a=c());let E=[1,1];if(h()&&h()){switch(o()){case 1:E=[1,1];break;case 2:E=[12,11];break;case 3:E=[10,11];break;case 4:E=[16,11];break;case 5:E=[40,33];break;case 6:E=[24,11];break;case 7:E=[20,11];break;case 8:E=[32,11];break;case 9:E=[80,33];break;case 10:E=[18,11];break;case 11:E=[15,11];break;case 12:E=[64,33];break;case 13:E=[160,99];break;case 14:E=[4,3];break;case 15:E=[3,2];break;case 16:E=[2,1];break;case 255:E=[o()<<8|o(),o()<<8|o()]}}return{width:Math.ceil(16*(y+1)-2*r-2*n),height:(2-A)*(v+1)*16-(A?2:4)*(s+a),pixelRatio:E}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class na extends ia{parseAVCPES(t,e,i,r,n){const s=this.parseAVCNALu(t,i.data);let a,o=this.VideoSample,l=!1;i.data=null,o&&s.length&&!t.audFound&&(this.pushAccessUnit(o,t),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts,"")),s.forEach((r=>{var s;switch(r.type){case 1:{let e=!1;a=!0;const n=r.data;if(l&&n.length>4){const t=new ra(n).readSliceType();2!==t&&4!==t&&7!==t&&9!==t||(e=!0)}var c;if(e)null!=(c=o)&&c.frame&&!o.key&&(this.pushAccessUnit(o,t),o=this.VideoSample=null);o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts,"")),o.frame=!0,o.key=e;break}case 5:a=!0,null!=(s=o)&&s.frame&&!o.key&&(this.pushAccessUnit(o,t),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts,"")),o.key=!0,o.frame=!0;break;case 6:a=!0,Wi(r.data,1,i.pts,e.samples);break;case 7:{var h,u;a=!0,l=!0;const e=r.data,i=new ra(e).readSPS();if(!t.sps||t.width!==i.width||t.height!==i.height||(null==(h=t.pixelRatio)?void 0:h[0])!==i.pixelRatio[0]||(null==(u=t.pixelRatio)?void 0:u[1])!==i.pixelRatio[1]){t.width=i.width,t.height=i.height,t.pixelRatio=i.pixelRatio,t.sps=[e],t.duration=n;const r=e.subarray(1,4);let s="avc1.";for(let t=0;t<3;t++){let e=r[t].toString(16);e.length<2&&(e="0"+e),s+=e}t.codec=s}break}case 8:a=!0,t.pps=[r.data];break;case 9:a=!0,t.audFound=!0,o&&this.pushAccessUnit(o,t),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts,"");break;case 12:a=!0;break;default:a=!1,o&&(o.debug+="unknown NAL "+r.type+" ")}if(o&&a){o.units.push(r)}})),r&&o&&(this.pushAccessUnit(o,t),this.VideoSample=null)}parseAVCNALu(t,e){const i=e.byteLength;let r=t.naluState||0;const n=r,s=[];let a,o,l,c=0,h=-1,u=0;for(-1===r&&(h=0,u=31&e[0],r=0,c=1);c<i;)if(a=e[c++],r)if(1!==r)if(a)if(1===a){if(o=c-r-1,h>=0){const t={data:e.subarray(h,o),type:u};s.push(t)}else{const i=this.getLastNalUnit(t.samples);i&&(n&&c<=4-n&&i.state&&(i.data=i.data.subarray(0,i.data.byteLength-n)),o>0&&(i.data=Vi(i.data,e.subarray(0,o)),i.state=0))}c<i?(l=31&e[c],h=c,u=l,r=0):r=-1}else r=0;else r=3;else r=a?0:2;else r=a?0:1;if(h>=0&&r>=0){const t={data:e.subarray(h,i),type:u,state:r};s.push(t)}if(0===s.length){const i=this.getLastNalUnit(t.samples);i&&(i.data=Vi(i.data,e))}return t.naluState=r,s}}class sa{constructor(t,e,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new ps(e,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(t,e,i){const r=t[e].unit;if(r.length<=16)return;const n=r.subarray(16,r.length-r.length%16),s=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(s).then((n=>{const s=new Uint8Array(n);r.set(s,16),this.decrypter.isSync()||this.decryptAacSamples(t,e+1,i)}))}decryptAacSamples(t,e,i){for(;;e++){if(e>=t.length)return void i();if(!(t[e].unit.length<32)&&(this.decryptAacSample(t,e,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const e=16*Math.floor((t.length-48)/160)+16,i=new Int8Array(e);let r=0;for(let e=32;e<t.length-16;e+=160,r+=16)i.set(t.subarray(e,e+16),r);return i}getAvcDecryptedUnit(t,e){const i=new Uint8Array(e);let r=0;for(let e=32;e<t.length-16;e+=160,r+=16)t.set(i.subarray(r,r+16),e);return t}decryptAvcSample(t,e,i,r,n){const s=zi(n.data),a=this.getAvcEncryptedData(s);this.decryptBuffer(a.buffer).then((a=>{n.data=this.getAvcDecryptedUnit(s,a),this.decrypter.isSync()||this.decryptAvcSamples(t,e,i+1,r)}))}decryptAvcSamples(t,e,i,r){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,i=0){if(e>=t.length)return void r();const n=t[e].units;for(;!(i>=n.length);i++){const s=n[i];if(!(s.data.length<=48||1!==s.type&&5!==s.type||(this.decryptAvcSample(t,e,i,r,s),this.decrypter.isSync())))return}}}}const aa=188;class oa{constructor(t,e,i){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._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=t,this.config=e,this.typeSupported=i,this.videoParser=new na}static probe(t){const e=oa.syncOffset(t);return e>0&&Pe.warn(`MPEG2-TS detected but first sync word found @ offset ${e}`),-1!==e}static syncOffset(t){const e=t.length;let i=Math.min(940,e-aa)+1,r=0;for(;r<i;){let n=!1,s=-1,a=0;for(let o=r;o<e;o+=aa){if(71!==t[o]||e-o!==aa&&71!==t[o+aa]){if(a)return-1;break}if(a++,-1===s&&(s=o,0!==s&&(i=Math.min(s+18612,t.length-aa)+1)),n||(n=0===la(t,o)),n&&a>1&&(0===s&&a>2||o+aa>i))return s}r++}return-1}static createTrack(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:Ci[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}}resetInitSegment(t,e,i,r){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=oa.createTrack("video"),this._audioTrack=oa.createTrack("audio",r),this._id3Track=oa.createTrack("id3"),this._txtTrack=oa.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=i,this._duration=r}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:e,_id3Track:i}=this;t&&(t.pesData=null),e&&(e.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,e,i=!1,r=!1){let n;i||(this.sampleAes=null);const s=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let c=s.pid,h=s.pesData,u=a.pid,d=o.pid,f=a.pesData,g=o.pesData,p=null,m=this.pmtParsed,y=this._pmtId,v=t.length;if(this.remainderData&&(v=(t=Vi(this.remainderData,t)).length,this.remainderData=null),v<aa&&!r)return this.remainderData=t,{audioTrack:a,videoTrack:s,id3Track:o,textTrack:l};const A=Math.max(0,oa.syncOffset(t));v-=(v-A)%aa,v<t.byteLength&&!r&&(this.remainderData=new Uint8Array(t.buffer,v,t.buffer.byteLength-v));let E=0;for(let e=A;e<v;e+=aa)if(71===t[e]){const r=!!(64&t[e+1]),v=la(t,e);let E;if((48&t[e+3])>>4>1){if(E=e+5+t[e+4],E===e+aa)continue}else E=e+4;switch(v){case c:r&&(h&&(n=fa(h))&&this.videoParser.parseAVCPES(s,l,n,!1,this._duration),h={data:[],size:0}),h&&(h.data.push(t.subarray(E,e+aa)),h.size+=e+aa-E);break;case u:if(r){if(f&&(n=fa(f)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,n);break;case"mp3":this.parseMPEGPES(a,n);break;case"ac3":this.parseAC3PES(a,n)}f={data:[],size:0}}f&&(f.data.push(t.subarray(E,e+aa)),f.size+=e+aa-E);break;case d:r&&(g&&(n=fa(g))&&this.parseID3PES(o,n),g={data:[],size:0}),g&&(g.data.push(t.subarray(E,e+aa)),g.size+=e+aa-E);break;case 0:r&&(E+=t[E]+1),y=this._pmtId=ca(t,E);break;case y:{r&&(E+=t[E]+1);const n=ha(t,E,this.typeSupported,i,this.observer);c=n.videoPid,c>0&&(s.pid=c,s.segmentCodec=n.segmentVideoCodec),u=n.audioPid,u>0&&(a.pid=u,a.segmentCodec=n.segmentAudioCodec),d=n.id3Pid,d>0&&(o.pid=d),null===p||m||(Pe.warn(`MPEG-TS PMT found at ${e} after unknown PID '${p}'. Backtracking to sync byte @${A} to parse all TS packets.`),p=null,e=A-188),m=this.pmtParsed=!0;break}case 17:case 8191:break;default:p=v}}else E++;E>0&&ua(this.observer,new Error(`Found ${E} TS packet/s that do not start with 0x47`)),s.pesData=h,a.pesData=f,o.pesData=g;const T={audioTrack:a,videoTrack:s,id3Track:o,textTrack:l};return r&&this.extractRemainingSamples(T),T}flush(){const{remainderData:t}=this;let e;return this.remainderData=null,e=t?this.demux(t,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e}extractRemainingSamples(t){const{audioTrack:e,videoTrack:i,id3Track:r,textTrack:n}=t,s=i.pesData,a=e.pesData,o=r.pesData;let l;if(s&&(l=fa(s))?(this.videoParser.parseAVCPES(i,n,l,!0,this._duration),i.pesData=null):i.pesData=s,a&&(l=fa(a))){switch(e.segmentCodec){case"aac":this.parseAACPES(e,l);break;case"mp3":this.parseMPEGPES(e,l);break;case"ac3":this.parseAC3PES(e,l)}e.pesData=null}else null!=a&&a.size&&Pe.log("last AAC PES packet truncated,might overlap between fragments"),e.pesData=a;o&&(l=fa(o))?(this.parseID3PES(r,l),r.pesData=null):r.pesData=o}demuxSampleAes(t,e,i){const r=this.demux(t,i,!0,!this.config.progressive),n=this.sampleAes=new sa(this.observer,this.config,e);return this.decrypt(r,n)}decrypt(t,e){return new Promise((i=>{const{audioTrack:r,videoTrack:n}=t;r.samples&&"aac"===r.segmentCodec?e.decryptAacSamples(r.samples,0,(()=>{n.samples?e.decryptAvcSamples(n.samples,0,0,(()=>{i(t)})):i(t)})):n.samples&&e.decryptAvcSamples(n.samples,0,0,(()=>{i(t)}))}))}destroy(){this._duration=0}parseAACPES(t,e){let i=0;const r=this.aacOverFlow;let n,s,a,o=e.data;if(r){this.aacOverFlow=null;const e=r.missing,n=r.sample.unit.byteLength;if(-1===e)o=Vi(r.sample.unit,o);else{const s=n-e;r.sample.unit.set(o.subarray(0,e),s),t.samples.push(r.sample),i=r.missing}}for(n=i,s=o.length;n<s-1&&!Ns(o,n);n++);if(n!==i){let t;const e=n<s-1;if(t=e?`AAC PES did not start with ADTS header,offset:${n}`:"No ADTS header found in AAC PES",ua(this.observer,new Error(t),e),!e)return}if(Bs(t,this.observer,o,n,this.audioCodec),void 0!==e.pts)a=e.pts;else{if(!r)return void Pe.warn("[tsdemuxer]: AAC PES unknown PTS");{const e=$s(t.samplerate);a=r.sample.pts+e}}let l,c=0;for(;n<s;){if(l=Gs(t,o,n,a,c),n+=l.length,l.missing){this.aacOverFlow=l;break}for(c++;n<s-1&&!Ns(o,n);n++);}}parseMPEGPES(t,e){const i=e.data,r=i.length;let n=0,s=0;const a=e.pts;if(void 0!==a)for(;s<r;)if(Xs(i,s)){const e=Ws(t,i,s,a,n);if(!e)break;s+=e.length,n++}else s++;else Pe.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(t,e){{const i=e.data,r=e.pts;if(void 0===r)return void Pe.warn("[tsdemuxer]: AC3 PES unknown PTS");const n=i.length;let s,a=0,o=0;for(;o<n&&(s=ea(t,i,o,r,a++))>0;)o+=s}}parseID3PES(t,e){if(void 0===e.pts)return void Pe.warn("[tsdemuxer]: ID3 PES unknown PTS");const i=Te({},e,{type:this._videoTrack?Yr:Hr,duration:Number.POSITIVE_INFINITY});t.samples.push(i)}}function la(t,e){return((31&t[e+1])<<8)+t[e+2]}function ca(t,e){return(31&t[e+10])<<8|t[e+11]}function ha(t,e,i,r,n){const s={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},a=e+3+((15&t[e+1])<<8|t[e+2])-4;for(e+=12+((15&t[e+10])<<8|t[e+11]);e<a;){const a=la(t,e),o=(15&t[e+3])<<8|t[e+4];switch(t[e]){case 207:if(!r){da("ADTS AAC");break}case 15:-1===s.audioPid&&(s.audioPid=a);break;case 21:-1===s.id3Pid&&(s.id3Pid=a);break;case 219:if(!r){da("H.264");break}case 27:-1===s.videoPid&&(s.videoPid=a,s.segmentVideoCodec="avc");break;case 3:case 4:i.mpeg||i.mp3?-1===s.audioPid&&(s.audioPid=a,s.segmentAudioCodec="mp3"):Pe.log("MPEG audio found, not supported in this browser");break;case 193:if(!r){da("AC-3");break}case 129:i.ac3?-1===s.audioPid&&(s.audioPid=a,s.segmentAudioCodec="ac3"):Pe.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===s.audioPid&&o>0){let r=e+5,n=o;for(;n>2;){if(106===t[r])!0!==i.ac3?Pe.log("AC-3 audio found, not supported in this browser for now"):(s.audioPid=a,s.segmentAudioCodec="ac3");const e=t[r+1]+2;r+=e,n-=e}}break;case 194:case 135:return ua(n,new Error("Unsupported EC-3 in M2TS found")),s;case 36:return ua(n,new Error("Unsupported HEVC in M2TS found")),s}e+=o+5}return s}function ua(t,e,i){Pe.warn(`parsing error: ${e.message}`),t.emit(_e.ERROR,_e.ERROR,{type:Le.MEDIA_ERROR,details:Re.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,error:e,reason:e.message})}function da(t){Pe.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function fa(t){let e,i,r,n,s,a=0;const o=t.data;if(!t||0===t.size)return null;for(;o[0].length<19&&o.length>1;)o[0]=Vi(o[0],o[1]),o.splice(1,1);e=o[0];if(1===(e[0]<<16)+(e[1]<<8)+e[2]){if(i=(e[4]<<8)+e[5],i&&i>t.size-6)return null;const l=e[7];192&l&&(n=536870912*(14&e[9])+4194304*(255&e[10])+16384*(254&e[11])+128*(255&e[12])+(254&e[13])/2,64&l?(s=536870912*(14&e[14])+4194304*(255&e[15])+16384*(254&e[16])+128*(255&e[17])+(254&e[18])/2,n-s>54e5&&(Pe.warn(`${Math.round((n-s)/9e4)}s delta between PTS and DTS, align them`),n=s)):s=n),r=e[8];let c=r+9;if(t.size<=c)return null;t.size-=c;const h=new Uint8Array(t.size);for(let t=0,i=o.length;t<i;t++){e=o[t];let i=e.byteLength;if(c){if(c>i){c-=i;continue}e=e.subarray(c),i-=c,c=0}h.set(e,a),a+=i}return i&&(i-=r+3),{data:h,pts:n,dts:s,len:i}}return null}class ga{static getSilentFrame(t,e){if("mp4a.40.2"===t){if(1===e)return new Uint8Array([0,200,0,128,35,128]);if(2===e)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===e)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===e)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===e)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])}}}const pa=Math.pow(2,32)-1;class ma{static init(){let t;for(t in ma.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},ma.types)ma.types.hasOwnProperty(t)&&(ma.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);const e=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);ma.HDLR_TYPES={video:e,audio:i};const 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]);ma.STTS=ma.STSC=ma.STCO=n,ma.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),ma.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),ma.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),ma.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const s=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);ma.FTYP=ma.box(ma.types.ftyp,s,o,s,a),ma.DINF=ma.box(ma.types.dinf,ma.box(ma.types.dref,r))}static box(t,...e){let i=8,r=e.length;const n=r;for(;r--;)i+=e[r].byteLength;const s=new Uint8Array(i);for(s[0]=i>>24&255,s[1]=i>>16&255,s[2]=i>>8&255,s[3]=255&i,s.set(t,4),r=0,i=8;r<n;r++)s.set(e[r],i),i+=e[r].byteLength;return s}static hdlr(t){return ma.box(ma.types.hdlr,ma.HDLR_TYPES[t])}static mdat(t){return ma.box(ma.types.mdat,t)}static mdhd(t,e){e*=t;const i=Math.floor(e/(pa+1)),r=Math.floor(e%(pa+1));return ma.box(ma.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,r>>24,r>>16&255,r>>8&255,255&r,85,196,0,0]))}static mdia(t){return ma.box(ma.types.mdia,ma.mdhd(t.timescale,t.duration),ma.hdlr(t.type),ma.minf(t))}static mfhd(t){return ma.box(ma.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}static minf(t){return"audio"===t.type?ma.box(ma.types.minf,ma.box(ma.types.smhd,ma.SMHD),ma.DINF,ma.stbl(t)):ma.box(ma.types.minf,ma.box(ma.types.vmhd,ma.VMHD),ma.DINF,ma.stbl(t))}static moof(t,e,i){return ma.box(ma.types.moof,ma.mfhd(t),ma.traf(i,e))}static moov(t){let e=t.length;const i=[];for(;e--;)i[e]=ma.trak(t[e]);return ma.box.apply(null,[ma.types.moov,ma.mvhd(t[0].timescale,t[0].duration)].concat(i).concat(ma.mvex(t)))}static mvex(t){let e=t.length;const i=[];for(;e--;)i[e]=ma.trex(t[e]);return ma.box.apply(null,[ma.types.mvex,...i])}static mvhd(t,e){e*=t;const i=Math.floor(e/(pa+1)),r=Math.floor(e%(pa+1)),n=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,r>>24,r>>16&255,r>>8&255,255&r,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 ma.box(ma.types.mvhd,n)}static sdtp(t){const e=t.samples||[],i=new Uint8Array(4+e.length);let r,n;for(r=0;r<e.length;r++)n=e[r].flags,i[r+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return ma.box(ma.types.sdtp,i)}static stbl(t){return ma.box(ma.types.stbl,ma.stsd(t),ma.box(ma.types.stts,ma.STTS),ma.box(ma.types.stsc,ma.STSC),ma.box(ma.types.stsz,ma.STSZ),ma.box(ma.types.stco,ma.STCO))}static avc1(t){let e,i,r,n=[],s=[];for(e=0;e<t.sps.length;e++)i=t.sps[e],r=i.byteLength,n.push(r>>>8&255),n.push(255&r),n=n.concat(Array.prototype.slice.call(i));for(e=0;e<t.pps.length;e++)i=t.pps[e],r=i.byteLength,s.push(r>>>8&255),s.push(255&r),s=s.concat(Array.prototype.slice.call(i));const a=ma.box(ma.types.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|t.sps.length].concat(n).concat([t.pps.length]).concat(s))),o=t.width,l=t.height,c=t.pixelRatio[0],h=t.pixelRatio[1];return ma.box(ma.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,o>>8&255,255&o,l>>8&255,255&l,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]),a,ma.box(ma.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),ma.box(ma.types.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,255&c,h>>24,h>>16&255,h>>8&255,255&h])))}static esds(t){const e=t.config.length;return new Uint8Array([0,0,0,0,3,23+e,0,1,0,4,15+e,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([e]).concat(t.config).concat([6,1,2]))}static audioStsd(t){const e=t.samplerate;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,e>>8&255,255&e,0,0])}static mp4a(t){return ma.box(ma.types.mp4a,ma.audioStsd(t),ma.box(ma.types.esds,ma.esds(t)))}static mp3(t){return ma.box(ma.types[".mp3"],ma.audioStsd(t))}static ac3(t){return ma.box(ma.types["ac-3"],ma.audioStsd(t),ma.box(ma.types.dac3,t.config))}static stsd(t){return"audio"===t.type?"mp3"===t.segmentCodec&&"mp3"===t.codec?ma.box(ma.types.stsd,ma.STSD,ma.mp3(t)):"ac3"===t.segmentCodec?ma.box(ma.types.stsd,ma.STSD,ma.ac3(t)):ma.box(ma.types.stsd,ma.STSD,ma.mp4a(t)):ma.box(ma.types.stsd,ma.STSD,ma.avc1(t))}static tkhd(t){const e=t.id,i=t.duration*t.timescale,r=t.width,n=t.height,s=Math.floor(i/(pa+1)),a=Math.floor(i%(pa+1));return ma.box(ma.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,a>>24,a>>16&255,a>>8&255,255&a,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,255&r,0,0,n>>8&255,255&n,0,0]))}static traf(t,e){const i=ma.sdtp(t),r=t.id,n=Math.floor(e/(pa+1)),s=Math.floor(e%(pa+1));return ma.box(ma.types.traf,ma.box(ma.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r])),ma.box(ma.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,s>>24,s>>16&255,s>>8&255,255&s])),ma.trun(t,i.length+16+20+8+16+8+8),i)}static trak(t){return t.duration=t.duration||4294967295,ma.box(ma.types.trak,ma.tkhd(t),ma.mdia(t))}static trex(t){const e=t.id;return ma.box(ma.types.trex,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,e){const i=t.samples||[],r=i.length,n=12+16*r,s=new Uint8Array(n);let a,o,l,c,h,u;for(e+=8+n,s.set(["video"===t.type?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,255&r,e>>>24&255,e>>>16&255,e>>>8&255,255&e],0),a=0;a<r;a++)o=i[a],l=o.duration,c=o.size,h=o.flags,u=o.cts,s.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,c>>>24&255,c>>>16&255,c>>>8&255,255&c,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,61440&h.degradPrio,15&h.degradPrio,u>>>24&255,u>>>16&255,u>>>8&255,255&u],12+16*a);return ma.box(ma.types.trun,s)}static initSegment(t){ma.types||ma.init();const e=ma.moov(t);return Vi(ma.FTYP,e)}}ma.types=void 0,ma.HDLR_TYPES=void 0,ma.STTS=void 0,ma.STSC=void 0,ma.STCO=void 0,ma.STSZ=void 0,ma.VMHD=void 0,ma.SMHD=void 0,ma.STSD=void 0,ma.FTYP=void 0,ma.DINF=void 0;function ya(t,e,i=1,r=!1){const n=t*e*i;return r?Math.round(n):n}function va(t,e=!1){return ya(t,1e3,1/9e4,e)}let Aa,Ea=null,Ta=null;class Sa{constructor(t,e,i,r=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=t,this.config=e,this.typeSupported=i,this.ISGenerated=!1,null===Ea){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ea=t?parseInt(t[1]):0}if(null===Ta){const t=navigator.userAgent.match(/Safari\/(\d+)/i);Ta=t?parseInt(t[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){Pe.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=t}resetNextTimestamp(){Pe.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){Pe.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let e=!1;const i=t.reduce(((t,i)=>{const r=i.pts-t;return r<-4294967296?(e=!0,ba(t,i.pts)):r>0?t:i.pts}),t[0].pts);return e&&Pe.debug("PTS rollover detected"),i}remux(t,e,i,r,n,s,a,o){let l,c,h,u,d,f,g=n,p=n;const m=t.pid>-1,y=e.pid>-1,v=e.samples.length,A=t.samples.length>0,E=a&&v>0||v>1;if((!m||A)&&(!y||E)||this.ISGenerated||a){if(this.ISGenerated){var T,S,b,k;const t=this.videoTrackConfig;!t||e.width===t.width&&e.height===t.height&&(null==(T=e.pixelRatio)?void 0:T[0])===(null==(S=t.pixelRatio)?void 0:S[0])&&(null==(b=e.pixelRatio)?void 0:b[1])===(null==(k=t.pixelRatio)?void 0:k[1])||this.resetInitSegment()}else h=this.generateIS(t,e,n,s);const i=this.isVideoContiguous;let r,a=-1;if(E&&(a=function(t){for(let e=0;e<t.length;e++)if(t[e].key)return e;return-1}(e.samples),!i&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,a>0){Pe.warn(`[mp4-remuxer]: Dropped ${a} out of ${v} video samples due to a missing keyframe`);const t=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(a),e.dropped+=a,p+=(e.samples[0].pts-t)/e.inputTimeScale,r=p}else-1===a&&(Pe.warn(`[mp4-remuxer]: No keyframe found out of ${v} video samples`),f=!1);if(this.ISGenerated){if(A&&E){const i=this.getVideoStartPts(e.samples),r=(ba(t.samples[0].pts,i)-i)/e.inputTimeScale;g+=Math.max(0,r),p+=Math.max(0,-r)}if(A){if(t.samplerate||(Pe.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),h=this.generateIS(t,e,n,s)),c=this.remuxAudio(t,g,this.isAudioContiguous,s,y||E||o===Or?p:void 0),E){const r=c?c.endPTS-c.startPTS:0;e.inputTimeScale||(Pe.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),h=this.generateIS(t,e,n,s)),l=this.remuxVideo(e,p,i,r)}}else E&&(l=this.remuxVideo(e,p,i,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=r)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(d=ka(i,n,this._initPTS,this._initDTS)),r.samples.length&&(u=_a(r,n,this._initPTS))),{audio:c,video:l,initSegment:h,independent:f,text:u,id3:d}}generateIS(t,e,i,r){const n=t.samples,s=e.samples,a=this.typeSupported,o={},l=this._initPTS;let c,h,u,d=!l||r,f="audio/mp4";if(d&&(c=h=1/0),t.config&&n.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",t.codec=""):a.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3"}o.audio={id:"audio",container:f,codec:t.codec,initSegment:"mp3"===t.segmentCodec&&a.mpeg?new Uint8Array(0):ma.initSegment([t]),metadata:{channelCount:t.channelCount}},d&&(u=t.inputTimeScale,l&&u===l.timescale?d=!1:c=h=n[0].pts-Math.round(u*i))}if(e.sps&&e.pps&&s.length){if(e.timescale=e.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:ma.initSegment([e]),metadata:{width:e.width,height:e.height}},d)if(u=e.inputTimeScale,l&&u===l.timescale)d=!1;else{const t=this.getVideoStartPts(s),e=Math.round(u*i);h=Math.min(h,ba(s[0].dts,t)-e),c=Math.min(c,t-e)}this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,d?(this._initPTS={baseTime:c,timescale:u},this._initDTS={baseTime:h,timescale:u}):c=u=void 0,{tracks:o,initPTS:c,timescale:u}}remuxVideo(t,e,i,r){const n=t.inputTimeScale,s=t.samples,a=[],o=s.length,l=this._initPTS;let c,h,u=this.nextAvcDts,d=8,f=this.videoSampleDuration,g=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,m=!1;if(!i||null===u){const t=e*n,r=s[0].pts-ba(s[0].dts,s[0].pts);Ea&&null!==u&&Math.abs(t-r-u)<15e3?i=!0:u=t-r}const y=l.baseTime*n/l.timescale;for(let t=0;t<o;t++){const e=s[t];e.pts=ba(e.pts-y,u),e.dts=ba(e.dts-y,u),e.dts<s[t>0?t-1:t].dts&&(m=!0)}m&&s.sort((function(t,e){const i=t.dts-e.dts,r=t.pts-e.pts;return i||r})),c=s[0].dts,h=s[s.length-1].dts;const v=h-c,A=v?Math.round(v/(o-1)):f||t.inputTimeScale/30;if(i){const t=c-u,i=t>A,r=t<-1;if((i||r)&&(i?Pe.warn(`AVC: ${va(t,!0)} ms (${t}dts) hole between fragments detected at ${e.toFixed(3)}`):Pe.warn(`AVC: ${va(-t,!0)} ms (${t}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!r||u>=s[0].pts||Ea)){c=u;const e=s[0].pts-t;if(i)s[0].dts=c,s[0].pts=e;else for(let i=0;i<s.length&&!(s[i].dts>e);i++)s[i].dts-=t,s[i].pts-=t;Pe.log(`Video: Initial PTS/DTS adjusted: ${va(e,!0)}/${va(c,!0)}, delta: ${va(t,!0)} ms`)}}c=Math.max(0,c);let E=0,T=0,S=c;for(let t=0;t<o;t++){const e=s[t],i=e.units,r=i.length;let n=0;for(let t=0;t<r;t++)n+=i[t].data.length;T+=n,E+=r,e.length=n,e.dts<S?(e.dts=S,S+=A/4|0||1):S=e.dts,g=Math.min(e.pts,g),p=Math.max(e.pts,p)}h=s[o-1].dts;const b=T+4*E+8;let k;try{k=new Uint8Array(b)}catch(t){return void this.observer.emit(_e.ERROR,_e.ERROR,{type:Le.MUX_ERROR,details:Re.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:b,reason:`fail allocating video mdat ${b}`})}const _=new DataView(k.buffer);_.setUint32(0,b),k.set(ma.types.mdat,4);let L=!1,R=Number.POSITIVE_INFINITY,C=Number.POSITIVE_INFINITY,D=Number.NEGATIVE_INFINITY,w=Number.NEGATIVE_INFINITY;for(let t=0;t<o;t++){const e=s[t],i=e.units;let l,c=0;for(let t=0,e=i.length;t<e;t++){const e=i[t],r=e.data,n=e.data.byteLength;_.setUint32(d,n),d+=4,k.set(r,d),d+=n,c+=4+n}if(t<o-1)f=s[t+1].dts-e.dts,l=s[t+1].pts-e.pts;else{const i=this.config,a=t>0?e.dts-s[t-1].dts:A;if(l=t>0?e.pts-s[t-1].pts:A,i.stretchShortVideoTrack&&null!==this.nextAudioPts){const t=Math.floor(i.maxBufferHole*n),s=(r?g+r*n:this.nextAudioPts)-e.pts;s>t?(f=s-a,f<0?f=a:L=!0,Pe.log(`[mp4-remuxer]: It is approximately ${s/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=a}else f=a}const h=Math.round(e.pts-e.dts);R=Math.min(R,f),D=Math.max(D,f),C=Math.min(C,l),w=Math.max(w,l),a.push(new La(e.key,f,c,h))}if(a.length)if(Ea){if(Ea<70){const t=a[0].flags;t.dependsOn=2,t.isNonSync=0}}else if(Ta&&w-C<D-R&&A/D<.025&&0===a[0].cts){Pe.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let t=c;for(let e=0,i=a.length;e<i;e++){const r=t+a[e].duration,n=t+a[e].cts;if(e<i-1){const t=r+a[e+1].cts;a[e].duration=t-n}else a[e].duration=e?a[e-1].duration:A;a[e].cts=0,t=r}}f=L||!f?A:f,this.nextAvcDts=u=h+f,this.videoSampleDuration=f,this.isVideoContiguous=!0;const I={data1:ma.moof(t.sequenceNumber++,c,Te({},t,{samples:a})),data2:k,startPTS:g/n,endPTS:(p+f)/n,startDTS:c/n,endDTS:u/n,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:t.dropped};return t.samples=[],t.dropped=0,I}getSamplesPerFrame(t){switch(t.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(t,e,i,r,n){const s=t.inputTimeScale,a=s/(t.samplerate?t.samplerate:s),o=this.getSamplesPerFrame(t),l=o*a,c=this._initPTS,h="mp3"===t.segmentCodec&&this.typeSupported.mpeg,u=[],d=void 0!==n;let f=t.samples,g=h?0:8,p=this.nextAudioPts||-1;const m=e*s,y=c.baseTime*s/c.timescale;if(this.isAudioContiguous=i=i||f.length&&p>0&&(r&&Math.abs(m-p)<9e3||Math.abs(ba(f[0].pts-y,m)-p)<20*l),f.forEach((function(t){t.pts=ba(t.pts-y,m)})),!i||p<0){if(f=f.filter((t=>t.pts>=0)),!f.length)return;p=0===n?0:r&&!d?Math.max(0,m):f[0].pts}if("aac"===t.segmentCodec){const e=this.config.maxAudioFramesDrift;for(let i=0,r=p;i<f.length;i++){const n=f[i],a=n.pts,o=a-r,c=Math.abs(1e3*o/s);if(o<=-e*l&&d)0===i&&(Pe.warn(`Audio frame @ ${(a/s).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*o/s)} ms.`),this.nextAudioPts=p=r=a);else if(o>=e*l&&c<1e4&&d){let e=Math.round(o/l);r=a-e*l,r<0&&(e--,r+=l),0===i&&(this.nextAudioPts=p=r),Pe.warn(`[mp4-remuxer]: Injecting ${e} audio frame @ ${(r/s).toFixed(3)}s due to ${Math.round(1e3*o/s)} ms gap.`);for(let s=0;s<e;s++){const e=Math.max(r,0);let s=ga.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);s||(Pe.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),s=n.unit.subarray()),f.splice(i,0,{unit:s,pts:e}),r+=l,i++}}n.pts=r,r+=l}}let v,A=null,E=null,T=0,S=f.length;for(;S--;)T+=f[S].unit.byteLength;for(let e=0,r=f.length;e<r;e++){const r=f[e],n=r.unit;let s=r.pts;if(null!==E){u[e-1].duration=Math.round((s-E)/a)}else{if(i&&"aac"===t.segmentCodec&&(s=p),A=s,!(T>0))return;T+=g;try{v=new Uint8Array(T)}catch(t){return void this.observer.emit(_e.ERROR,_e.ERROR,{type:Le.MUX_ERROR,details:Re.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:T,reason:`fail allocating audio mdat ${T}`})}if(!h){new DataView(v.buffer).setUint32(0,T),v.set(ma.types.mdat,4)}}v.set(n,g);const l=n.byteLength;g+=l,u.push(new La(!0,o,l,0)),E=s}const b=u.length;if(!b)return;const k=u[u.length-1];this.nextAudioPts=p=E+a*k.duration;const _=h?new Uint8Array(0):ma.moof(t.sequenceNumber++,A/a,Te({},t,{samples:u}));t.samples=[];const L=A/s,R=p/s,C={data1:_,data2:v,startPTS:L,endPTS:R,startDTS:L,endDTS:R,type:"audio",hasAudio:!0,hasVideo:!1,nb:b};return this.isAudioContiguous=!0,C}remuxEmptyAudio(t,e,i,r){const n=t.inputTimeScale,s=n/(t.samplerate?t.samplerate:n),a=this.nextAudioPts,o=this._initDTS,l=9e4*o.baseTime/o.timescale,c=(null!==a?a:r.startDTS*n)+l,h=r.endDTS*n+l,u=1024*s,d=Math.ceil((h-c)/u),f=ga.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);if(Pe.warn("[mp4-remuxer]: remux empty Audio"),!f)return void Pe.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");const g=[];for(let t=0;t<d;t++){const e=c+t*u;g.push({unit:f,pts:e,dts:e})}return t.samples=g,this.remuxAudio(t,e,i,!1)}}function ba(t,e){let i;if(null===e)return t;for(i=e<t?-8589934592:8589934592;Math.abs(t-e)>4294967296;)t+=i;return t}function ka(t,e,i,r){const n=t.samples.length;if(!n)return;const s=t.inputTimeScale;for(let a=0;a<n;a++){const n=t.samples[a];n.pts=ba(n.pts-i.baseTime*s/i.timescale,e*s)/s,n.dts=ba(n.dts-r.baseTime*s/r.timescale,e*s)/s}const a=t.samples;return t.samples=[],{samples:a}}function _a(t,e,i){const r=t.samples.length;if(!r)return;const n=t.inputTimeScale;for(let s=0;s<r;s++){const r=t.samples[s];r.pts=ba(r.pts-i.baseTime*n/i.timescale,e*n)/n}t.samples.sort(((t,e)=>t.pts-e.pts));const s=t.samples;return t.samples=[],{samples:s}}class La{constructor(t,e,i,r){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=e,this.size=i,this.cts=r,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1}}}function Ra(t,e){const i=null==t?void 0:t.codec;if(i&&i.length>4)return i;if(e===Be){if("ec-3"===i||"ac-3"===i||"alac"===i)return i;if("fLaC"===i||"Opus"===i){return fr(i,!1)}const t="mp4a.40.5";return Pe.info(`Parsed audio codec "${i}" or audio object type not handled. Using "${t}"`),t}return Pe.warn(`Unhandled video codec "${i}"`),"hvc1"===i||"hev1"===i?"hvc1.1.6.L120.90":"av01"===i?"av01.0.04M.08":"avc1.42e01e"}try{Aa=self.performance.now.bind(self.performance)}catch(t){Pe.debug("Unable to use Performance API on this environment"),Aa=null==qe?void 0:qe.Date.now}const Ca=[{demux:class{constructor(t,e){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=e}resetTimeStamp(){}resetInitSegment(t,e,i,r){const n=this.videoTrack=Is("video",1),s=this.audioTrack=Is("audio",1),a=this.txtTrack=Is("text",1);if(this.id3Track=Is("id3",1),this.timeOffset=0,null==t||!t.byteLength)return;const o=Ni(t);if(o.video){const{id:t,timescale:e,codec:i}=o.video;n.id=t,n.timescale=a.timescale=e,n.codec=i}if(o.audio){const{id:t,timescale:e,codec:i}=o.audio;s.id=t,s.timescale=e,s.codec=i}a.id=Ci.text,n.sampleDuration=0,n.duration=s.duration=r}resetContiguity(){this.remainderData=null}static probe(t){return function(t){const e=t.byteLength;for(let i=0;i<e;){const r=Ii(t,i);if(r>8&&109===t[i+4]&&111===t[i+5]&&111===t[i+6]&&102===t[i+7])return!0;i=r>1?i+r:e}return!1}(t)}demux(t,e){this.timeOffset=e;let i=t;const r=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=Vi(this.remainderData,t));const e=function(t){const e={valid:null,remainder:null},i=Mi(t,["moof"]);if(i.length<2)return e.remainder=t,e;const r=i[i.length-1];return e.valid=oi(t,0,r.byteOffset-8),e.remainder=oi(t,r.byteOffset-8),e}(i);this.remainderData=e.remainder,r.samples=e.valid||new Uint8Array}else r.samples=i;const s=this.extractID3Track(r,e);return n.samples=Yi(e,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:s,textTrack:this.txtTrack}}flush(){const t=this.timeOffset,e=this.videoTrack,i=this.txtTrack;e.samples=this.remainderData||new Uint8Array,this.remainderData=null;const r=this.extractID3Track(e,this.timeOffset);return i.samples=Yi(t,e),{videoTrack:e,audioTrack:Is(),id3Track:r,textTrack:Is()}}extractID3Track(t,e){const i=this.id3Track;if(t.samples.length){const r=Mi(t.samples,["emsg"]);r&&r.forEach((t=>{const r=function(t){const e=t[0];let i="",r="",n=0,s=0,a=0,o=0,l=0,c=0;if(0===e){for(;"\0"!==Di(t.subarray(c,c+1));)i+=Di(t.subarray(c,c+1)),c+=1;for(i+=Di(t.subarray(c,c+1)),c+=1;"\0"!==Di(t.subarray(c,c+1));)r+=Di(t.subarray(c,c+1)),c+=1;r+=Di(t.subarray(c,c+1)),c+=1,n=Ii(t,12),s=Ii(t,16),o=Ii(t,20),l=Ii(t,24),c=28}else if(1===e){c+=4,n=Ii(t,c),c+=4;const e=Ii(t,c);c+=4;const s=Ii(t,c);for(c+=4,a=2**32*e+s,be(a)||(a=Number.MAX_SAFE_INTEGER,Pe.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Ii(t,c),c+=4,l=Ii(t,c),c+=4;"\0"!==Di(t.subarray(c,c+1));)i+=Di(t.subarray(c,c+1)),c+=1;for(i+=Di(t.subarray(c,c+1)),c+=1;"\0"!==Di(t.subarray(c,c+1));)r+=Di(t.subarray(c,c+1)),c+=1;r+=Di(t.subarray(c,c+1)),c+=1}return{schemeIdUri:i,value:r,timeScale:n,presentationTime:a,presentationTimeDelta:s,eventDuration:o,id:l,payload:t.subarray(c,t.byteLength)}}(t);if(Zs.test(r.schemeIdUri)){const t=Se(r.presentationTime)?r.presentationTime/r.timeScale:e+r.presentationTimeDelta/r.timeScale;let n=4294967295===r.eventDuration?Number.POSITIVE_INFINITY:r.eventDuration/r.timeScale;n<=.001&&(n=Number.POSITIVE_INFINITY);const s=r.payload;i.samples.push({data:s,len:s.byteLength,dts:t,pts:t,type:Yr,duration:n})}}))}return i}demuxSampleAes(t,e,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}},remux:class{constructor(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null}destroy(){}resetTimeStamp(t){this.initPTS=t,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(t,e,i,r){this.audioCodec=e,this.videoCodec=i,this.generateInitSegment(function(t,e){if(!t||!e)return t;const i=e.keyId;i&&e.isCommonEncryption&&Mi(t,["moov","trak"]).forEach((t=>{const e=Mi(t,["mdia","minf","stbl","stsd"])[0].subarray(8);let r=Mi(e,["enca"]);const n=r.length>0;n||(r=Mi(e,["encv"])),r.forEach((t=>{Mi(n?t.subarray(28):t.subarray(78),["sinf"]).forEach((t=>{const e=Ki(t);if(e){const t=e.subarray(8,24);t.some((t=>0!==t))||(Pe.log(`[eme] Patching keyId in 'enc${n?"a":"v"}>sinf>>tenc' box: ${_i(t)} -> ${_i(i)}`),e.set(i,8))}}))}))}));return t}(t,r)),this.emitInitSegment=!0}generateInitSegment(t){let{audioCodec:e,videoCodec:i}=this;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const r=this.initData=Ni(t);r.audio&&(e=Ra(r.audio,Be)),r.video&&(i=Ra(r.video,$e));const n={};r.audio&&r.video?n.audiovideo={container:"video/mp4",codec:e+","+i,initSegment:t,id:"main"}:r.audio?n.audio={container:"audio/mp4",codec:e,initSegment:t,id:"audio"}:r.video?n.video={container:"video/mp4",codec:i,initSegment:t,id:"main"}:Pe.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=n}remux(t,e,i,r,n,s){var a,o;let{initPTS:l,lastEndTime:c}=this;const h={audio:void 0,video:void 0,text:r,id3:i,initSegment:void 0};Se(c)||(c=this.lastEndTime=n||0);const u=e.samples;if(null==u||!u.length)return h;const d={initPTS:void 0,timescale:1};let f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(u),f=this.initData),null==(o=f)||!o.length)return Pe.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),h;this.emitInitSegment&&(d.tracks=this.initTracks,this.emitInitSegment=!1);const g=function(t,e){let i=0,r=0,n=0;const s=Mi(t,["moof","traf"]);for(let t=0;t<s.length;t++){const a=s[t],o=Mi(a,["tfhd"])[0],l=e[Ii(o,4)];if(!l)continue;const c=l.default,h=Ii(o,0)|(null==c?void 0:c.flags);let u=null==c?void 0:c.duration;8&h&&(u=Ii(o,2&h?12:8));const d=l.timescale||9e4,f=Mi(a,["trun"]);for(let t=0;t<f.length;t++)i=Hi(f[t]),!i&&u&&(i=u*Ii(f[t],4)),l.type===$e?r+=i/d:l.type===Be&&(n+=i/d)}if(0===r&&0===n){let e=1/0,i=0,r=0;const n=Mi(t,["sidx"]);for(let t=0;t<n.length;t++){const s=Fi(n[t]);if(null!=s&&s.references){e=Math.min(e,s.earliestPresentationTime/s.timescale);const t=s.references.reduce(((t,e)=>t+e.info.duration||0),0);i=Math.max(i,t+s.earliestPresentationTime/s.timescale),r=i-e}}if(r&&Se(r))return r}return r||n}(u,f),p=function(t,e){return Mi(e,["moof","traf"]).reduce(((e,i)=>{const r=Mi(i,["tfdt"])[0],n=r[0],s=Mi(i,["tfhd"]).reduce(((e,i)=>{const s=Ii(i,4),a=t[s];if(a){let t=Ii(r,4);if(1===n){if(t===Li)return Pe.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),e;t*=Li+1,t+=Ii(r,8)}const i=t/(a.timescale||9e4);if(Se(i)&&(null===e||i<e))return i}return e}),null);return null!==s&&Se(s)&&(null===e||s<e)?s:e}),null)}(f,u),m=null===p?n:p;(function(t,e,i,r){if(null===t)return!0;const n=Math.max(r,1),s=e-t.baseTime/t.timescale;return Math.abs(s-i)>n}(l,m,n,g)||d.timescale!==l.timescale&&s)&&(d.initPTS=m-n,l&&1===l.timescale&&Pe.warn("Adjusting initPTS by "+(d.initPTS-l.baseTime)),this.initPTS=l={baseTime:d.initPTS,timescale:1});const y=t?m-l.baseTime/l.timescale:c,v=y+g;!function(t,e,i){Mi(e,["moof","traf"]).forEach((e=>{Mi(e,["tfhd"]).forEach((r=>{const n=Ii(r,4),s=t[n];if(!s)return;const a=s.timescale||9e4;Mi(e,["tfdt"]).forEach((t=>{const e=t[0],r=i*a;if(r){let i=Ii(t,4);if(0===e)i-=r,i=Math.max(i,0),xi(t,4,i);else{i*=Math.pow(2,32),i+=Ii(t,8),i-=r,i=Math.max(i,0);const e=Math.floor(i/(Li+1)),n=Math.floor(i%(Li+1));xi(t,4,e),xi(t,8,n)}}}))}))}))}(f,u,l.baseTime/l.timescale),g>0?this.lastEndTime=v:(Pe.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const A=!!f.audio,E=!!f.video;let T="";A&&(T+="audio"),E&&(T+="video");const S={data1:u,startPTS:y,startDTS:y,endPTS:v,endDTS:v,type:T,hasAudio:A,hasVideo:E,nb:1,dropped:0};return h.audio="audio"===S.type?S:void 0,h.video="audio"!==S.type?S:void 0,h.initSegment=d,h.id3=ka(i,n,l,l),r.samples.length&&(h.text=_a(r,n,l)),h}}},{demux:oa,remux:Sa},{demux:class extends Ps{constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.observer=t,this.config=e}resetInitSegment(t,e,i,r){super.resetInitSegment(t,e,i,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:r,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=hi(t,0);let i=(null==e?void 0:e.length)||0;if(Qs(t,i))return!1;for(let e=t.length;i<e;i++)if(Us(t,i))return Pe.log("ADTS sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return function(t,e){return e+5<t.length}(t,e)&&xs(t,e)&&Fs(t,e)<=t.length-e}(t,e)}appendFrame(t,e,i){Bs(t,this.observer,e,i,t.manifestCodec);const r=Gs(t,e,i,this.basePTS,this.frameIndex);if(r&&0===r.missing)return r}},remux:Sa},{demux:class extends Ps{resetInitSegment(t,e,i,r){super.resetInitSegment(t,e,i,r),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:r,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=hi(t,0);let i=(null==e?void 0:e.length)||0;if(e&&11===t[i]&&119===t[i+1]&&void 0!==fi(e)&&Js(t,i)<=16)return!1;for(let e=t.length;i<e;i++)if(Qs(t,i))return Pe.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return qs(t,e)&&4<=t.length-e}(t,e)}appendFrame(t,e,i){if(null!==this.basePTS)return Ws(t,e,i,this.basePTS,this.frameIndex)}},remux:Sa}];Ca.splice(2,0,{demux:ta,remux:Sa});class Da{constructor(t,e,i,r,n){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=t,this.typeSupported=e,this.config=i,this.vendor=r,this.id=n}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,i,r){const n=i.transmuxing;n.executeStart=Aa();let s=new Uint8Array(t);const{currentTransmuxState:a,transmuxConfig:o}=this;r&&(this.currentTransmuxState=r);const{contiguous:l,discontinuity:c,trackSwitch:h,accurateTimeOffset:u,timeOffset:d,initSegmentChange:f}=r||a,{audioCodec:g,videoCodec:p,defaultInitPts:m,duration:y,initSegmentData:v}=o,A=function(t,e){let i=null;t.byteLength>0&&null!=(null==e?void 0:e.key)&&null!==e.iv&&null!=e.method&&(i=e);return i}(s,e);if(A&&"AES-128"===A.method){const t=this.getDecrypter();if(!t.isSync())return this.decryptionPromise=t.webCryptoDecrypt(s,A.key.buffer,A.iv.buffer).then((t=>{const e=this.push(t,null,i);return this.decryptionPromise=null,e})),this.decryptionPromise;{let e=t.softwareDecrypt(s,A.key.buffer,A.iv.buffer);if(i.part>-1&&(e=t.flush()),!e)return n.executeEnd=Aa(),wa(i);s=new Uint8Array(e)}}const E=this.needsProbing(c,h);if(E){const t=this.configureTransmuxer(s);if(t)return Pe.warn(`[transmuxer] ${t.message}`),this.observer.emit(_e.ERROR,_e.ERROR,{type:Le.MEDIA_ERROR,details:Re.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),n.executeEnd=Aa(),wa(i)}(c||h||f||E)&&this.resetInitSegment(v,g,p,y,e),(c||f||E)&&this.resetInitialTimestamp(m),l||this.resetContiguity();const T=this.transmux(s,A,d,u,i),S=this.currentTransmuxState;return S.contiguous=!0,S.discontinuity=!1,S.trackSwitch=!1,n.executeEnd=Aa(),T}flush(t){const e=t.transmuxing;e.executeStart=Aa();const{decrypter:i,currentTransmuxState:r,decryptionPromise:n}=this;if(n)return n.then((()=>this.flush(t)));const s=[],{timeOffset:a}=r;if(i){const e=i.flush();e&&s.push(this.push(e,null,t))}const{demuxer:o,remuxer:l}=this;if(!o||!l)return e.executeEnd=Aa(),[wa(t)];const c=o.flush(a);return Ia(c)?c.then((e=>(this.flushRemux(s,e,t),s))):(this.flushRemux(s,c,t),s)}flushRemux(t,e,i){const{audioTrack:r,videoTrack:n,id3Track:s,textTrack:a}=e,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;Pe.log(`[transmuxer.ts]: Flushed fragment ${i.sn}${i.part>-1?" p: "+i.part:""} of level ${i.level}`);const c=this.remuxer.remux(r,n,s,a,l,o,!0,this.id);t.push({remuxResult:c,chunkMeta:i}),i.transmuxing.executeEnd=Aa()}resetInitialTimestamp(t){const{demuxer:e,remuxer:i}=this;e&&i&&(e.resetTimeStamp(t),i.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:e}=this;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())}resetInitSegment(t,e,i,r,n){const{demuxer:s,remuxer:a}=this;s&&a&&(s.resetInitSegment(t,e,i,r),a.resetInitSegment(t,e,i,n))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,e,i,r,n){let s;return s=e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,i,r,n):this.transmuxUnencrypted(t,i,r,n),s}transmuxUnencrypted(t,e,i,r){const{audioTrack:n,videoTrack:s,id3Track:a,textTrack:o}=this.demuxer.demux(t,e,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(n,s,a,o,e,i,!1,this.id),chunkMeta:r}}transmuxSampleAes(t,e,i,r,n){return this.demuxer.demuxSampleAes(t,e,i).then((t=>({remuxResult:this.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,i,r,!1,this.id),chunkMeta:n})))}configureTransmuxer(t){const{config:e,observer:i,typeSupported:r,vendor:n}=this;let s;for(let e=0,i=Ca.length;e<i;e++){var a;if(null!=(a=Ca[e].demux)&&a.probe(t)){s=Ca[e];break}}if(!s)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,l=this.remuxer,c=s.remux,h=s.demux;l&&l instanceof c||(this.remuxer=new c(i,e,r,n)),o&&o instanceof h||(this.demuxer=new h(i,e,r),this.probe=h.probe)}needsProbing(t,e){return!this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new ps(this.config)),t}}const wa=t=>({remuxResult:{},chunkMeta:t});function Ia(t){return"then"in t&&t.then instanceof Function}class Pa{constructor(t,e,i,r,n){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=e,this.initSegmentData=i,this.duration=r,this.defaultInitPts=n||null}}class Oa{constructor(t,e,i,r,n,s){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=t,this.contiguous=e,this.accurateTimeOffset=i,this.trackSwitch=r,this.timeOffset=n,this.initSegmentChange=s}}var xa={exports:{}};!function(t){var e=Object.prototype.hasOwnProperty,i="~";function r(){}function n(t,e,i){this.fn=t,this.context=e,this.once=i||!1}function s(t,e,r,s,a){if("function"!=typeof r)throw new TypeError("The listener must be a function");var o=new n(r,s||t,a),l=i?i+e:e;return t._events[l]?t._events[l].fn?t._events[l]=[t._events[l],o]:t._events[l].push(o):(t._events[l]=o,t._eventsCount++),t}function a(t,e){0==--t._eventsCount?t._events=new r:delete t._events[e]}function o(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(i=!1)),o.prototype.eventNames=function(){var t,r,n=[];if(0===this._eventsCount)return n;for(r in t=this._events)e.call(t,r)&&n.push(i?r.slice(1):r);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(t)):n},o.prototype.listeners=function(t){var e=i?i+t:t,r=this._events[e];if(!r)return[];if(r.fn)return[r.fn];for(var n=0,s=r.length,a=new Array(s);n<s;n++)a[n]=r[n].fn;return a},o.prototype.listenerCount=function(t){var e=i?i+t:t,r=this._events[e];return r?r.fn?1:r.length:0},o.prototype.emit=function(t,e,r,n,s,a){var o=i?i+t:t;if(!this._events[o])return!1;var l,c,h=this._events[o],u=arguments.length;if(h.fn){switch(h.once&&this.removeListener(t,h.fn,void 0,!0),u){case 1:return h.fn.call(h.context),!0;case 2:return h.fn.call(h.context,e),!0;case 3:return h.fn.call(h.context,e,r),!0;case 4:return h.fn.call(h.context,e,r,n),!0;case 5:return h.fn.call(h.context,e,r,n,s),!0;case 6:return h.fn.call(h.context,e,r,n,s,a),!0}for(c=1,l=new Array(u-1);c<u;c++)l[c-1]=arguments[c];h.fn.apply(h.context,l)}else{var d,f=h.length;for(c=0;c<f;c++)switch(h[c].once&&this.removeListener(t,h[c].fn,void 0,!0),u){case 1:h[c].fn.call(h[c].context);break;case 2:h[c].fn.call(h[c].context,e);break;case 3:h[c].fn.call(h[c].context,e,r);break;case 4:h[c].fn.call(h[c].context,e,r,n);break;default:if(!l)for(d=1,l=new Array(u-1);d<u;d++)l[d-1]=arguments[d];h[c].fn.apply(h[c].context,l)}}return!0},o.prototype.on=function(t,e,i){return s(this,t,e,i,!1)},o.prototype.once=function(t,e,i){return s(this,t,e,i,!0)},o.prototype.removeListener=function(t,e,r,n){var s=i?i+t:t;if(!this._events[s])return this;if(!e)return a(this,s),this;var o=this._events[s];if(o.fn)o.fn!==e||n&&!o.once||r&&o.context!==r||a(this,s);else{for(var l=0,c=[],h=o.length;l<h;l++)(o[l].fn!==e||n&&!o[l].once||r&&o[l].context!==r)&&c.push(o[l]);c.length?this._events[s]=1===c.length?c[0]:c:a(this,s)}return this},o.prototype.removeAllListeners=function(t){var e;return t?(e=i?i+t:t,this._events[e]&&a(this,e)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=i,o.EventEmitter=o,t.exports=o}(xa);var Ma=ce(xa.exports);class Fa{constructor(t,e,i,r){this.error=null,this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0;const n=t.config;this.hls=t,this.id=e,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=i,this.onFlush=r;const s=(t,e)=>{(e=e||{}).frag=this.frag,e.id=this.id,t===_e.ERROR&&(this.error=e.error),this.hls.trigger(t,e)};this.observer=new Ma,this.observer.on(_e.FRAG_DECRYPTED,s),this.observer.on(_e.ERROR,s);const a=nr(n.preferManagedMediaSource)||{isTypeSupported:()=>!1},o={mpeg:a.isTypeSupported("audio/mpeg"),mp3:a.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:a.isTypeSupported('audio/mp4; codecs="ac-3"')};if(this.useWorker&&"undefined"!=typeof Worker){if(n.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{n.workerPath?(Pe.log(`loading Web Worker ${n.workerPath} for "${e}"`),this.workerContext=function(t){const e=new self.URL(t,self.location.href).href;return{worker:new self.Worker(e),scriptURL:e}}(n.workerPath)):(Pe.log(`injecting Web Worker for "${e}"`),this.workerContext=function(){const t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),e=self.URL.createObjectURL(t);return{worker:new self.Worker(e),objectURL:e}}()),this.onwmsg=t=>this.onWorkerMessage(t);const{worker:t}=this.workerContext;t.addEventListener("message",this.onwmsg),t.onerror=t=>{const i=new Error(`${t.message} (${t.filename}:${t.lineno})`);n.enableWorker=!1,Pe.warn(`Error in "${e}" Web Worker, fallback to inline`),this.hls.trigger(_e.ERROR,{type:Le.OTHER_ERROR,details:Re.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:i})},t.postMessage({cmd:"init",typeSupported:o,vendor:"",id:e,config:JSON.stringify(n)})}catch(t){Pe.warn(`Error setting up "${e}" Web Worker, fallback to inline`,t),this.resetWorker(),this.error=null,this.transmuxer=new Da(this.observer,o,n,"",e)}return}}this.transmuxer=new Da(this.observer,o,n,"",e)}resetWorker(){if(this.workerContext){const{worker:t,objectURL:e}=this.workerContext;e&&self.URL.revokeObjectURL(e),t.removeEventListener("message",this.onwmsg),t.onerror=null,t.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(t,e,i,r,n,s,a,o,l,c){var h,u;l.transmuxing.start=self.performance.now();const{transmuxer:d}=this,f=s?s.start:n.start,g=n.decryptdata,p=this.frag,m=!(p&&n.cc===p.cc),y=!(p&&l.level===p.level),v=p?l.sn-p.sn:-1,A=this.part?l.part-this.part.index:-1,E=0===v&&l.id>1&&l.id===(null==p?void 0:p.stats.chunkCount),T=!y&&(1===v||0===v&&(1===A||E&&A<=0)),S=self.performance.now();(y||v||0===n.stats.parsing.start)&&(n.stats.parsing.start=S),!s||!A&&T||(s.stats.parsing.start=S);const b=!(p&&(null==(h=n.initSegment)?void 0:h.url)===(null==(u=p.initSegment)?void 0:u.url)),k=new Oa(m,T,o,y,f,b);if(!T||m||b){Pe.log(`[transmuxer-interface, ${n.type}]: Starting new transmux session for sn: ${l.sn} p: ${l.part} level: ${l.level} id: ${l.id}\n discontinuity: ${m}\n trackSwitch: ${y}\n contiguous: ${T}\n accurateTimeOffset: ${o}\n timeOffset: ${f}\n initSegmentChange: ${b}`);const t=new Pa(i,r,e,a,c);this.configureTransmuxer(t)}if(this.frag=n,this.part=s,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:t,decryptdata:g,chunkMeta:l,state:k},t instanceof ArrayBuffer?[t]:[]);else if(d){const e=d.push(t,g,l,k);Ia(e)?(d.async=!0,e.then((t=>{this.handleTransmuxComplete(t)})).catch((t=>{this.transmuxerError(t,l,"transmuxer-interface push error")}))):(d.async=!1,this.handleTransmuxComplete(e))}}flush(t){t.transmuxing.start=self.performance.now();const{transmuxer:e}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:t});else if(e){let i=e.flush(t);Ia(i)||e.async?(Ia(i)||(i=Promise.resolve(i)),i.then((e=>{this.handleFlushResult(e,t)})).catch((e=>{this.transmuxerError(e,t,"transmuxer-interface flush error")}))):this.handleFlushResult(i,t)}}transmuxerError(t,e,i){this.hls&&(this.error=t,this.hls.trigger(_e.ERROR,{type:Le.MEDIA_ERROR,details:Re.FRAG_PARSING_ERROR,chunkMeta:e,frag:this.frag||void 0,fatal:!1,error:t,err:t,reason:i}))}handleFlushResult(t,e){t.forEach((t=>{this.handleTransmuxComplete(t)})),this.onFlush(e)}onWorkerMessage(t){const e=t.data;if(null==e||!e.event)return void Pe.warn("worker message received with no "+(e?"event name":"data"));const i=this.hls;if(this.hls)switch(e.event){case"init":{var r;const t=null==(r=this.workerContext)?void 0:r.objectURL;t&&self.URL.revokeObjectURL(t);break}case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;case"workerLog":Pe[e.data.logType]&&Pe[e.data.logType](e.data.message);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.id=this.id,i.trigger(e.event,e.data)}}configureTransmuxer(t){const{transmuxer:e}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:t}):e&&e.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}function Na(t,e){if(t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(!Ua(t[i].attrs,e[i].attrs))return!1;return!0}function Ua(t,e,i){const r=t["STABLE-RENDITION-ID"];return r&&!i?r===e["STABLE-RENDITION-ID"]:!(i||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some((i=>t[i]!==e[i]))}function Ba(t,e){return e.label.toLowerCase()===t.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(t.lang||"").toLowerCase())}class $a{constructor(t){this.buffered=void 0;const e=(e,i,r)=>{if((i>>>=0)>r-1)throw new DOMException(`Failed to execute '${e}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${r})`);return t[i][e]};this.buffered={get length(){return t.length},end:i=>e("end",i,t.length),start:i=>e("start",i,t.length)}}}class Ga{constructor(t){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=t}append(t,e,i){const r=this.queues[e];r.push(t),1!==r.length||i||this.executeNext(e)}insertAbort(t,e){this.queues[e].unshift(t),this.executeNext(e)}appendBlocker(t){let e;const i=new Promise((t=>{e=t})),r={execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(r,t),i}executeNext(t){const e=this.queues[t];if(e.length){const i=e[0];try{i.execute()}catch(e){Pe.warn(`[buffer-operation-queue]: Exception executing "${t}" SourceBuffer operation: ${e}`),i.onError(e);const r=this.buffers[t];null!=r&&r.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){this.queues[t].shift(),this.executeNext(t)}current(t){return this.queues[t][0]}}const Ka=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;function Ha(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach((e=>{t.removeChild(e)}))}const Va={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},Ya=t=>String.fromCharCode(Va[t]||t),ja=15,Wa=100,za={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},qa={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Xa={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Qa={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Za=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Ja{constructor(){this.time=null,this.verboseLevel=0}log(t,e){if(this.verboseLevel>=t){const i="function"==typeof e?e():e;Pe.log(`${this.time} [${t}] ${i}`)}}}const to=function(t){const e=[];for(let i=0;i<t.length;i++)e.push(t[i].toString(16));return e};class eo{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(t){const e=["foreground","underline","italics","background","flash"];for(let i=0;i<e.length;i++){const r=e[i];t.hasOwnProperty(r)&&(this[r]=t[r])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(t){return this.foreground===t.foreground&&this.underline===t.underline&&this.italics===t.italics&&this.background===t.background&&this.flash===t.flash}copy(t){this.foreground=t.foreground,this.underline=t.underline,this.italics=t.italics,this.background=t.background,this.flash=t.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class io{constructor(){this.uchar=" ",this.penState=new eo}reset(){this.uchar=" ",this.penState.reset()}setChar(t,e){this.uchar=t,this.penState.copy(e)}setPenState(t){this.penState.copy(t)}equals(t){return this.uchar===t.uchar&&this.penState.equals(t.penState)}copy(t){this.uchar=t.uchar,this.penState.copy(t.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}}class ro{constructor(t){this.chars=[],this.pos=0,this.currPenState=new eo,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Wa;t++)this.chars.push(new io);this.logger=t}equals(t){for(let e=0;e<Wa;e++)if(!this.chars[e].equals(t.chars[e]))return!1;return!0}copy(t){for(let e=0;e<Wa;e++)this.chars[e].copy(t.chars[e])}isEmpty(){let t=!0;for(let e=0;e<Wa;e++)if(!this.chars[e].isEmpty()){t=!1;break}return t}setCursor(t){this.pos!==t&&(this.pos=t),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Wa&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Wa)}moveCursor(t){const e=this.pos+t;if(t>1)for(let t=this.pos+1;t<e+1;t++)this.chars[t].setPenState(this.currPenState);this.setCursor(e)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(t){t>=144&&this.backSpace();const e=Ya(t);this.pos>=Wa?this.logger.log(0,(()=>"Cannot insert "+t.toString(16)+" ("+e+") at position "+this.pos+". Skipping it!")):(this.chars[this.pos].setChar(e,this.currPenState),this.moveCursor(1))}clearFromPos(t){let e;for(e=t;e<Wa;e++)this.chars[e].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const t=[];let e=!0;for(let i=0;i<Wa;i++){const r=this.chars[i].uchar;" "!==r&&(e=!1),t.push(r)}return e?"":t.join("")}setPenStyles(t){this.currPenState.setStyles(t);this.chars[this.pos].setPenState(this.currPenState)}}class no{constructor(t){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let e=0;e<ja;e++)this.rows.push(new ro(t));this.logger=t}reset(){for(let t=0;t<ja;t++)this.rows[t].clear();this.currRow=14}equals(t){let e=!0;for(let i=0;i<ja;i++)if(!this.rows[i].equals(t.rows[i])){e=!1;break}return e}copy(t){for(let e=0;e<ja;e++)this.rows[e].copy(t.rows[e])}isEmpty(){let t=!0;for(let e=0;e<ja;e++)if(!this.rows[e].isEmpty()){t=!1;break}return t}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(t){this.rows[this.currRow].insertChar(t)}setPen(t){this.rows[this.currRow].setPenStyles(t)}moveCursor(t){this.rows[this.currRow].moveCursor(t)}setCursor(t){this.logger.log(2,"setCursor: "+t);this.rows[this.currRow].setCursor(t)}setPAC(t){this.logger.log(2,(()=>"pacData = "+JSON.stringify(t)));let e=t.row-1;if(this.nrRollUpRows&&e<this.nrRollUpRows-1&&(e=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==e){for(let t=0;t<ja;t++)this.rows[t].clear();const t=this.currRow+1-this.nrRollUpRows,i=this.lastOutputScreen;if(i){const r=i.rows[t].cueStartTime,n=this.logger.time;if(null!==r&&null!==n&&r<n)for(let r=0;r<this.nrRollUpRows;r++)this.rows[e-this.nrRollUpRows+r+1].copy(i.rows[t+r])}}this.currRow=e;const i=this.rows[this.currRow];if(null!==t.indent){const e=t.indent,r=Math.max(e-1,0);i.setCursor(t.indent),t.color=i.chars[r].penState.foreground}const r={foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:!1};this.setPen(r)}setBkgData(t){this.logger.log(2,(()=>"bkgData = "+JSON.stringify(t))),this.backSpace(),this.setPen(t),this.insertChar(32)}setRollUpRows(t){this.nrRollUpRows=t}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,(()=>this.getDisplayText()));const t=this.currRow+1-this.nrRollUpRows,e=this.rows.splice(t,1)[0];e.clear(),this.rows.splice(this.currRow,0,e),this.logger.log(2,"Rolling up")}getDisplayText(t){t=t||!1;const e=[];let i="",r=-1;for(let i=0;i<ja;i++){const n=this.rows[i].getTextString();n&&(r=i+1,t?e.push("Row "+r+": '"+n+"'"):e.push(n.trim()))}return e.length>0&&(i=t?"["+e.join(" | ")+"]":e.join("\n")),i}getTextAndFormat(){return this.rows}}class so{constructor(t,e,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=e,this.mode=null,this.verbose=0,this.displayedMemory=new no(i),this.nonDisplayedMemory=new no(i),this.lastOutputScreen=new no(i),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(t){this.outputFilter=t}setPAC(t){this.writeScreen.setPAC(t)}setBkgData(t){this.writeScreen.setBkgData(t)}setMode(t){t!==this.mode&&(this.mode=t,this.logger.log(2,(()=>"MODE="+t)),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=t)}insertChars(t){for(let e=0;e<t.length;e++)this.writeScreen.insertChar(t[e]);const e=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,(()=>e+": "+this.writeScreen.getDisplayText(!0))),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,(()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0))),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(t){this.logger.log(2,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){const t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,(()=>"DISP: "+this.displayedMemory.getDisplayText()))}this.outputDataUpdate(!0)}ccTO(t){this.logger.log(2,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)}ccMIDROW(t){const e={flash:!1};if(e.underline=t%2==1,e.italics=t>=46,e.italics)e.foreground="white";else{const i=Math.floor(t/2)-16,r=["white","green","blue","cyan","red","yellow","magenta"];e.foreground=r[i]}this.logger.log(2,"MIDROW: "+JSON.stringify(e)),this.writeScreen.setPen(e)}outputDataUpdate(t=!1){const e=this.logger.time;null!==e&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:e):this.cueStartTime=e,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))}}class ao{constructor(t,e,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const r=this.logger=new Ja;this.channels=[null,new so(t,e,r),new so(t+1,i,r)]}getHandler(t){return this.channels[t].getHandler()}setHandler(t,e){this.channels[t].setHandler(e)}addData(t,e){this.logger.time=t;for(let t=0;t<e.length;t+=2){const i=127&e[t],r=127&e[t+1];let n=!1,s=null;if(0===i&&0===r)continue;this.logger.log(3,(()=>"["+to([e[t],e[t+1]])+"] -> ("+to([i,r])+")"));const a=this.cmdHistory;if(i>=16&&i<=31){if(lo(i,r,a)){oo(null,null,a),this.logger.log(3,(()=>"Repeated command ("+to([i,r])+") is dropped"));continue}oo(i,r,this.cmdHistory),n=this.parseCmd(i,r),n||(n=this.parseMidrow(i,r)),n||(n=this.parsePAC(i,r)),n||(n=this.parseBackgroundAttributes(i,r))}else oo(null,null,a);if(!n&&(s=this.parseChars(i,r),s)){const t=this.currentChannel;if(t&&t>0){this.channels[t].insertChars(s)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}n||s||this.logger.log(2,(()=>"Couldn't parse cleaned data "+to([i,r])+" orig: "+to([e[t],e[t+1]])))}}parseCmd(t,e){if(!((20===t||28===t||21===t||29===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=33&&e<=35))return!1;const i=20===t||21===t||23===t?1:2,r=this.channels[i];return 20===t||21===t||28===t||29===t?32===e?r.ccRCL():33===e?r.ccBS():34===e?r.ccAOF():35===e?r.ccAON():36===e?r.ccDER():37===e?r.ccRU(2):38===e?r.ccRU(3):39===e?r.ccRU(4):40===e?r.ccFON():41===e?r.ccRDC():42===e?r.ccTR():43===e?r.ccRTD():44===e?r.ccEDM():45===e?r.ccCR():46===e?r.ccENM():47===e&&r.ccEOC():r.ccTO(e-32),this.currentChannel=i,!0}parseMidrow(t,e){let i=0;if((17===t||25===t)&&e>=32&&e<=47){if(i=17===t?1:2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const r=this.channels[i];return!!r&&(r.ccMIDROW(e),this.logger.log(3,(()=>"MIDROW ("+to([t,e])+")")),!0)}return!1}parsePAC(t,e){let i;if(!((t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127)&&!((16===t||24===t)&&e>=64&&e<=95))return!1;const r=t<=23?1:2;i=e>=64&&e<=95?1===r?za[t]:Xa[t]:1===r?qa[t]:Qa[t];const n=this.channels[r];return!!n&&(n.setPAC(this.interpretPAC(i,e)),this.currentChannel=r,!0)}interpretPAC(t,e){let i;const r={color:null,italics:!1,indent:null,underline:!1,row:t};return i=e>95?e-96:e-64,r.underline=!(1&~i),i<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(r.italics=!0,r.color="white"):r.indent=4*Math.floor((i-16)/2),r}parseChars(t,e){let i,r=null,n=null;if(t>=25?(i=2,n=t-8):(i=1,n=t),n>=17&&n<=19){let t;t=17===n?e+80:18===n?e+112:e+144,this.logger.log(2,(()=>"Special char '"+Ya(t)+"' in channel "+i)),r=[t]}else t>=32&&t<=127&&(r=0===e?[t]:[t,e]);return r&&this.logger.log(3,(()=>"Char codes = "+to(r).join(","))),r}parseBackgroundAttributes(t,e){if(!((16===t||24===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=45&&e<=47))return!1;let i;const r={};16===t||24===t?(i=Math.floor((e-32)/2),r.background=Za[i],e%2==1&&(r.background=r.background+"_semi")):45===e?r.background="transparent":(r.foreground="black",47===e&&(r.underline=!0));const n=t<=23?1:2;return this.channels[n].setBkgData(r),!0}reset(){for(let t=0;t<Object.keys(this.channels).length;t++){const e=this.channels[t];e&&e.reset()}oo(null,null,this.cmdHistory)}cueSplitAtTime(t){for(let e=0;e<this.channels.length;e++){const i=this.channels[e];i&&i.cueSplitAtTime(t)}}}function oo(t,e,i){i.a=t,i.b=e}function lo(t,e,i){return i.a===t&&i.b===e}class co{constructor(t,e){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=e}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(t,e,i){(null===this.startTime||this.startTime>t)&&(this.startTime=t),this.endTime=e,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var ho=function(){if(null!=qe&&qe.VTTCue)return self.VTTCue;const t=["","lr","rl"],e=["start","middle","end","left","right"];function i(t,e){if("string"!=typeof e)return!1;if(!Array.isArray(t))return!1;const i=e.toLowerCase();return!!~t.indexOf(i)&&i}function r(t){return i(e,t)}function n(t,...e){let i=1;for(;i<arguments.length;i++){const e=arguments[i];for(const i in e)t[i]=e[i]}return t}function s(e,s,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let c="",h=!1,u=e,d=s,f=a,g=null,p="",m=!0,y="auto",v="start",A=50,E="middle",T=50,S="middle";Object.defineProperty(o,"id",n({},l,{get:function(){return c},set:function(t){c=""+t}})),Object.defineProperty(o,"pauseOnExit",n({},l,{get:function(){return h},set:function(t){h=!!t}})),Object.defineProperty(o,"startTime",n({},l,{get:function(){return u},set:function(t){if("number"!=typeof t)throw new TypeError("Start time must be set to a number.");u=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",n({},l,{get:function(){return d},set:function(t){if("number"!=typeof t)throw new TypeError("End time must be set to a number.");d=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",n({},l,{get:function(){return f},set:function(t){f=""+t,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",n({},l,{get:function(){return g},set:function(t){g=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",n({},l,{get:function(){return p},set:function(e){const r=function(e){return i(t,e)}(e);if(!1===r)throw new SyntaxError("An invalid or illegal string was specified.");p=r,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",n({},l,{get:function(){return m},set:function(t){m=!!t,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",n({},l,{get:function(){return y},set:function(t){if("number"!=typeof t&&"auto"!==t)throw new SyntaxError("An invalid number or illegal string was specified.");y=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",n({},l,{get:function(){return v},set:function(t){const e=r(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");v=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",n({},l,{get:function(){return A},set:function(t){if(t<0||t>100)throw new Error("Position must be between 0 and 100.");A=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",n({},l,{get:function(){return E},set:function(t){const e=r(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",n({},l,{get:function(){return T},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");T=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",n({},l,{get:function(){return S},set:function(t){const e=r(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");S=e,this.hasBeenReset=!0}})),o.displayState=void 0}return s.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},s}();class uo{decode(t,e){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function fo(t){function e(t,e,i,r){return 3600*(0|t)+60*(0|e)+(0|i)+parseFloat(r||0)}const i=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?e(i[2],i[3],0,i[4]):e(i[1],i[2],i[3],i[4]):null}class go{constructor(){this.values=Object.create(null)}set(t,e){this.get(t)||""===e||(this.values[t]=e)}get(t,e,i){return i?this.has(t)?this.values[t]:e[i]:this.has(t)?this.values[t]:e}has(t){return t in this.values}alt(t,e,i){for(let r=0;r<i.length;++r)if(e===i[r]){this.set(t,e);break}}integer(t,e){/^-?\d+$/.test(e)&&this.set(t,parseInt(e,10))}percent(t,e){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(e)){const i=parseFloat(e);if(i>=0&&i<=100)return this.set(t,i),!0}return!1}}function po(t,e,i,r){const n=r?t.split(r):[t];for(const t in n){if("string"!=typeof n[t])continue;const r=n[t].split(i);if(2!==r.length)continue;e(r[0],r[1])}}const mo=new ho(0,0,""),yo="middle"===mo.align?"middle":"center";function vo(t,e,i){const r=t;function n(){const e=fo(t);if(null===e)throw new Error("Malformed timestamp: "+r);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function s(){t=t.replace(/^\s+/,"")}if(s(),e.startTime=n(),s(),"--\x3e"!==t.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+r);t=t.slice(3),s(),e.endTime=n(),s(),function(t,e){const r=new go;po(t,(function(t,e){let n;switch(t){case"region":for(let n=i.length-1;n>=0;n--)if(i[n].id===e){r.set(t,i[n].region);break}break;case"vertical":r.alt(t,e,["rl","lr"]);break;case"line":n=e.split(","),r.integer(t,n[0]),r.percent(t,n[0])&&r.set("snapToLines",!1),r.alt(t,n[0],["auto"]),2===n.length&&r.alt("lineAlign",n[1],["start",yo,"end"]);break;case"position":n=e.split(","),r.percent(t,n[0]),2===n.length&&r.alt("positionAlign",n[1],["start",yo,"end","line-left","line-right","auto"]);break;case"size":r.percent(t,e);break;case"align":r.alt(t,e,["start",yo,"end","left","right"])}}),/:/,/\s/),e.region=r.get("region",null),e.vertical=r.get("vertical","");let n=r.get("line","auto");"auto"===n&&-1===mo.line&&(n=-1),e.line=n,e.lineAlign=r.get("lineAlign","start"),e.snapToLines=r.get("snapToLines",!0),e.size=r.get("size",100),e.align=r.get("align",yo);let s=r.get("position","auto");"auto"===s&&50===mo.position&&(s="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=s}(t,e)}function Ao(t){return t.replace(/<br(?: \/)?>/gi,"\n")}class Eo{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new uo,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(t){const e=this;function i(){let t=e.buffer,i=0;for(t=Ao(t);i<t.length&&"\r"!==t[i]&&"\n"!==t[i];)++i;const r=t.slice(0,i);return"\r"===t[i]&&++i,"\n"===t[i]&&++i,e.buffer=t.slice(i),r}t&&(e.buffer+=e.decoder.decode(t,{stream:!0}));try{let t="";if("INITIAL"===e.state){if(!/\r\n|\n/.test(e.buffer))return this;t=i();const r=t.match(/^()?WEBVTT([ \t].*)?$/);if(null==r||!r[0])throw new Error("Malformed WebVTT signature.");e.state="HEADER"}let r=!1;for(;e.buffer;){if(!/\r\n|\n/.test(e.buffer))return this;switch(r?r=!1:t=i(),e.state){case"HEADER":/:/.test(t)?po(t,(function(t,e){}),/:/):t||(e.state="ID");continue;case"NOTE":t||(e.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(t)){e.state="NOTE";break}if(!t)continue;if(e.cue=new ho(0,0,""),e.state="CUE",-1===t.indexOf("--\x3e")){e.cue.id=t;continue}case"CUE":if(!e.cue){e.state="BADCUE";continue}try{vo(t,e.cue,e.regionList)}catch(t){e.cue=null,e.state="BADCUE";continue}e.state="CUETEXT";continue;case"CUETEXT":{const i=-1!==t.indexOf("--\x3e");if(!t||i&&(r=!0)){e.oncue&&e.cue&&e.oncue(e.cue),e.cue=null,e.state="ID";continue}if(null===e.cue)continue;e.cue.text&&(e.cue.text+="\n"),e.cue.text+=t}continue;case"BADCUE":t||(e.state="ID")}}}catch(t){"CUETEXT"===e.state&&e.cue&&e.oncue&&e.oncue(e.cue),e.cue=null,e.state="INITIAL"===e.state?"BADWEBVTT":"BADCUE"}return this}flush(){const t=this;try{if((t.cue||"HEADER"===t.state)&&(t.buffer+="\n\n",t.parse()),"INITIAL"===t.state||"BADWEBVTT"===t.state)throw new Error("Malformed WebVTT signature.")}catch(e){t.onparsingerror&&t.onparsingerror(e)}return t.onflush&&t.onflush(),this}}const To=/\r\n|\n\r|\n|\r/g,So=function(t,e,i=0){return t.slice(i,i+e.length)===e},bo=function(t){let e=5381,i=t.length;for(;i;)e=33*e^t.charCodeAt(--i);return(e>>>0).toString()};function ko(t,e,i){return bo(t.toString())+bo(e.toString())+bo(i)}function _o(t,e,i,r,n,s,a){const o=new Eo,l=Si(new Uint8Array(t)).trim().replace(To,"\n").split("\n"),c=[],h=e?function(t,e=1){return ya(t,9e4,1/e)}(e.baseTime,e.timescale):0;let u,d="00:00.000",f=0,g=0,p=!0;o.oncue=function(t){const s=i[r];let a=i.ccOffset;const o=(f-h)/9e4;if(null!=s&&s.new&&(void 0!==g?a=i.ccOffset=s.start:function(t,e,i){let r=t[e],n=t[r.prevCC];if(!n||!n.new&&r.new)return t.ccOffset=t.presentationOffset=r.start,void(r.new=!1);for(;null!=(s=n)&&s.new;){var s;t.ccOffset+=r.start-n.start,r.new=!1,r=n,n=t[r.prevCC]}t.presentationOffset=i}(i,r,o)),o){if(!e)return void(u=new Error("Missing initPTS for VTT MPEGTS"));a=o-i.presentationOffset}const l=t.endTime-t.startTime,d=ba(9e4*(t.startTime+a-g),9e4*n)/9e4;t.startTime=Math.max(d,0),t.endTime=Math.max(d+l,0);const p=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(p)),t.id||(t.id=ko(t.startTime,t.endTime,p)),t.endTime>0&&c.push(t)},o.onparsingerror=function(t){u=t},o.onflush=function(){u?a(u):s(c)},l.forEach((t=>{if(p){if(So(t,"X-TIMESTAMP-MAP=")){p=!1,t.slice(16).split(",").forEach((t=>{So(t,"LOCAL:")?d=t.slice(6):So(t,"MPEGTS:")&&(f=parseInt(t.slice(7)))}));try{g=function(t){let e=parseInt(t.slice(-3));const i=parseInt(t.slice(-6,-4)),r=parseInt(t.slice(-9,-7)),n=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!(Se(e)&&Se(i)&&Se(r)&&Se(n)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return e+=1e3*i,e+=6e4*r,e+=36e5*n,e}(d)/1e3}catch(t){u=t}return}""===t&&(p=!1)}o.parse(t+"\n")})),o.flush()}const Lo="stpp.ttml.im1t",Ro=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Co=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Do={left:"start",center:"center",right:"end",start:"start",end:"end"};function wo(t,e,i,r){const n=Mi(new Uint8Array(t),["mdat"]);if(0===n.length)return void r(new Error("Could not parse IMSC1 mdat"));const s=n.map((t=>Si(t))),a=function(t,e,i=1,r=!1){return ya(t,e,1/i,r)}(e.baseTime,1,e.timescale);try{s.forEach((t=>i(function(t,e){const i=(new DOMParser).parseFromString(t,"text/xml"),r=i.getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");const n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},s=Object.keys(n).reduce(((t,e)=>(t[e]=r.getAttribute(`ttp:${e}`)||n[e],t)),{}),a="preserve"!==r.getAttribute("xml:space"),o=Po(Io(r,"styling","style")),l=Po(Io(r,"layout","region")),c=Io(r,"body","[begin]");return[].map.call(c,(t=>{const i=Oo(t,a);if(!i||!t.hasAttribute("begin"))return null;const r=Fo(t.getAttribute("begin"),s),n=Fo(t.getAttribute("dur"),s);let c=Fo(t.getAttribute("end"),s);if(null===r)throw Mo(t);if(null===c){if(null===n)throw Mo(t);c=r+n}const h=new ho(r-e,c-e,i);h.id=ko(h.startTime,h.endTime,h.text);const u=function(t,e,i){const r="http://www.w3.org/ns/ttml#styling";let n=null;const s=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;a&&i.hasOwnProperty(a)&&(n=i[a]);return s.reduce(((i,s)=>{const a=xo(e,r,s)||xo(t,r,s)||xo(n,r,s);return a&&(i[s]=a),i}),{})}(l[t.getAttribute("region")],o[t.getAttribute("style")],o),{textAlign:d}=u;if(d){const t=Do[d];t&&(h.lineAlign=t),h.align=d}return Te(h,u),h})).filter((t=>null!==t))}(t,a))))}catch(t){r(t)}}function Io(t,e,i){const r=t.getElementsByTagName(e)[0];return r?[].slice.call(r.querySelectorAll(i)):[]}function Po(t){return t.reduce(((t,e)=>{const i=e.getAttribute("xml:id");return i&&(t[i]=e),t}),{})}function Oo(t,e){return[].slice.call(t.childNodes).reduce(((t,i,r)=>{var n;return"br"===i.nodeName&&r?t+"\n":null!=(n=i.childNodes)&&n.length?Oo(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent}),"")}function xo(t,e,i){return t&&t.hasAttributeNS(e,i)?t.getAttributeNS(e,i):null}function Mo(t){return new Error(`Could not parse ttml timestamp ${t}`)}function Fo(t,e){if(!t)return null;let i=fo(t);return null===i&&(Ro.test(t)?i=function(t,e){const i=Ro.exec(t),r=(0|i[4])+(0|i[5])/e.subFrameRate;return 3600*(0|i[1])+60*(0|i[2])+(0|i[3])+r/e.frameRate}(t,e):Co.test(t)&&(i=function(t,e){const i=Co.exec(t),r=Number(i[1]);switch(i[2]){case"h":return 3600*r;case"m":return 60*r;case"ms":return 1e3*r;case"f":return r/e.frameRate;case"t":return r/e.tickRate}return r}(t,e))),i}function No(t){return t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles"}function Uo(t,e){return!!t&&t.kind===No(e)&&Ba(e,t)}class Bo{constructor(t){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:t}=this;t.on(_e.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(_e.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(_e.MANIFEST_PARSED,this.onManifestParsed,this),t.on(_e.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(_e.BUFFER_CODECS,this.onBufferCodecs,this),t.on(_e.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(_e.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(_e.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(_e.MANIFEST_PARSED,this.onManifestParsed,this),t.off(_e.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(_e.BUFFER_CODECS,this.onBufferCodecs,this),t.off(_e.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,e){const i=this.hls.levels[e.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(t,e){this.media=e.media instanceof HTMLVideoElement?e.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(t,e){const i=this.hls;this.restrictedLevels=[],this.firstLevel=e.firstLevel,i.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onLevelsUpdated(t,e){this.timer&&Se(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,e){this.hls.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const t=this.hls.levels;if(t.length){const e=this.hls,i=this.getMaxLevel(t.length-1);i!==this.autoLevelCapping&&Pe.log(`Setting autoLevelCapping to ${i}: ${t[i].height}p@${t[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),e.autoLevelCapping=i,e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}}getMaxLevel(t){const e=this.hls.levels;if(!e.length)return-1;const i=e.filter(((e,i)=>this.isLevelAllowed(e)&&i<=t));return this.clientRect=null,Bo.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const t=this.media,e={width:0,height:0};if(t){const i=t.getBoundingClientRect();e.width=i.width,e.height=i.height,e.width||e.height||(e.width=i.right-i.left||t.width||0,e.height=i.bottom-i.top||t.height||0)}return this.clientRect=e,e}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch(t){}return t}isLevelAllowed(t){return!this.restrictedLevels.some((e=>t.bitrate===e.bitrate&&t.width===e.width&&t.height===e.height))}static getMaxLevelByMediaSize(t,e,i){if(null==t||!t.length)return-1;let r=t.length-1;const n=Math.max(e,i);for(let e=0;e<t.length;e+=1){const i=t[e];if((i.width>=n||i.height>=n)&&(s=i,!(a=t[e+1])||s.width!==a.width||s.height!==a.height)){r=e;break}}var s,a;return r}}const $o="[eme]";class Go{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=Go.CDMCleanupPromise?[Go.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=Pe.debug.bind(Pe,$o),this.log=Pe.log.bind(Pe,$o),this.warn=Pe.warn.bind(Pe,$o),this.error=Pe.error.bind(Pe,$o),this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(_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)}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)}getLicenseServerUrl(t){const{drmSystems:e,widevineLicenseUrl:i}=this.config,r=e[t];if(r)return r.licenseUrl;if(t===Xe.WIDEVINE&&i)return i;throw new Error(`no license server URL configured for key-system "${t}"`)}getServerCertificateUrl(t){const{drmSystems:e}=this.config,i=e[t];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const e=this.hls.levels,i=(t,e,i)=>!!t&&i.indexOf(t)===e,r=e.map((t=>t.audioCodec)).filter(i),n=e.map((t=>t.videoCodec)).filter(i);return r.length+n.length===0&&n.push("avc1.42e01e"),new Promise(((e,i)=>{const s=t=>{const a=t.shift();this.getMediaKeysPromise(a,r,n).then((t=>e({keySystem:a,mediaKeys:t}))).catch((e=>{t.length?s(t):i(e instanceof Ko?e:new Ko({type:Le.KEY_SYSTEM_ERROR,details:Re.KEY_SYSTEM_NO_ACCESS,error:e,fatal:!0},e.message))}))};s(t)}))}requestMediaKeySystemAccess(t,e){const{requestMediaKeySystemAccessFunc:i}=this.config;if("function"!=typeof i){let t=`Configured requestMediaKeySystemAccess is not a function ${i}`;return null===si&&"http:"===self.location.protocol&&(t=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(t))}return i(t,e)}getMediaKeysPromise(t,e,i){const r=function(t,e,i,r){let n;switch(t){case Xe.FAIRPLAY:n=["cenc","sinf"];break;case Xe.WIDEVINE:case Xe.PLAYREADY:n=["cenc"];break;case Xe.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${t}`)}return function(t,e,i,r){return[{initDataTypes:t,persistentState:r.persistentState||"optional",distinctiveIdentifier:r.distinctiveIdentifier||"optional",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:e.map((t=>({contentType:`audio/mp4; codecs="${t}"`,robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null}))),videoCapabilities:i.map((t=>({contentType:`video/mp4; codecs="${t}"`,robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null})))}]}(n,e,i,r)}(t,e,i,this.config.drmSystemOptions),n=this.keySystemAccessPromises[t];let s=null==n?void 0:n.keySystemAccess;if(!s){this.log(`Requesting encrypted media "${t}" key-system access with config: ${JSON.stringify(r)}`),s=this.requestMediaKeySystemAccess(t,r);const e=this.keySystemAccessPromises[t]={keySystemAccess:s};return s.catch((e=>{this.log(`Failed to obtain access to key-system "${t}": ${e}`)})),s.then((i=>{this.log(`Access for key-system "${i.keySystem}" obtained`);const r=this.fetchServerCertificate(t);return this.log(`Create media-keys for "${t}"`),e.mediaKeys=i.createMediaKeys().then((e=>(this.log(`Media-keys created for "${t}"`),r.then((i=>i?this.setMediaKeysServerCertificate(e,t,i):e))))),e.mediaKeys.catch((e=>{this.error(`Failed to create media-keys for "${t}"}: ${e}`)})),e.mediaKeys}))}return s.then((()=>n.mediaKeys))}createMediaKeySessionContext({decryptdata:t,keySystem:e,mediaKeys:i}){this.log(`Creating key-system session "${e}" keyId: ${_i(t.keyId||[])}`);const r=i.createSession(),n={decryptdata:t,keySystem:e,mediaKeys:i,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n}renewKeySession(t){const e=t.decryptdata;if(e.pssh){const i=this.createMediaKeySessionContext(t),r=this.getKeyIdString(e),n="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(i,n,e.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}getKeyIdString(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(null===t.keyId)throw new Error("keyId is null");return _i(t.keyId)}updateKeySession(t,e){var i;const r=t.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyID ${_i((null==(i=t.decryptdata)?void 0:i.keyId)||[])}\n } (data length: ${e?e.byteLength:e})`),r.update(e)}selectKeySystemFormat(t){const e=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)),this.keyFormatPromise}getKeyFormatPromise(t){return new Promise(((e,i)=>{const r=ni(this.config),n=t.map(ei).filter((t=>!!t&&-1!==r.indexOf(t)));return this.getKeySystemSelectionPromise(n).then((({keySystem:t})=>{const r=ri(t);r?e(r):i(new Error(`Unable to find format for key-system "${t}"`))})).catch(i)}))}loadKey(t){const e=t.keyInfo.decryptdata,i=this.getKeyIdString(e),r=`(keyId: ${i} format: "${e.keyFormat}" method: ${e.method} uri: ${e.uri})`;this.log(`Starting session for key ${r}`);let n=this.keyIdToKeySessionPromise[i];return n||(n=this.keyIdToKeySessionPromise[i]=this.getKeySystemForKeyPromise(e).then((({keySystem:i,mediaKeys:n})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${r}`),this.attemptSetMediaKeys(i,n).then((()=>{this.throwIfDestroyed();const t=this.createMediaKeySessionContext({keySystem:i,mediaKeys:n,decryptdata:e});return this.generateRequestWithPreferredKeySession(t,"cenc",e.pssh,"playlist-key")}))))),n.catch((t=>this.handleError(t)))),n}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t){this.hls&&(this.error(t.message),t instanceof Ko?this.hls.trigger(_e.ERROR,t.data):this.hls.trigger(_e.ERROR,{type:Le.KEY_SYSTEM_ERROR,details:Re.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0}))}getKeySystemForKeyPromise(t){const e=this.getKeyIdString(t),i=this.keyIdToKeySessionPromise[e];if(!i){const e=ei(t.keyFormat),i=e?[e]:ni(this.config);return this.attemptKeySystemAccess(i)}return i}getKeySystemSelectionPromise(t){if(t.length||(t=ni(this.config)),0===t.length)throw new Ko({type:Le.KEY_SYSTEM_ERROR,details:Re.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}_onMediaEncrypted(t){const{initDataType:e,initData:i}=t;if(this.debug(`"${t.type}" event: init data type: "${e}"`),null===i)return;let r,n;if("sinf"===e&&this.config.drmSystems[Xe.FAIRPLAY]){const t=Di(new Uint8Array(i));try{const e=je(JSON.parse(t).sinf),i=Ki(new Uint8Array(e));if(!i)return;r=i.subarray(8,24),n=Xe.FAIRPLAY}catch(t){return void this.warn('Failed to parse sinf "encrypted" event message initData')}}else{const t=function(t){if(!(t instanceof ArrayBuffer)||t.byteLength<32)return null;const e={version:0,systemId:"",kids:null,data:null},i=new DataView(t),r=i.getUint32(0);if(t.byteLength!==r&&r>44)return null;if(1886614376!==i.getUint32(4))return null;if(e.version=i.getUint32(8)>>>24,e.version>1)return null;e.systemId=_i(new Uint8Array(t,12,16));const n=i.getUint32(28);if(0===e.version){if(r-32<n)return null;e.data=new Uint8Array(t,32,n)}else if(1===e.version){e.kids=[];for(let i=0;i<n;i++)e.kids.push(new Uint8Array(t,32+16*i,16))}return e}(i);if(null===t)return;0===t.version&&t.systemId===ii&&t.data&&(r=t.data.subarray(8,24)),n=function(t){if(t===ii)return Xe.WIDEVINE}(t.systemId)}if(!n||!r)return;const s=_i(r),{keyIdToKeySessionPromise:a,mediaKeySessions:o}=this;let l=a[s];for(let t=0;t<o.length;t++){const n=o[t],c=n.decryptdata;if(c.pssh||!c.keyId)continue;const h=_i(c.keyId);if(s===h||-1!==c.uri.replace(/-/g,"").indexOf(s)){l=a[h],delete a[h],c.pssh=new Uint8Array(i),c.keyId=r,l=a[s]=l.then((()=>this.generateRequestWithPreferredKeySession(n,e,i,"encrypted-event-key-match")));break}}l||(l=a[s]=this.getKeySystemSelectionPromise([n]).then((({keySystem:t,mediaKeys:n})=>{var a;this.throwIfDestroyed();const o=new Qi("ISO-23001-7",s,null!=(a=ri(t))?a:"");return o.pssh=new Uint8Array(i),o.keyId=r,this.attemptSetMediaKeys(t,n).then((()=>{this.throwIfDestroyed();const r=this.createMediaKeySessionContext({decryptdata:o,keySystem:t,mediaKeys:n});return this.generateRequestWithPreferredKeySession(r,e,i,"encrypted-event-no-match")}))}))),l.catch((t=>this.handleError(t)))}_onWaitingForKey(t){this.log(`"${t.type}" event`)}attemptSetMediaKeys(t,e){const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const r=Promise.all(i).then((()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(e)}));return this.setMediaKeysQueue.push(r),r.then((()=>{this.log(`Media-keys set for "${t}"`),i.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter((t=>-1===i.indexOf(t)))}))}generateRequestWithPreferredKeySession(t,e,i,r){var n,s;const a=null==(n=this.config.drmSystems)||null==(s=n[t.keySystem])?void 0:s.generateRequest;if(a)try{const r=a.call(this.hls,e,i,t);if(!r)throw new Error("Invalid response from configured generateRequest filter");e=r.initDataType,i=t.decryptdata.pssh=r.initData?new Uint8Array(r.initData):null}catch(t){var o;if(this.warn(t.message),null!=(o=this.hls)&&o.config.debug)throw t}if(null===i)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(t);const l=this.getKeyIdString(t.decryptdata);this.log(`Generating key-session request for "${r}": ${l} (init data type: ${e} length: ${i?i.byteLength:null})`);const c=new Ma,h=t._onmessage=e=>{const i=t.mediaKeysSession;if(!i)return void c.emit("error",new Error("invalid state"));const{messageType:r,message:n}=e;this.log(`"${r}" message event for session "${i.sessionId}" message size: ${n.byteLength}`),"license-request"===r||"license-renewal"===r?this.renewLicense(t,n).catch((t=>{this.handleError(t),c.emit("error",t)})):"license-release"===r?t.keySystem===Xe.FAIRPLAY&&(this.updateKeySession(t,ze("acknowledged")),this.removeSession(t)):this.warn(`unhandled media key message type "${r}"`)},u=t._onkeystatuseschange=e=>{if(!t.mediaKeysSession)return void c.emit("error",new Error("invalid state"));this.onKeyStatusChange(t);const i=t.keyStatus;c.emit("keyStatus",i),"expired"===i&&(this.warn(`${t.keySystem} expired for key ${l}`),this.renewKeySession(t))};t.mediaKeysSession.addEventListener("message",h),t.mediaKeysSession.addEventListener("keystatuseschange",u);const d=new Promise(((t,e)=>{c.on("error",e),c.on("keyStatus",(i=>{i.startsWith("usable")?t():"output-restricted"===i?e(new Ko({type:Le.KEY_SYSTEM_ERROR,details:Re.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===i?e(new Ko({type:Le.KEY_SYSTEM_ERROR,details:Re.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${i}"`)):"expired"===i?e(new Error("key expired while generating request")):this.warn(`unhandled key status change "${i}"`)}))}));return t.mediaKeysSession.generateRequest(e,i).then((()=>{var e;this.log(`Request generated for key-session "${null==(e=t.mediaKeysSession)?void 0:e.sessionId}" keyId: ${l}`)})).catch((t=>{throw new Ko({type:Le.KEY_SYSTEM_ERROR,details:Re.KEY_SYSTEM_NO_SESSION,error:t,fatal:!1},`Error generating key-session request: ${t}`)})).then((()=>d)).catch((e=>{throw c.removeAllListeners(),this.removeSession(t),e})).then((()=>(c.removeAllListeners(),t)))}onKeyStatusChange(t){t.mediaKeysSession.keyStatuses.forEach(((e,i)=>{this.log(`key status change "${e}" for keyStatuses keyId: ${_i("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${_i(new Uint8Array(t.decryptdata.keyId||[]))} uri: ${t.decryptdata.uri}`),t.keyStatus=e}))}fetchServerCertificate(t){const e=this.config,i=new(0,e.loader)(e),r=this.getServerCertificateUrl(t);return r?(this.log(`Fetching server certificate for "${t}"`),new Promise(((n,s)=>{const a={responseType:"arraybuffer",url:r},o=e.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(t,e,i,r)=>{n(t.data)},onError:(e,i,n,o)=>{s(new Ko({type:Le.KEY_SYSTEM_ERROR,details:Re.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:n,response:ve({url:a.url,data:void 0},e)},`"${t}" certificate request failed (${r}). Status: ${e.code} (${e.text})`))},onTimeout:(e,i,n)=>{s(new Ko({type:Le.KEY_SYSTEM_ERROR,details:Re.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:n,response:{url:a.url,data:void 0}},`"${t}" certificate request timed out (${r})`))},onAbort:(t,e,i)=>{s(new Error("aborted"))}};i.load(a,l,c)}))):Promise.resolve()}setMediaKeysServerCertificate(t,e,i){return new Promise(((r,n)=>{t.setServerCertificate(i).then((n=>{this.log(`setServerCertificate ${n?"success":"not supported by CDM"} (${null==i?void 0:i.byteLength}) on "${e}"`),r(t)})).catch((t=>{n(new Ko({type:Le.KEY_SYSTEM_ERROR,details:Re.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:t,fatal:!0},t.message))}))}))}renewLicense(t,e){return this.requestLicense(t,new Uint8Array(e)).then((e=>this.updateKeySession(t,new Uint8Array(e)).catch((t=>{throw new Ko({type:Le.KEY_SYSTEM_ERROR,details:Re.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:t,fatal:!0},t.message)}))))}unpackPlayReadyKeyMessage(t,e){const i=String.fromCharCode.apply(null,new Uint16Array(e.buffer));if(!i.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),e;const r=(new DOMParser).parseFromString(i,"application/xml"),n=r.querySelectorAll("HttpHeader");if(n.length>0){let e;for(let i=0,r=n.length;i<r;i++){var s,a;e=n[i];const r=null==(s=e.querySelector("name"))?void 0:s.textContent,o=null==(a=e.querySelector("value"))?void 0:a.textContent;r&&o&&t.setRequestHeader(r,o)}}const o=r.querySelector("Challenge"),l=null==o?void 0:o.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return ze(atob(l))}setupLicenseXHR(t,e,i,r){const n=this.config.licenseXhrSetup;return n?Promise.resolve().then((()=>{if(!i.decryptdata)throw new Error("Key removed");return n.call(this.hls,t,e,i,r)})).catch((s=>{if(!i.decryptdata)throw s;return t.open("POST",e,!0),n.call(this.hls,t,e,i,r)})).then((i=>{t.readyState||t.open("POST",e,!0);return{xhr:t,licenseChallenge:i||r}})):(t.open("POST",e,!0),Promise.resolve({xhr:t,licenseChallenge:r}))}requestLicense(t,e){const i=this.config.keyLoadPolicy.default;return new Promise(((r,n)=>{const s=this.getLicenseServerUrl(t.keySystem);this.log(`Sending license request to URL: ${s}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return n(new Error("invalid state"));if(4===a.readyState)if(200===a.status){this._requestLicenseFailureCount=0;let e=a.response;this.log(`License received ${e instanceof ArrayBuffer?e.byteLength:e}`);const i=this.config.licenseResponseCallback;if(i)try{e=i.call(this.hls,a,s,t)}catch(t){this.error(t)}r(e)}else{const o=i.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)n(new Ko({type:Le.KEY_SYSTEM_ERROR,details:Re.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:{url:s,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${s}). Status: ${a.status} (${a.statusText})`));else{const i=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${i} attempts left`),this.requestLicense(t,e).then(r,n)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=a,this.setupLicenseXHR(a,s,t,e).then((({xhr:e,licenseChallenge:i})=>{t.keySystem==Xe.PLAYREADY&&(i=this.unpackPlayReadyKeyMessage(e,i)),e.send(i)}))}))}onMediaAttached(t,e){if(!this.config.emeEnabled)return;const i=e.media;this.media=i,i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const t=this.media,e=this.mediaKeySessions;t&&(t.removeEventListener("encrypted",this.onMediaEncrypted),t.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},Qi.clearKeyUriToKeyIdMap();const i=e.length;Go.CDMCleanupPromise=Promise.all(e.map((t=>this.removeSession(t))).concat(null==t?void 0:t.setMediaKeys(null).catch((t=>{this.log(`Could not clear media keys: ${t}`)})))).then((()=>{i&&(this.log("finished closing key sessions and clearing media keys"),e.length=0)})).catch((t=>{this.log(`Could not close sessions and clear media keys: ${t}`)}))}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(t,{sessionKeys:e}){if(e&&this.config.emeEnabled&&!this.keyFormatPromise){const t=e.reduce(((t,e)=>(-1===t.indexOf(e.keyFormat)&&t.push(e.keyFormat),t)),[]);this.log(`Selecting key-system from session-keys ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)}}removeSession(t){const{mediaKeysSession:e,licenseXhr:i}=t;if(e){this.log(`Remove licenses and keys and close session ${e.sessionId}`),t._onmessage&&(e.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(e.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(t);return r>-1&&this.mediaKeySessions.splice(r,1),e.remove().catch((t=>{this.log(`Could not remove session: ${t}`)})).then((()=>e.close())).catch((t=>{this.log(`Could not close session: ${t}`)}))}}}Go.CDMCleanupPromise=void 0;class Ko extends Error{constructor(t,e){super(e),this.data=void 0,t.error||(t.error=new Error(e)),this.data=t,t.err=t.error}}var Ho,Vo,Yo;!function(t){t.MANIFEST="m",t.AUDIO="a",t.VIDEO="v",t.MUXED="av",t.INIT="i",t.CAPTION="c",t.TIMED_TEXT="tt",t.KEY="k",t.OTHER="o"}(Ho||(Ho={})),function(t){t.DASH="d",t.HLS="h",t.SMOOTH="s",t.OTHER="o"}(Vo||(Vo={})),function(t){t.OBJECT="CMCD-Object",t.REQUEST="CMCD-Request",t.SESSION="CMCD-Session",t.STATUS="CMCD-Status"}(Yo||(Yo={}));const jo={[Yo.OBJECT]:["br","d","ot","tb"],[Yo.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[Yo.SESSION]:["cid","pr","sf","sid","st","v"],[Yo.STATUS]:["bs","rtp"]};class Wo{constructor(t,e){this.value=void 0,this.params=void 0,Array.isArray(t)&&(t=t.map((t=>t instanceof Wo?t:new Wo(t)))),this.value=t,this.params=e}}class zo{constructor(t){this.description=void 0,this.description=t}}function qo(t,e,i,r){return new Error(`failed to ${t} "${n=e,Array.isArray(n)?JSON.stringify(n):n instanceof Map?"Map{}":n instanceof Set?"Set{}":"object"==typeof n?JSON.stringify(n):String(n)}" as ${i}`,{cause:r});var n}const Xo="Bare Item";const Qo=/[\x00-\x1f\x7f]+/;function Zo(t,e,i){return qo("serialize",t,e,i)}function Jo(t){if(!1===ArrayBuffer.isView(t))throw Zo(t,"Byte Sequence");return`:${e=t,btoa(String.fromCharCode(...e))}:`;var e}function tl(t){if(function(t){return t<-999999999999999||999999999999999<t}(t))throw Zo(t,"Integer");return t.toString()}function el(t,e){if(t<0)return-el(-t,e);const i=Math.pow(10,e);if(Math.abs(t*i%1-.5)<Number.EPSILON){const e=Math.floor(t*i);return(e%2==0?e:e+1)/i}return Math.round(t*i)/i}function il(t){const e=el(t,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Zo(t,"Decimal");const i=e.toString();return i.includes(".")?i:`${i}.0`}function rl(t){const e=(i=t).description||i.toString().slice(7,-1);var i;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e))throw Zo(e,"Token");return e}function nl(t){switch(typeof t){case"number":if(!Se(t))throw Zo(t,Xo);return Number.isInteger(t)?tl(t):il(t);case"string":return function(t){if(Qo.test(t))throw Zo(t,"String");return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(t);case"symbol":return rl(t);case"boolean":return function(t){if("boolean"!=typeof t)throw Zo(t,"Boolean");return t?"?1":"?0"}(t);case"object":if(t instanceof Date)return function(t){return`@${tl(t.getTime()/1e3)}`}(t);if(t instanceof Uint8Array)return Jo(t);if(t instanceof zo)return rl(t);default:throw Zo(t,Xo)}}function sl(t){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(t))throw Zo(t,"Key");return t}function al(t){return null==t?"":Object.entries(t).map((([t,e])=>!0===e?`;${sl(t)}`:`;${sl(t)}=${nl(e)}`)).join("")}function ol(t){return t instanceof Wo?`${nl(t.value)}${al(t.params)}`:nl(t)}function ll(t,e={whitespace:!0}){if("object"!=typeof t)throw Zo(t,"Dict");const i=t instanceof Map?t.entries():Object.entries(t),r=null!=e&&e.whitespace?" ":"";return Array.from(i).map((([t,e])=>{e instanceof Wo==!1&&(e=new Wo(e));let i=sl(t);var r;return!0===e.value?i+=al(e.params):(i+="=",Array.isArray(e.value)?i+=`(${(r=e).value.map(ol).join(" ")})${al(r.params)}`:i+=ol(e)),i})).join(`,${r}`)}const cl=t=>Math.round(t),hl=t=>100*cl(t/100),ul={br:cl,d:cl,bl:hl,dl:hl,mtp:hl,nor:(t,e)=>(null!=e&&e.baseUrl&&(t=function(t,e){const i=new URL(t),r=new URL(e);if(i.origin!==r.origin)return t;const n=i.pathname.split("/").slice(1),s=r.pathname.split("/").slice(1,-1);for(;n[0]===s[0];)n.shift(),s.shift();for(;s.length;)s.shift(),n.unshift("..");return n.join("/")}(t,e.baseUrl)),encodeURIComponent(t)),rtp:hl,tb:cl};function dl(t,e){const i={};if(null==t||"object"!=typeof t)return i;const r=Object.keys(t).sort(),n=Te({},ul,null==e?void 0:e.formatters),s=null==e?void 0:e.filter;return r.forEach((r=>{if(null!=s&&s(r))return;let a=t[r];const o=n[r];o&&(a=o(a,e)),"v"===r&&1===a||"pr"==r&&1===a||(t=>"number"==typeof t?Se(t):null!=t&&""!==t&&!1!==t)(a)&&((t=>"ot"===t||"sf"===t||"st"===t)(r)&&"string"==typeof a&&(a=new zo(a)),i[r]=a)})),i}function fl(t,e={}){return t?function(t,e){return ll(t,e)}(dl(t,e),Te({whitespace:!1},e)):""}function gl(t,e,i){return Te(t,function(t,e={}){if(!t)return{};const i=Object.entries(t),r=Object.entries(jo).concat(Object.entries((null==e?void 0:e.customHeaderMap)||{})),n=i.reduce(((t,e)=>{var i;const[n,s]=e,a=(null==(i=r.find((t=>t[1].includes(n))))?void 0:i[0])||Yo.REQUEST;return null!=t[a]||(t[a]={}),t[a][n]=s,t}),{});return Object.entries(n).reduce(((t,[i,r])=>(t[i]=fl(r,e),t)),{})}(e,i))}const pl=/CMCD=[^&#]+/;function ml(t,e,i){const r=function(t,e={}){if(!t)return"";const i=fl(t,e);return`CMCD=${encodeURIComponent(i)}`}(e,i);if(!r)return t;if(pl.test(t))return t.replace(pl,r);const n=t.includes("?")?"&":"?";return`${t}${n}${r}`}function yl(t,e,i,r){t&&Object.keys(e).forEach((n=>{const s=t.filter((t=>t.groupId===n)).map((t=>{const s=Te({},t);return s.details=void 0,s.attrs=new Me(s.attrs),s.url=s.attrs.URI=vl(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),s.groupId=s.attrs["GROUP-ID"]=e[n],s.attrs["PATHWAY-ID"]=r,s}));t.push(...s)}))}function vl(t,e,i,r){const{HOST:n,PARAMS:s,[i]:a}=r;let o;e&&(o=null==a?void 0:a[e],o&&(t=o));const l=new self.URL(t);return n&&!o&&(l.host=n),s&&Object.keys(s).sort().forEach((t=>{t&&l.searchParams.set(t,s[t])})),l.href}const Al=/^age:\s*[\d.]+\s*$/im;class El{constructor(t){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=t&&t.xhrSetup||null,this.stats=new Ue,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,4!==t.readyState&&(this.stats.aborted=!0,t.abort()))}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(t,e,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=i,this.loadInternal()}loadInternal(){const{config:t,context:e}=this;if(!t||!e)return;const i=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;const n=this.xhrSetup;n?Promise.resolve().then((()=>{if(this.loader===i&&!this.stats.aborted)return n(i,e.url)})).catch((t=>{if(this.loader===i&&!this.stats.aborted)return i.open("GET",e.url,!0),n(i,e.url)})).then((()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,e,t)})).catch((t=>{this.callbacks.onError({code:i.status,text:t.message},e,i,r)})):this.openAndSendXhr(i,e,t)}openAndSendXhr(t,e,i){t.readyState||t.open("GET",e.url,!0);const r=e.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:s}=i.loadPolicy;if(r)for(const e in r)t.setRequestHeader(e,r[e]);e.rangeEnd&&t.setRequestHeader("Range","bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=e.responseType,self.clearTimeout(this.requestTimeout),i.timeout=n&&Se(n)?n:s,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),t.send()}readystatechange(){const{context:t,loader:e,stats:i}=this;if(!t||!e)return;const r=e.readyState,n=this.config;if(!i.aborted&&r>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),4===r)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;const r=e.status,s="text"!==e.responseType;if(r>=200&&r<300&&(s&&e.response||null!==e.responseText)){i.loading.end=Math.max(self.performance.now(),i.loading.first);const n=s?e.response:e.responseText,a="arraybuffer"===e.responseType?n.byteLength:n.length;if(i.loaded=i.total=a,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first),!this.callbacks)return;const o=this.callbacks.onProgress;if(o&&o(i,t,n,e),!this.callbacks)return;const l={url:e.responseURL,data:n,code:r};this.callbacks.onSuccess(l,i,t,e)}else{const s=n.loadPolicy.errorRetry;En(s,i.retry,!1,{url:t.url,data:void 0,code:r})?this.retry(s):(Pe.error(`${r} while loading ${t.url}`),this.callbacks.onError({code:r,text:e.statusText},t,e,i))}}}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry;if(En(t,this.stats.retry,!0))this.retry(t);else{var e;Pe.warn(`timeout while loading ${null==(e=this.context)?void 0:e.url}`);const t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.loader))}}retry(t){const{context:e,stats:i}=this;this.retryDelay=vn(t,i.retry),i.retry++,Pe.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==e?void 0:e.url}, retrying ${i.retry}/${t.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(t){const e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)}getCacheAge(){let t=null;if(this.loader&&Al.test(this.loader.getAllResponseHeaders())){const e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.loader&&new RegExp(`^${t}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null}}const Tl=/(\d+)-(\d+)\/(\d+)/;class Sl{constructor(t){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=t.fetchSetup||bl,this.controller=new self.AbortController,this.stats=new Ue}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 t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(t,e,i){const r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();const n=function(t,e){const i={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(Te({},t.headers))};t.rangeEnd&&i.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1));return i}(t,this.controller.signal),s=i.onProgress,a="arraybuffer"===t.responseType,o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:c}=e.loadPolicy;this.context=t,this.config=e,this.callbacks=i,this.request=this.fetchSetup(t,n),self.clearTimeout(this.requestTimeout),e.timeout=l&&Se(l)?l:c,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),i.onTimeout(r,t,this.response)}),e.timeout),self.fetch(this.request).then((n=>{this.response=this.loader=n;const o=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=c,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),i.onTimeout(r,t,this.response)}),c-(o-r.loading.start)),!n.ok){const{status:t,statusText:e}=n;throw new kl(e||"fetch, bad network response",t,n)}return r.loading.first=o,r.total=function(t){const e=t.get("Content-Range");if(e){const t=function(t){const e=Tl.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}(e);if(Se(t))return t}const i=t.get("Content-Length");if(i)return parseInt(i)}(n.headers)||r.total,s&&Se(e.highWaterMark)?this.loadProgressively(n,r,t,e.highWaterMark,s):a?n.arrayBuffer():"json"===t.responseType?n.json():n.text()})).then((n=>{const a=this.response;if(!a)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);const l=n[o];l&&(r.loaded=r.total=l);const c={url:a.url,data:n,code:a.status};s&&!Se(e.highWaterMark)&&s(r,t,n,a),i.onSuccess(c,r,t,a)})).catch((e=>{if(self.clearTimeout(this.requestTimeout),r.aborted)return;const n=e&&e.code||0,s=e?e.message:null;i.onError({code:n,text:s},t,e?e.details:null,r)}))}getCacheAge(){let t=null;if(this.response){const e=this.response.headers.get("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,e,i,r=0,n){const s=new ws,a=t.body.getReader(),o=()=>a.read().then((a=>{if(a.done)return s.dataLength&&n(e,i,s.flush(),t),Promise.resolve(new ArrayBuffer(0));const l=a.value,c=l.length;return e.loaded+=c,c<r||s.dataLength?(s.push(l),s.dataLength>=r&&n(e,i,s.flush(),t)):n(e,i,l,t),o()})).catch((()=>Promise.reject()));return o()}}function bl(t,e){return new self.Request(t.url,e)}class kl extends Error{constructor(t,e,i){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=i}}const _l=/\s/,Ll={newCue(t,e,i,r){const n=[];let s,a,o,l,c;const h=self.VTTCue||self.TextTrackCue;for(let d=0;d<r.rows.length;d++)if(s=r.rows[d],o=!0,l=0,c="",!s.isEmpty()){var u;for(let t=0;t<s.chars.length;t++)_l.test(s.chars[t].uchar)&&o?l++:(c+=s.chars[t].uchar,o=!1);s.cueStartTime=e,e===i&&(i+=1e-4),l>=16?l--:l++;const r=Ao(c.trim()),f=ko(e,i,r);null!=t&&null!=(u=t.cues)&&u.getCueById(f)||(a=new h(e,i,r),a.id=f,a.line=d+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),n.push(a))}return t&&n.length&&(n.sort(((t,e)=>"auto"===t.line||"auto"===e.line?0:t.line>8&&e.line>8?e.line-t.line:t.line-e.line)),n.forEach((e=>Br(t,e)))),n}},Rl=ve(ve({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:6e7,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:El,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class{constructor(t){this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this._abandonRulesCheck=()=>{const{fragCurrent:t,partCurrent:e,hls:i}=this,{autoLevelEnabled:r,media:n}=i;if(!t||!n)return;const s=performance.now(),a=e?e.stats:t.stats,o=e?e.duration:t.duration,l=s-a.loading.start,c=i.minAutoLevel;if(a.aborted||a.loaded&&a.loaded===a.total||t.level<=c)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!r||n.paused||!n.playbackRate||!n.readyState)return;const h=i.mainForwardBufferInfo;if(null===h)return;const u=this.bwEstimator.getEstimateTTFB(),d=Math.abs(n.playbackRate);if(l<=Math.max(u,o/(2*d)*1e3))return;const f=h.len/d,g=a.loading.first?a.loading.first-a.loading.start:-1,p=a.loaded&&g>-1,m=this.getBwEstimate(),y=i.levels,v=y[t.level],A=a.total||Math.max(a.loaded,Math.round(o*v.averageBitrate/8));let E=p?l-g:l;E<1&&p&&(E=Math.min(l,8*a.loaded/m));const T=p?1e3*a.loaded/E:0,S=T?(A-a.loaded)/T:8*A/m+u/1e3;if(S<=f)return;const b=T?8*T:m;let k,_=Number.POSITIVE_INFINITY;for(k=t.level-1;k>c;k--){const t=y[k].maxBitrate;if(_=this.getTimeToLoadFrag(u/1e3,b,o*t,!y[k].details),_<f)break}if(_>=S)return;if(_>10*o)return;i.nextLoadLevel=i.nextAutoLevel=k,p?this.bwEstimator.sample(l-Math.min(u,g),a.loaded):this.bwEstimator.sampleTTFB(l);const L=y[k].maxBitrate;this.getBwEstimate()*this.hls.config.abrBandWidthUpFactor>L&&this.resetEstimator(L),this.clearTimer(),Pe.warn(`[abr] Fragment ${t.sn}${e?" part "+e.index:""} of level ${t.level} is loading too slowly;\n Time to underbuffer: ${f.toFixed(3)} s\n Estimated load time for current fragment: ${S.toFixed(3)} s\n Estimated load time for down switch fragment: ${_.toFixed(3)} s\n TTFB estimate: ${0|g} ms\n Current BW estimate: ${Se(m)?0|m:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${k} @ ${0|L} bps`),i.trigger(_e.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:e,stats:a})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){t&&(Pe.log(`setting initial bwe to ${t}`),this.hls.config.abrEwmaDefaultEstimate=t),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const t=this.hls.config;return new xn(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(_e.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_e.FRAG_LOADING,this.onFragLoading,this),t.on(_e.FRAG_LOADED,this.onFragLoaded,this),t.on(_e.FRAG_BUFFERED,this.onFragBuffered,this),t.on(_e.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(_e.LEVEL_LOADED,this.onLevelLoaded,this),t.on(_e.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(_e.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(_e.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(_e.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_e.FRAG_LOADING,this.onFragLoading,this),t.off(_e.FRAG_LOADED,this.onFragLoaded,this),t.off(_e.FRAG_BUFFERED,this.onFragBuffered,this),t.off(_e.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(_e.LEVEL_LOADED,this.onLevelLoaded,this),t.off(_e.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(_e.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(_e.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(t,e){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(t,e){const i=e.frag;if(!this.ignoreFragment(i)){var r;if(!i.bitrateTest)this.fragCurrent=i,this.partCurrent=null!=(r=e.part)?r:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(t,e){this.clearTimer()}onError(t,e){if(!e.fatal)switch(e.details){case Re.BUFFER_ADD_CODEC_ERROR:case Re.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case Re.FRAG_LOAD_TIMEOUT:{const t=e.frag,{fragCurrent:i,partCurrent:r}=this;if(t&&i&&t.sn===i.sn&&t.level===i.level){const e=performance.now(),i=r?r.stats:t.stats,n=e-i.loading.start,s=i.loading.first?i.loading.first-i.loading.start:-1;if(i.loaded&&s>-1){const t=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(n-Math.min(t,s),i.loaded)}else this.bwEstimator.sampleTTFB(n)}break}}}getTimeToLoadFrag(t,e,i,r){return t+i/e+(r?this.lastLevelLoadSec:0)}onLevelLoaded(t,e){const i=this.hls.config,{loading:r}=e.stats,n=r.end-r.start;Se(n)&&(this.lastLevelLoadSec=n/1e3),e.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD)}onFragLoaded(t,{frag:e,part:i}){const r=i?i.stats:e.stats;if(e.type===Pr&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(e)){if(this.clearTimer(),e.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const t=i?i.duration:e.duration,n=this.hls.levels[e.level],s=(n.loaded?n.loaded.bytes:0)+r.loaded,a=(n.loaded?n.loaded.duration:0)+t;n.loaded={bytes:s,duration:a},n.realBitrate=Math.round(8*s/a)}if(e.bitrateTest){const t={stats:r,frag:e,part:i,id:e.type};this.onFragBuffered(_e.FRAG_BUFFERED,t),e.bitrateTest=!1}else this.lastLoadedFragLevel=e.level}}onFragBuffered(t,e){const{frag:i,part:r}=e,n=null!=r&&r.stats.loaded?r.stats:i.stats;if(n.aborted)return;if(this.ignoreFragment(i))return;const s=n.parsing.end-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(s,n.loaded),n.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=s/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==Pr||"initSegment"===t.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:t,minAutoLevel:e}=this.hls,i=this.getBwEstimate(),r=this.hls.config.maxStarvationDelay,n=this.findBestLevel(i,e,t,0,r,1,1);if(n>-1)return n;const s=this.hls.firstLevel,a=Math.min(Math.max(s,e),t);return Pe.warn(`[abr] Could not find best starting auto level. Defaulting to first in playlist ${s} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const t=this.forcedAutoLevel,e=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(!(-1===t||e&&i&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return t;const r=e&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==t){const e=this.hls.levels;if(e.length>Math.max(t,r)&&e[t].loadError<=e[r].loadError)return t}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:i}=this,{maxAutoLevel:r,config:n,minAutoLevel:s}=i,a=e?e.duration:t?t.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let c=n.abrBandWidthFactor,h=n.abrBandWidthUpFactor;if(l){const t=this.findBestLevel(o,s,r,l,0,c,h);if(t>=0)return t}let u=a?Math.min(a,n.maxStarvationDelay):n.maxStarvationDelay;if(!l){const t=this.bitrateTestDelay;if(t){u=(a?Math.min(a,n.maxLoadingDelay):n.maxLoadingDelay)-t,Pe.info(`[abr] bitrate test took ${Math.round(1e3*t)}ms, set first fragment max fetchDuration to ${Math.round(1e3*u)} ms`),c=h=1}}const d=this.findBestLevel(o,s,r,l,u,c,h);if(Pe.info(`[abr] ${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${d}`),d>-1)return d;const f=i.levels[s],g=i.levels[i.loadLevel];return(null==f?void 0:f.bitrate)<(null==g?void 0:g.bitrate)?s:i.loadLevel}getStarvationDelay(){const t=this.hls,e=t.media;if(!e)return 1/0;const i=e&&0!==e.playbackRate?Math.abs(e.playbackRate):1,r=t.mainForwardBufferInfo;return(r?r.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(t,e,i,r,n,s,a){var o;const l=r+n,c=this.lastLoadedFragLevel,h=-1===c?this.hls.firstLevel:c,{fragCurrent:u,partCurrent:d}=this,{levels:f,allAudioTracks:g,loadLevel:p,config:m}=this.hls;if(1===f.length)return 0;const y=f[h],v=!(null==y||null==(o=y.details)||!o.live),A=-1===p||-1===c;let E,T="SDR",S=(null==y?void 0:y.frameRate)||0;const{audioPreference:b,videoPreference:k}=m,_=this.audioTracksByGroup||(this.audioTracksByGroup=function(t){return t.reduce(((t,e)=>{let i=t.groups[e.groupId];i||(i=t.groups[e.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(e);const r=e.channels||"2";return i.channels[r]=(i.channels[r]||0)+1,i.hasDefault=i.hasDefault||e.default,i.hasAutoSelect=i.hasAutoSelect||e.autoselect,i.hasDefault&&(t.hasDefaultAudio=!0),i.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}(g));if(A){if(-1!==this.firstSelection)return this.firstSelection;const r=this.codecTiers||(this.codecTiers=function(t,e,i,r){return t.slice(i,r+1).reduce(((t,i)=>{if(!i.codecSet)return t;const r=i.audioGroups;let n=t[i.codecSet];n||(t[i.codecSet]=n={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!r,fragmentError:0}),n.minBitrate=Math.min(n.minBitrate,i.bitrate);const s=Math.min(i.height,i.width);return n.minHeight=Math.min(n.minHeight,s),n.minFramerate=Math.min(n.minFramerate,i.frameRate),n.maxScore=Math.max(n.maxScore,i.score),n.fragmentError+=i.fragmentError,n.videoRanges[i.videoRange]=(n.videoRanges[i.videoRange]||0)+1,r&&r.forEach((t=>{if(!t)return;const i=e.groups[t];i&&(n.hasDefaultAudio=n.hasDefaultAudio||e.hasDefaultAudio?i.hasDefault:i.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(i.channels).forEach((t=>{n.channels[t]=(n.channels[t]||0)+i.channels[t]})))})),t}),{})}(f,_,e,i)),n=function(t,e,i,r,n){const s=Object.keys(t),a=null==r?void 0:r.channels,o=null==r?void 0:r.audioCodec,l=a&&2===parseInt(a);let c=!0,h=!1,u=1/0,d=1/0,f=1/0,g=0,p=[];const{preferHDR:m,allowedVideoRanges:y}=Bn(e,n);for(let e=s.length;e--;){const i=t[s[e]];c=i.channels[2]>0,u=Math.min(u,i.minHeight),d=Math.min(d,i.minFramerate),f=Math.min(f,i.minBitrate);const r=y.filter((t=>i.videoRanges[t]>0));r.length>0&&(h=!0,p=r)}u=Se(u)?u:0,d=Se(d)?d:0;const v=Math.max(1080,u),A=Math.max(30,d);return f=Se(f)?f:i,i=Math.max(f,i),h||(e=void 0,p=[]),{codecSet:s.reduce(((e,r)=>{const n=t[r];if(r===e)return e;if(n.minBitrate>i)return $n(r,`min bitrate of ${n.minBitrate} > current estimate of ${i}`),e;if(!n.hasDefaultAudio)return $n(r,"no renditions with default or auto-select sound found"),e;if(o&&r.indexOf(o.substring(0,4))%5!=0)return $n(r,`audio codec preference "${o}" not found`),e;if(a&&!l){if(!n.channels[a])return $n(r,`no renditions with ${a} channel sound found (channels options: ${Object.keys(n.channels)})`),e}else if((!o||l)&&c&&0===n.channels[2])return $n(r,"no renditions with stereo sound found"),e;return n.minHeight>v?($n(r,`min resolution of ${n.minHeight} > maximum of ${v}`),e):n.minFramerate>A?($n(r,`min framerate of ${n.minFramerate} > maximum of ${A}`),e):p.some((t=>n.videoRanges[t]>0))?n.maxScore<g?($n(r,`max score of ${n.maxScore} < selected max of ${g}`),e):e&&(hr(r)>=hr(e)||n.fragmentError>t[e].fragmentError)?e:(g=n.maxScore,r):($n(r,`no variants with VIDEO-RANGE of ${JSON.stringify(p)} found`),e)}),void 0),videoRanges:p,preferHDR:m,minFramerate:d,minBitrate:f}}(r,T,t,b,k),{codecSet:s,videoRanges:a,minFramerate:o,minBitrate:l,preferHDR:c}=n;E=s,T=c?a[a.length-1]:a[0],S=o,t=Math.max(t,l),Pe.log(`[abr] picked start tier ${JSON.stringify(n)}`)}else E=null==y?void 0:y.codecSet,T=null==y?void 0:y.videoRange;const L=d?d.duration:u?u.duration:0,R=this.bwEstimator.getEstimateTTFB()/1e3,C=[];for(let o=i;o>=e;o--){var D;const e=f[o],u=o>h;if(!e)continue;if(m.useMediaCapabilities&&!e.supportedResult&&!e.supportedPromise){const i=navigator.mediaCapabilities;"function"==typeof(null==i?void 0:i.decodingInfo)&&Nn(e,_,T,S,t,b)?(e.supportedPromise=Un(e,_,i),e.supportedPromise.then((t=>{if(!this.hls)return;e.supportedResult=t;const i=this.hls.levels,r=i.indexOf(e);t.error?Pe.warn(`[abr] MediaCapabilities decodingInfo error: "${t.error}" for level ${r} ${JSON.stringify(t)}`):t.supported||(Pe.warn(`[abr] Unsupported MediaCapabilities decodingInfo result for level ${r} ${JSON.stringify(t)}`),r>-1&&i.length>1&&(Pe.log(`[abr] Removing unsupported level ${r}`),this.hls.removeLevel(r)))}))):e.supportedResult=Mn}if(E&&e.codecSet!==E||T&&e.videoRange!==T||u&&S>e.frameRate||!u&&S>0&&S<e.frameRate||e.supportedResult&&(null==(D=e.supportedResult.decodingInfoResults)||!D[0].smooth)){C.push(o);continue}const g=e.details,k=(d?null==g?void 0:g.partTarget:null==g?void 0:g.averagetargetduration)||L;let w;w=u?a*t:s*t;const I=L&&r>=2*L&&0===n?f[o].averageBitrate:f[o].maxBitrate,P=this.getTimeToLoadFrag(R,w,I*k,void 0===g);if(w>=I&&(o===c||0===e.loadError&&0===e.fragmentError)&&(P<=R||!Se(P)||v&&!this.bitrateTestDelay||P<l)){const t=this.forcedAutoLevel;return o===p||-1!==t&&t===p||(C.length&&Pe.trace(`[abr] Skipped level(s) ${C.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${f[C[0]].codecs}" ${f[C[0]].videoRange}; not compatible with "${y.codecs}" ${T}`),Pe.info(`[abr] switch candidate:${h}->${o} adjustedbw(${Math.round(w)})-bitrate=${Math.round(w-I)} ttfb:${R.toFixed(1)} avgDuration:${k.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${P.toFixed(1)} firstSelection:${A} codecSet:${E} videoRange:${T} hls.loadLevel:${p}`)),A&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(t){const{maxAutoLevel:e,minAutoLevel:i}=this.hls,r=Math.min(Math.max(t,i),e);this._nextAutoLevel!==r&&(this.nextAutoLevelKey="",this._nextAutoLevel=r)}},bufferController:class{constructor(t){this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendSource=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this.log=void 0,this.warn=void 0,this.error=void 0,this._onEndStreaming=t=>{this.hls&&this.hls.pauseBuffering()},this._onStartStreaming=t=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=()=>{const{media:t,mediaSource:e}=this;this.log("Media source opened"),t&&(t.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(_e.MEDIA_ATTACHED,{media:t,mediaSource:e})),e&&e.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:t,_objectUrl:e}=this;t!==e&&Pe.error(`Media element src was set while attaching MediaSource (${e} > ${t})`)},this.hls=t;const e="[buffer-controller]";var i;this.appendSource=(i=nr(t.config.preferManagedMediaSource),"undefined"!=typeof self&&i===self.ManagedMediaSource),this.log=Pe.log.bind(Pe,e),this.warn=Pe.warn.bind(Pe,e),this.error=Pe.error.bind(Pe,e),this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.hls=null}registerListeners(){const{hls:t}=this;t.on(_e.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(_e.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(_e.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_e.MANIFEST_PARSED,this.onManifestParsed,this),t.on(_e.BUFFER_RESET,this.onBufferReset,this),t.on(_e.BUFFER_APPENDING,this.onBufferAppending,this),t.on(_e.BUFFER_CODECS,this.onBufferCodecs,this),t.on(_e.BUFFER_EOS,this.onBufferEos,this),t.on(_e.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(_e.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(_e.FRAG_PARSED,this.onFragParsed,this),t.on(_e.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:t}=this;t.off(_e.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(_e.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(_e.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_e.MANIFEST_PARSED,this.onManifestParsed,this),t.off(_e.BUFFER_RESET,this.onBufferReset,this),t.off(_e.BUFFER_APPENDING,this.onBufferAppending,this),t.off(_e.BUFFER_CODECS,this.onBufferCodecs,this),t.off(_e.BUFFER_EOS,this.onBufferEos,this),t.off(_e.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(_e.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(_e.FRAG_PARSED,this.onFragParsed,this),t.off(_e.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new Ga(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.appendErrors={audio:0,video:0,audiovideo:0},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(t,e){let i=2;(e.audio&&!e.video||!e.altAudio)&&(i=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=i,this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(t,e){const i=this.media=e.media,r=nr(this.appendSource);if(i&&r){var n;const t=this.mediaSource=new r;this.log(`created media source: ${null==(n=t.constructor)?void 0:n.name}`),t.addEventListener("sourceopen",this._onMediaSourceOpen),t.addEventListener("sourceended",this._onMediaSourceEnded),t.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.addEventListener("startstreaming",this._onStartStreaming),t.addEventListener("endstreaming",this._onEndStreaming));const e=this._objectUrl=self.URL.createObjectURL(t);if(this.appendSource)try{i.removeAttribute("src");const r=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||r&&t instanceof r,Ha(i),function(t,e){const i=self.document.createElement("source");i.type="video/mp4",i.src=e,t.appendChild(i)}(i,e),i.load()}catch(t){i.src=e}else i.src=e;i.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:t,mediaSource:e,_objectUrl:i}=this;if(e){if(this.log("media source detaching"),"open"===e.readyState)try{e.endOfStream()}catch(t){this.warn(`onMediaDetaching: ${t.message} while calling endOfStream`)}this.onBufferReset(),e.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("sourceended",this._onMediaSourceEnded),e.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.removeEventListener("startstreaming",this._onStartStreaming),e.removeEventListener("endstreaming",this._onEndStreaming)),t&&(t.removeEventListener("emptied",this._onMediaEmptied),i&&self.URL.revokeObjectURL(i),this.mediaSrc===i?(t.removeAttribute("src"),this.appendSource&&Ha(t),t.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(_e.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach((t=>{this.resetBuffer(t)})),this._initSourceBuffer()}resetBuffer(t){const e=this.sourceBuffer[t];try{var i;if(e)this.removeBufferListeners(t),this.sourceBuffer[t]=void 0,null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(e)}catch(e){this.warn(`onBufferReset ${t}`,e)}}onBufferCodecs(t,e){const i=this.getSourceBufferTypes().length,r=Object.keys(e);if(r.forEach((t=>{if(i){const i=this.tracks[t];if(i&&"function"==typeof i.buffer.changeType){var r;const{id:n,codec:s,levelCodec:a,container:o,metadata:l}=e[t],c=gr(i.codec,i.levelCodec),h=null==c?void 0:c.replace(Ka,"$1");let u=gr(s,a);const d=null==(r=u)?void 0:r.replace(Ka,"$1");if(u&&h!==d){"audio"===t.slice(0,5)&&(u=fr(u,this.appendSource));const e=`${o};codecs=${u}`;this.appendChangeType(t,e),this.log(`switching codec ${c} to ${u}`),this.tracks[t]={buffer:i.buffer,codec:s,container:o,levelCodec:a,metadata:l,id:n}}}}else this.pendingTracks[t]=e[t]})),i)return;const n=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==n&&(this.log(`${n} bufferCodec event(s) expected ${r.join(",")}`),this.bufferCodecEventsExpected=n),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks()}appendChangeType(t,e){const{operationQueue:i}=this,r={execute:()=>{const r=this.sourceBuffer[t];r&&(this.log(`changing ${t} sourceBuffer type to ${e}`),r.changeType(e)),i.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn(`Failed to change ${t} SourceBuffer type`,e)}};i.append(r,t,!!this.pendingTracks[t])}onBufferAppending(t,e){const{hls:i,operationQueue:r,tracks:n}=this,{data:s,type:a,frag:o,part:l,chunkMeta:c}=e,h=c.buffering[a],u=self.performance.now();h.start=u;const d=o.stats.buffering,f=l?l.stats.buffering:null;0===d.start&&(d.start=u),f&&0===f.start&&(f.start=u);const g=n.audio;let p=!1;"audio"===a&&"audio/mpeg"===(null==g?void 0:g.container)&&(p=!this.lastMpegAudioChunk||1===c.id||this.lastMpegAudioChunk.sn!==c.sn,this.lastMpegAudioChunk=c);const m=o.start,y={execute:()=>{if(h.executeStart=self.performance.now(),p){const t=this.sourceBuffer[a];if(t){const e=m-t.timestampOffset;Math.abs(e)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${m} (delta: ${e}) sn: ${o.sn})`),t.timestampOffset=m)}}this.appendExecutor(s,a)},onStart:()=>{},onComplete:()=>{const t=self.performance.now();h.executeEnd=h.end=t,0===d.first&&(d.first=t),f&&0===f.first&&(f.first=t);const{sourceBuffer:e}=this,i={};for(const t in e)i[t]=ts.getBuffered(e[t]);this.appendErrors[a]=0,"audio"===a||"video"===a?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(_e.BUFFER_APPENDED,{type:a,frag:o,part:l,chunkMeta:c,parent:o.type,timeRanges:i})},onError:t=>{const e={type:Le.MEDIA_ERROR,parent:o.type,details:Re.BUFFER_APPEND_ERROR,sourceBufferName:a,frag:o,part:l,chunkMeta:c,error:t,err:t,fatal:!1};if(t.code===DOMException.QUOTA_EXCEEDED_ERR)e.details=Re.BUFFER_FULL_ERROR;else{const t=++this.appendErrors[a];e.details=Re.BUFFER_APPEND_ERROR,this.warn(`Failed ${t}/${i.config.appendErrorMaxRetry} times to append segment in "${a}" sourceBuffer`),t>=i.config.appendErrorMaxRetry&&(e.fatal=!0)}i.trigger(_e.ERROR,e)}};r.append(y,a,!!this.pendingTracks[a])}onBufferFlushing(t,e){const{operationQueue:i}=this,r=t=>({execute:this.removeExecutor.bind(this,t,e.startOffset,e.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(_e.BUFFER_FLUSHED,{type:t})},onError:e=>{this.warn(`Failed to remove from ${t} SourceBuffer`,e)}});e.type?i.append(r(e.type),e.type):this.getSourceBufferTypes().forEach((t=>{i.append(r(t),t)}))}onFragParsed(t,e){const{frag:i,part:r}=e,n=[],s=r?r.elementaryStreams:i.elementaryStreams;s[Ge]?n.push("audiovideo"):(s[Be]&&n.push("audio"),s[$e]&&n.push("video"));0===n.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers((()=>{const t=self.performance.now();i.stats.buffering.end=t,r&&(r.stats.buffering.end=t);const e=r?r.stats:i.stats;this.hls.trigger(_e.FRAG_BUFFERED,{frag:i,part:r,stats:e,id:i.type})}),n)}onFragChanged(t,e){this.trimBuffers()}onBufferEos(t,e){this.getSourceBufferTypes().reduce(((t,i)=>{const r=this.sourceBuffer[i];return!r||e.type&&e.type!==i||(r.ending=!0,r.ended||(r.ended=!0,this.log(`${i} sourceBuffer now EOS`))),t&&!(r&&!r.ended)}),!0)&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers((()=>{this.getSourceBufferTypes().forEach((t=>{const e=this.sourceBuffer[t];e&&(e.ending=!1)}));const{mediaSource:t}=this;t&&"open"===t.readyState?(this.log("Calling mediaSource.endOfStream()"),t.endOfStream()):t&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${t.readyState}`)})))}onLevelUpdated(t,{details:e}){e.fragments.length&&(this.details=e,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}trimBuffers(){const{hls:t,details:e,media:i}=this;if(!i||null===e)return;if(!this.getSourceBufferTypes().length)return;const r=t.config,n=i.currentTime,s=e.levelTargetDuration,a=e.live&&null!==r.liveBackBufferLength?r.liveBackBufferLength:r.backBufferLength;if(Se(a)&&a>0){const t=Math.max(a,s),e=Math.floor(n/s)*s-t;this.flushBackBuffer(n,s,e)}if(Se(r.frontBufferFlushThreshold)&&r.frontBufferFlushThreshold>0){const t=Math.max(r.maxBufferLength,r.frontBufferFlushThreshold),e=Math.max(t,s),i=Math.floor(n/s)*s+e;this.flushFrontBuffer(n,s,i)}}flushBackBuffer(t,e,i){const{details:r,sourceBuffer:n}=this;this.getSourceBufferTypes().forEach((s=>{const a=n[s];if(a){const n=ts.getBuffered(a);if(n.length>0&&i>n.start(0)){if(this.hls.trigger(_e.BACK_BUFFER_REACHED,{bufferEnd:i}),null!=r&&r.live)this.hls.trigger(_e.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(a.ended&&n.end(n.length-1)-t<2*e)return void this.log(`Cannot flush ${s} back buffer while SourceBuffer is in ended state`);this.hls.trigger(_e.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:s})}}}))}flushFrontBuffer(t,e,i){const{sourceBuffer:r}=this;this.getSourceBufferTypes().forEach((n=>{const s=r[n];if(s){const r=ts.getBuffered(s),a=r.length;if(a<2)return;const o=r.start(a-1),l=r.end(a-1);if(i>o||t>=o&&t<=l)return;if(s.ended&&t-l<2*e)return void this.log(`Cannot flush ${n} front buffer while SourceBuffer is in ended state`);this.hls.trigger(_e.BUFFER_FLUSHING,{startOffset:o,endOffset:1/0,type:n})}}))}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||"open"!==this.mediaSource.readyState)return;const{details:t,hls:e,media:i,mediaSource:r}=this,n=t.fragments[0].start+t.totalduration,s=i.duration,a=Se(r.duration)?r.duration:0;t.live&&e.config.liveDurationInfinity?(r.duration=1/0,this.updateSeekableRange(t)):(n>a&&n>s||!Se(s))&&(this.log(`Updating Media Source duration to ${n.toFixed(3)}`),r.duration=n)}updateSeekableRange(t){const e=this.mediaSource,i=t.fragments;if(i.length&&t.live&&null!=e&&e.setLiveSeekableRange){const r=Math.max(0,i[0].start),n=Math.max(r,r+t.totalduration);this.log(`Media Source duration is set to ${e.duration}. Setting seekable range to ${r}-${n}.`),e.setLiveSeekableRange(r,n)}}checkPendingTracks(){const{bufferCodecEventsExpected:t,operationQueue:e,pendingTracks:i}=this,r=Object.keys(i).length;if(r&&(!t||2===r||"audiovideo"in i)){this.createSourceBuffers(i),this.pendingTracks={};const t=this.getSourceBufferTypes();if(t.length)this.hls.trigger(_e.BUFFER_CREATED,{tracks:this.tracks}),t.forEach((t=>{e.executeNext(t)}));else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(_e.ERROR,{type:Le.MEDIA_ERROR,details:Re.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}}createSourceBuffers(t){const{sourceBuffer:e,mediaSource:i}=this;if(!i)throw Error("createSourceBuffers called when mediaSource was null");for(const n in t)if(!e[n]){var r;const s=t[n];if(!s)throw Error(`source buffer exists for track ${n}, however track does not`);let a=-1===(null==(r=s.levelCodec)?void 0:r.indexOf(","))?s.levelCodec:s.codec;a&&"audio"===n.slice(0,5)&&(a=fr(a,this.appendSource));const o=`${s.container};codecs=${a}`;this.log(`creating sourceBuffer(${o})`);try{const t=e[n]=i.addSourceBuffer(o),r=n;this.addBufferListener(r,"updatestart",this._onSBUpdateStart),this.addBufferListener(r,"updateend",this._onSBUpdateEnd),this.addBufferListener(r,"error",this._onSBUpdateError),this.appendSource&&this.addBufferListener(r,"bufferedchange",((t,e)=>{const i=e.removedRanges;null!=i&&i.length&&this.hls.trigger(_e.BUFFER_FLUSHED,{type:n})})),this.tracks[n]={buffer:t,codec:a,container:s.container,levelCodec:s.levelCodec,metadata:s.metadata,id:s.id}}catch(t){this.error(`error while trying to add sourceBuffer: ${t.message}`),this.hls.trigger(_e.ERROR,{type:Le.MEDIA_ERROR,details:Re.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:n,mimeType:o})}}}get mediaSrc(){var t,e;const i=(null==(t=this.media)||null==(e=t.querySelector)?void 0:e.call(t,"source"))||this.media;return null==i?void 0:i.src}_onSBUpdateStart(t){const{operationQueue:e}=this;e.current(t).onStart()}_onSBUpdateEnd(t){var e;if("closed"===(null==(e=this.mediaSource)?void 0:e.readyState))return void this.resetBuffer(t);const{operationQueue:i}=this;i.current(t).onComplete(),i.shiftAndExecuteNext(t)}_onSBUpdateError(t,e){var i;const r=new Error(`${t} SourceBuffer error. MediaSource readyState: ${null==(i=this.mediaSource)?void 0:i.readyState}`);this.error(`${r}`,e),this.hls.trigger(_e.ERROR,{type:Le.MEDIA_ERROR,details:Re.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:r,fatal:!1});const n=this.operationQueue.current(t);n&&n.onError(r)}removeExecutor(t,e,i){const{media:r,mediaSource:n,operationQueue:s,sourceBuffer:a}=this,o=a[t];if(!r||!n||!o)return this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),void s.shiftAndExecuteNext(t);const l=Se(r.duration)?r.duration:1/0,c=Se(n.duration)?n.duration:1/0,h=Math.max(0,e),u=Math.min(i,l,c);u>h&&(!o.ending||o.ended)?(o.ended=!1,this.log(`Removing [${h},${u}] from the ${t} SourceBuffer`),o.remove(h,u)):s.shiftAndExecuteNext(t)}appendExecutor(t,e){const i=this.sourceBuffer[e];if(i)i.ended=!1,i.appendBuffer(t);else if(!this.pendingTracks[e])throw new Error(`Attempting to append to the ${e} SourceBuffer, but it does not exist`)}blockBuffers(t,e=this.getSourceBufferTypes()){if(!e.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve().then(t);const{operationQueue:i}=this,r=e.map((t=>i.appendBlocker(t)));Promise.all(r).then((()=>{t(),e.forEach((t=>{const e=this.sourceBuffer[t];null!=e&&e.updating||i.shiftAndExecuteNext(t)}))}))}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(t,e,i){const r=this.sourceBuffer[t];if(!r)return;const n=i.bind(this,t);this.listeners[t].push({event:e,listener:n}),r.addEventListener(e,n)}removeBufferListeners(t){const e=this.sourceBuffer[t];e&&this.listeners[t].forEach((t=>{e.removeEventListener(t.event,t.listener)}))}},capLevelController:Bo,errorController:class{constructor(t){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=t,this.log=Pe.log.bind(Pe,"[info]:"),this.warn=Pe.warn.bind(Pe,"[warning]:"),this.error=Pe.error.bind(Pe,"[error]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(_e.ERROR,this.onError,this),t.on(_e.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_e.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(_e.ERROR,this.onError,this),t.off(_e.ERROR,this.onErrorOut,this),t.off(_e.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_e.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){return(null==t?void 0:t.type)===Pr?t.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(t,e){var i,r;if(e.fatal)return;const n=this.hls,s=e.context;switch(e.details){case Re.FRAG_LOAD_ERROR:case Re.FRAG_LOAD_TIMEOUT:case Re.KEY_LOAD_ERROR:case Re.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case Re.FRAG_PARSING_ERROR:if(null!=(i=e.frag)&&i.gap)return void(e.errorAction={action:_n,flags:Dn});case Re.FRAG_GAP:case Re.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=Ln);case Re.LEVEL_EMPTY_ERROR:case Re.LEVEL_PARSING_ERROR:{var a,o;const t=e.parent===Pr?e.level:n.loadLevel;e.details===Re.LEVEL_EMPTY_ERROR&&null!=(a=e.context)&&null!=(o=a.levelDetails)&&o.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,t):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t))}return;case Re.LEVEL_LOAD_ERROR:case Re.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==s?void 0:s.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,s.level)));case Re.AUDIO_TRACK_LOAD_ERROR:case Re.AUDIO_TRACK_LOAD_TIMEOUT:case Re.SUBTITLE_LOAD_ERROR:case Re.SUBTITLE_TRACK_LOAD_TIMEOUT:if(s){const t=n.levels[n.loadLevel];if(t&&(s.type===wr&&t.hasAudioGroup(s.groupId)||s.type===Ir&&t.hasSubtitleGroup(s.groupId)))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,n.loadLevel),e.errorAction.action=Ln,void(e.errorAction.flags=wn)}return;case Re.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const t=n.levels[n.loadLevel],i=null==t?void 0:t.attrs["HDCP-LEVEL"];i?e.errorAction={action:Ln,flags:In,hdcpLevel:i}:this.keySystemError(e)}return;case Re.BUFFER_ADD_CODEC_ERROR:case Re.REMUX_ALLOC_ERROR:case Re.BUFFER_APPEND_ERROR:return void(e.errorAction=this.getLevelSwitchAction(e,null!=(r=e.level)?r:n.loadLevel));case Re.INTERNAL_EXCEPTION:case Re.BUFFER_APPENDING_ERROR:case Re.BUFFER_FULL_ERROR:case Re.LEVEL_SWITCH_ERROR:case Re.BUFFER_STALLED_ERROR:case Re.BUFFER_SEEK_OVER_HOLE:case Re.BUFFER_NUDGE_ON_STALL:return void(e.errorAction={action:_n,flags:Dn})}e.type===Le.KEY_SYSTEM_ERROR&&this.keySystemError(e)}keySystemError(t){const e=this.getVariantLevelIndex(t.frag);t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e)}getPlaylistRetryOrSwitchAction(t,e){const i=yn(this.hls.config.playlistLoadPolicy,t),r=this.playlistError++;if(En(i,r,mn(t),t.response))return{action:Cn,flags:Dn,retryConfig:i,retryCount:r};const n=this.getLevelSwitchAction(t,e);return i&&(n.retryConfig=i,n.retryCount=r),n}getFragRetryOrSwitchAction(t){const e=this.hls,i=this.getVariantLevelIndex(t.frag),r=e.levels[i],{fragLoadPolicy:n,keyLoadPolicy:s}=e.config,a=yn(t.details.startsWith("key")?s:n,t),o=e.levels.reduce(((t,e)=>t+e.fragmentError),0);if(r){t.details!==Re.FRAG_GAP&&r.fragmentError++;if(En(a,o,mn(t),t.response))return{action:Cn,flags:Dn,retryConfig:a,retryCount:o}}const l=this.getLevelSwitchAction(t,i);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(t,e){const i=this.hls;null==e&&(e=i.loadLevel);const r=this.hls.levels[e];if(r){var n,s;const e=t.details;r.loadError++,e===Re.BUFFER_APPEND_ERROR&&r.fragmentError++;let l=-1;const{levels:c,loadLevel:h,minAutoLevel:u,maxAutoLevel:d}=i;i.autoLevelEnabled||(i.loadLevel=-1);const f=null==(n=t.frag)?void 0:n.type,g=(f===Or&&e===Re.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&(e===Re.BUFFER_ADD_CODEC_ERROR||e===Re.BUFFER_APPEND_ERROR))&&c.some((({audioCodec:t})=>r.audioCodec!==t)),p="video"===t.sourceBufferName&&(e===Re.BUFFER_ADD_CODEC_ERROR||e===Re.BUFFER_APPEND_ERROR)&&c.some((({codecSet:t,audioCodec:e})=>r.codecSet!==t&&r.audioCodec===e)),{type:m,groupId:y}=null!=(s=t.context)?s:{};for(let i=c.length;i--;){const n=(i+h)%c.length;if(n!==h&&n>=u&&n<=d&&0===c[n].loadError){var a,o;const i=c[n];if(e===Re.FRAG_GAP&&f===Pr&&t.frag){const e=c[n].details;if(e){const i=Sn(t.frag,e.fragments,t.frag.start);if(null!=i&&i.gap)continue}}else{if(m===wr&&i.hasAudioGroup(y)||m===Ir&&i.hasSubtitleGroup(y))continue;if(f===Or&&null!=(a=r.audioGroups)&&a.some((t=>i.hasAudioGroup(t)))||f===xr&&null!=(o=r.subtitleGroups)&&o.some((t=>i.hasSubtitleGroup(t)))||g&&r.audioCodec===i.audioCodec||!g&&r.audioCodec!==i.audioCodec||p&&r.codecSet===i.codecSet)continue}l=n;break}}if(l>-1&&i.loadLevel!==l)return t.levelRetry=!0,this.playlistError=0,{action:Ln,flags:Dn,nextAutoLevel:l}}return{action:Ln,flags:wn}}onErrorOut(t,e){var i;switch(null==(i=e.errorAction)?void 0:i.action){case _n:break;case Ln:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===Re.FRAG_GAP?/MediaSource readyState: ended/.test(e.error.message)&&(this.warn(`MediaSource ended after "${e.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):e.fatal=!0}e.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(t){const e=this.hls,i=t.errorAction;if(!i)return;const{flags:r,hdcpLevel:n,nextAutoLevel:s}=i;switch(r){case Dn:this.switchLevel(t,s);break;case In:n&&(e.maxHdcpLevel=Zr[Zr.indexOf(n)-1],i.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`)}i.resolved||this.switchLevel(t,s)}switchLevel(t,e){void 0!==e&&t.errorAction&&(this.warn(`switching to level ${e} after ${t.details}`),this.hls.nextAutoLevel=e,t.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}},fpsController:class{constructor(t){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners()}setStreamController(t){this.streamController=t}registerListeners(){this.hls.on(_e.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(_e.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,e){const i=this.hls.config;if(i.capLevelOnFPSDrop){const t=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=t,t&&"function"==typeof t.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}checkFPS(t,e,i){const r=performance.now();if(e){if(this.lastTime){const t=r-this.lastTime,n=i-this.lastDroppedFrames,s=e-this.lastDecodedFrames,a=1e3*n/t,o=this.hls;if(o.trigger(_e.FPS_DROP,{currentDropped:n,currentDecoded:s,totalDroppedFrames:i}),a>0&&n>o.config.fpsDroppedMonitoringThreshold*s){let t=o.currentLevel;Pe.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=t)&&(t-=1,o.trigger(_e.FPS_DROP_LEVEL_CAPPING,{level:t,droppedLevel:o.currentLevel}),o.autoLevelCapping=t,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=i,this.lastDecodedFrames=e}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)}},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:si,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:Ll,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:class extends Ds{constructor(t,e,i){super(t,e,i,"[subtitle-stream-controller]",xr),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}_registerListeners(){const{hls:t}=this;t.on(_e.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(_e.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(_e.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_e.LEVEL_LOADED,this.onLevelLoaded,this),t.on(_e.ERROR,this.onError,this),t.on(_e.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(_e.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(_e.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(_e.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(_e.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(_e.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(_e.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(_e.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(_e.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_e.LEVEL_LOADED,this.onLevelLoaded,this),t.off(_e.ERROR,this.onError,this),t.off(_e.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(_e.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(_e.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(_e.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(_e.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(_e.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(t){this.stopLoad(),this.state=vs,this.setInterval(500),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(t,e){this.mainDetails=e.details}onSubtitleFragProcessed(t,e){const{frag:i,success:r}=e;if(this.fragPrevious=i,this.state=vs,!r)return;const n=this.tracksBuffered[this.currentTrackId];if(!n)return;let s;const a=i.start;for(let t=0;t<n.length;t++)if(a>=n[t].start&&a<=n[t].end){s=n[t];break}const o=i.start+i.duration;s?s.end=o:(s={start:a,end:o},n.push(s)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null)}onBufferFlushing(t,e){const{startOffset:i,endOffset:r}=e;if(0===i&&r!==Number.POSITIVE_INFINITY){const t=r-1;if(t<=0)return;e.endOffsetSubtitles=Math.max(0,t),this.tracksBuffered.forEach((e=>{for(let i=0;i<e.length;)if(e[i].end<=t)e.shift();else{if(!(e[i].start<t))break;e[i].start=t,i++}})),this.fragmentTracker.removeFragmentsInRange(i,t,xr)}}onFragBuffered(t,e){var i;this.loadedmetadata||e.frag.type!==Pr||null!=(i=this.media)&&i.buffered.length&&(this.loadedmetadata=!0)}onError(t,e){const i=e.frag;(null==i?void 0:i.type)===xr&&(e.details===Re.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==ys&&(this.state=vs))}onSubtitleTracksUpdated(t,{subtitleTracks:e}){this.levels&&Na(this.levels,e)?this.levels=e.map((t=>new an(t))):(this.tracksBuffered=[],this.levels=e.map((t=>{const e=new an(t);return this.tracksBuffered[e.id]=[],e})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,xr),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(t,e){var i;if(this.currentTrackId=e.id,null==(i=this.levels)||!i.length||-1===this.currentTrackId)return void this.clearInterval();const r=this.levels[this.currentTrackId];null!=r&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.setInterval(500)}onSubtitleTrackLoaded(t,e){var i;const{currentTrackId:r,levels:n}=this,{details:s,id:a}=e;if(!n)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=n[a];if(a>=n.length||!o)return;this.log(`Subtitle track ${a} loaded [${s.startSN},${s.endSN}]${s.lastPartSn?`[part-${s.lastPartSn}-${s.lastPartIndex}]`:""},duration:${s.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(s.live||null!=(i=o.details)&&i.live){const t=this.mainDetails;if(s.deltaUpdateFailed||!t)return;const e=t.fragments[0];var c;if(o.details)l=this.alignPlaylists(s,o.details,null==(c=this.levelLastLoaded)?void 0:c.details),0===l&&e&&(l=e.start,dn(s,l));else s.hasProgramDateTime&&t.hasProgramDateTime?(as(s,t),l=s.fragments[0].start):e&&(l=e.start,dn(s,l))}if(o.details=s,this.levelLastLoaded=o,a===r&&(this.startFragRequested||!this.mainDetails&&s.live||this.setStartPosition(this.mainDetails||s,l),this.tick(),s.live&&!this.fragCurrent&&this.media&&this.state===vs)){Sn(null,s.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}_handleFragmentLoadComplete(t){const{frag:e,payload:i}=t,r=e.decryptdata,n=this.hls;if(!this.fragContextChanged(e)&&i&&i.byteLength>0&&null!=r&&r.key&&r.iv&&"AES-128"===r.method){const t=performance.now();this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer).catch((t=>{throw n.trigger(_e.ERROR,{type:Le.MEDIA_ERROR,details:Re.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t})).then((i=>{const r=performance.now();n.trigger(_e.FRAG_DECRYPTED,{frag:e,payload:i,stats:{tstart:t,tdecrypt:r}})})).catch((t=>{this.warn(`${t.name}: ${t.message}`),this.state=vs}))}}doTick(){if(this.media){if(this.state===vs){const{currentTrackId:t,levels:e}=this,i=null==e?void 0:e[t];if(!i||!e.length||!i.details)return;const{config:r}=this,n=this.getLoadPosition(),s=ts.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,r.maxBufferHole),{end:a,len:o}=s,l=this.getFwdBufferInfo(this.media,Pr),c=i.details;if(o>this.getMaxBufferLength(null==l?void 0:l.len)+c.levelTargetDuration)return;const h=c.fragments,u=h.length,d=c.edge;let f=null;const g=this.fragPrevious;if(a<d){const t=r.maxFragLookUpTolerance,e=a>d-t?0:t;f=Sn(g,h,Math.max(h[0].start,a),e),!f&&g&&g.start<h[0].start&&(f=h[0])}else f=h[u-1];if(!f)return;if(f=this.mapToInitFragWhenRequired(f),"initSegment"!==f.sn){const t=h[f.sn-c.startSN-1];t&&t.cc===f.cc&&this.fragmentTracker.getState(t)===jn&&(f=t)}this.fragmentTracker.getState(f)===jn&&this.loadFragment(f,i,a)}}else this.state=vs}getMaxBufferLength(t){const e=super.getMaxBufferLength();return t?Math.max(e,t):e}loadFragment(t,e,i){this.fragCurrent=t,"initSegment"===t.sn?this._loadInitSegment(t,e):(this.startFragRequested=!0,super.loadFragment(t,e,i))}get mediaBufferTimeRanges(){return new $a(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends Pn{constructor(t){super(t,"[subtitle-track-controller]"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const e=Kr(this.media.textTracks);for(let i=0;i<e.length;i++)if("hidden"===e[i].mode)t=e[i];else if("showing"===e[i].mode){t=e[i];break}const i=this.findTrackForTextTrack(t);this.subtitleTrack!==i&&this.setSubtitleTrack(i)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(_e.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(_e.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(_e.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_e.MANIFEST_PARSED,this.onManifestParsed,this),t.on(_e.LEVEL_LOADING,this.onLevelLoading,this),t.on(_e.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(_e.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(_e.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(_e.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(_e.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(_e.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_e.MANIFEST_PARSED,this.onManifestParsed,this),t.off(_e.LEVEL_LOADING,this.onLevelLoading,this),t.off(_e.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(_e.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(_e.ERROR,this.onError,this)}onMediaAttached(t,e){this.media=e.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,t)}onMediaDetaching(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId);Kr(this.media.textTracks).forEach((t=>{$r(t)})),this.subtitleTrack=-1,this.media=null}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.subtitleTracks}onSubtitleTrackLoaded(t,e){const{id:i,groupId:r,details:n}=e,s=this.tracksInGroup[i];if(!s||s.groupId!==r)return void this.warn(`Subtitle track with id:${i} and group:${r} not found in active group ${null==s?void 0:s.groupId}`);const a=s.details;s.details=e.details,this.log(`Subtitle track ${i} "${s.name}" lang:${s.lang} group:${r} loaded [${n.startSN}-${n.endSN}]`),i===this.trackId&&this.playlistLoaded(i,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const i=e.subtitleGroups||null,r=this.groupIds;let n=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some((t=>-1===(null==r?void 0:r.indexOf(t))))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter((t=>!i||-1!==i.indexOf(t.groupId)));if(t.length)this.selectDefaultTrack&&!t.some((t=>t.default))&&(this.selectDefaultTrack=!1),t.forEach(((t,e)=>{t.id=e}));else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.subtitlePreference;if(!n&&e){this.selectDefaultTrack=!1;const i=Gn(e,t);if(i>-1)n=t[i];else{const t=Gn(e,this.tracks);n=this.tracks[t]}}let r=this.findTrackId(n);-1===r&&n&&(r=this.findTrackId(null));const s={subtitleTracks:t};this.log(`Updating subtitle tracks, ${t.length} track(s) found in "${null==i?void 0:i.join(",")}" group-id`),this.hls.trigger(_e.SUBTITLE_TRACKS_UPDATED,s),-1!==r&&-1===this.trackId&&this.setSubtitleTrack(r)}else this.shouldReloadPlaylist(n)&&this.setSubtitleTrack(this.trackId)}findTrackId(t){const e=this.tracksInGroup,i=this.selectDefaultTrack;for(let r=0;r<e.length;r++){const n=e[r];if((!i||n.default)&&(i||t)&&(!t||Kn(n,t)))return r}if(t){for(let i=0;i<e.length;i++){const r=e[i];if(Ua(t.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<e.length;i++){const r=e[i];if(Ua(t.attrs,r.attrs,["LANGUAGE"]))return i}}return-1}findTrackForTextTrack(t){if(t){const e=this.tracksInGroup;for(let i=0;i<e.length;i++){if(Ba(e[i],t))return i}}return-1}onError(t,e){!e.fatal&&e.context&&(e.context.type!==Ir||e.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||this.checkRetry(e))}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(t){this.selectDefaultTrack=!1,this.setSubtitleTrack(t)}setSubtitleOption(t){if(this.hls.config.subtitlePreference=t,t){const e=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,e.length){const i=this.currentTrack;if(i&&Kn(t,i))return i;const r=Gn(t,this.tracksInGroup);if(r>-1){const t=this.tracksInGroup[r];return this.setSubtitleTrack(r),t}if(i)return null;{const i=Gn(t,e);if(i>-1)return e[i]}}}return null}loadPlaylist(t){super.loadPlaylist();const e=this.currentTrack;if(this.shouldLoadPlaylist(e)&&e){const i=e.id,r=e.groupId;let n=e.url;if(t)try{n=t.addDirectives(n)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}this.log(`Loading subtitle playlist for id ${i}`),this.hls.trigger(_e.SUBTITLE_TRACK_LOADING,{url:n,id:i,groupId:r,deliveryDirectives:t||null})}}toggleTrackModes(){const{media:t}=this;if(!t)return;const e=Kr(t.textTracks),i=this.currentTrack;let r;if(i&&(r=e.filter((t=>Ba(i,t)))[0],r||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(e).forEach((t=>{"disabled"!==t.mode&&t!==r&&(t.mode="disabled")})),r){const t=this.subtitleDisplay?"showing":"hidden";r.mode!==t&&(r.mode=t)}}setSubtitleTrack(t){const e=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=t);if(t<-1||t>=e.length||!Se(t))return void this.warn(`Invalid subtitle track id: ${t}`);this.clearTimer(),this.selectDefaultTrack=!1;const i=this.currentTrack,r=e[t]||null;if(this.trackId=t,this.currentTrack=r,this.toggleTrackModes(),!r)return void this.hls.trigger(_e.SUBTITLE_TRACK_SWITCH,{id:t});const n=!!r.details&&!r.details.live;if(t===this.trackId&&r===i&&n)return;this.log(`Switching to subtitle-track ${t}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));const{id:s,groupId:a="",name:o,type:l,url:c}=r;this.hls.trigger(_e.SUBTITLE_TRACK_SWITCH,{id:s,groupId:a,name:o,type:l,url:c});const h=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(h)}},timelineController:class{constructor(t){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},t.on(_e.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(_e.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(_e.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_e.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(_e.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(_e.FRAG_LOADING,this.onFragLoading,this),t.on(_e.FRAG_LOADED,this.onFragLoaded,this),t.on(_e.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(_e.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(_e.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(_e.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(_e.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(_e.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(_e.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(_e.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_e.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(_e.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(_e.FRAG_LOADING,this.onFragLoading,this),t.off(_e.FRAG_LOADED,this.onFragLoaded,this),t.off(_e.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(_e.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(_e.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(_e.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(_e.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){if(this.config.enableCEA708Captions&&(!this.cea608Parser1||!this.cea608Parser2)){const t=new co(this,"textTrack1"),e=new co(this,"textTrack2"),i=new co(this,"textTrack3"),r=new co(this,"textTrack4");this.cea608Parser1=new ao(1,t,e),this.cea608Parser2=new ao(3,i,r)}}addCues(t,e,i,r,n){let s=!1;for(let t=n.length;t--;){const r=n[t],h=(a=r[0],o=r[1],l=e,c=i,Math.min(o,c)-Math.max(a,l));if(h>=0&&(r[0]=Math.min(r[0],e),r[1]=Math.max(r[1],i),s=!0,h/(i-e)>.5))return}var a,o,l,c;if(s||n.push([e,i]),this.config.renderTextTracksNatively){const n=this.captionsTracks[t];this.Cues.newCue(n,e,i,r)}else{const n=this.Cues.newCue(null,e,i,r);this.hls.trigger(_e.CUES_PARSED,{type:"captions",cues:n,track:t})}}onInitPtsFound(t,{frag:e,id:i,initPTS:r,timescale:n}){const{unparsedVttFrags:s}=this;"main"===i&&(this.initPTS[e.cc]={baseTime:r,timescale:n}),s.length&&(this.unparsedVttFrags=[],s.forEach((t=>{this.onFragLoaded(_e.FRAG_LOADED,t)})))}getExistingTrack(t,e){const{media:i}=this;if(i)for(let r=0;r<i.textTracks.length;r++){const n=i.textTracks[r];if(Uo(n,{name:t,lang:e,attrs:{}}))return n}return null}createCaptionsTrack(t){this.config.renderTextTracksNatively?this.createNativeTrack(t):this.createNonNativeTrack(t)}createNativeTrack(t){if(this.captionsTracks[t])return;const{captionsProperties:e,captionsTracks:i,media:r}=this,{label:n,languageCode:s}=e[t],a=this.getExistingTrack(n,s);if(a)i[t]=a,$r(i[t]),Ur(i[t],r);else{const e=this.createTextTrack("captions",n,s);e&&(e[t]=!0,i[t]=e)}}createNonNativeTrack(t){if(this.nonNativeCaptionsTracks[t])return;const e=this.captionsProperties[t];if(!e)return;const i={_id:t,label:e.label,kind:"captions",default:!!e.media&&!!e.media.default,closedCaptions:e.media};this.nonNativeCaptionsTracks[t]=i,this.hls.trigger(_e.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(t,e,i){const r=this.media;if(r)return r.addTextTrack(t,e,i)}onMediaAttaching(t,e){this.media=e.media,this._cleanTracks()}onMediaDetaching(){const{captionsTracks:t}=this;Object.keys(t).forEach((e=>{$r(t[e]),delete t[e]})),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:t}=this;if(!t)return;const e=t.textTracks;if(e)for(let t=0;t<e.length;t++)$r(e[t])}onSubtitleTracksUpdated(t,e){const i=e.subtitleTracks||[],r=i.some((t=>t.textCodec===Lo));if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(Na(this.tracks,i))return void(this.tracks=i);if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const t=this.media,e=t?Kr(t.textTracks):null;if(this.tracks.forEach(((t,i)=>{let r;if(e){let i=null;for(let r=0;r<e.length;r++)if(e[r]&&Uo(e[r],t)){i=e[r],e[r]=null;break}i&&(r=i)}if(r)$r(r);else{const e=No(t);r=this.createTextTrack(e,t.name,t.lang),r&&(r.mode="disabled")}r&&this.textTracks.push(r)})),null!=e&&e.length){const t=e.filter((t=>null!==t)).map((t=>t.label));t.length&&Pe.warn(`Media element contains unused subtitle tracks: ${t.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const t=this.tracks.map((t=>({label:t.name,kind:t.type.toLowerCase(),default:t.default,subtitleTrack:t})));this.hls.trigger(_e.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:t})}}}onManifestLoaded(t,e){this.config.enableCEA708Captions&&e.captions&&e.captions.forEach((t=>{const e=/(?:CC|SERVICE)([1-4])/.exec(t.instreamId);if(!e)return;const i=`textTrack${e[1]}`,r=this.captionsProperties[i];r&&(r.label=t.name,t.lang&&(r.languageCode=t.lang),r.media=t)}))}closedCaptionsForLevel(t){const e=this.hls.levels[t.level];return null==e?void 0:e.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,e){if(this.enabled&&e.frag.type===Pr){var i,r;const{cea608Parser1:t,cea608Parser2:n,lastSn:s}=this,{cc:a,sn:o}=e.frag,l=null!=(i=null==(r=e.part)?void 0:r.index)?i:-1;t&&n&&(o!==s+1||o===s&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(t.reset(),n.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(t,e){const{frag:i,payload:r}=e;if(i.type===xr)if(r.byteLength){const t=i.decryptdata,n="stats"in e;if(null==t||!t.encrypted||n){const t=this.tracks[i.level],n=this.vttCCs;n[i.cc]||(n[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),t&&t.textCodec===Lo?this._parseIMSC1(i,r):this._parseVTTs(e)}}else this.hls.trigger(_e.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,e){const i=this.hls;wo(e,this.initPTS[t.cc],(e=>{this._appendCues(e,t.level),i.trigger(_e.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})}),(e=>{Pe.log(`Failed to parse IMSC1: ${e}`),i.trigger(_e.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:e})}))}_parseVTTs(t){var e;const{frag:i,payload:r}=t,{initPTS:n,unparsedVttFrags:s}=this,a=n.length-1;if(!n[i.cc]&&-1===a)return void s.push(t);const o=this.hls;_o(null!=(e=i.initSegment)&&e.data?Vi(i.initSegment.data,new Uint8Array(r)):r,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,(t=>{this._appendCues(t,i.level),o.trigger(_e.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})}),(e=>{const n="Missing initPTS for VTT MPEGTS"===e.message;n?s.push(t):this._fallbackToIMSC1(i,r),Pe.log(`Failed to parse VTT cue: ${e}`),n&&a>i.cc||o.trigger(_e.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:e})}))}_fallbackToIMSC1(t,e){const i=this.tracks[t.level];i.textCodec||wo(e,this.initPTS[t.cc],(()=>{i.textCodec=Lo,this._parseIMSC1(t,e)}),(()=>{i.textCodec="wvtt"}))}_appendCues(t,e){const i=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[e];if(!i||"disabled"===i.mode)return;t.forEach((t=>Br(i,t)))}else{const r=this.tracks[e];if(!r)return;const n=r.default?"default":"subtitles"+e;i.trigger(_e.CUES_PARSED,{type:"subtitles",cues:t,track:n})}}onFragDecrypted(t,e){const{frag:i}=e;i.type===xr&&this.onFragLoaded(_e.FRAG_LOADED,e)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,e){this.initCea608Parsers();const{cea608Parser1:i,cea608Parser2:r}=this;if(!this.enabled||!i||!r)return;const{frag:n,samples:s}=e;if(n.type!==Pr||"NONE"!==this.closedCaptionsForLevel(n))for(let t=0;t<s.length;t++){const e=s[t].bytes;if(e){const n=this.extractCea608Data(e);i.addData(s[t].pts,n[0]),r.addData(s[t].pts,n[1])}}}onBufferFlushing(t,{startOffset:e,endOffset:i,endOffsetSubtitles:r,type:n}){const{media:s}=this;if(s&&!(s.currentTime<i)){if(!n||"video"===n){const{captionsTracks:t}=this;Object.keys(t).forEach((r=>Gr(t[r],e,i)))}if(this.config.renderTextTracksNatively&&0===e&&void 0!==r){const{textTracks:t}=this;Object.keys(t).forEach((i=>Gr(t[i],e,r)))}}}extractCea608Data(t){const e=[[],[]],i=31&t[0];let r=2;for(let n=0;n<i;n++){const i=t[r++],n=127&t[r++],s=127&t[r++];if(0===n&&0===s)continue;if(!!(4&i)){const t=3&i;0!==t&&1!==t||(e[t].push(n),e[t].push(s))}}return e}},audioStreamController:class extends Ds{constructor(t,e,i){super(t,e,i,"[audio-stream-controller]",Or),this.videoBuffer=null,this.videoTrackCC=-1,this.waitingVideoCC=-1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}_registerListeners(){const{hls:t}=this;t.on(_e.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(_e.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(_e.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_e.LEVEL_LOADED,this.onLevelLoaded,this),t.on(_e.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(_e.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(_e.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(_e.ERROR,this.onError,this),t.on(_e.BUFFER_RESET,this.onBufferReset,this),t.on(_e.BUFFER_CREATED,this.onBufferCreated,this),t.on(_e.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(_e.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(_e.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(_e.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(_e.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(_e.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(_e.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_e.LEVEL_LOADED,this.onLevelLoaded,this),t.off(_e.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(_e.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(_e.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(_e.ERROR,this.onError,this),t.off(_e.BUFFER_RESET,this.onBufferReset,this),t.off(_e.BUFFER_CREATED,this.onBufferCreated,this),t.off(_e.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(_e.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(_e.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(_e.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(t,{frag:e,id:i,initPTS:r,timescale:n}){if("main"===i){const t=e.cc;this.initPTS[e.cc]={baseTime:r,timescale:n},this.log(`InitPTS for cc: ${t} found from main: ${r}`),this.videoTrackCC=t,this.state===Rs&&this.tick()}}startLoad(t){if(!this.levels)return this.startPosition=t,void(this.state=ys);const e=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),e>0&&-1===t?(this.log(`Override startPosition with lastCurrentTime @${e.toFixed(3)}`),t=e,this.state=vs):(this.loadedmetadata=!1,this.state=Ss),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}doTick(){switch(this.state){case vs:this.doTickIdle();break;case Ss:{var t;const{levels:e,trackId:i}=this,r=null==e||null==(t=e[i])?void 0:t.details;if(r){if(this.waitForCdnTuneIn(r))break;this.state=Rs}break}case Ts:{var e;const t=performance.now(),i=this.retryDate;if(!i||t>=i||null!=(e=this.media)&&e.seeking){const{levels:t,trackId:e}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((null==t?void 0:t[e])||null),this.state=vs}break}case Rs:{const t=this.waitingData;if(t){const{frag:e,part:i,cache:r,complete:n}=t;if(void 0!==this.initPTS[e.cc]){this.waitingData=null,this.waitingVideoCC=-1,this.state=Es;const t={frag:e,part:i,payload:r.flush(),networkDetails:null};this._handleFragmentLoadProgress(t),n&&super._handleFragmentLoadComplete(t)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${e.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const t=this.getLoadPosition(),i=ts.bufferInfo(this.mediaBuffer,t,this.config.maxBufferHole);bn(i.end,this.config.maxFragLookUpTolerance,e)<0&&(this.log(`Waiting fragment cc (${e.cc}) @ ${e.start} cancelled because another fragment at ${i.end} is needed`),this.clearWaitingFragment())}}else this.state=vs}}this.onTickEnd()}clearWaitingFragment(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=vs)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:t}=this;null!=t&&t.readyState&&(this.lastCurrentTime=t.currentTime)}doTickIdle(){const{hls:t,levels:e,media:i,trackId:r}=this,n=t.config;if(!i&&(this.startFragRequested||!n.startFragPrefetch)||null==e||!e[r])return;const s=e[r],a=s.details;if(!a||a.live&&this.levelLastLoaded!==s||this.waitForCdnTuneIn(a))return void(this.state=Ss);const o=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&o&&(this.bufferFlushed=!1,this.afterBufferFlushed(o,Be,Or));const l=this.getFwdBufferInfo(o,Or);if(null===l)return;const{bufferedTrack:c,switchingTrack:h}=this;if(!h&&this._streamEnded(l,a))return t.trigger(_e.BUFFER_EOS,{type:"audio"}),void(this.state=_s);const u=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,Pr),d=l.len,f=this.getMaxBufferLength(null==u?void 0:u.len),g=a.fragments,p=g[0].start;let m=this.flushing?this.getLoadPosition():l.end;if(h&&i){const t=this.getLoadPosition();c&&!Ua(h.attrs,c.attrs)&&(m=t),a.PTSKnown&&t<p&&(l.end>p||l.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=p+.05)}if(d>=f&&!h&&m<g[g.length-1].start)return;let y=this.getNextFragment(m,a),v=!1;if(y&&this.isLoopLoading(y,m)&&(v=!!y.gap,y=this.getNextFragmentLoopLoading(y,a,l,Pr,f)),!y)return void(this.bufferFlushed=!0);const A=u&&y.start>u.end+a.targetduration;if(A||(null==u||!u.len)&&l.len){const t=this.getAppendedFrag(y.start,Pr);if(null===t)return;if(v||(v=!!t.gap||!!A&&0===u.len),A&&!v||v&&l.nextStart&&l.nextStart<t.end)return}this.loadFragment(y,s,m)}getMaxBufferLength(t){const e=super.getMaxBufferLength();return t?Math.min(Math.max(e,t),this.config.maxMaxBufferLength):e}onMediaDetaching(){this.videoBuffer=null,this.bufferFlushed=this.flushing=!1,super.onMediaDetaching()}onAudioTracksUpdated(t,{audioTracks:e}){this.resetTransmuxer(),this.levels=e.map((t=>new an(t)))}onAudioTrackSwitching(t,e){const i=!!e.url;this.trackId=e.id;const{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),i?this.setInterval(100):this.resetTransmuxer(),i?(this.switchingTrack=e,this.state=vs,this.flushAudioIfNeeded(e)):(this.switchingTrack=null,this.bufferedTrack=e,this.state=ys),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=this.flushing=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}onLevelLoaded(t,e){this.mainDetails=e.details,null!==this.cachedTrackLoadedData&&(this.hls.trigger(_e.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(t,e){var i;if(null==this.mainDetails)return void(this.cachedTrackLoadedData=e);const{levels:r}=this,{details:n,id:s}=e;if(!r)return void this.warn(`Audio tracks were reset while loading level ${s}`);this.log(`Audio track ${s} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);const a=r[s];let o=0;if(n.live||null!=(i=a.details)&&i.live){this.checkLiveUpdate(n);const t=this.mainDetails;if(n.deltaUpdateFailed||!t)return;var l;if(!a.details&&n.hasProgramDateTime&&t.hasProgramDateTime)as(n,t),o=n.fragments[0].start;else o=this.alignPlaylists(n,a.details,null==(l=this.levelLastLoaded)?void 0:l.details)}a.details=n,this.levelLastLoaded=a,this.startFragRequested||!this.mainDetails&&n.live||this.setStartPosition(this.mainDetails||n,o),this.state!==Ss||this.waitForCdnTuneIn(n)||(this.state=vs),this.tick()}_handleFragmentLoadProgress(t){var e;const{frag:i,part:r,payload:n}=t,{config:s,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const c=l.details;if(!c)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(i.start);const h=s.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let u=this.transmuxer;u||(u=this.transmuxer=new Fa(this.hls,Or,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const d=this.initPTS[i.cc],f=null==(e=i.initSegment)?void 0:e.data;if(void 0!==d){const t=!1,e=r?r.index:-1,s=-1!==e,a=new es(i.level,i.sn,i.stats.chunkCount,n.byteLength,e,s);u.push(n,f,h,"",i,r,c.totalduration,t,a,d)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${c.startSN} ,${c.endSN}],track ${a}`);const{cache:t}=this.waitingData=this.waitingData||{frag:i,part:r,cache:new ws,complete:!1};t.push(new Uint8Array(n)),this.waitingVideoCC=this.videoTrackCC,this.state=Rs}}_handleFragmentLoadComplete(t){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(t,e){const i=e.tracks.audio;i&&(this.mediaBuffer=i.buffer||null),e.tracks.video&&(this.videoBuffer=e.tracks.video.buffer||null)}onFragBuffered(t,e){const{frag:i,part:r}=e;if(i.type===Or)if(this.fragContextChanged(i))this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if("initSegment"!==i.sn){this.fragPrevious=i;const t=this.switchingTrack;t&&(this.bufferedTrack=t,this.switchingTrack=null,this.hls.trigger(_e.AUDIO_TRACK_SWITCHED,ve({},t)))}this.fragBufferedComplete(i,r)}else if(!this.loadedmetadata&&i.type===Pr){const t=this.videoBuffer||this.media;if(t){ts.getBuffered(t).length&&(this.loadedmetadata=!0)}}}onError(t,e){var i;if(e.fatal)this.state=Ls;else switch(e.details){case Re.FRAG_GAP:case Re.FRAG_PARSING_ERROR:case Re.FRAG_DECRYPT_ERROR:case Re.FRAG_LOAD_ERROR:case Re.FRAG_LOAD_TIMEOUT:case Re.KEY_LOAD_ERROR:case Re.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Or,e);break;case Re.AUDIO_TRACK_LOAD_ERROR:case Re.AUDIO_TRACK_LOAD_TIMEOUT:case Re.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==Ss||(null==(i=e.context)?void 0:i.type)!==wr||(this.state=vs);break;case Re.BUFFER_APPEND_ERROR:case Re.BUFFER_FULL_ERROR:if(!e.parent||"audio"!==e.parent)return;if(e.details===Re.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case Re.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onBufferFlushing(t,{type:e}){e!==$e&&(this.flushing=!0)}onBufferFlushed(t,{type:e}){if(e!==$e){this.flushing=!1,this.bufferFlushed=!0,this.state===_s&&(this.state=vs);const t=this.mediaBuffer||this.media;t&&(this.afterBufferFlushed(t,e,Or),this.tick())}}_handleTransmuxComplete(t){var e;const i="audio",{hls:r}=this,{remuxResult:n,chunkMeta:s}=t,a=this.getCurrentContext(s);if(!a)return void this.resetWhenMissingContext(s);const{frag:o,part:l,level:c}=a,{details:h}=c,{audio:u,text:d,id3:f,initSegment:g}=n;if(!this.fragContextChanged(o)&&h){if(this.state=bs,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),null!=g&&g.tracks){const t=o.initSegment||o;this._bufferInitSegment(c,g.tracks,t,s),r.trigger(_e.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:i,tracks:g.tracks})}if(u){const{startPTS:t,endPTS:e,startDTS:i,endDTS:r}=u;l&&(l.elementaryStreams[Be]={startPTS:t,endPTS:e,startDTS:i,endDTS:r}),o.setElementaryStreamInfo(Be,t,e,i,r),this.bufferFragmentData(u,o,l,s)}if(null!=f&&null!=(e=f.samples)&&e.length){const t=Te({id:i,frag:o,details:h},f);r.trigger(_e.FRAG_PARSING_METADATA,t)}if(d){const t=Te({id:i,frag:o,details:h},d);r.trigger(_e.FRAG_PARSING_USERDATA,t)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(t,e,i,r){if(this.state!==bs)return;e.video&&delete e.video;const n=e.audio;if(!n)return;n.id="audio";const s=t.audioCodec;this.log(`Init audio buffer, container:${n.container}, codecs[level/parsed]=[${s}/${n.codec}]`),s&&1===s.split(",").length&&(n.levelCodec=s),this.hls.trigger(_e.BUFFER_CODECS,e);const a=n.initSegment;if(null!=a&&a.byteLength){const t={type:"audio",frag:i,part:null,chunkMeta:r,parent:i.type,data:a};this.hls.trigger(_e.BUFFER_APPENDING,t)}this.tickImmediate()}loadFragment(t,e,i){const r=this.fragmentTracker.getState(t);var n;if(this.fragCurrent=t,this.switchingTrack||r===jn||r===zn)if("initSegment"===t.sn)this._loadInitSegment(t,e);else if(null!=(n=e.details)&&n.live&&!this.initPTS[t.cc]){this.log(`Waiting for video PTS in continuity counter ${t.cc} of live stream before loading audio fragment ${t.sn} of level ${this.trackId}`),this.state=Rs;const i=this.mainDetails;i&&i.fragments[0].start!==e.details.fragments[0].start&&as(e.details,i)}else this.startFragRequested=!0,super.loadFragment(t,e,i);else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){const{media:e,bufferedTrack:i}=this,r=null==i?void 0:i.attrs,n=t.attrs;e&&r&&(r.CHANNELS!==n.CHANNELS||i.name!==t.name||i.lang!==t.lang)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null)}completeAudioSwitch(t){const{hls:e}=this;this.flushAudioIfNeeded(t),this.bufferedTrack=t,this.switchingTrack=null,e.trigger(_e.AUDIO_TRACK_SWITCHED,ve({},t))}},audioTrackController:class extends Pn{constructor(t){super(t,"[audio-track-controller]"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:t}=this;t.on(_e.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_e.MANIFEST_PARSED,this.onManifestParsed,this),t.on(_e.LEVEL_LOADING,this.onLevelLoading,this),t.on(_e.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(_e.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(_e.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(_e.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_e.MANIFEST_PARSED,this.onManifestParsed,this),t.off(_e.LEVEL_LOADING,this.onLevelLoading,this),t.off(_e.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(_e.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.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(t,e){this.tracks=e.audioTracks||[]}onAudioTrackLoaded(t,e){const{id:i,groupId:r,details:n}=e,s=this.tracksInGroup[i];if(!s||s.groupId!==r)return void this.warn(`Audio track with id:${i} and group:${r} not found in active group ${null==s?void 0:s.groupId}`);const a=s.details;s.details=e.details,this.log(`Audio track ${i} "${s.name}" lang:${s.lang} group:${r} loaded [${n.startSN}-${n.endSN}]`),i===this.trackId&&this.playlistLoaded(i,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const i=e.audioGroups||null,r=this.groupIds;let n=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some((t=>-1===(null==r?void 0:r.indexOf(t))))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter((t=>!i||-1!==i.indexOf(t.groupId)));if(t.length)this.selectDefaultTrack&&!t.some((t=>t.default))&&(this.selectDefaultTrack=!1),t.forEach(((t,e)=>{t.id=e}));else if(!n&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.audioPreference;if(!n&&e){const i=Gn(e,t,Hn);if(i>-1)n=t[i];else{const t=Gn(e,this.tracks);n=this.tracks[t]}}let r=this.findTrackId(n);-1===r&&n&&(r=this.findTrackId(null));const a={audioTracks:t};this.log(`Updating audio tracks, ${t.length} track(s) found in group(s): ${null==i?void 0:i.join(",")}`),this.hls.trigger(_e.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==r&&-1===o)this.setAudioTrack(r);else if(t.length&&-1===o){var s;const e=new Error(`No audio track selected for current audio group-ID(s): ${null==(s=this.groupIds)?void 0:s.join(",")} track count: ${t.length}`);this.warn(e.message),this.hls.trigger(_e.ERROR,{type:Le.MEDIA_ERROR,details:Re.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:e})}}else this.shouldReloadPlaylist(n)&&this.setAudioTrack(this.trackId)}onError(t,e){!e.fatal&&e.context&&(e.context.type!==wr||e.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||(this.requestScheduled=-1,this.checkRetry(e)))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}setAudioOption(t){const e=this.hls;if(e.config.audioPreference=t,t){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const r=this.currentTrack;if(r&&Kn(t,r,Hn))return r;const n=Gn(t,this.tracksInGroup,Hn);if(n>-1){const t=this.tracksInGroup[n];return this.setAudioTrack(n),t}if(r){let r=e.loadLevel;-1===r&&(r=e.firstAutoLevel);const n=function(t,e,i,r,n){const s=e[r],a=e.reduce(((t,e,i)=>{const r=e.uri;return(t[r]||(t[r]=[])).push(i),t}),{})[s.uri];a.length>1&&(r=Math.max.apply(Math,a));const o=s.videoRange,l=s.frameRate,c=s.codecSet.substring(0,4),h=Vn(e,r,(e=>{if(e.videoRange!==o||e.frameRate!==l||e.codecSet.substring(0,4)!==c)return!1;const r=e.audioGroups,s=i.filter((t=>!r||-1!==r.indexOf(t.groupId)));return Gn(t,s,n)>-1}));return h>-1?h:Vn(e,r,(e=>{const r=e.audioGroups,s=i.filter((t=>!r||-1!==r.indexOf(t.groupId)));return Gn(t,s,n)>-1}))}(t,e.levels,i,r,Hn);if(-1===n)return null;e.nextLoadLevel=n}if(t.channels||t.audioCodec){const e=Gn(t,i);if(e>-1)return i[e]}}}return null}setAudioTrack(t){const e=this.tracksInGroup;if(t<0||t>=e.length)return void this.warn(`Invalid audio track id: ${t}`);this.clearTimer(),this.selectDefaultTrack=!1;const i=this.currentTrack,r=e[t],n=r.details&&!r.details.live;if(t===this.trackId&&r===i&&n)return;if(this.log(`Switching to audio-track ${t} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=t,this.currentTrack=r,this.hls.trigger(_e.AUDIO_TRACK_SWITCHING,ve({},r)),n)return;const s=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(s)}findTrackId(t){const e=this.tracksInGroup;for(let i=0;i<e.length;i++){const r=e[i];if((!this.selectDefaultTrack||r.default)&&(!t||Kn(t,r,Hn)))return i}if(t){const{name:i,lang:r,assocLang:n,characteristics:s,audioCodec:a,channels:o}=t;for(let t=0;t<e.length;t++){if(Kn({name:i,lang:r,assocLang:n,characteristics:s,audioCodec:a,channels:o},e[t],Hn))return t}for(let i=0;i<e.length;i++){const r=e[i];if(Ua(t.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<e.length;i++){const r=e[i];if(Ua(t.attrs,r.attrs,["LANGUAGE"]))return i}}return-1}loadPlaylist(t){const e=this.currentTrack;if(this.shouldLoadPlaylist(e)&&e){super.loadPlaylist();const i=e.id,r=e.groupId;let n=e.url;if(t)try{n=t.addDirectives(n)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}this.log(`loading audio-track playlist ${i} "${e.name}" lang:${e.lang} group:${r}`),this.clearTimer(),this.hls.trigger(_e.AUDIO_TRACK_LOADING,{url:n,id:i,groupId:r,deliveryDirectives:t||null})}}},emeController:Go,cmcdController:class{constructor(t){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.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=t=>{try{this.apply(t,{ot:Ho.MANIFEST,su:!this.initialized})}catch(t){Pe.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=t=>{try{const e=t.frag,i=this.hls.levels[e.level],r=this.getObjectType(e),n={d:1e3*e.duration,ot:r};r!==Ho.VIDEO&&r!==Ho.AUDIO&&r!=Ho.MUXED||(n.br=i.bitrate/1e3,n.tb=this.getTopBandwidth(r)/1e3,n.bl=this.getBufferLength(r)),this.apply(t,n)}catch(t){Pe.warn("Could not generate segment CMCD data.",t)}},this.hls=t;const e=this.config=t.config,{cmcd:i}=e;null!=i&&(e.pLoader=this.createPlaylistLoader(),e.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||function(){try{return crypto.randomUUID()}catch(t){try{const t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}catch(t){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(t=>{const i=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?i:3&i|8).toString(16)}))}}}(),this.cid=i.contentId,this.useHeaders=!0===i.useHeaders,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const t=this.hls;t.on(_e.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(_e.MEDIA_DETACHED,this.onMediaDetached,this),t.on(_e.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(_e.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(_e.MEDIA_DETACHED,this.onMediaDetached,this),t.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=null}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(t,e){var i,r;this.audioBuffer=null==(i=e.tracks.audio)?void 0:i.buffer,this.videoBuffer=null==(r=e.tracks.video)?void 0:r.buffer}createData(){var t;return{v:1,sf:Vo.HLS,sid:this.sid,cid:this.cid,pr:null==(t=this.media)?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,e={}){Te(e,this.createData());const i=e.ot===Ho.INIT||e.ot===Ho.VIDEO||e.ot===Ho.MUXED;this.starved&&i&&(e.bs=!0,e.su=!0,this.starved=!1),null==e.su&&(e.su=this.buffering);const{includeKeys:r}=this;r&&(e=Object.keys(e).reduce(((t,i)=>(r.includes(i)&&(t[i]=e[i]),t)),{})),this.useHeaders?(t.headers||(t.headers={}),gl(t.headers,e)):t.url=ml(t.url,e)}getObjectType(t){const{type:e}=t;return"subtitle"===e?Ho.TIMED_TEXT:"initSegment"===t.sn?Ho.INIT:"audio"===e?Ho.AUDIO:"main"===e?this.hls.audioTracks.length?Ho.VIDEO:Ho.MUXED:void 0}getTopBandwidth(t){let e,i=0;const r=this.hls;if(t===Ho.AUDIO)e=r.audioTracks;else{const t=r.maxAutoLevel,i=t>-1?t+1:r.levels.length;e=r.levels.slice(0,i)}for(const t of e)t.bitrate>i&&(i=t.bitrate);return i>0?i:NaN}getBufferLength(t){const e=this.hls.media,i=t===Ho.AUDIO?this.audioBuffer:this.videoBuffer;if(!i||!e)return NaN;return 1e3*ts.bufferInfo(i,e.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:t}=this.config,e=this.applyPlaylistData,i=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new i(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,i,r){e(t),this.loader.load(t,i,r)}}}createFragmentLoader(){const{fLoader:t}=this.config,e=this.applyFragmentData,i=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new i(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,i,r){e(t),this.loader.load(t,i,r)}}}},contentSteeringController:class{constructor(t){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=t,this.log=Pe.log.bind(Pe,"[content-steering]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(_e.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_e.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(_e.MANIFEST_PARSED,this.onManifestParsed,this),t.on(_e.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(_e.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_e.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(_e.MANIFEST_PARSED,this.onManifestParsed,this),t.off(_e.ERROR,this.onError,this))}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const t=1e3*this.timeToLoad-(performance.now()-this.updated);if(t>0)return void this.scheduleRefresh(this.uri,t)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(t){const e=this.levels;e&&(this.levels=e.filter((e=>e!==t)))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(t,e){const{contentSteering:i}=e;null!==i&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks}onError(t,e){const{errorAction:i}=e;if((null==i?void 0:i.action)===Ln&&i.flags===wn){const t=this.levels;let r=this.pathwayPriority,n=this.pathwayId;if(e.context){const{groupId:i,pathwayId:r,type:s}=e.context;i&&t?n=this.getPathwayForGroupId(i,s,n):r&&(n=r)}n in this.penalizedPathways||(this.penalizedPathways[n]=performance.now()),!r&&t&&(r=t.reduce(((t,e)=>(-1===t.indexOf(e.pathwayId)&&t.push(e.pathwayId),t)),[])),r&&r.length>1&&(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==n),i.resolved||Pe.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${n} levels: ${t?t.length:t} priorities: ${JSON.stringify(r)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(t){this.levels=t;let e=this.getLevelsForPathway(this.pathwayId);if(0===e.length){const i=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),e=this.getLevelsForPathway(i),this.pathwayId=i}return e.length!==t.length?(this.log(`Found ${e.length}/${t.length} levels in Pathway "${this.pathwayId}"`),e):t}getLevelsForPathway(t){return null===this.levels?[]:this.levels.filter((e=>t===e.pathwayId))}updatePathwayPriority(t){let e;this.pathwayPriority=t;const i=this.penalizedPathways,r=performance.now();Object.keys(i).forEach((t=>{r-i[t]>3e5&&delete i[t]}));for(let r=0;r<t.length;r++){const n=t[r];if(n in i)continue;if(n===this.pathwayId)return;const s=this.hls.nextLoadLevel,a=this.hls.levels[s];if(e=this.getLevelsForPathway(n),e.length>0){this.log(`Setting Pathway to "${n}"`),this.pathwayId=n,pn(e),this.hls.trigger(_e.LEVELS_UPDATED,{levels:e});const t=this.hls.levels[s];a&&t&&this.levels&&(t.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&t.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${t.bitrate}`),this.hls.nextLoadLevel=s);break}}}getPathwayForGroupId(t,e,i){const r=this.getLevelsForPathway(i).concat(this.levels||[]);for(let i=0;i<r.length;i++)if(e===wr&&r[i].hasAudioGroup(t)||e===Ir&&r[i].hasSubtitleGroup(t))return r[i].pathwayId;return i}clonePathways(t){const e=this.levels;if(!e)return;const i={},r={};t.forEach((t=>{const{ID:n,"BASE-ID":s,"URI-REPLACEMENT":a}=t;if(e.some((t=>t.pathwayId===n)))return;const o=this.getLevelsForPathway(s).map((t=>{const e=new Me(t.attrs);e["PATHWAY-ID"]=n;const s=e.AUDIO&&`${e.AUDIO}_clone_${n}`,o=e.SUBTITLES&&`${e.SUBTITLES}_clone_${n}`;s&&(i[e.AUDIO]=s,e.AUDIO=s),o&&(r[e.SUBTITLES]=o,e.SUBTITLES=o);const l=vl(t.uri,e["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),c=new an({attrs:e,audioCodec:t.audioCodec,bitrate:t.bitrate,height:t.height,name:t.name,url:l,videoCodec:t.videoCodec,width:t.width});if(t.audioGroups)for(let e=1;e<t.audioGroups.length;e++)c.addGroupId("audio",`${t.audioGroups[e]}_clone_${n}`);if(t.subtitleGroups)for(let e=1;e<t.subtitleGroups.length;e++)c.addGroupId("text",`${t.subtitleGroups[e]}_clone_${n}`);return c}));e.push(...o),yl(this.audioTracks,i,a,n),yl(this.subtitleTracks,r,a,n)}))}loadSteeringManifest(t){const e=this.hls.config,i=e.loader;let r;this.loader&&this.loader.destroy(),this.loader=new i(e);try{r=new self.URL(t)}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${t}`)}if("data:"!==r.protocol){const t=0|(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate);r.searchParams.set("_HLS_pathway",this.pathwayId),r.searchParams.set("_HLS_throughput",""+t)}const n={responseType:"json",url:r.href},s=e.steeringManifestLoadPolicy.default,a=s.errorRetry||s.timeoutRetry||{},o={loadPolicy:s,timeout:s.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(t,e,i,n)=>{this.log(`Loaded steering manifest: "${r}"`);const s=t.data;if(1!==s.VERSION)return void this.log(`Steering VERSION ${s.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=s.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=s;if(a)try{this.uri=new self.URL(a,r).href}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||i.url),o&&this.clonePathways(o);const c={steeringManifest:s,url:r.toString()};this.hls.trigger(_e.STEERING_MANIFEST_LOADED,c),l&&this.updatePathwayPriority(l)},onError:(t,e,i,r)=>{if(this.log(`Error loading steering manifest: ${t.code} ${t.text} (${e.url})`),this.stopLoad(),410===t.code)return this.enabled=!1,void this.log(`Steering manifest ${e.url} no longer available`);let n=1e3*this.timeToLoad;if(429!==t.code)this.scheduleRefresh(this.uri||e.url,n);else{const t=this.loader;if("function"==typeof(null==t?void 0:t.getResponseHeader)){const e=t.getResponseHeader("Retry-After");e&&(n=1e3*parseFloat(e))}this.log(`Steering manifest ${e.url} rate limited`)}},onTimeout:(t,e,i)=>{this.log(`Timeout loading steering manifest (${e.url})`),this.scheduleRefresh(this.uri||e.url)}};this.log(`Requesting steering manifest: ${r}`),this.loader.load(n,o,l)}scheduleRefresh(t,e=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout((()=>{var e;const i=null==(e=this.hls)?void 0:e.media;!i||i.ended?this.scheduleRefresh(t,1e3*this.timeToLoad):this.loadSteeringManifest(t)}),e)}}});function Cl(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(Cl):Object.keys(t).reduce(((e,i)=>(e[i]=Cl(t[i]),e)),{}):t}function Dl(t){const e=t.loader;if(e!==Sl&&e!==El)Pe.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1;else{(function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1})()&&(t.loader=Sl,t.progressive=!0,t.enableSoftwareAES=!0,Pe.log("[config]: Progressive streaming enabled, using FetchLoader"))}}let wl;class Il extends Pn{constructor(t,e){super(t,"[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=e,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(_e.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_e.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(_e.LEVEL_LOADED,this.onLevelLoaded,this),t.on(_e.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(_e.FRAG_BUFFERED,this.onFragBuffered,this),t.on(_e.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(_e.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_e.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(_e.LEVEL_LOADED,this.onLevelLoaded,this),t.off(_e.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(_e.FRAG_BUFFERED,this.onFragBuffered,this),t.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(t,e){this.resetLevels()}onManifestLoaded(t,e){const i=this.hls.config.preferManagedMediaSource,r=[],n={},s={};let a=!1,o=!1,l=!1;e.levels.forEach((t=>{var e,c;const h=t.attrs;let{audioCodec:u,videoCodec:d}=t;-1!==(null==(e=u)?void 0:e.indexOf("mp4a.40.34"))&&(wl||(wl=/chrome|firefox/i.test(navigator.userAgent)),wl&&(t.audioCodec=u=void 0)),u&&(t.audioCodec=u=fr(u,i)),0===(null==(c=d)?void 0:c.indexOf("avc1"))&&(d=t.videoCodec=function(t){const e=t.split(",");for(let t=0;t<e.length;t++){const i=e[t].split(".");if(i.length>2){let r=i.shift()+".";r+=parseInt(i.shift()).toString(16),r+=("000"+parseInt(i.shift()).toString(16)).slice(-4),e[t]=r}}return e.join(",")}(d));const{width:f,height:g,unknownCodecs:p}=t;if(a||(a=!(!f||!g)),o||(o=!!d),l||(l=!!u),null!=p&&p.length||u&&!ar(u,"audio",i)||d&&!ar(d,"video",i))return;const{CODECS:m,"FRAME-RATE":y,"HDCP-LEVEL":v,"PATHWAY-ID":A,RESOLUTION:E,"VIDEO-RANGE":T}=h,S=`${`${A||"."}-`}${t.bitrate}-${E}-${y}-${m}-${T}-${v}`;if(n[S])if(n[S].uri===t.url||t.attrs["PATHWAY-ID"])n[S].addGroupId("audio",h.AUDIO),n[S].addGroupId("text",h.SUBTITLES);else{const e=s[S]+=1;t.attrs["PATHWAY-ID"]=new Array(e+1).join(".");const i=new an(t);n[S]=i,r.push(i)}else{const e=new an(t);n[S]=e,s[S]=1,r.push(e)}})),this.filterAndSortMediaOptions(r,e,a,o,l)}filterAndSortMediaOptions(t,e,i,r,n){let s=[],a=[],o=t;if((i||r)&&n&&(o=o.filter((({videoCodec:t,videoRange:e,width:i,height:r})=>{return(!!t||!(!i||!r))&&(!!(n=e)&&Jr.indexOf(n)>-1);var n}))),0===o.length)return void Promise.resolve().then((()=>{if(this.hls){e.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(e.levels[0].attrs)}`);const t=new Error("no level with compatible codecs found in manifest");this.hls.trigger(_e.ERROR,{type:Le.MEDIA_ERROR,details:Re.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:t,reason:t.message})}}));if(e.audioTracks){const{preferManagedMediaSource:t}=this.hls.config;s=e.audioTracks.filter((e=>!e.audioCodec||ar(e.audioCodec,"audio",t))),Pl(s)}e.subtitles&&(a=e.subtitles,Pl(a));const l=o.slice(0);o.sort(((t,e)=>{if(t.attrs["HDCP-LEVEL"]!==e.attrs["HDCP-LEVEL"])return(t.attrs["HDCP-LEVEL"]||"")>(e.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&t.height!==e.height)return t.height-e.height;if(t.frameRate!==e.frameRate)return t.frameRate-e.frameRate;if(t.videoRange!==e.videoRange)return Jr.indexOf(t.videoRange)-Jr.indexOf(e.videoRange);if(t.videoCodec!==e.videoCodec){const i=cr(t.videoCodec),r=cr(e.videoCodec);if(i!==r)return r-i}if(t.uri===e.uri&&t.codecSet!==e.codecSet){const i=hr(t.codecSet),r=hr(e.codecSet);if(i!==r)return r-i}return t.averageBitrate!==e.averageBitrate?t.averageBitrate-e.averageBitrate:0}));let c=l[0];if(this.steering&&(o=this.steering.filterParsedLevels(o),o.length!==l.length))for(let t=0;t<l.length;t++)if(l[t].pathwayId===o[0].pathwayId){c=l[t];break}this._levels=o;for(let t=0;t<o.length;t++)if(o[t]===c){var h;this._firstLevel=t;const e=c.bitrate,i=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${o.length} level(s) found, first bitrate: ${e}`),void 0===(null==(h=this.hls.userConfig)?void 0:h.abrEwmaDefaultEstimate)){const t=Math.min(e,this.hls.config.abrEwmaDefaultEstimateMax);t>i&&i===Rl.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=t)}break}const u=n&&!r,d={levels:o,audioTracks:s,subtitleTracks:a,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:n,video:r,altAudio:!u&&s.some((t=>!!t.url))};this.hls.trigger(_e.MANIFEST_PARSED,d),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return 0===this._levels.length?null:this._levels}get level(){return this.currentLevelIndex}set level(t){const e=this._levels;if(0===e.length)return;if(t<0||t>=e.length){const i=new Error("invalid level idx"),r=t<0;if(this.hls.trigger(_e.ERROR,{type:Le.OTHER_ERROR,details:Re.LEVEL_SWITCH_ERROR,level:t,fatal:r,error:i,reason:i.message}),r)return;t=Math.min(t,e.length-1)}const i=this.currentLevelIndex,r=this.currentLevel,n=r?r.attrs["PATHWAY-ID"]:void 0,s=e[t],a=s.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=s,i===t&&s.details&&r&&n===a)return;this.log(`Switching to level ${t} (${s.height?s.height+"p ":""}${s.videoRange?s.videoRange+" ":""}${s.codecSet?s.codecSet+" ":""}@${s.bitrate})${a?" with Pathway "+a:""} from level ${i}${n?" with Pathway "+n:""}`);const o={level:t,attrs:s.attrs,details:s.details,bitrate:s.bitrate,averageBitrate:s.averageBitrate,maxBitrate:s.maxBitrate,realBitrate:s.realBitrate,width:s.width,height:s.height,codecSet:s.codecSet,audioCodec:s.audioCodec,videoCodec:s.videoCodec,audioGroups:s.audioGroups,subtitleGroups:s.subtitleGroups,loaded:s.loaded,loadError:s.loadError,fragmentError:s.fragmentError,name:s.name,id:s.id,uri:s.uri,url:s.url,urlId:0,audioGroupIds:s.audioGroupIds,textGroupIds:s.textGroupIds};this.hls.trigger(_e.LEVEL_SWITCHING,o);const l=s.details;if(!l||l.live){const t=this.switchParams(s.uri,null==r?void 0:r.details,l);this.loadPlaylist(t)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(void 0===this._startLevel){const t=this.hls.config.startLevel;return void 0!==t?t:this.hls.firstAutoLevel}return this._startLevel}set startLevel(t){this._startLevel=t}onError(t,e){!e.fatal&&e.context&&e.context.type===Dr&&e.context.level===this.level&&this.checkRetry(e)}onFragBuffered(t,{frag:e}){if(void 0!==e&&e.type===Pr){const t=e.elementaryStreams;if(!Object.keys(t).some((e=>!!t[e])))return;const i=this._levels[e.level];null!=i&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(t,e){var i;const{level:r,details:n}=e,s=this._levels[r];var a;if(!s)return this.warn(`Invalid level index ${r}`),void(null!=(a=e.deliveryDirectives)&&a.skip&&(n.deltaUpdateFailed=!0));r===this.currentLevelIndex?(0===s.fragmentError&&(s.loadError=0),this.playlistLoaded(r,e,s.details)):null!=(i=e.deliveryDirectives)&&i.skip&&(n.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist();const e=this.currentLevelIndex,i=this.currentLevel;if(i&&this.shouldLoadPlaylist(i)){let r=i.uri;if(t)try{r=t.addDirectives(r)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}const n=i.attrs["PATHWAY-ID"];this.log(`Loading level index ${e}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""} with${n?" Pathway "+n:""} ${r}`),this.clearTimer(),this.hls.trigger(_e.LEVEL_LOADING,{url:r,level:e,pathwayId:i.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}removeLevel(t){var e;const i=this._levels.filter(((e,i)=>i!==t||(this.steering&&this.steering.removeLevel(e),e===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,e.details&&e.details.fragments.forEach((t=>t.level=-1))),!1)));pn(i),this._levels=i,this.currentLevelIndex>-1&&null!=(e=this.currentLevel)&&e.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(_e.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(t,{levels:e}){this._levels=e}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:e,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==e&&(this._maxAutoLevel=e,this.hls.trigger(_e.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function Pl(t){const e={};t.forEach((t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++}))}class Ol{constructor(t){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=t}abort(t){for(const i in this.keyUriToKeyInfo){const r=this.keyUriToKeyInfo[i].loader;if(r){var e;if(t&&t!==(null==(e=r.context)?void 0:e.frag.type))return;r.abort()}}}detach(){for(const t in this.keyUriToKeyInfo){const e=this.keyUriToKeyInfo[t];(e.mediaKeySessionContext||e.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[t]}}destroy(){this.detach();for(const t in this.keyUriToKeyInfo){const e=this.keyUriToKeyInfo[t].loader;e&&e.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(t,e=Re.KEY_LOAD_ERROR,i,r,n){return new us({type:Le.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:n,error:i,networkDetails:r})}loadClear(t,e){if(this.emeController&&this.config.emeEnabled){const{sn:i,cc:r}=t;for(let t=0;t<e.length;t++){const n=e[t];if(r<=n.cc&&("initSegment"===i||"initSegment"===n.sn||i<n.sn)){this.emeController.selectKeySystemFormat(n).then((t=>{n.setKeyFormat(t)}));break}}}}load(t){return!t.decryptdata&&t.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(t).then((e=>this.loadInternal(t,e))):this.loadInternal(t)}loadInternal(t,e){var i,r;e&&t.setKeyFormat(e);const n=t.decryptdata;if(!n){const i=new Error(e?`Expected frag.decryptdata to be defined after setting format ${e}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(t,Re.KEY_LOAD_ERROR,i))}const s=n.uri;if(!s)return Promise.reject(this.createKeyLoadError(t,Re.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${s}"`)));let a=this.keyUriToKeyInfo[s];if(null!=(i=a)&&i.decryptdata.key)return n.key=a.decryptdata.key,Promise.resolve({frag:t,keyInfo:a});var o;if(null!=(r=a)&&r.keyLoadPromise)switch(null==(o=a.mediaKeySessionContext)?void 0:o.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return a.keyLoadPromise.then((e=>(n.key=e.keyInfo.decryptdata.key,{frag:t,keyInfo:a})))}switch(a=this.keyUriToKeyInfo[s]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===n.keyFormat?this.loadKeyHTTP(a,t):this.loadKeyEME(a,t);case"AES-128":return this.loadKeyHTTP(a,t);default:return Promise.reject(this.createKeyLoadError(t,Re.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(t,e){const i={frag:e,keyInfo:t};if(this.emeController&&this.config.emeEnabled){const e=this.emeController.loadKey(i);if(e)return(t.keyLoadPromise=e.then((e=>(t.mediaKeySessionContext=e,i)))).catch((e=>{throw t.keyLoadPromise=null,e}))}return Promise.resolve(i)}loadKeyHTTP(t,e){const i=this.config,r=new(0,i.loader)(i);return e.keyLoader=t.loader=r,t.keyLoadPromise=new Promise(((n,s)=>{const a={keyInfo:t,frag:e,responseType:"arraybuffer",url:t.decryptdata.uri},o=i.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(t,e,i,r)=>{const{frag:a,keyInfo:o,url:l}=i;if(!a.decryptdata||o!==this.keyUriToKeyInfo[l])return s(this.createKeyLoadError(a,Re.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),r));o.decryptdata.key=a.decryptdata.key=new Uint8Array(t.data),a.keyLoader=null,o.loader=null,n({frag:a,keyInfo:o})},onError:(t,i,r,n)=>{this.resetLoader(i),s(this.createKeyLoadError(e,Re.KEY_LOAD_ERROR,new Error(`HTTP Error ${t.code} loading key ${t.text}`),r,ve({url:a.url,data:void 0},t)))},onTimeout:(t,i,r)=>{this.resetLoader(i),s(this.createKeyLoadError(e,Re.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),r))},onAbort:(t,i,r)=>{this.resetLoader(i),s(this.createKeyLoadError(e,Re.INTERNAL_ABORTED,new Error("key loading aborted"),r))}};r.load(a,l,c)}))}resetLoader(t){const{frag:e,keyInfo:i,url:r}=t,n=i.loader;e.keyLoader===n&&(e.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[r],n&&n.destroy()}}function xl(){return self.SourceBuffer||self.WebKitSourceBuffer}function Ml(){if(!nr())return!1;const t=xl();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}class Fl{constructor(t,e,i,r){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=t,this.media=e,this.fragmentTracker=i,this.hls=r}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(t,e){const{config:i,media:r,stalled:n}=this;if(null===r)return;const{currentTime:s,seeking:a}=r,o=this.seeking&&!a,l=!this.seeking&&a;if(this.seeking=a,s!==t){if(this.moved=!0,a||(this.nudgeRetry=0),null!==n){if(this.stallReported){const t=self.performance.now()-n;Pe.warn(`playback not stuck anymore @${s}, after ${Math.round(t)}ms`),this.stallReported=!1}this.stalled=null}return}if(l||o)return void(this.stalled=null);if(r.paused&&!a||r.ended||0===r.playbackRate||!ts.getBuffered(r).length)return void(this.nudgeRetry=0);const c=ts.bufferInfo(r,s,0),h=c.nextStart||0;if(a){const t=c.len>2,i=!h||e&&e.start<=s||h-s>2&&!this.fragmentTracker.getPartialFragment(s);if(t||i)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var u;if(!(c.len>0)&&!h)return;const t=Math.max(h,c.start||0)-s,e=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,i=(null==e||null==(u=e.details)?void 0:u.live)?2*e.details.targetduration:2,n=this.fragmentTracker.getPartialFragment(s);if(t>0&&(t<=i||n))return void(r.paused||this._trySkipBufferHole(n))}const d=self.performance.now();if(null===n)return void(this.stalled=d);const f=d-n;if(!a&&f>=250&&(this._reportStall(c),!this.media))return;const g=ts.bufferInfo(r,s,i.maxBufferHole);this._tryFixBufferStall(g,f)}_tryFixBufferStall(t,e){const{config:i,fragmentTracker:r,media:n}=this;if(null===n)return;const s=n.currentTime,a=r.getPartialFragment(s);if(a){if(this._trySkipBufferHole(a)||!this.media)return}(t.len>i.maxBufferHole||t.nextStart&&t.nextStart-s<i.maxBufferHole)&&e>1e3*i.highBufferWatchdogPeriod&&(Pe.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(t){const{hls:e,media:i,stallReported:r}=this;if(!r&&i){this.stallReported=!0;const r=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${JSON.stringify(t)})`);Pe.warn(r.message),e.trigger(_e.ERROR,{type:Le.MEDIA_ERROR,details:Re.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:t.len})}}_trySkipBufferHole(t){const{config:e,hls:i,media:r}=this;if(null===r)return 0;const n=r.currentTime,s=ts.bufferInfo(r,n,0),a=n<s.start?s.start:s.nextStart;if(a){const o=s.len<=e.maxBufferHole,l=s.len>0&&s.len<1&&r.readyState<3,c=a-n;if(c>0&&(o||l)){if(c>e.maxBufferHole){const{fragmentTracker:e}=this;let i=!1;if(0===n){const t=e.getAppendedFrag(0,Pr);t&&a<t.end&&(i=!0)}if(!i){const i=t||e.getAppendedFrag(n,Pr);if(i){let t=!1,r=i.end;for(;r<a;){const i=e.getPartialFragment(r);if(!i){t=!0;break}r+=i.duration}if(t)return 0}}}const s=Math.max(a+.05,n+.1);if(Pe.warn(`skipping hole, adjusting currentTime from ${n} to ${s}`),this.moved=!0,this.stalled=null,r.currentTime=s,t&&!t.gap){const e=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${s}`);i.trigger(_e.ERROR,{type:Le.MEDIA_ERROR,details:Re.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:e,reason:e.message,frag:t})}return s}}return 0}_tryNudgeBuffer(){const{config:t,hls:e,media:i,nudgeRetry:r}=this;if(null===i)return;const n=i.currentTime;if(this.nudgeRetry++,r<t.nudgeMaxRetry){const s=n+(r+1)*t.nudgeOffset,a=new Error(`Nudging 'currentTime' from ${n} to ${s}`);Pe.warn(a.message),i.currentTime=s,e.trigger(_e.ERROR,{type:Le.MEDIA_ERROR,details:Re.BUFFER_NUDGE_ON_STALL,error:a,fatal:!1})}else{const i=new Error(`Playhead still not moving while enough data buffered @${n} after ${t.nudgeMaxRetry} nudges`);Pe.error(i.message),e.trigger(_e.ERROR,{type:Le.MEDIA_ERROR,details:Re.BUFFER_STALLED_ERROR,error:i,fatal:!0})}}}class Nl extends Ds{constructor(t,e,i){super(t,e,i,"[stream-controller]",Pr),this.audioCodecSwap=!1,this.gapController=null,this.level=-1,this._forceStartLoad=!1,this.altAudio=!1,this.audioOnly=!1,this.fragPlaying=null,this.onvplaying=null,this.onvseeked=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(_e.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(_e.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(_e.MANIFEST_LOADING,this.onManifestLoading,this),t.on(_e.MANIFEST_PARSED,this.onManifestParsed,this),t.on(_e.LEVEL_LOADING,this.onLevelLoading,this),t.on(_e.LEVEL_LOADED,this.onLevelLoaded,this),t.on(_e.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(_e.ERROR,this.onError,this),t.on(_e.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(_e.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(_e.BUFFER_CREATED,this.onBufferCreated,this),t.on(_e.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(_e.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(_e.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(_e.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(_e.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(_e.MANIFEST_LOADING,this.onManifestLoading,this),t.off(_e.MANIFEST_PARSED,this.onManifestParsed,this),t.off(_e.LEVEL_LOADED,this.onLevelLoaded,this),t.off(_e.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(_e.ERROR,this.onError,this),t.off(_e.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(_e.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(_e.BUFFER_CREATED,this.onBufferCreated,this),t.off(_e.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(_e.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(_e.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying()}startLoad(t){if(this.levels){const{lastCurrentTime:e,hls:i}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let t=i.startLevel;-1===t&&(i.config.testBandwidth&&this.levels.length>1?(t=0,this.bitrateTest=!0):t=i.firstAutoLevel),i.nextLoadLevel=t,this.level=i.loadLevel,this.loadedmetadata=!1}e>0&&-1===t&&(this.log(`Override startPosition with lastCurrentTime @${e.toFixed(3)}`),t=e),this.state=vs,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}else this._forceStartLoad=!0,this.state=ys}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Cs:{const{levels:t,level:e}=this,i=null==t?void 0:t[e],r=null==i?void 0:i.details;if(r&&(!r.live||this.levelLastLoaded===i)){if(this.waitForCdnTuneIn(r))break;this.state=vs;break}if(this.hls.nextLoadLevel!==this.level){this.state=vs;break}break}case Ts:{var t;const e=self.performance.now(),i=this.retryDate;if(!i||e>=i||null!=(t=this.media)&&t.seeking){const{levels:t,level:e}=this,i=null==t?void 0:t[e];this.resetStartWhenNotLoaded(i||null),this.state=vs}}}this.state===vs&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:i,media:r}=this;if(null===e||!r&&(this.startFragRequested||!t.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const n=t.nextLoadLevel;if(null==i||!i[n])return;const s=i[n],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const t={};return this.altAudio&&(t.type="video"),this.hls.trigger(_e.BUFFER_EOS,t),void(this.state=_s)}t.loadLevel!==n&&-1===t.manualLevel&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=t.nextLoadLevel=n;const l=s.details;if(!l||this.state===Cs||l.live&&this.levelLastLoaded!==s)return this.level=n,void(this.state=Cs);const c=a.len,h=this.getMaxBufferLength(s.maxBitrate);if(c>=h)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const u=this.backtrackFragment?this.backtrackFragment.start:a.end;let d=this.getNextFragment(u,l);if(this.couldBacktrack&&!this.fragPrevious&&d&&"initSegment"!==d.sn&&this.fragmentTracker.getState(d)!==qn){var f;const t=(null!=(f=this.backtrackFragment)?f:d).sn-l.startSN,e=l.fragments[t-1];e&&d.cc===e.cc&&(d=e,this.fragmentTracker.removeFragment(e))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(d&&this.isLoopLoading(d,u)){if(!d.gap){const t=this.audioOnly&&!this.altAudio?Be:$e,e=(t===$e?this.videoBuffer:this.mediaBuffer)||this.media;e&&this.afterBufferFlushed(e,t,Pr)}d=this.getNextFragmentLoopLoading(d,l,a,Pr,h)}d&&(!d.initSegment||d.initSegment.data||this.bitrateTest||(d=d.initSegment),this.loadFragment(d,s,u))}loadFragment(t,e,i){const r=this.fragmentTracker.getState(t);this.fragCurrent=t,r===jn||r===zn?"initSegment"===t.sn?this._loadInitSegment(t,e):this.bitrateTest?(this.log(`Fragment ${t.sn} of level ${t.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(t,e)):(this.startFragRequested=!0,super.loadFragment(t,e,i)):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,Pr)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:t,media:e}=this;if(null!=e&&e.readyState){let i;const r=this.getAppendedFrag(e.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);const n=this.getLevelDetails();if(null!=n&&n.live){const t=this.getMainFwdBufferInfo();if(!t||t.len<2*n.targetduration)return}if(!e.paused&&t){const e=t[this.hls.nextLoadLevel],r=this.fragLastKbps;i=r&&this.fragCurrent?this.fragCurrent.duration*e.maxBitrate/(1e3*r)+1:0}else i=0;const s=this.getBufferedFrag(e.currentTime+i);if(s){const t=this.followingBufferedFrag(s);if(t){this.abortCurrentFrag();const e=t.maxStartPTS?t.maxStartPTS:t.start,i=t.duration,r=Math.max(s.end,e+Math.min(Math.max(i-this.config.maxFragLookUpTolerance,i*(this.couldBacktrack?.5:.125)),i*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(r,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const t=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.state){case As:case Es:case Ts:case bs:case ks:this.state=vs}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,this.altAudio?"video":null)}onMediaAttached(t,e){super.onMediaAttached(t,e);const i=e.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new Fl(this.config,i,this.fragmentTracker,this.hls)}onMediaDetaching(){const{media:t}=this;t&&this.onvplaying&&this.onvseeked&&(t.removeEventListener("playing",this.onvplaying),t.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){const t=this.media,e=t?t.currentTime:null;Se(e)&&this.log(`Media seeked to ${e.toFixed(3)}`);const i=this.getMainFwdBufferInfo();null!==i&&0!==i.len?this.tick():this.warn(`Main forward buffer length on "seeked" event ${i?i.len:"empty"})`)}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(_e.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=this.fragLastKbps=0,this.levels=this.fragPlaying=this.backtrackFragment=this.levelLastLoaded=null,this.altAudio=this.audioOnly=this.startFragRequested=!1}onManifestParsed(t,e){let i=!1,r=!1;e.levels.forEach((t=>{const e=t.audioCodec;e&&(i=i||-1!==e.indexOf("mp4a.40.2"),r=r||-1!==e.indexOf("mp4a.40.5"))})),this.audioCodecSwitch=i&&r&&!function(){var t;const e=xl();return"function"==typeof(null==e||null==(t=e.prototype)?void 0:t.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1}onLevelLoading(t,e){const{levels:i}=this;if(!i||this.state!==vs)return;const r=i[e.level];(!r.details||r.details.live&&this.levelLastLoaded!==r||this.waitForCdnTuneIn(r.details))&&(this.state=Cs)}onLevelLoaded(t,e){var i;const{levels:r}=this,n=e.level,s=e.details,a=s.totalduration;if(!r)return void this.warn(`Levels were reset while loading level ${n}`);this.log(`Level ${n} loaded [${s.startSN},${s.endSN}]${s.lastPartSn?`[part-${s.lastPartSn}-${s.lastPartIndex}]`:""}, cc [${s.startCC}, ${s.endCC}] duration:${a}`);const o=r[n],l=this.fragCurrent;!l||this.state!==Es&&this.state!==Ts||l.level!==e.level&&l.loader&&this.abortCurrentFrag();let c=0;if(s.live||null!=(i=o.details)&&i.live){var h;if(this.checkLiveUpdate(s),s.deltaUpdateFailed)return;c=this.alignPlaylists(s,o.details,null==(h=this.levelLastLoaded)?void 0:h.details)}if(o.details=s,this.levelLastLoaded=o,this.hls.trigger(_e.LEVEL_UPDATED,{details:s,level:n}),this.state===Cs){if(this.waitForCdnTuneIn(s))return;this.state=vs}this.startFragRequested?s.live&&this.synchronizeToLiveEdge(s):this.setStartPosition(s,c),this.tick()}_handleFragmentLoadProgress(t){var e;const{frag:i,part:r,payload:n}=t,{levels:s}=this;if(!s)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);const a=s[i.level],o=a.details;if(!o)return this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),void this.fragmentTracker.removeFragment(i);const l=a.videoCodec,c=o.PTSKnown||!o.live,h=null==(e=i.initSegment)?void 0:e.data,u=this._getAudioCodec(a),d=this.transmuxer=this.transmuxer||new Fa(this.hls,Pr,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=r?r.index:-1,g=-1!==f,p=new es(i.level,i.sn,i.stats.chunkCount,n.byteLength,f,g),m=this.initPTS[i.cc];d.push(n,h,u,l,i,r,o.totalduration,c,p,m)}onAudioTrackSwitching(t,e){const i=this.altAudio;if(!!!e.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const t=this.fragCurrent;t&&(this.log("Switching to main audio track, cancel main fragment load"),t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const t=this.hls;i&&(t.trigger(_e.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),t.trigger(_e.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const i=e.id,r=!!this.hls.audioTracks[i].url;if(r){const t=this.videoBuffer;t&&this.mediaBuffer!==t&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=t)}this.altAudio=r,this.tick()}onBufferCreated(t,e){const i=e.tracks;let r,n,s=!1;for(const t in i){const e=i[t];if("main"===e.id){if(n=t,r=e,"video"===t){const e=i[t];e&&(this.videoBuffer=e.buffer)}}else s=!0}s&&r?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:i,part:r}=e;if(i&&i.type!==Pr)return;if(this.fragContextChanged(i))return this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===ks&&(this.state=vs));const n=r?r.stats:i.stats;this.fragLastKbps=Math.round(8*n.total/(n.buffering.end-n.loading.first)),"initSegment"!==i.sn&&(this.fragPrevious=i),this.fragBufferedComplete(i,r)}onError(t,e){var i;if(e.fatal)this.state=Ls;else switch(e.details){case Re.FRAG_GAP:case Re.FRAG_PARSING_ERROR:case Re.FRAG_DECRYPT_ERROR:case Re.FRAG_LOAD_ERROR:case Re.FRAG_LOAD_TIMEOUT:case Re.KEY_LOAD_ERROR:case Re.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Pr,e);break;case Re.LEVEL_LOAD_ERROR:case Re.LEVEL_LOAD_TIMEOUT:case Re.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==Cs||(null==(i=e.context)?void 0:i.type)!==Dr||(this.state=vs);break;case Re.BUFFER_APPEND_ERROR:case Re.BUFFER_FULL_ERROR:if(!e.parent||"main"!==e.parent)return;if(e.details===Re.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(e)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case Re.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}checkBuffer(){const{media:t,gapController:e}=this;if(t&&e&&t.readyState){if(this.loadedmetadata||!ts.getBuffered(t).length){const t=this.state!==vs?this.fragCurrent:null;e.poll(this.lastCurrentTime,t)}this.lastCurrentTime=t.currentTime}}onFragLoadEmergencyAborted(){this.state=vs,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==Be||this.audioOnly&&!this.altAudio){const t=(e===$e?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(t,e,Pr),this.tick()}}onLevelsUpdated(t,e){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=e.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:t}=this;if(!t)return;const e=t.currentTime;let i=this.startPosition;if(i>=0&&e<i){if(t.seeking)return void this.log(`could not seek to ${i}, already seeking at ${e}`);const r=ts.getBuffered(t),n=(r.length?r.start(0):0)-i;n>0&&(n<this.config.maxBufferHole||n<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${n} to match buffer start`),i+=n,this.startPosition=i),this.log(`seek to target start position ${i} from current time ${e}`),t.currentTime=i}}_getAudioCodec(t){let e=this.config.defaultAudioCodec||t.audioCodec;return this.audioCodecSwap&&e&&(this.log("Swapping audio codec"),e=-1!==e.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),e}_loadBitrateTestFrag(t,e){t.bitrateTest=!0,this._doFragLoad(t,e).then((i=>{const{hls:r}=this;if(!i||this.fragContextChanged(t))return;e.fragmentError=0,this.state=vs,this.startFragRequested=!1,this.bitrateTest=!1;const n=t.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),r.trigger(_e.FRAG_LOADED,i),t.bitrateTest=!1}))}_handleTransmuxComplete(t){var e;const i="main",{hls:r}=this,{remuxResult:n,chunkMeta:s}=t,a=this.getCurrentContext(s);if(!a)return void this.resetWhenMissingContext(s);const{frag:o,part:l,level:c}=a,{video:h,text:u,id3:d,initSegment:f}=n,{details:g}=c,p=this.altAudio?void 0:n.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=bs,f){if(null!=f&&f.tracks){const t=o.initSegment||o;this._bufferInitSegment(c,f.tracks,t,s),r.trigger(_e.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:i,tracks:f.tracks})}const t=f.initPTS,e=f.timescale;Se(t)&&(this.initPTS[o.cc]={baseTime:t,timescale:e},r.trigger(_e.INIT_PTS_FOUND,{frag:o,id:i,initPTS:t,timescale:e}))}if(h&&g&&"initSegment"!==o.sn){const t=g.fragments[o.sn-1-g.startSN],e=o.sn===g.startSN,i=!t||o.cc>t.cc;if(!1!==n.independent){const{startPTS:t,endPTS:r,startDTS:n,endDTS:a}=h;if(l)l.elementaryStreams[h.type]={startPTS:t,endPTS:r,startDTS:n,endDTS:a};else if(h.firstKeyFrame&&h.independent&&1===s.id&&!i&&(this.couldBacktrack=!0),h.dropped&&h.independent){const n=this.getMainFwdBufferInfo(),s=(n?n.end:this.getLoadPosition())+this.config.maxBufferHole,l=h.firstKeyFramePTS?h.firstKeyFramePTS:t;if(!e&&s<l-this.config.maxBufferHole&&!i)return void this.backtrack(o);i&&(o.gap=!0),o.setElementaryStreamInfo(h.type,o.start,r,o.start,a,!0)}else e&&t>2&&(o.gap=!0);o.setElementaryStreamInfo(h.type,t,r,n,a),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(h,o,l,s,e||i)}else{if(!e&&!i)return void this.backtrack(o);o.gap=!0}}if(p){const{startPTS:t,endPTS:e,startDTS:i,endDTS:r}=p;l&&(l.elementaryStreams[Be]={startPTS:t,endPTS:e,startDTS:i,endDTS:r}),o.setElementaryStreamInfo(Be,t,e,i,r),this.bufferFragmentData(p,o,l,s)}if(g&&null!=d&&null!=(e=d.samples)&&e.length){const t={id:i,frag:o,details:g,samples:d.samples};r.trigger(_e.FRAG_PARSING_METADATA,t)}if(g&&u){const t={id:i,frag:o,details:g,samples:u.samples};r.trigger(_e.FRAG_PARSING_USERDATA,t)}}}_bufferInitSegment(t,e,i,r){if(this.state!==bs)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&delete e.audio;const{audio:n,video:s,audiovideo:a}=e;if(n){let e=t.audioCodec;const i=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){e&&(e=-1!==e.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const t=n.metadata;t&&"channelCount"in t&&1!==(t.channelCount||1)&&-1===i.indexOf("firefox")&&(e="mp4a.40.5")}e&&-1!==e.indexOf("mp4a.40.5")&&-1!==i.indexOf("android")&&"audio/mpeg"!==n.container&&(e="mp4a.40.2",this.log(`Android: force audio codec to ${e}`)),t.audioCodec&&t.audioCodec!==e&&this.log(`Swapping manifest audio codec "${t.audioCodec}" for "${e}"`),n.levelCodec=e,n.id="main",this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${e||""}/${t.audioCodec||""}/${n.codec}]`)}s&&(s.levelCodec=t.videoCodec,s.id="main",this.log(`Init video buffer, container:${s.container}, codecs[level/parsed]=[${t.videoCodec||""}/${s.codec}]`)),a&&this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${t.codecs}/${a.codec}]`),this.hls.trigger(_e.BUFFER_CODECS,e),Object.keys(e).forEach((t=>{const n=e[t].initSegment;null!=n&&n.byteLength&&this.hls.trigger(_e.BUFFER_APPENDING,{type:t,data:n,frag:i,part:null,chunkMeta:r,parent:i.type})})),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,Pr)}backtrack(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=vs}checkFragmentChanged(){const t=this.media;let e=null;if(t&&t.readyState>1&&!1===t.seeking){const i=t.currentTime;if(ts.isBuffered(t,i)?e=this.getAppendedFrag(i):ts.isBuffered(t,i+.1)&&(e=this.getAppendedFrag(i+.1)),e){this.backtrackFragment=null;const t=this.fragPlaying,i=e.level;t&&e.sn===t.sn&&t.level===i||(this.fragPlaying=e,this.hls.trigger(_e.FRAG_CHANGED,{frag:e}),t&&t.level===i||this.hls.trigger(_e.LEVEL_SWITCHED,{level:i}))}}}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){const t=this.media;return t?this.fragPlaying||this.getAppendedFrag(t.currentTime):null}get currentProgramDateTime(){const t=this.media;if(t){const e=t.currentTime,i=this.currentFrag;if(i&&Se(e)&&Se(i.programDateTime)){const t=i.programDateTime+1e3*(e-i.start);return new Date(t)}}return null}get currentLevel(){const t=this.currentFrag;return t?t.level:-1}get nextBufferedFrag(){const t=this.currentFrag;return t?this.followingBufferedFrag(t):null}get forceStartLoad(){return this._forceStartLoad}}class Ul{static get version(){return"1.5.14"}static isMSESupported(){return Ml()}static isSupported(){return function(){if(!Ml())return!1;const t=nr();return"function"==typeof(null==t?void 0:t.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((e=>t.isTypeSupported(lr(e,"video"))))||["mp4a.40.2","fLaC"].some((e=>t.isTypeSupported(lr(e,"audio")))))}()}static getMediaSource(){return nr()}static get Events(){return _e}static get ErrorTypes(){return Le}static get ErrorDetails(){return Re}static get DefaultConfig(){return Ul.defaultConfig?Ul.defaultConfig:Rl}static set DefaultConfig(t){Ul.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new Ma,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,this.triggeringException=void 0,function(t,e){if("object"==typeof console&&!0===t||"object"==typeof t){Ie(t,"debug","log","info","warn","error");try{we.log(`Debug logs enabled for "${e}" in hls.js version 1.5.14`)}catch(t){we=De}}else we=De}(t.debug||!1,"Hls instance");const e=this.config=function(t,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==e.liveMaxLatencyDurationCount&&(void 0===e.liveSyncDurationCount||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==e.liveMaxLatencyDuration&&(void 0===e.liveSyncDuration||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const i=Cl(t),r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((t=>{const n=`${"level"===t?"playlist":t}LoadPolicy`,s=void 0===e[n],a=[];r.forEach((r=>{const o=`${t}Loading${r}`,l=e[o];if(void 0!==l&&s){a.push(o);const t=i[n].default;switch(e[n]={default:t},r){case"TimeOut":t.maxLoadTimeMs=l,t.maxTimeToFirstByteMs=l;break;case"MaxRetry":t.errorRetry.maxNumRetry=l,t.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":t.errorRetry.retryDelayMs=l,t.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":t.errorRetry.maxRetryDelayMs=l,t.timeoutRetry.maxRetryDelayMs=l}}})),a.length&&Pe.warn(`hls.js config: "${a.join('", "')}" setting(s) are deprecated, use "${n}": ${JSON.stringify(e[n])}`)})),ve(ve({},i),e)}(Ul.DefaultConfig,t);this.userConfig=t,e.progressive&&Dl(e);const{abrController:i,bufferController:r,capLevelController:n,errorController:s,fpsController:a}=e,o=new s(this),l=this.abrController=new i(this),c=this.bufferController=new r(this),h=this.capLevelController=new n(this),u=new a(this),d=new Nr(this),f=new Xr(this),g=e.contentSteeringController,p=g?new g(this):null,m=this.levelController=new Il(this,p),y=new Xn(this),v=new Ol(this.config),A=this.streamController=new Nl(this,y,v);h.setStreamController(A),u.setStreamController(A);const E=[d,m,A];p&&E.splice(1,0,p),this.networkControllers=E;const T=[l,c,h,u,f,y];this.audioTrackController=this.createController(e.audioTrackController,E);const S=e.audioStreamController;S&&E.push(new S(this,y,v)),this.subtitleTrackController=this.createController(e.subtitleTrackController,E);const b=e.subtitleStreamController;b&&E.push(new b(this,y,v)),this.createController(e.timelineController,T),v.emeController=this.emeController=this.createController(e.emeController,T),this.cmcdController=this.createController(e.cmcdController,T),this.latencyController=this.createController(Qr,T),this.coreComponents=T,E.push(o);const k=o.onErrorOut;"function"==typeof k&&this.on(_e.ERROR,k,o)}createController(t,e){if(t){const i=new t(this);return e&&e.push(i),i}return null}on(t,e,i=this){this._emitter.on(t,e,i)}once(t,e,i=this){this._emitter.once(t,e,i)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,e,i=this,r){this._emitter.off(t,e,i,r)}listeners(t){return this._emitter.listeners(t)}emit(t,e,i){return this._emitter.emit(t,e,i)}trigger(t,e){if(this.config.debug)return this.emit(t,t,e);try{return this.emit(t,t,e)}catch(e){if(Pe.error("An internal error happened while handling event "+t+'. Error message: "'+e.message+'". Here is a stacktrace:',e),!this.triggeringException){this.triggeringException=!0;const i=t===_e.ERROR;this.trigger(_e.ERROR,{type:Le.OTHER_ERROR,details:Re.INTERNAL_EXCEPTION,fatal:i,event:t,error:e}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){Pe.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;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){Pe.log("attachMedia"),this._media=t,this.trigger(_e.MEDIA_ATTACHING,{media:t})}detachMedia(){Pe.log("detachMedia"),this.trigger(_e.MEDIA_DETACHING,void 0),this._media=null}loadSource(t){this.stopLoad();const e=this.media,i=this.url,r=this.url=me.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,Pe.log(`loadSource:${r}`),e&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(e)),this.trigger(_e.MANIFEST_LOADING,{url:t})}startLoad(t=-1){Pe.log(`startLoad(${t})`),this.started=!0,this.networkControllers.forEach((e=>{e.startLoad(t)}))}stopLoad(){Pe.log("stopLoad"),this.started=!1,this.networkControllers.forEach((t=>{t.stopLoad()}))}resumeBuffering(){this.started&&this.networkControllers.forEach((t=>{"fragmentLoader"in t&&t.startLoad(-1)}))}pauseBuffering(){this.networkControllers.forEach((t=>{"fragmentLoader"in t&&t.stopLoad()}))}swapAudioCodec(){Pe.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){Pe.log("recoverMediaError");const t=this._media;this.detachMedia(),t&&this.attachMedia(t)}removeLevel(t){this.levelController.removeLevel(t)}get levels(){const t=this.levelController.levels;return t||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){Pe.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){Pe.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){Pe.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){Pe.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return-1===t&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){Pe.log(`set startLevel:${t}`),-1!==t&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const e=!!t;e!==this.config.capLevelToPlayerSize&&(e?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=e)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(Pe.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){(function(t){return Zr.indexOf(t)>-1})(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:e}}=this;if(!t)return 0;const i=t.length;for(let r=0;r<i;r++)if(t[r].maxBitrate>=e)return r;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:i}=this;let r;if(r=-1===e&&null!=t&&t.length?t.length-1:e,i)for(let e=r;e--;){const r=t[e].attrs["HDCP-LEVEL"];if(r&&r<=i)return e}return r}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}setAudioOption(t){var e;return null==(e=this.audioTrackController)?void 0:e.setAudioOption(t)}setSubtitleOption(t){var e;return null==(e=this.subtitleTrackController)||e.setSubtitleOption(t),null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const e=this.audioTrackController;e&&(e.audioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return!!t&&t.subtitleDisplay}set subtitleDisplay(t){const e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}Ul.defaultConfig=void 0;var Bl=lt,$l=ct;Et.register("PLAYBACK_FRAGMENT_CHANGED"),Et.register("PLAYBACK_FRAGMENT_PARSING_METADATA");var Gl=function(t){function r(){var t;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,r);for(var i=arguments.length,n=new Array(i),s=0;s<i;s++)n[s]=arguments[s];return(t=e(this,r,[].concat(n))).options.hlsPlayback=l(l({},t.defaultOptions),t.options.hlsPlayback),t._timeUpdateThrottleDelay=200,t._timeUpdateFiringRate=.2,t._durationChangeMinOffset=.5,t._setInitialState(),t}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&c(t,e)}(r,t),n=r,a=[{key:"HLSJS",get:function(){return Ul}}],(s=[{key:"name",get:function(){return"hls"}},{key:"supportedVersion",get:function(){return{min:"0.11.4"}}},{key:"levels",get:function(){return this._levels||[]}},{key:"currentLevel",get:function(){return null===this._currentLevel||void 0===this._currentLevel?-1:this._currentLevel},set:function(t){this._currentLevel=t,this.trigger(Et.PLAYBACK_LEVEL_SWITCH_START),this.options.playback.hlsUseNextLevel?this._hls.nextLevel=this._currentLevel:this._hls.currentLevel=this._currentLevel}},{key:"isReady",get:function(){return this._isReadyState}},{key:"latency",get:function(){return this._hls.latency}},{key:"currentProgramDateTime",get:function(){return this._hls.playingDate}},{key:"_startTime",get:function(){return this._playbackType===Ut.LIVE&&"EVENT"!==this._playlistType?this._extrapolatedStartTime:this._playableRegionStartTime}},{key:"_now",get:function(){return Bl()}},{key:"_extrapolatedStartTime",get:function(){if(!this._localStartTimeCorrelation)return this._playableRegionStartTime;var t=this._localStartTimeCorrelation,e=this._now-t.local,i=(t.remote+e)/1e3;return Math.min(i,this._playableRegionStartTime+this._extrapolatedWindowDuration)}},{key:"_extrapolatedEndTime",get:function(){var t=this._playableRegionStartTime+this._playableRegionDuration;if(!this._localEndTimeCorrelation)return t;var e=this._localEndTimeCorrelation,i=this._now-e.local,r=(e.remote+i)/1e3;return Math.max(t-this._extrapolatedWindowDuration,Math.min(r,t))}},{key:"_duration",get:function(){return this._extrapolatedEndTime-this._startTime}},{key:"_extrapolatedWindowDuration",get:function(){return null===this._segmentTargetDuration?0:this._extrapolatedWindowNumSegments*this._segmentTargetDuration}},{key:"bandwidthEstimate",get:function(){return this._hls&&this._hls.bandwidthEstimate}},{key:"defaultOptions",get:function(){return{preload:!0}}},{key:"customListeners",get:function(){return this.options.hlsPlayback&&this.options.hlsPlayback.customListeners||[]}},{key:"sourceMedia",get:function(){return this.options.src}},{key:"currentTimestamp",get:function(){return this._currentFragment?(this._currentFragment.programDateTime+1e3*(this.el.currentTime-this._currentFragment.start))/1e3:null}},{key:"_setInitialState",value:function(){this._minDvrSize=void 0===this.options.hlsMinimumDvrSize?60:this.options.hlsMinimumDvrSize,this._extrapolatedWindowNumSegments=this.options.playback&&void 0!==this.options.playback.extrapolatedWindowNumSegments?this.options.playback.extrapolatedWindowNumSegments:2,this._playbackType=Ut.VOD,this._lastTimeUpdate={current:0,total:0,firstFragDateTime:0},this._lastTimeUpdateFiredTime=0,this._lastDuration=null,this._playableRegionStartTime=0,this._localStartTimeCorrelation=null,this._localEndTimeCorrelation=null,this._playableRegionDuration=0,this._programDateTime=0,this._durationExcludesAfterLiveSyncPoint=!1,this._segmentTargetDuration=null,this._playlistType=null,this._recoverAttemptsRemaining=this.options.hlsRecoverAttempts||16}},{key:"_setup",value:function(){this._destroyHLSInstance(),this._createHLSInstance(),this._listenHLSEvents(),this._attachHLSMedia()}},{key:"_destroyHLSInstance",value:function(){this._hls&&(this._manifestLoading=!1,this._ccIsSetup=!1,this._ccTracksUpdated=!1,this._setInitialState(),this._hls.destroy(),this._hls=null)}},{key:"_createHLSInstance",value:function(){var t=l({},this.options.playback.hlsjsConfig);this._hls=new Ul(t)}},{key:"_attachHLSMedia",value:function(){this._hls&&this._hls.attachMedia(this.el)}},{key:"_listenHLSEvents",value:function(){var t=this;this._hls&&(this._hls.once(Ul.Events.MEDIA_ATTACHED,(function(){t.options.hlsPlayback.preload&&t._hls.loadSource(t.options.src)})),this._hls.on(Ul.Events.MANIFEST_LOADING,(function(){return t._manifestLoading=!0})),this._hls.on(Ul.Events.LEVEL_LOADED,(function(e,i){return t._updatePlaybackType(e,i)})),this._hls.on(Ul.Events.LEVEL_UPDATED,(function(e,i){return t._onLevelUpdated(e,i)})),this._hls.on(Ul.Events.LEVEL_SWITCHED,(function(e,i){return t._onLevelSwitch(e,i)})),this._hls.on(Ul.Events.FRAG_CHANGED,(function(e,i){return t._onFragmentChanged(e,i)})),this._hls.on(Ul.Events.FRAG_LOADED,(function(e,i){return t._onFragmentLoaded(e,i)})),this._hls.on(Ul.Events.FRAG_BUFFERED,(function(e,i){return t._onFragmentBuffered(e,i)})),this._hls.on(Ul.Events.FRAG_PARSING_METADATA,(function(e,i){return t._onFragmentParsingMetadata(e,i)})),this._hls.on(Ul.Events.ERROR,(function(e,i){return t._onHLSJSError(e,i)})),this._hls.on(Ul.Events.SUBTITLE_TRACK_LOADED,(function(e,i){return t._onSubtitleLoaded(e,i)})),this._hls.on(Ul.Events.SUBTITLE_TRACKS_UPDATED,(function(){return t._ccTracksUpdated=!0})),this.bindCustomListeners())}},{key:"bindCustomListeners",value:function(){var t=this;this.customListeners.forEach((function(e){var i=e.eventName,r=e.once?"once":"on";i&&t._hls["".concat(r)](i,e.callback)}))}},{key:"unbindCustomListeners",value:function(){var t=this;this.customListeners.forEach((function(e){var i=e.eventName;i&&t._hls.off(i,e.callback)}))}},{key:"_onFragmentParsingMetadata",value:function(t,e){this.trigger(Et.Custom.PLAYBACK_FRAGMENT_PARSING_METADATA,{evt:t,data:e})}},{key:"render",value:function(){return this._ready(),h(r,"render",this,3)([])}},{key:"_ready",value:function(){this._isReadyState||(!this._hls&&this._setup(),this._isReadyState=!0,this.trigger(Et.PLAYBACK_READY,this.name))}},{key:"_recover",value:function(t,e,i){if(this._recoveredDecodingError)if(this._recoveredAudioCodecError){pt.error("hlsjs: failed to recover",{evt:t,data:e}),i.level=xt.Levels.FATAL;var r=this.createError(i);this.trigger(Et.PLAYBACK_ERROR,r),this.stop()}else this._recoveredAudioCodecError=!0,this._hls.swapAudioCodec(),this._hls.recoverMediaError(),this.play();else this._recoveredDecodingError=!0,this._hls.recoverMediaError(),this.play()}},{key:"_setupSrc",value:function(t){}},{key:"_startTimeUpdateTimer",value:function(){var t=this;this._timeUpdateTimer||(this._timeUpdateTimer=setInterval((function(){t._onDurationChange(),t._onTimeUpdate()}),100))}},{key:"_stopTimeUpdateTimer",value:function(){this._timeUpdateTimer&&(clearInterval(this._timeUpdateTimer),this._timeUpdateTimer=null)}},{key:"getProgramDateTime",value:function(){return this._programDateTime}},{key:"getDuration",value:function(){return this._duration}},{key:"getCurrentTime",value:function(){return Math.max(0,this.el.currentTime-this._startTime)}},{key:"getStartTimeOffset",value:function(){return this._startTime}},{key:"seekPercentage",value:function(t){var e=t>0?this._duration*(t/100):this._duration;this.seek(e)}},{key:"seek",value:function(t){t<0&&(pt.warn("Attempt to seek to a negative time. Resetting to live point. Use seekToLivePoint() to seek to the live point."),t=this.getDuration()),t+=this._startTime,this.el.currentTime=t}},{key:"seekToLivePoint",value:function(){this.seek(this.getDuration())}},{key:"_updateSettings",value:function(){this._playbackType===Ut.VOD?this.settings.left=["playpause","position","duration"]:this.dvrEnabled?this.settings.left=["playpause"]:this.settings.left=["playstop"],this.settings.seekEnabled=this.isSeekEnabled(),this.trigger(Et.PLAYBACK_SETTINGSUPDATE)}},{key:"_onHLSJSError",value:function(t,e){var i,r={code:"".concat(e.type,"_").concat(e.details),description:"".concat(this.name," error: type: ").concat(e.type,", details: ").concat(e.details),raw:e};if(e.response&&(r.description+=", response: ".concat(JSON.stringify(e.response))),e.fatal)if(this._recoverAttemptsRemaining>0)switch(this._recoverAttemptsRemaining-=1,e.type){case Ul.ErrorTypes.NETWORK_ERROR:switch(e.details){case Ul.ErrorDetails.MANIFEST_LOAD_ERROR:case Ul.ErrorDetails.MANIFEST_LOAD_TIMEOUT:case Ul.ErrorDetails.MANIFEST_PARSING_ERROR:case Ul.ErrorDetails.LEVEL_LOAD_ERROR:case Ul.ErrorDetails.LEVEL_LOAD_TIMEOUT:pt.error("hlsjs: unrecoverable network fatal error.",{evt:t,data:e}),i=this.createError(r),this.trigger(Et.PLAYBACK_ERROR,i),this.stop();break;default:pt.warn("hlsjs: trying to recover from network error.",{evt:t,data:e}),r.level=xt.Levels.WARN,this._hls.startLoad()}break;case Ul.ErrorTypes.MEDIA_ERROR:pt.warn("hlsjs: trying to recover from media error.",{evt:t,data:e}),r.level=xt.Levels.WARN,this._recover(t,e,r);break;default:pt.error("hlsjs: could not recover from error.",{evt:t,data:e}),i=this.createError(r),this.trigger(Et.PLAYBACK_ERROR,i),this.stop()}else pt.error("hlsjs: could not recover from error after maximum number of attempts.",{evt:t,data:e}),i=this.createError(r),this.trigger(Et.PLAYBACK_ERROR,i),this.stop();else{if(this.options.playback.triggerFatalErrorOnResourceDenied&&this._keyIsDenied(e))return pt.error("hlsjs: could not load decrypt key.",{evt:t,data:e}),i=this.createError(r),this.trigger(Et.PLAYBACK_ERROR,i),void this.stop();r.level=xt.Levels.WARN,pt.warn("hlsjs: non-fatal error occurred",{evt:t,data:e})}}},{key:"_keyIsDenied",value:function(t){return t.type===Ul.ErrorTypes.NETWORK_ERROR&&t.details===Ul.ErrorDetails.KEY_LOAD_ERROR&&t.response&&t.response.code>=400}},{key:"_onTimeUpdate",value:function(){var t={current:this.getCurrentTime(),total:this.getDuration(),firstFragDateTime:this.getProgramDateTime()};this._shouldThrottleTimeUpdate(t)||(this._lastTimeUpdate=t,this._lastTimeUpdateFiredTime=this._now,this.trigger(Et.PLAYBACK_TIMEUPDATE,t,this.name))}},{key:"_shouldThrottleTimeUpdate",value:function(t){var e=Math.abs(t.current-this._lastTimeUpdate.current)<this._timeUpdateFiringRate,i=Math.abs(t.total-this._lastTimeUpdate.total)<this._durationChangeMinOffset,r=t.firstFragDateTime===this._lastTimeUpdate.firstFragDateTime,n=e&&i&&r,s=this._now-this._lastTimeUpdateFiredTime<this._timeUpdateThrottleDelay;return n&&s}},{key:"_onDurationChange",value:function(){var t=this.getDuration();Math.abs(this._lastDuration-t)<this._durationChangeMinOffset||(this._lastDuration=t,h(r,"_onDurationChange",this,3)([]))}},{key:"_onProgress",value:function(){if(this.el.buffered.length){for(var t=[],e=0,i=0;i<this.el.buffered.length;i++)t=[].concat(u(t),[{start:Math.max(0,this.el.buffered.start(i)-this._playableRegionStartTime),end:Math.max(0,this.el.buffered.end(i)-this._playableRegionStartTime)}]),this.el.currentTime>=t[i].start&&this.el.currentTime<=t[i].end&&(e=i);var r={start:t[e].start,current:t[e].end,total:this.getDuration()};this.trigger(Et.PLAYBACK_PROGRESS,r,t)}}},{key:"load",value:function(t){this._stopTimeUpdateTimer(),this.options.src=t,this._setup()}},{key:"play",value:function(){!this._hls&&this._setup(),!this._manifestLoading&&!this.options.hlsPlayback.preload&&this._hls.loadSource(this.options.src),h(r,"play",this,3)([]),this._startTimeUpdateTimer()}},{key:"pause",value:function(){this._hls&&this.el.pause()}},{key:"stop",value:function(){this._stopTimeUpdateTimer(),this._hls&&h(r,"stop",this,3)([]),this._destroyHLSInstance()}},{key:"destroy",value:function(){this._stopTimeUpdateTimer(),this._destroyHLSInstance(),h(r,"destroy",this,3)([])}},{key:"_updatePlaybackType",value:function(t,e){this._playbackType=e.details.live?Ut.LIVE:Ut.VOD,this._onLevelUpdated(t,e),this._ccTracksUpdated&&this._playbackType===Ut.LIVE&&this.hasClosedCaptionsTracks&&this._onSubtitleLoaded()}},{key:"_fillLevels",value:function(){this._levels=this._hls.levels.map((function(t,e){return{id:e,level:t,label:"".concat(t.bitrate/1e3,"Kbps")}})),this.trigger(Et.PLAYBACK_LEVELS_AVAILABLE,this._levels)}},{key:"_onLevelUpdated",value:function(t,e){this._segmentTargetDuration=e.details.targetduration,this._playlistType=e.details.type||null;var i=!1,r=!1,n=e.details.fragments,s=this._playableRegionStartTime,a=this._playableRegionDuration;if(0!==n.length){if(n[0].rawProgramDateTime&&(this._programDateTime=n[0].rawProgramDateTime),this._playableRegionStartTime!==n[0].start&&(i=!0,this._playableRegionStartTime=n[0].start),i)if(this._localStartTimeCorrelation){var o=this._localStartTimeCorrelation,l=this._now-o.local,c=(o.remote+l)/1e3;c<n[0].start?this._localStartTimeCorrelation={local:this._now,remote:1e3*n[0].start}:c>s+this._extrapolatedWindowDuration&&(this._localStartTimeCorrelation={local:this._now,remote:1e3*Math.max(n[0].start,s+this._extrapolatedWindowDuration)})}else this._localStartTimeCorrelation={local:this._now,remote:1e3*(n[0].start+this._extrapolatedWindowDuration/2)};var h=e.details.totalduration;if(this._playbackType===Ut.LIVE){var u=e.details.targetduration*((this.options.playback.hlsjsConfig||{}).liveSyncDurationCount||Ul.DefaultConfig.liveSyncDurationCount);u<=h?(h-=u,this._durationExcludesAfterLiveSyncPoint=!0):this._durationExcludesAfterLiveSyncPoint=!1}h!==this._playableRegionDuration&&(r=!0,this._playableRegionDuration=h);var d=n[0].start+h,f=s+a;if(d!==f)if(this._localEndTimeCorrelation){var g=this._localEndTimeCorrelation,p=this._now-g.local,m=(g.remote+p)/1e3;m>d?this._localEndTimeCorrelation={local:this._now,remote:1e3*d}:m<d-this._extrapolatedWindowDuration?this._localEndTimeCorrelation={local:this._now,remote:1e3*(d-this._extrapolatedWindowDuration)}:m>f&&(this._localEndTimeCorrelation={local:this._now,remote:1e3*f})}else this._localEndTimeCorrelation={local:this._now,remote:1e3*d};r&&this._onDurationChange(),i&&this._onProgress()}}},{key:"_onFragmentChanged",value:function(t,e){this._currentFragment=e.frag,this.trigger(Et.Custom.PLAYBACK_FRAGMENT_CHANGED,e)}},{key:"_onFragmentLoaded",value:function(t,e){this.trigger(Et.PLAYBACK_FRAGMENT_LOADED,e)}},{key:"_onFragmentBuffered",value:function(t,e){this.trigger(Et.PLAYBACK_FRAGMENT_BUFFERED,e)}},{key:"_onSubtitleLoaded",value:function(){if(!this._ccIsSetup){this.trigger(Et.PLAYBACK_SUBTITLE_AVAILABLE);var t=this._playbackType===Ut.LIVE?-1:this.closedCaptionsTrackId;this.closedCaptionsTrackId=t,this._ccIsSetup=!0}}},{key:"_onLevelSwitch",value:function(t,e){this.levels.length||this._fillLevels(),this.trigger(Et.PLAYBACK_LEVEL_SWITCH_END),this.trigger(Et.PLAYBACK_LEVEL_SWITCH,e);var i=this._hls.levels[e.level];i&&(this.highDefinition=i.height>=720||i.bitrate/1e3>=2e3,this.trigger(Et.PLAYBACK_HIGHDEFINITIONUPDATE,this.highDefinition),this.trigger(Et.PLAYBACK_BITRATE,{height:i.height,width:i.width,bandwidth:i.bitrate,bitrate:i.bitrate,level:e.level}))}},{key:"dvrEnabled",get:function(){return this._durationExcludesAfterLiveSyncPoint&&this._duration>=this._minDvrSize&&this.getPlaybackType()===Ut.LIVE}},{key:"getPlaybackType",value:function(){return this._playbackType}},{key:"isSeekEnabled",value:function(){return this._playbackType===Ut.VOD||this.dvrEnabled}}])&&i(n.prototype,s),a&&i(n,a),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,s,a}(re);return Gl.canPlay=function(t,e){var i=t.split("?")[0].match(/.*\.(.*)$/)||[],r=i.length>1&&"m3u8"===i[1].toLowerCase()||$l(e,["application/vnd.apple.mpegurl","application/x-mpegURL"]);return!(!Ul.isSupported()||!r)},Gl}();
|
|
1
|
+
var HlsjsPlayback=function(t){"use strict";function e(t,e){(null==e||e>t.length)&&(e=t.length);for(var s=0,i=Array(e);s<e;s++)i[s]=t[s];return i}function s(t,e,s){return e=a(e),function(t,e){if(e&&("object"==typeof e||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}(t,o()?Reflect.construct(e,s||[],a(t).constructor):e.apply(t,s))}function i(t,e){for(var s=0;s<e.length;s++){var i=e[s];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,f(i.key),i)}}function r(t,e,s){return(e=f(e))in t?Object.defineProperty(t,e,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[e]=s,t}function n(){return n="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(t,e,s){var i=function(t,e){for(;!{}.hasOwnProperty.call(t,e)&&null!==(t=a(t)););return t}(t,e);if(i){var r=Object.getOwnPropertyDescriptor(i,e);return r.get?r.get.call(arguments.length<3?t:s):r.value}},n.apply(null,arguments)}function a(t){return a=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},a(t)}function o(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(t){}return(o=function(){return!!t})()}function l(t,e){var s=Object.keys(t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);e&&(i=i.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),s.push.apply(s,i)}return s}function h(t){for(var e=1;e<arguments.length;e++){var s=null!=arguments[e]?arguments[e]:{};e%2?l(Object(s),!0).forEach((function(e){r(t,e,s[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(s)):l(Object(s)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(s,e))}))}return t}function d(t,e){return d=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},d(t,e)}function c(t,e,s,i){var r=n(a(1&i?t.prototype:t),e,s);return 2&i&&"function"==typeof r?function(t){return r.apply(s,t)}:r}function u(t){return function(t){if(Array.isArray(t))return e(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||function(t,s){if(t){if("string"==typeof t)return e(t,s);var i={}.toString.call(t).slice(8,-1);return"Object"===i&&t.constructor&&(i=t.constructor.name),"Map"===i||"Set"===i?Array.from(t):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?e(t,s):void 0}}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function f(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var s=t[Symbol.toPrimitive];if(void 0!==s){var i=s.call(t,e||"default");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}function g(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var m,p,y,v,T,E={exports:{}};m=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,p=/^(?=([^\/?#]*))\1([^]*)$/,y=/(?:\/|^)\.(?=\/)/g,v=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,E.exports=T={buildAbsoluteURL:function(t,e,s){if(s=s||{},t=t.trim(),!(e=e.trim())){if(!s.alwaysNormalize)return t;var i=T.parseURL(t);if(!i)throw new Error("Error trying to parse base URL.");return i.path=T.normalizePath(i.path),T.buildURLFromParts(i)}var r=T.parseURL(e);if(!r)throw new Error("Error trying to parse relative URL.");if(r.scheme)return s.alwaysNormalize?(r.path=T.normalizePath(r.path),T.buildURLFromParts(r)):e;var n=T.parseURL(t);if(!n)throw new Error("Error trying to parse base URL.");if(!n.netLoc&&n.path&&"/"!==n.path[0]){var a=p.exec(n.path);n.netLoc=a[1],n.path=a[2]}n.netLoc&&!n.path&&(n.path="/");var o={scheme:n.scheme,netLoc:r.netLoc,path:null,params:r.params,query:r.query,fragment:r.fragment};if(!r.netLoc&&(o.netLoc=n.netLoc,"/"!==r.path[0]))if(r.path){var l=n.path,h=l.substring(0,l.lastIndexOf("/")+1)+r.path;o.path=T.normalizePath(h)}else o.path=n.path,r.params||(o.params=n.params,r.query||(o.query=n.query));return null===o.path&&(o.path=s.alwaysNormalize?T.normalizePath(r.path):r.path),T.buildURLFromParts(o)},parseURL:function(t){var e=m.exec(t);return e?{scheme:e[1]||"",netLoc:e[2]||"",path:e[3]||"",params:e[4]||"",query:e[5]||"",fragment:e[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(y,"");t.length!==(t=t.replace(v,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}};var S=E.exports;function L(t,e){var s=Object.keys(t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);e&&(i=i.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),s.push.apply(s,i)}return s}function A(t){for(var e=1;e<arguments.length;e++){var s=null!=arguments[e]?arguments[e]:{};e%2?L(Object(s),!0).forEach((function(e){b(t,e,s[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(s)):L(Object(s)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(s,e))}))}return t}function R(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var s=t[Symbol.toPrimitive];if(void 0!==s){var i=s.call(t,e||"default");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}function b(t,e,s){return(e=R(e))in t?Object.defineProperty(t,e,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[e]=s,t}function k(){return k=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var s=arguments[e];for(var i in s)Object.prototype.hasOwnProperty.call(s,i)&&(t[i]=s[i])}return t},k.apply(this,arguments)}const D=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},_=Number.isSafeInteger||function(t){return"number"==typeof t&&Math.abs(t)<=I},I=Number.MAX_SAFE_INTEGER||9007199254740991;let w=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached",t.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",t}({}),C=function(t){return t.NETWORK_ERROR="networkError",t.MEDIA_ERROR="mediaError",t.KEY_SYSTEM_ERROR="keySystemError",t.MUX_ERROR="muxError",t.OTHER_ERROR="otherError",t}({}),P=function(t){return t.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",t.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",t.KEY_SYSTEM_NO_SESSION="keySystemNoSession",t.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",t.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",t.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",t.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",t.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",t.MANIFEST_LOAD_ERROR="manifestLoadError",t.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",t.MANIFEST_PARSING_ERROR="manifestParsingError",t.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",t.LEVEL_EMPTY_ERROR="levelEmptyError",t.LEVEL_LOAD_ERROR="levelLoadError",t.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",t.LEVEL_PARSING_ERROR="levelParsingError",t.LEVEL_SWITCH_ERROR="levelSwitchError",t.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",t.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",t.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",t.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",t.FRAG_LOAD_ERROR="fragLoadError",t.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",t.FRAG_DECRYPT_ERROR="fragDecryptError",t.FRAG_PARSING_ERROR="fragParsingError",t.FRAG_GAP="fragGap",t.REMUX_ALLOC_ERROR="remuxAllocError",t.KEY_LOAD_ERROR="keyLoadError",t.KEY_LOAD_TIMEOUT="keyLoadTimeOut",t.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",t.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",t.BUFFER_APPEND_ERROR="bufferAppendError",t.BUFFER_APPENDING_ERROR="bufferAppendingError",t.BUFFER_STALLED_ERROR="bufferStalledError",t.BUFFER_FULL_ERROR="bufferFullError",t.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",t.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.UNKNOWN="unknown",t}({});const x=function(){},F={trace:x,debug:x,log:x,warn:x,info:x,error:x};let M=F;function O(t,...e){e.forEach((function(e){M[e]=t[e]?t[e].bind(t):function(t){const e=self.console[t];return e?e.bind(self.console,`[${t}] >`):x}(e)}))}const N=M,U=/^(\d+)x(\d+)$/,B=/(.+?)=(".*?"|.*?)(?:,|$)/g;class ${constructor(t){"string"==typeof t&&(t=$.parseAttrList(t)),k(this,t)}get clientAttrs(){return Object.keys(this).filter((t=>"X-"===t.substring(0,2)))}decimalInteger(t){const e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e}hexadecimalInteger(t){if(this[t]){let e=(this[t]||"0x").slice(2);e=(1&e.length?"0":"")+e;const s=new Uint8Array(e.length/2);for(let t=0;t<e.length/2;t++)s[t]=parseInt(e.slice(2*t,2*t+2),16);return s}return null}hexadecimalIntegerAsNumber(t){const e=parseInt(this[t],16);return e>Number.MAX_SAFE_INTEGER?1/0:e}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,e){const s=this[t];return s?parseFloat(s):e}enumeratedString(t){return this[t]}bool(t){return"YES"===this[t]}decimalResolution(t){const e=U.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t){let e;const s={};for(B.lastIndex=0;null!==(e=B.exec(t));){let t=e[2];0===t.indexOf('"')&&t.lastIndexOf('"')===t.length-1&&(t=t.slice(1,-1));s[e[1].trim()]=t}return s}}function G(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t}class K{constructor(t,e){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,e){const s=e.attr;for(const e in s)if(Object.prototype.hasOwnProperty.call(t,e)&&t[e]!==s[e]){N.warn(`DATERANGE tag attribute: "${e}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=e;break}t=k(new $({}),s,t)}if(this.attr=t,this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){const t=new Date(this.attr["END-DATE"]);D(t.getTime())&&(this._endDate=t)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get startDate(){return this._startDate}get endDate(){if(this._endDate)return this._endDate;const t=this.duration;return null!==t?new Date(this._startDate.getTime()+1e3*t):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(D(t))return t}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isValid(){return!!this.id&&!this._badValueForSameId&&D(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class H{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var V="audio",Y="video",W="audiovideo";class j{constructor(t){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[V]:null,[Y]:null,[W]:null},this.baseurl=t}setByteRange(t,e){const s=t.split("@",2);let i;i=1===s.length?(null==e?void 0:e.byteRangeEndOffset)||0:parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}get byteRange(){return this._byteRange?this._byteRange:[]}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=S.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}}class q extends j{constructor(t,e){super(e),this._decryptdata=null,this.rawProgramDateTime=null,this.programDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.stats=new H,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=t}get decryptdata(){const{levelkeys:t}=this;if(!t&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const t=this.levelkeys.identity;if(t)this._decryptdata=t.getDecryptData(this.sn);else{const t=Object.keys(this.levelkeys);if(1===t.length)return this._decryptdata=this.levelkeys[t[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;if(!D(this.programDateTime))return null;const t=D(this.duration)?this.duration:0;return this.programDateTime+1e3*t}get encrypted(){var t;if(null!=(t=this._decryptdata)&&t.encrypted)return!0;if(this.levelkeys){const t=Object.keys(this.levelkeys),e=t.length;if(e>1||1===e&&this.levelkeys[t[0]].encrypted)return!0}return!1}setKeyFormat(t){if(this.levelkeys){const e=this.levelkeys[t];e&&!this._decryptdata&&(this._decryptdata=e.getDecryptData(this.sn))}}abortRequests(){var t,e;null==(t=this.loader)||t.abort(),null==(e=this.keyLoader)||e.abort()}setElementaryStreamInfo(t,e,s,i,r,n=!1){const{elementaryStreams:a}=this,o=a[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,s),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,r)):a[t]={startPTS:e,endPTS:s,startDTS:i,endDTS:r,partial:n}}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[V]=null,t[Y]=null,t[W]=null}}class X extends j{constructor(t,e,s,i,r){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.stats=new H,this.duration=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=e,this.index=i;const n=t.enumeratedString("BYTERANGE");n&&this.setByteRange(n,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:t}=this;return!!(t.audio||t.video||t.audiovideo)}}class z{constructor(t){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t}reloaded(t){if(!t)return this.advanced=!0,void(this.updated=!0);const e=this.lastPartSn-t.lastPartSn,s=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!s||!!e||!this.live,this.advanced=this.endSN>t.endSN||e>0||0===e&&s>0,this.updated||this.advanced?this.misses=Math.floor(.6*t.misses):this.misses=t.misses+1,this.availabilityDelay=t.availabilityDelay}get hasProgramDateTime(){return!!this.fragments.length&&D(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const t=this.driftEndTime-this.driftStartTime;if(t>0){return 1e3*(this.driftEnd-this.driftStart)/t}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var t;return null!=(t=this.fragments)&&t.length?this.fragments[this.fragments.length-1].end:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].index:-1}get lastPartSn(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}function Q(t){return Uint8Array.from(atob(t),(t=>t.charCodeAt(0)))}function J(t){const e=t.split(":");let s=null;if("data"===e[0]&&2===e.length){const t=e[1].split(";"),i=t[t.length-1].split(",");if(2===i.length){const e="base64"===i[0],r=i[1];e?(t.splice(-1,1),s=Q(r)):s=function(t){const e=Z(t).subarray(0,16),s=new Uint8Array(16);return s.set(e,16-e.length),s}(r)}}return s}function Z(t){return Uint8Array.from(unescape(encodeURIComponent(t)),(t=>t.charCodeAt(0)))}const tt="undefined"!=typeof self?self:void 0;var et={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},st="org.w3.clearkey",it="com.apple.streamingkeydelivery",rt="com.microsoft.playready",nt="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function at(t){switch(t){case it:return et.FAIRPLAY;case rt:return et.PLAYREADY;case nt:return et.WIDEVINE;case st:return et.CLEARKEY}}var ot="edef8ba979d64acea3c827dcd51d21ed";function lt(t){switch(t){case et.FAIRPLAY:return it;case et.PLAYREADY:return rt;case et.WIDEVINE:return nt;case et.CLEARKEY:return st}}function ht(t){const{drmSystems:e,widevineLicenseUrl:s}=t,i=e?[et.FAIRPLAY,et.WIDEVINE,et.PLAYREADY,et.CLEARKEY].filter((t=>!!e[t])):[];return!i[et.WIDEVINE]&&s&&i.push(et.WIDEVINE),i}const dt=null!=tt&&null!=(ct=tt.navigator)&&ct.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var ct;function ut(t,e,s){return Uint8Array.prototype.slice?t.slice(e,s):new Uint8Array(Array.prototype.slice.call(t,e,s))}const ft=(t,e)=>e+10<=t.length&&73===t[e]&&68===t[e+1]&&51===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128,gt=(t,e)=>e+10<=t.length&&51===t[e]&&68===t[e+1]&&73===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128,mt=(t,e)=>{const s=e;let i=0;for(;ft(t,e);){i+=10;i+=pt(t,e+6),gt(t,e+10)&&(i+=10),e+=i}if(i>0)return t.subarray(s,s+i)},pt=(t,e)=>{let s=0;return s=(127&t[e])<<21,s|=(127&t[e+1])<<14,s|=(127&t[e+2])<<7,s|=127&t[e+3],s},yt=(t,e)=>ft(t,e)&&pt(t,e+6)+10<=t.length-e,vt=t=>{const e=St(t);for(let t=0;t<e.length;t++){const s=e[t];if(Tt(s))return kt(s)}},Tt=t=>t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info,Et=t=>{const e=String.fromCharCode(t[0],t[1],t[2],t[3]),s=pt(t,4);return{type:e,size:s,data:t.subarray(10,10+s)}},St=t=>{let e=0;const s=[];for(;ft(t,e);){const i=pt(t,e+6);e+=10;const r=e+i;for(;e+8<r;){const i=Et(t.subarray(e)),r=Lt(i);r&&s.push(r),e+=i.size+10}gt(t,e)&&(e+=10)}return s},Lt=t=>"PRIV"===t.type?At(t):"W"===t.type[0]?bt(t):Rt(t),At=t=>{if(t.size<2)return;const e=Dt(t.data,!0),s=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:s.buffer}},Rt=t=>{if(t.size<2)return;if("TXXX"===t.type){let e=1;const s=Dt(t.data.subarray(e),!0);e+=s.length+1;const i=Dt(t.data.subarray(e));return{key:t.type,info:s,data:i}}const e=Dt(t.data.subarray(1));return{key:t.type,data:e}},bt=t=>{if("WXXX"===t.type){if(t.size<2)return;let e=1;const s=Dt(t.data.subarray(e),!0);e+=s.length+1;const i=Dt(t.data.subarray(e));return{key:t.type,info:s,data:i}}const e=Dt(t.data);return{key:t.type,data:e}},kt=t=>{if(8===t.data.byteLength){const e=new Uint8Array(t.data),s=1&e[3];let i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,s&&(i+=47721858.84),Math.round(i)}},Dt=(t,e=!1)=>{const s=It();if(s){const i=s.decode(t);if(e){const t=i.indexOf("\0");return-1!==t?i.substring(0,t):i}return i.replace(/\0/g,"")}const i=t.length;let r,n,a,o="",l=0;for(;l<i;){if(r=t[l++],0===r&&e)return o;if(0!==r&&3!==r)switch(r>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(r);break;case 12:case 13:n=t[l++],o+=String.fromCharCode((31&r)<<6|63&n);break;case 14:n=t[l++],a=t[l++],o+=String.fromCharCode((15&r)<<12|(63&n)<<6|63&a)}}return o};let _t;function It(){if(!navigator.userAgent.includes("PlayStation 4"))return _t||void 0===self.TextDecoder||(_t=new self.TextDecoder("utf-8")),_t}const wt=function(t){let e="";for(let s=0;s<t.length;s++){let i=t[s].toString(16);i.length<2&&(i="0"+i),e+=i}return e},Ct=Math.pow(2,32)-1,Pt=[].push,xt={video:1,audio:2,id3:3,text:4};function Ft(t){return String.fromCharCode.apply(null,t)}function Mt(t,e){const s=t[e]<<8|t[e+1];return s<0?65536+s:s}function Ot(t,e){const s=Ut(t,e);return s<0?4294967296+s:s}function Nt(t,e){let s=Ot(t,e);return s*=Math.pow(2,32),s+=Ot(t,e+4),s}function Ut(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function Bt(t,e,s){t[e]=s>>24,t[e+1]=s>>16&255,t[e+2]=s>>8&255,t[e+3]=255&s}function $t(t,e){const s=[];if(!e.length)return s;const i=t.byteLength;for(let r=0;r<i;){const n=Ot(t,r),a=n>1?r+n:i;if(Ft(t.subarray(r+4,r+8))===e[0])if(1===e.length)s.push(t.subarray(r+8,a));else{const i=$t(t.subarray(r+8,a),e.slice(1));i.length&&Pt.apply(s,i)}r=a}return s}function Gt(t){const e=[],s=t[0];let i=8;const r=Ot(t,i);i+=4;let n=0,a=0;0===s?(n=Ot(t,i),a=Ot(t,i+4),i+=8):(n=Nt(t,i),a=Nt(t,i+8),i+=16),i+=2;let o=t.length+a;const l=Mt(t,i);i+=2;for(let s=0;s<l;s++){let s=i;const n=Ot(t,s);s+=4;const a=2147483647&n;if(1===(2147483648&n)>>>31)return N.warn("SIDX has hierarchical references (not supported)"),null;const l=Ot(t,s);s+=4,e.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/r,start:o,end:o+a-1}}),o+=a,s+=4,i=s}return{earliestPresentationTime:n,timescale:r,version:s,referencesCount:l,references:e}}function Kt(t){const e=[],s=$t(t,["moov","trak"]);for(let t=0;t<s.length;t++){const i=s[t],r=$t(i,["tkhd"])[0];if(r){let t=r[0];const s=Ot(r,0===t?12:20),n=$t(i,["mdia","mdhd"])[0];if(n){t=n[0];const r=Ot(n,0===t?12:20),a=$t(i,["mdia","hdlr"])[0];if(a){const t=Ft(a.subarray(8,12)),n={soun:V,vide:Y}[t];if(n){const t=Ht($t(i,["mdia","minf","stbl","stsd"])[0]);e[s]={timescale:r,type:n},e[n]=A({timescale:r,id:s},t)}}}}}return $t(t,["moov","mvex","trex"]).forEach((t=>{const s=Ot(t,4),i=e[s];i&&(i.default={duration:Ot(t,12),flags:Ot(t,20)})})),e}function Ht(t){const e=t.subarray(8),s=e.subarray(86),i=Ft(e.subarray(4,8));let r=i;const n="enca"===i||"encv"===i;if(n){const t=$t(e,[i])[0];$t(t.subarray("enca"===i?28:78),["sinf"]).forEach((t=>{const e=$t(t,["schm"])[0];if(e){const s=Ft(e.subarray(4,8));if("cbcs"===s||"cenc"===s){const e=$t(t,["frma"])[0];e&&(r=Ft(e))}}}))}switch(r){case"avc1":case"avc2":case"avc3":case"avc4":{const t=$t(s,["avcC"])[0];r+="."+Yt(t[1])+Yt(t[2])+Yt(t[3]);break}case"mp4a":{const t=$t(e,[i])[0],s=$t(t.subarray(28),["esds"])[0];if(s&&s.length>12){let t=4;if(3!==s[t++])break;t=Vt(s,t),t+=2;const e=s[t++];if(128&e&&(t+=2),64&e&&(t+=s[t++]),4!==s[t++])break;t=Vt(s,t);const i=s[t++];if(64!==i)break;if(r+="."+Yt(i),t+=12,5!==s[t++])break;t=Vt(s,t);const n=s[t++];let a=(248&n)>>3;31===a&&(a+=1+((7&n)<<3)+((224&s[t])>>5)),r+="."+a}break}case"hvc1":case"hev1":{const t=$t(s,["hvcC"])[0],e=t[1],i=["","A","B","C"][e>>6],n=31&e,a=Ot(t,2),o=(32&e)>>5?"H":"L",l=t[12],h=t.subarray(6,12);r+="."+i+n,r+="."+a.toString(16).toUpperCase(),r+="."+o+l;let d="";for(let t=h.length;t--;){const e=h[t];if(e||d){d="."+e.toString(16).toUpperCase()+d}}r+=d;break}case"dvh1":case"dvhe":{const t=$t(s,["dvcC"])[0],e=t[2]>>1&127,i=t[2]<<5&32|t[3]>>3&31;r+="."+Wt(e)+"."+Wt(i);break}case"vp09":{const t=$t(s,["vpcC"])[0],e=t[4],i=t[5],n=t[6]>>4&15;r+="."+Wt(e)+"."+Wt(i)+"."+Wt(n);break}case"av01":{const t=$t(s,["av1C"])[0],e=t[1]>>>5,i=31&t[1],n=t[2]>>>7?"H":"M",a=(64&t[2])>>6,o=(32&t[2])>>5,l=2===e&&a?o?12:10:a?10:8,h=(16&t[2])>>4,d=(8&t[2])>>3,c=(4&t[2])>>2,u=3&t[2],f=1,g=1,m=1,p=0;r+="."+e+"."+Wt(i)+n+"."+Wt(l)+"."+h+"."+d+c+u+"."+Wt(f)+"."+Wt(g)+"."+Wt(m)+"."+p;break}}return{codec:r,encrypted:n}}function Vt(t,e){const s=e+5;for(;128&t[e++]&&e<s;);return e}function Yt(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function Wt(t){return(t<10?"0":"")+t}function jt(t){const e=$t(t,["schm"])[0];if(e){const s=Ft(e.subarray(4,8));if("cbcs"===s||"cenc"===s)return $t(t,["schi","tenc"])[0]}return N.error("[eme] missing 'schm' box"),null}function qt(t){const e=Ot(t,0);let s=8;1&e&&(s+=4),4&e&&(s+=4);let i=0;const r=Ot(t,4);for(let n=0;n<r;n++){if(256&e){i+=Ot(t,s),s+=4}512&e&&(s+=4),1024&e&&(s+=4),2048&e&&(s+=4)}return i}function Xt(t,e){const s=new Uint8Array(t.length+e.length);return s.set(t),s.set(e,t.length),s}function zt(t,e){const s=[],i=e.samples,r=e.timescale,n=e.id;let a=!1;return $t(i,["moof"]).map((o=>{const l=o.byteOffset-8;$t(o,["traf"]).map((o=>{const h=$t(o,["tfdt"]).map((t=>{const e=t[0];let s=Ot(t,4);return 1===e&&(s*=Math.pow(2,32),s+=Ot(t,8)),s/r}))[0];return void 0!==h&&(t=h),$t(o,["tfhd"]).map((h=>{const d=Ot(h,4),c=16777215&Ot(h,0);let u=0;const f=!!(16&c);let g=0;const m=!!(32&c);let p=8;d===n&&(!!(1&c)&&(p+=8),!!(2&c)&&(p+=4),!!(8&c)&&(u=Ot(h,p),p+=4),f&&(g=Ot(h,p),p+=4),m&&(p+=4),"video"===e.type&&(a=function(t){if(!t)return!1;const e=t.indexOf("."),s=e<0?t:t.substring(0,e);return"hvc1"===s||"hev1"===s||"dvh1"===s||"dvhe"===s}(e.codec)),$t(o,["trun"]).map((n=>{const o=n[0],h=16777215&Ot(n,0),d=!!(1&h);let c=0;const f=!!(4&h),m=!!(256&h);let p=0;const y=!!(512&h);let v=0;const T=!!(1024&h),E=!!(2048&h);let S=0;const L=Ot(n,4);let A=8;d&&(c=Ot(n,A),A+=4),f&&(A+=4);let R=c+l;for(let l=0;l<L;l++){if(m?(p=Ot(n,A),A+=4):p=u,y?(v=Ot(n,A),A+=4):v=g,T&&(A+=4),E&&(S=0===o?Ot(n,A):Ut(n,A),A+=4),e.type===Y){let e=0;for(;e<v;){const n=Ot(i,R);if(R+=4,Qt(a,i[R])){Jt(i.subarray(R,R+n),a?2:1,t+S/r,s)}R+=n,e+=n+4}}t+=p/r}})))}))}))})),s}function Qt(t,e){if(t){const t=e>>1&63;return 39===t||40===t}return 6===(31&e)}function Jt(t,e,s,i){const r=Zt(t);let 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(255===l);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(255===l);const t=r.length-n;let e=n;if(o<t)n+=o;else if(o>t){N.error(`Malformed SEI payload. ${o} is too small, only ${t} bytes left to parse.`);break}if(4===a){if(181===r[e++]){const t=Mt(r,e);if(e+=2,49===t){const t=Ot(r,e);if(e+=4,1195456820===t){const t=r[e++];if(3===t){const n=r[e++],o=64&n,l=o?2+3*(31&n):0,h=new Uint8Array(l);if(o){h[0]=n;for(let t=1;t<l;t++)h[t]=r[e++]}i.push({type:t,payloadType:a,pts:s,bytes:h})}}}}}else if(5===a&&o>16){const t=[];for(let s=0;s<16;s++){const i=r[e++].toString(16);t.push(1==i.length?"0"+i:i),3!==s&&5!==s&&7!==s&&9!==s||t.push("-")}const n=o-16,l=new Uint8Array(n);for(let t=0;t<n;t++)l[t]=r[e++];i.push({payloadType:a,pts:s,uuid:t.join(""),userData:Dt(l),userDataBytes:l})}}}function Zt(t){const e=t.byteLength,s=[];let i=1;for(;i<e-2;)0===t[i]&&0===t[i+1]&&3===t[i+2]?(s.push(i+2),i+=2):i++;if(0===s.length)return t;const r=e-s.length,n=new Uint8Array(r);let a=0;for(i=0;i<r;a++,i++)a===s[0]&&(a++,s.shift()),n[i]=t[a];return n}function te(t,e,s){if(16!==t.byteLength)throw new RangeError("Invalid system id");let i,r,n;if(e){i=1,r=new Uint8Array(16*e.length);for(let t=0;t<e.length;t++){const s=e[t];if(16!==s.byteLength)throw new RangeError("Invalid key");r.set(s,16*t)}}else i=0,r=new Uint8Array;i>0?(n=new Uint8Array(4),e.length>0&&new DataView(n.buffer).setUint32(0,e.length,!1)):n=new Uint8Array;const a=new Uint8Array(4);return s&&s.byteLength>0&&new DataView(a.buffer).setUint32(0,s.byteLength,!1),function(t,...e){const s=e.length;let i=8,r=s;for(;r--;)i+=e[r].byteLength;const n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=255&i,n.set(t,4),r=0,i=8;r<s;r++)n.set(e[r],i),i+=e[r].byteLength;return n}([112,115,115,104],new Uint8Array([i,0,0,0]),t,n,r,a,s||new Uint8Array)}let ee={};class se{static clearKeyUriToKeyIdMap(){ee={}}constructor(t,e,s,i=[1],r=null){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=t,this.uri=e,this.keyFormat=s,this.keyFormatVersions=i,this.iv=r,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&"AES-128"!==t}isSupported(){if(this.method){if("AES-128"===this.method||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case it:case nt:case rt:case st:return-1!==["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(t){if(!this.encrypted||!this.uri)return null;if("AES-128"===this.method&&this.uri&&!this.iv){"number"!=typeof t&&("AES-128"!==this.method||this.iv||N.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0);const e=function(t){const e=new Uint8Array(16);for(let s=12;s<16;s++)e[s]=t>>8*(15-s)&255;return e}(t);return new se(this.method,this.uri,"identity",this.keyFormatVersions,e)}const e=J(this.uri);if(e)switch(this.keyFormat){case nt:this.pssh=e,e.length>=22&&(this.keyId=e.subarray(e.length-22,e.length-6));break;case rt:{const t=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=te(t,null,e);const s=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),i=String.fromCharCode.apply(null,Array.from(s)),r=i.substring(i.indexOf("<"),i.length),n=(new DOMParser).parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(n){const t=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(t){const e=Q(t).subarray(0,16);!function(t){const e=function(t,e,s){const i=t[e];t[e]=t[s],t[s]=i};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}(e),this.keyId=e}}break}default:{let t=e.subarray(0,16);if(16!==t.length){const e=new Uint8Array(16);e.set(t,16-t.length),t=e}this.keyId=t;break}}if(!this.keyId||16!==this.keyId.byteLength){let t=ee[this.uri];if(!t){const e=Object.keys(ee).length%Number.MAX_SAFE_INTEGER;t=new Uint8Array(16);new DataView(t.buffer,12,4).setUint32(0,e),ee[this.uri]=t}this.keyId=t}return this}}const ie=/\{\$([a-zA-Z0-9-_]+)\}/g;function re(t){return ie.test(t)}function ne(t,e,s){if(null!==t.variableList||t.hasVariableRefs)for(let i=s.length;i--;){const r=s[i],n=e[r];n&&(e[r]=ae(t,n))}}function ae(t,e){if(null!==t.variableList||t.hasVariableRefs){const s=t.variableList;return e.replace(ie,(e=>{const i=e.substring(2,e.length-1),r=null==s?void 0:s[i];return void 0===r?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),e):r}))}return e}function oe(t,e,s){let i,r,n=t.variableList;if(n||(t.variableList=n={}),"QUERYPARAM"in e){i=e.QUERYPARAM;try{const t=new self.URL(s).searchParams;if(!t.has(i))throw new Error(`"${i}" does not match any query parameter in URI: "${s}"`);r=t.get(i)}catch(e){t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${e.message}`))}}else i=e.NAME,r=e.VALUE;i in n?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):n[i]=r||""}function le(t,e,s){const i=e.IMPORT;if(s&&i in s){let e=t.variableList;e||(t.variableList=e={}),e[i]=s[i]}else t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}function he(t=!0){if("undefined"==typeof self)return;return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}const de={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function ce(t,e,s=!0){return!t.split(",").some((t=>!ue(t,e,s)))}function ue(t,e,s=!0){var i;const r=he(s);return null!=(i=null==r?void 0:r.isTypeSupported(fe(t,e)))&&i}function fe(t,e){return`${e}/mp4;codecs="${t}"`}function ge(t){if(t){const e=t.substring(0,4);return de.video[e]}return 2}function me(t){return t.split(",").reduce(((t,e)=>{const s=de.video[e];return s?(2*s+t)/(t?3:2):(de.audio[e]+t)/(t?2:1)}),0)}const pe={};const ye=/flac|opus/i;function ve(t,e=!0){return t.replace(ye,(t=>function(t,e=!0){if(pe[t])return pe[t];const s={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[t];for(let i=0;i<s.length;i++)if(ue(s[i],"audio",e))return pe[t]=s[i],s[i];return t}(t.toLowerCase(),e)))}function Te(t,e){return t&&"mp4a"!==t?t:e?e.split(",")[0]:e}const Ee=/#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,Se=/#EXT-X-MEDIA:(.*)/g,Le=/^#EXT(?:INF|-X-TARGETDURATION):/m,Ae=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),Re=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class be{static findGroup(t,e){for(let s=0;s<t.length;s++){const i=t[s];if(i.id===e)return i}}static resolve(t,e){return S.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return Le.test(t)}static parseMasterPlaylist(t,e){const s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:re(t)},i=[];let r;for(Ee.lastIndex=0;null!=(r=Ee.exec(t));)if(r[1]){var n;const t=new $(r[1]);ne(s,t,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const a=ae(s,r[2]),o={attrs:t,bitrate:t.decimalInteger("BANDWIDTH")||t.decimalInteger("AVERAGE-BANDWIDTH"),name:t.NAME,url:be.resolve(a,e)},l=t.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),_e(t.CODECS,o),null!=(n=o.unknownCodecs)&&n.length||i.push(o),s.levels.push(o)}else if(r[3]){const t=r[3],i=r[4];switch(t){case"SESSION-DATA":{const t=new $(i);ne(s,t,["DATA-ID","LANGUAGE","VALUE","URI"]);const e=t["DATA-ID"];e&&(null===s.sessionData&&(s.sessionData={}),s.sessionData[e]=t);break}case"SESSION-KEY":{const t=ke(i,e,s);t.encrypted&&t.isSupported()?(null===s.sessionKeys&&(s.sessionKeys=[]),s.sessionKeys.push(t)):N.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${i}"`);break}case"DEFINE":{const t=new $(i);ne(s,t,["NAME","VALUE","QUERYPARAM"]),oe(s,t,e)}break;case"CONTENT-STEERING":{const t=new $(i);ne(s,t,["SERVER-URI","PATHWAY-ID"]),s.contentSteering={uri:be.resolve(t["SERVER-URI"],e),pathwayId:t["PATHWAY-ID"]||"."};break}case"START":s.startTimeOffset=De(i)}}const a=i.length>0&&i.length<s.levels.length;return s.levels=a?i:s.levels,0===s.levels.length&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(t,e,s){let i;const r={},n=s.levels,a={AUDIO:n.map((t=>({id:t.attrs.AUDIO,audioCodec:t.audioCodec}))),SUBTITLES:n.map((t=>({id:t.attrs.SUBTITLES,textCodec:t.textCodec}))),"CLOSED-CAPTIONS":[]};let o=0;for(Se.lastIndex=0;null!==(i=Se.exec(t));){const t=new $(i[1]),n=t.TYPE;if(n){const i=a[n],l=r[n]||[];r[n]=l,ne(s,t,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const h=t.LANGUAGE,d=t["ASSOC-LANGUAGE"],c=t.CHANNELS,u=t.CHARACTERISTICS,f=t["INSTREAM-ID"],g={attrs:t,bitrate:0,id:o++,groupId:t["GROUP-ID"]||"",name:t.NAME||h||"",type:n,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:h,url:t.URI?be.resolve(t.URI,e):""};if(d&&(g.assocLang=d),c&&(g.channels=c),u&&(g.characteristics=u),f&&(g.instreamId=f),null!=i&&i.length){const t=be.findGroup(i,g.groupId)||i[0];Ie(g,t,"audioCodec"),Ie(g,t,"textCodec")}l.push(g)}}return r}static parseLevelPlaylist(t,e,s,i,r,n){const a=new z(e),o=a.fragments;let l,h,d,c=null,u=0,f=0,g=0,m=0,p=null,y=new q(i,e),v=-1,T=!1,E=null;for(Ae.lastIndex=0,a.m3u8=t,a.hasVariableRefs=re(t);null!==(l=Ae.exec(t));){T&&(T=!1,y=new q(i,e),y.start=g,y.sn=u,y.cc=m,y.level=s,c&&(y.initSegment=c,y.rawProgramDateTime=c.rawProgramDateTime,c.rawProgramDateTime=null,E&&(y.setByteRange(E),E=null)));const t=l[1];if(t){y.duration=parseFloat(t);const e=(" "+l[2]).slice(1);y.title=e||null,y.tagList.push(e?["INF",t,e]:["INF",t])}else if(l[3]){if(D(y.duration)){y.start=g,d&&Pe(y,d,a),y.sn=u,y.level=s,y.cc=m,o.push(y);const t=(" "+l[3]).slice(1);y.relurl=ae(a,t),we(y,p),p=y,g+=y.duration,u++,f=0,T=!0}}else if(l[4]){const t=(" "+l[4]).slice(1);p?y.setByteRange(t,p):y.setByteRange(t)}else if(l[5])y.rawProgramDateTime=(" "+l[5]).slice(1),y.tagList.push(["PROGRAM-DATE-TIME",y.rawProgramDateTime]),-1===v&&(v=o.length);else{if(l=l[0].match(Re),!l){N.warn("No matches on slow regex match for level playlist!");continue}for(h=1;h<l.length&&void 0===l[h];h++);const t=(" "+l[h]).slice(1),r=(" "+l[h+1]).slice(1),g=l[h+2]?(" "+l[h+2]).slice(1):"";switch(t){case"PLAYLIST-TYPE":a.type=r.toUpperCase();break;case"MEDIA-SEQUENCE":u=a.startSN=parseInt(r);break;case"SKIP":{const t=new $(r);ne(a,t,["RECENTLY-REMOVED-DATERANGES"]);const e=t.decimalInteger("SKIPPED-SEGMENTS");if(D(e)){a.skippedSegments=e;for(let t=e;t--;)o.unshift(null);u+=e}const s=t.enumeratedString("RECENTLY-REMOVED-DATERANGES");s&&(a.recentlyRemovedDateranges=s.split("\t"));break}case"TARGETDURATION":a.targetduration=Math.max(parseInt(r),1);break;case"VERSION":a.version=parseInt(r);break;case"INDEPENDENT-SEGMENTS":case"EXTM3U":break;case"ENDLIST":a.live=!1;break;case"#":(r||g)&&y.tagList.push(g?[r,g]:[r]);break;case"DISCONTINUITY":m++,y.tagList.push(["DIS"]);break;case"GAP":y.gap=!0,y.tagList.push([t]);break;case"BITRATE":y.tagList.push([t,r]);break;case"DATERANGE":{const t=new $(r);ne(a,t,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),ne(a,t,t.clientAttrs);const e=new K(t,a.dateRanges[t.ID]);e.isValid||a.skippedSegments?a.dateRanges[e.id]=e:N.warn(`Ignoring invalid DATERANGE tag: "${r}"`),y.tagList.push(["EXT-X-DATERANGE",r]);break}case"DEFINE":{const t=new $(r);ne(a,t,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in t?le(a,t,n):oe(a,t,e)}break;case"DISCONTINUITY-SEQUENCE":m=parseInt(r);break;case"KEY":{const t=ke(r,e,a);if(t.isSupported()){if("NONE"===t.method){d=void 0;break}d||(d={}),d[t.keyFormat]&&(d=k({},d)),d[t.keyFormat]=t}else N.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${r}"`);break}case"START":a.startTimeOffset=De(r);break;case"MAP":{const t=new $(r);if(ne(a,t,["BYTERANGE","URI"]),y.duration){const r=new q(i,e);Ce(r,t,s,d),c=r,y.initSegment=c,c.rawProgramDateTime&&!y.rawProgramDateTime&&(y.rawProgramDateTime=c.rawProgramDateTime)}else{const e=y.byteRangeEndOffset;if(e){const t=y.byteRangeStartOffset;E=`${e-t}@${t}`}else E=null;Ce(y,t,s,d),c=y,T=!0}break}case"SERVER-CONTROL":{const t=new $(r);a.canBlockReload=t.bool("CAN-BLOCK-RELOAD"),a.canSkipUntil=t.optionalFloat("CAN-SKIP-UNTIL",0),a.canSkipDateRanges=a.canSkipUntil>0&&t.bool("CAN-SKIP-DATERANGES"),a.partHoldBack=t.optionalFloat("PART-HOLD-BACK",0),a.holdBack=t.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const t=new $(r);a.partTarget=t.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=a.partList;t||(t=a.partList=[]);const s=f>0?t[t.length-1]:void 0,i=f++,n=new $(r);ne(a,n,["BYTERANGE","URI"]);const o=new X(n,y,e,i,s);t.push(o),y.duration+=o.duration;break}case"PRELOAD-HINT":{const t=new $(r);ne(a,t,["URI"]),a.preloadHint=t;break}case"RENDITION-REPORT":{const t=new $(r);ne(a,t,["URI"]),a.renditionReports=a.renditionReports||[],a.renditionReports.push(t);break}default:N.warn(`line parsed but not handled: ${l}`)}}}p&&!p.relurl?(o.pop(),g-=p.duration,a.partList&&(a.fragmentHint=p)):a.partList&&(we(y,p),y.cc=m,a.fragmentHint=y,d&&Pe(y,d,a));const S=o.length,L=o[0],A=o[S-1];if(g+=a.skippedSegments*a.targetduration,g>0&&S&&A){a.averagetargetduration=g/S;const t=A.sn;a.endSN="initSegment"!==t?t:0,a.live||(A.endList=!0),L&&(a.startCC=L.cc)}else a.endSN=0,a.startCC=0;return a.fragmentHint&&(g+=a.fragmentHint.duration),a.totalduration=g,a.endCC=m,v>0&&function(t,e){let s=t[e];for(let i=e;i--;){const e=t[i];if(!e)return;e.programDateTime=s.programDateTime-1e3*e.duration,s=e}}(o,v),a}}function ke(t,e,s){var i,r;const n=new $(t);ne(s,n,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const a=null!=(i=n.METHOD)?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,d=null!=(r=n.KEYFORMAT)?r:"identity";o&&n.IV&&!l&&N.error(`Invalid IV: ${n.IV}`);const c=o?be.resolve(o,e):"",u=(h||"1").split("/").map(Number).filter(Number.isFinite);return new se(a,c,d,u,l)}function De(t){const e=new $(t).decimalFloatingPoint("TIME-OFFSET");return D(e)?e:null}function _e(t,e){let s=(t||"").split(/[ ,]+/).filter((t=>t));["video","audio","text"].forEach((t=>{const i=s.filter((e=>function(t,e){const s=de[e];return!!s&&!!s[t.slice(0,4)]}(e,t)));i.length&&(e[`${t}Codec`]=i.join(","),s=s.filter((t=>-1===i.indexOf(t))))})),e.unknownCodecs=s}function Ie(t,e,s){const i=e[s];i&&(t[s]=i)}function we(t,e){t.rawProgramDateTime?t.programDateTime=Date.parse(t.rawProgramDateTime):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime),D(t.programDateTime)||(t.programDateTime=null,t.rawProgramDateTime=null)}function Ce(t,e,s,i){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=s,t.sn="initSegment",i&&(t.levelkeys=i),t.initSegment=null}function Pe(t,e,s){t.levelkeys=e;const{encryptedFragments:i}=s;i.length&&i[i.length-1].levelkeys===e||!Object.keys(e).some((t=>e[t].isCommonEncryption))||i.push(t)}var xe="manifest",Fe="level",Me="audioTrack",Oe="subtitleTrack",Ne="main",Ue="audio",Be="subtitle";function $e(t){const{type:e}=t;switch(e){case Me:return Ue;case Oe:return Be;default:return Ne}}function Ge(t,e){let s=t.url;return void 0!==s&&0!==s.indexOf("data:")||(s=e.url),s}class Ke{constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=t,this.registerListeners()}startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:t}=this;t.on(w.MANIFEST_LOADING,this.onManifestLoading,this),t.on(w.LEVEL_LOADING,this.onLevelLoading,this),t.on(w.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(w.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:t}=this;t.off(w.MANIFEST_LOADING,this.onManifestLoading,this),t.off(w.LEVEL_LOADING,this.onLevelLoading,this),t.off(w.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(w.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(t){const e=this.hls.config,s=e.pLoader,i=e.loader,r=new(s||i)(e);return this.loaders[t.type]=r,r}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}destroyInternalLoaders(){for(const t in this.loaders){const e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,e){const{url:s}=e;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:xe,url:s,deliveryDirectives:null})}onLevelLoading(t,e){const{id:s,level:i,pathwayId:r,url:n,deliveryDirectives:a}=e;this.load({id:s,level:i,pathwayId:r,responseType:"text",type:Fe,url:n,deliveryDirectives:a})}onAudioTrackLoading(t,e){const{id:s,groupId:i,url:r,deliveryDirectives:n}=e;this.load({id:s,groupId:i,level:null,responseType:"text",type:Me,url:r,deliveryDirectives:n})}onSubtitleTrackLoading(t,e){const{id:s,groupId:i,url:r,deliveryDirectives:n}=e;this.load({id:s,groupId:i,level:null,responseType:"text",type:Oe,url:r,deliveryDirectives:n})}load(t){var e;const s=this.hls.config;let i,r=this.getInternalLoader(t);if(r){const e=r.context;if(e&&e.url===t.url&&e.level===t.level)return void N.trace("[playlist-loader]: playlist request ongoing");N.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),r.abort()}if(i=t.type===xe?s.manifestLoadPolicy.default:k({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(t),D(null==(e=t.deliveryDirectives)?void 0:e.part)){let e;if(t.type===Fe&&null!==t.level?e=this.hls.levels[t.level].details:t.type===Me&&null!==t.id?e=this.hls.audioTracks[t.id].details:t.type===Oe&&null!==t.id&&(e=this.hls.subtitleTracks[t.id].details),e){const t=e.partTarget,s=e.targetduration;if(t&&s){const e=1e3*Math.max(3*t,.8*s);i=k({},i,{maxTimeToFirstByteMs:Math.min(e,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(e,i.maxTimeToFirstByteMs)})}}}const n=i.errorRetry||i.timeoutRetry||{},a={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},o={onSuccess:(t,e,s,i)=>{const r=this.getInternalLoader(s);this.resetInternalLoader(s.type);const n=t.data;0===n.indexOf("#EXTM3U")?(e.parsing.start=performance.now(),be.isMediaPlaylist(n)?this.handleTrackOrLevelPlaylist(t,e,s,i||null,r):this.handleMasterPlaylist(t,e,s,i)):this.handleManifestParsingError(t,s,new Error("no EXTM3U delimiter"),i||null,e)},onError:(t,e,s,i)=>{this.handleNetworkError(e,s,!1,t,i)},onTimeout:(t,e,s)=>{this.handleNetworkError(e,s,!0,void 0,t)}};r.load(t,a,o)}handleMasterPlaylist(t,e,s,i){const r=this.hls,n=t.data,a=Ge(t,s),o=be.parseMasterPlaylist(n,a);if(o.playlistParsingError)return void this.handleManifestParsingError(t,s,o.playlistParsingError,i,e);const{contentSteering:l,levels:h,sessionData:d,sessionKeys:c,startTimeOffset:u,variableList:f}=o;this.variableList=f;const{AUDIO:g=[],SUBTITLES:m,"CLOSED-CAPTIONS":p}=be.parseMasterPlaylistMedia(n,a,o);if(g.length){g.some((t=>!t.url))||!h[0].audioCodec||h[0].attrs.AUDIO||(N.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new $({}),bitrate:0,url:""}))}r.trigger(w.MANIFEST_LOADED,{levels:h,audioTracks:g,subtitles:m,captions:p,contentSteering:l,url:a,stats:e,networkDetails:i,sessionData:d,sessionKeys:c,startTimeOffset:u,variableList:f})}handleTrackOrLevelPlaylist(t,e,s,i,r){const n=this.hls,{id:a,level:o,type:l}=s,h=Ge(t,s),d=D(o)?o:D(a)?a:0,c=$e(s),u=be.parseLevelPlaylist(t.data,h,d,c,0,this.variableList);if(l===xe){const t={attrs:new $({}),bitrate:0,details:u,name:"",url:h};n.trigger(w.MANIFEST_LOADED,{levels:[t],audioTracks:[],url:h,stats:e,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),s.levelDetails=u,this.handlePlaylistLoaded(u,t,e,s,i,r)}handleManifestParsingError(t,e,s,i,r){this.hls.trigger(w.ERROR,{type:C.NETWORK_ERROR,details:P.MANIFEST_PARSING_ERROR,fatal:e.type===xe,url:t.url,err:s,error:s,reason:s.message,response:t,context:e,networkDetails:i,stats:r})}handleNetworkError(t,e,s=!1,i,r){let n=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${t.type}`;t.type===Fe?n+=`: ${t.level} id: ${t.id}`:t.type!==Me&&t.type!==Oe||(n+=` id: ${t.id} group-id: "${t.groupId}"`);const a=new Error(n);N.warn(`[playlist-loader]: ${n}`);let o=P.UNKNOWN,l=!1;const h=this.getInternalLoader(t);switch(t.type){case xe:o=s?P.MANIFEST_LOAD_TIMEOUT:P.MANIFEST_LOAD_ERROR,l=!0;break;case Fe:o=s?P.LEVEL_LOAD_TIMEOUT:P.LEVEL_LOAD_ERROR,l=!1;break;case Me:o=s?P.AUDIO_TRACK_LOAD_TIMEOUT:P.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case Oe:o=s?P.SUBTITLE_TRACK_LOAD_TIMEOUT:P.SUBTITLE_LOAD_ERROR,l=!1}h&&this.resetInternalLoader(t.type);const d={type:C.NETWORK_ERROR,details:o,fatal:l,url:t.url,loader:h,context:t,error:a,networkDetails:e,stats:r};if(i){const s=(null==e?void 0:e.url)||t.url;d.response=A({url:s,data:void 0},i)}this.hls.trigger(w.ERROR,d)}handlePlaylistLoaded(t,e,s,i,r,n){const a=this.hls,{type:o,level:l,id:h,groupId:d,deliveryDirectives:c}=i,u=Ge(e,i),f=$e(i),g="number"==typeof i.level&&f===Ne?l:void 0;if(!t.fragments.length){const t=new Error("No Segments found in Playlist");return void a.trigger(w.ERROR,{type:C.NETWORK_ERROR,details:P.LEVEL_EMPTY_ERROR,fatal:!1,url:u,error:t,reason:t.message,response:e,context:i,level:g,parent:f,networkDetails:r,stats:s})}t.targetduration||(t.playlistParsingError=new Error("Missing Target Duration"));const m=t.playlistParsingError;if(m)a.trigger(w.ERROR,{type:C.NETWORK_ERROR,details:P.LEVEL_PARSING_ERROR,fatal:!1,url:u,error:m,reason:m.message,response:e,context:i,level:g,parent:f,networkDetails:r,stats:s});else switch(t.live&&n&&(n.getCacheAge&&(t.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),o){case xe:case Fe:a.trigger(w.LEVEL_LOADED,{details:t,level:g||0,id:h||0,stats:s,networkDetails:r,deliveryDirectives:c});break;case Me:a.trigger(w.AUDIO_TRACK_LOADED,{details:t,id:h||0,groupId:d||"",stats:s,networkDetails:r,deliveryDirectives:c});break;case Oe:a.trigger(w.SUBTITLE_TRACK_LOADED,{details:t,id:h||0,groupId:d||"",stats:s,networkDetails:r,deliveryDirectives:c})}}}function He(t,e){let s;try{s=new Event("addtrack")}catch(t){s=document.createEvent("Event"),s.initEvent("addtrack",!1,!1)}s.track=t,e.dispatchEvent(s)}function Ve(t,e){const s=t.mode;if("disabled"===s&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(e.id))try{if(t.addCue(e),!t.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(s){N.debug(`[texttrack-utils]: ${s}`);try{const s=new self.TextTrackCue(e.startTime,e.endTime,e.text);s.id=e.id,t.addCue(s)}catch(t){N.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${t}`)}}"disabled"===s&&(t.mode=s)}function Ye(t){const e=t.mode;if("disabled"===e&&(t.mode="hidden"),t.cues)for(let e=t.cues.length;e--;)t.removeCue(t.cues[e]);"disabled"===e&&(t.mode=e)}function We(t,e,s,i){const r=t.mode;if("disabled"===r&&(t.mode="hidden"),t.cues&&t.cues.length>0){const r=function(t,e,s){const i=[],r=function(t,e){if(e<t[0].startTime)return 0;const s=t.length-1;if(e>t[s].endTime)return-1;let i=0,r=s;for(;i<=r;){const n=Math.floor((r+i)/2);if(e<t[n].startTime)r=n-1;else{if(!(e>t[n].startTime&&i<s))return n;i=n+1}}return t[i].startTime-e<e-t[r].startTime?i:r}(t,e);if(r>-1)for(let n=r,a=t.length;n<a;n++){const r=t[n];if(r.startTime>=e&&r.endTime<=s)i.push(r);else if(r.startTime>s)return i}return i}(t.cues,e,s);for(let e=0;e<r.length;e++)i&&!i(r[e])||t.removeCue(r[e])}"disabled"===r&&(t.mode=r)}function je(t){const e=[];for(let s=0;s<t.length;s++){const i=t[s];"subtitles"!==i.kind&&"captions"!==i.kind||!i.label||e.push(t[s])}return e}var qe="org.id3",Xe="com.apple.quicktime.HLS",ze="https://aomedia.org/emsg/ID3";function Qe(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function Je(t,e,s,i,r){let n=new t(e,s,"");try{n.value=i,r&&(n.type=r)}catch(a){n=new t(e,s,JSON.stringify(r?A({type:r},i):i))}return n}const Ze=(()=>{const t=Qe();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function ts(t,e){return t.getTime()/1e3-e}class es{constructor(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){const{hls:t}=this;t.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(w.MANIFEST_LOADING,this.onManifestLoading,this),t.on(w.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(w.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(w.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:t}=this;t.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(w.MANIFEST_LOADING,this.onManifestLoading,this),t.off(w.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(w.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(w.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(t,e){this.media=e.media}onMediaDetaching(){this.id3Track&&(Ye(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){const e=this.getID3Track(t.textTracks);return e.mode="hidden",e}getID3Track(t){if(this.media){for(let e=0;e<t.length;e++){const s=t[e];if("metadata"===s.kind&&"id3"===s.label)return He(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(t,e){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:s,enableID3MetadataCues:i}}}=this;if(!s&&!i)return;const{samples:r}=e;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=Qe();if(n)for(let t=0;t<r.length;t++){const e=r[t].type;if(e===ze&&!s||!i)continue;const a=St(r[t].data);if(a){const s=r[t].pts;let i=s+r[t].duration;i>Ze&&(i=Ze);i-s<=0&&(i=s+.25);for(let t=0;t<a.length;t++){const r=a[t];if(!Tt(r)){this.updateId3CueEnds(s,e);const t=Je(n,s,i,r,e);t&&this.id3Track.addCue(t)}}}}}updateId3CueEnds(t,e){var s;const i=null==(s=this.id3Track)?void 0:s.cues;if(i)for(let s=i.length;s--;){const r=i[s];r.type===e&&r.startTime<t&&r.endTime===Ze&&(r.endTime=t)}}onBufferFlushing(t,{startOffset:e,endOffset:s,type:i}){const{id3Track:r,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(r&&(a||o)){let t;t="audio"===i?t=>t.type===qe&&o:"video"===i?t=>t.type===ze&&a:t=>t.type===qe&&o||t.type===ze&&a,We(r,e,s,t)}}onLevelUpdated(t,{details:e}){if(!this.media||!e.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:s,id3Track:i}=this,{dateRanges:r}=e,n=Object.keys(r);if(i){const t=Object.keys(s).filter((t=>!n.includes(t)));for(let e=t.length;e--;){const r=t[e];Object.keys(s[r].cues).forEach((t=>{i.removeCue(s[r].cues[t])})),delete s[r]}}const a=e.fragments[e.fragments.length-1];if(0===n.length||!D(null==a?void 0:a.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const o=a.programDateTime/1e3-a.start,l=Qe();for(let t=0;t<n.length;t++){const e=n[t],i=r[e],a=ts(i.startDate,o),c=s[e],u=(null==c?void 0:c.cues)||{};let f=(null==c?void 0:c.durationKnown)||!1,g=Ze;const m=i.endDate;if(m)g=ts(m,o),f=!0;else if(i.endOnNext&&!f){const t=n.reduce(((t,e)=>{if(e!==i.id){const s=r[e];if(s.class===i.class&&s.startDate>i.startDate&&(!t||i.startDate<t.startDate))return s}return t}),null);t&&(g=ts(t.startDate,o),f=!0)}const p=Object.keys(i.attr);for(let t=0;t<p.length;t++){const s=p[t];if("ID"===(d=s)||"CLASS"===d||"START-DATE"===d||"DURATION"===d||"END-DATE"===d||"END-ON-NEXT"===d)continue;const r=u[s];if(r)f&&!c.durationKnown&&(r.endTime=g);else if(l){let t=i.attr[s];G(s)&&(h=t,t=Uint8Array.from(h.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer);const r=Je(l,a,g,{key:s,data:t},Xe);r&&(r.id=e,this.id3Track.addCue(r),u[s]=r)}}s[e]={cues:u,dateRange:i,durationKnown:f}}var h,d}}class ss{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.levelDetails=null,this.currentTime=0,this.stallCount=0,this._latency=null,this.timeupdateHandler=()=>this.timeupdate(),this.hls=t,this.config=t.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:t,levelDetails:e}=this;return void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:e?t.liveMaxLatencyDurationCount*e.targetduration:0}get targetLatency(){const{levelDetails:t}=this;if(null===t)return null;const{holdBack:e,partHoldBack:s,targetduration:i}=t,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&s||e;(o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==r?r:n*i);const h=i;return l+Math.min(1*this.stallCount,h)}get liveSyncPosition(){const t=this.estimateLiveEdge(),e=this.targetLatency,s=this.levelDetails;if(null===t||null===e||null===s)return null;const i=s.edge,r=t-e-this.edgeStalled,n=i-s.totalduration,a=i-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(n,r),a)}get drift(){const{levelDetails:t}=this;return null===t?1:t.drift}get edgeStalled(){const{levelDetails:t}=this;if(null===t)return 0;const e=3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}get forwardBufferLength(){const{media:t,levelDetails:e}=this;if(!t||!e)return 0;const s=t.buffered.length;return(s?t.buffered.end(s-1):e.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(w.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(w.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(w.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(w.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(w.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(w.ERROR,this.onError,this)}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}onLevelUpdated(t,{details:e}){this.levelDetails=e,e.advanced&&this.timeupdate(),!e.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(t,e){var s;e.details===P.BUFFER_STALLED_ERROR&&(this.stallCount++,null!=(s=this.levelDetails)&&s.live&&N.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:t,levelDetails:e}=this;if(!t||!e)return;this.currentTime=t.currentTime;const s=this.computeLatency();if(null===s)return;this._latency=s;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:r}=this.config;if(!i||1===r||!e.live)return;const n=this.targetLatency;if(null===n)return;const a=s-n;if(a<Math.min(this.maxLatency,n+e.targetduration)&&a>.05&&this.forwardBufferLength>1){const e=Math.min(2,Math.max(1,r)),s=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20;t.playbackRate=Math.min(e,Math.max(1,s))}else 1!==t.playbackRate&&0!==t.playbackRate&&(t.playbackRate=1)}estimateLiveEdge(){const{levelDetails:t}=this;return null===t?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return null===t?null:t-this.currentTime}}const is=["NONE","TYPE-0","TYPE-1",null];const rs=["SDR","PQ","HLG"];var ns="",as="YES",os="v2";function ls(t){const{canSkipUntil:e,canSkipDateRanges:s,age:i}=t;return e&&i<e/2?s?os:as:ns}class hs{constructor(t,e,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=e,this.skip=s}addDirectives(t){const e=new self.URL(t);return void 0!==this.msn&&e.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&e.searchParams.set("_HLS_part",this.part.toString()),this.skip&&e.searchParams.set("_HLS_skip",this.skip),e.href}}class ds{constructor(t){this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[t.url],this._attrs=[t.attrs],this.bitrate=t.bitrate,t.details&&(this.details=t.details),this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.frameRate=t.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=t.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,this.codecSet=[t.videoCodec,t.audioCodec].filter((t=>!!t)).map((t=>t.substring(0,4))).join(","),this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.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(t){return cs(this._audioGroups,t)}hasSubtitleGroup(t){return cs(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,e){if(e)if("audio"===t){let t=this._audioGroups;t||(t=this._audioGroups=[]),-1===t.indexOf(e)&&t.push(e)}else if("text"===t){let t=this._subtitleGroups;t||(t=this._subtitleGroups=[]),-1===t.indexOf(e)&&t.push(e)}}get urlId(){return 0}set urlId(t){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var t;return null==(t=this.audioGroups)?void 0:t[0]}get textGroupId(){var t;return null==(t=this.subtitleGroups)?void 0:t[0]}addFallback(){}}function cs(t,e){return!(!e||!t)&&-1!==t.indexOf(e)}function us(t,e){const s=e.startPTS;if(D(s)){let i,r=0;e.sn>t.sn?(r=s-t.start,i=t):(r=t.start-s,i=e),i.duration!==r&&(i.duration=r)}else if(e.sn>t.sn){t.cc===e.cc&&t.minEndPTS?e.start=t.start+(t.minEndPTS-t.start):e.start=t.start+t.duration}else e.start=Math.max(t.start-e.duration,0)}function fs(t,e,s,i,r,n){i-s<=0&&(N.warn("Fragment should have a positive duration",e),i=s+e.duration,n=r+e.duration);let a=s,o=i;const l=e.startPTS,h=e.endPTS;if(D(l)){const t=Math.abs(l-s);D(e.deltaPTS)?e.deltaPTS=Math.max(t,e.deltaPTS):e.deltaPTS=t,a=Math.max(s,l),s=Math.min(s,l),r=Math.min(r,e.startDTS),o=Math.min(i,h),i=Math.max(i,h),n=Math.max(n,e.endDTS)}const d=s-e.start;0!==e.start&&(e.start=s),e.duration=i-e.start,e.startPTS=s,e.maxStartPTS=a,e.startDTS=r,e.endPTS=i,e.minEndPTS=o,e.endDTS=n;const c=e.sn;if(!t||c<t.startSN||c>t.endSN)return 0;let u;const f=c-t.startSN,g=t.fragments;for(g[f]=e,u=f;u>0;u--)us(g[u],g[u-1]);for(u=f;u<g.length-1;u++)us(g[u],g[u+1]);return t.fragmentHint&&us(g[g.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,d}function gs(t,e){let s=null;const i=t.fragments;for(let t=i.length-1;t>=0;t--){const e=i[t].initSegment;if(e){s=e;break}}t.fragmentHint&&delete t.fragmentHint.endPTS;let r,n=0;if(function(t,e,s){const i=e.skippedSegments,r=Math.max(t.startSN,e.startSN)-e.startSN,n=(t.fragmentHint?1:0)+(i?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,a=e.startSN-t.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments;for(let t=r;t<=n;t++){const r=l[a+t];let n=o[t];i&&!n&&t<i&&(n=e.fragments[t]=r),r&&n&&s(r,n)}}(t,e,((t,i)=>{t.relurl&&(n=t.cc-i.cc),D(t.startPTS)&&D(t.endPTS)&&(i.start=i.startPTS=t.startPTS,i.startDTS=t.startDTS,i.maxStartPTS=t.maxStartPTS,i.endPTS=t.endPTS,i.endDTS=t.endDTS,i.minEndPTS=t.minEndPTS,i.duration=t.endPTS-t.startPTS,i.duration&&(r=i),e.PTSKnown=e.alignedSliding=!0),i.elementaryStreams=t.elementaryStreams,i.loader=t.loader,i.stats=t.stats,t.initSegment&&(i.initSegment=t.initSegment,s=t.initSegment)})),s){(e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments).forEach((t=>{var e;!t||t.initSegment&&t.initSegment.relurl!==(null==(e=s)?void 0:e.relurl)||(t.initSegment=s)}))}if(e.skippedSegments)if(e.deltaUpdateFailed=e.fragments.some((t=>!t)),e.deltaUpdateFailed){N.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let t=e.skippedSegments;t--;)e.fragments.shift();e.startSN=e.fragments[0].sn,e.startCC=e.fragments[0].cc}else e.canSkipDateRanges&&(e.dateRanges=function(t,e,s){const i=k({},t);s&&s.forEach((t=>{delete i[t]}));return Object.keys(e).forEach((t=>{const s=new K(e[t].attr,i[t]);s.isValid?i[t]=s:N.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(e[t].attr)}"`)})),i}(t.dateRanges,e.dateRanges,e.recentlyRemovedDateranges));const a=e.fragments;if(n){N.warn("discontinuity sliding from playlist, take drift into account");for(let t=0;t<a.length;t++)a[t].cc+=n}e.skippedSegments&&(e.startCC=e.fragments[0].cc),function(t,e,s){if(t&&e){let i=0;for(let r=0,n=t.length;r<=n;r++){const n=t[r],a=e[r+i];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?s(n,a):i--}}}(t.partList,e.partList,((t,e)=>{e.elementaryStreams=t.elementaryStreams,e.stats=t.stats})),r?fs(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS):ms(t,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;const o=e.advancedDateTime;if(e.advanced&&o){const t=e.edge;e.driftStart||(e.driftStartTime=o,e.driftStart=t),e.driftEndTime=o,e.driftEnd=t}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime}function ms(t,e){const s=e.startSN+e.skippedSegments-t.startSN,i=t.fragments;s<0||s>=i.length||ps(e,i[s].start)}function ps(t,e){if(e){const s=t.fragments;for(let i=t.skippedSegments;i<s.length;i++)s[i].start+=e;t.fragmentHint&&(t.fragmentHint.start+=e)}}function ys(t,e,s){var i;return null!=t&&t.details?vs(null==(i=t.details)?void 0:i.partList,e,s):null}function vs(t,e,s){if(t)for(let i=t.length;i--;){const r=t[i];if(r.index===s&&r.fragment.sn===e)return r}return null}function Ts(t){t.forEach(((t,e)=>{const{details:s}=t;null!=s&&s.fragments&&s.fragments.forEach((t=>{t.level=e}))}))}function Es(t){switch(t.details){case P.FRAG_LOAD_TIMEOUT:case P.KEY_LOAD_TIMEOUT:case P.LEVEL_LOAD_TIMEOUT:case P.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Ss(t,e){const s=Es(e);return t.default[(s?"timeout":"error")+"Retry"]}function Ls(t,e){const s="linear"===t.backoff?1:Math.pow(2,e);return Math.min(s*t.retryDelayMs,t.maxRetryDelayMs)}function As(t){return A(A({},t),{errorRetry:null,timeoutRetry:null})}function Rs(t,e,s,i){if(!t)return!1;const r=null==i?void 0:i.code,n=e<t.maxNumRetry&&(function(t){return 0===t&&!1===navigator.onLine||!!t&&(t<400||t>499)}(r)||!!s);return t.shouldRetry?t.shouldRetry(t,e,s,i,n):n}const bs=function(t,e){let s=0,i=t.length-1,r=null,n=null;for(;s<=i;){r=(s+i)/2|0,n=t[r];const a=e(n);if(a>0)s=r+1;else{if(!(a<0))return n;i=r-1}}return null};function ks(t,e,s=0,i=0,r=.005){let n=null;if(t){n=e[t.sn-e[0].sn+1]||null;const i=t.endDTS-s;i>0&&i<15e-7&&(s+=15e-7)}else 0===s&&0===e[0].start&&(n=e[0]);if(n&&((!t||t.level===n.level)&&0===Ds(s,i,n)||function(t,e,s){if(e&&0===e.start&&e.level<t.level&&(e.endPTS||0)>0){const i=e.tagList.reduce(((t,e)=>("INF"===e[0]&&(t+=parseFloat(e[1])),t)),s);return t.start<=i}return!1}(n,t,Math.min(r,i))))return n;const a=bs(e,Ds.bind(null,s,i));return!a||a===t&&n?n:a}function Ds(t=0,e=0,s){if(s.start<=t&&s.start+s.duration>t)return 0;const i=Math.min(e,s.duration+(s.deltaPTS?s.deltaPTS:0));return s.start+s.duration-i<=t?1:s.start-i>t&&s.start?-1:0}function _s(t,e,s){const i=1e3*Math.min(e,s.duration+(s.deltaPTS?s.deltaPTS:0));return(s.endProgramDateTime||0)-i>t}var Is=0,ws=2,Cs=3,Ps=5,xs=0,Fs=1,Ms=2;class Os{constructor(t,e){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=N.log.bind(N,`${e}:`),this.warn=N.warn.bind(N,`${e}:`),this.hls=t}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,e,s){const i=null==e?void 0:e.renditionReports;if(i){let r=-1;for(let s=0;s<i.length;s++){const n=i[s];let a;try{a=new self.URL(n.URI,e.url).href}catch(t){N.warn(`Could not construct new URL for Rendition Report: ${t}`),a=n.URI||""}if(a===t){r=s;break}a===t.substring(0,a.length)&&(r=s)}if(-1!==r){const t=i[r],n=parseInt(t["LAST-MSN"])||(null==e?void 0:e.lastPartSn);let a=parseInt(t["LAST-PART"])||(null==e?void 0:e.lastPartIndex);if(this.hls.config.lowLatencyMode){const t=Math.min(e.age-e.partTarget,e.targetduration);a>=0&&t>e.partTarget&&(a+=1)}const o=s&&ls(s);return new hs(n,a>=0?a:void 0,o)}}}loadPlaylist(t){-1===this.requestScheduled&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}shouldReloadPlaylist(t){return-1===this.timer&&-1===this.requestScheduled&&this.shouldLoadPlaylist(t)}playlistLoaded(t,e,s){const{details:i,stats:r}=e,n=self.performance.now(),a=r.loading.first?Math.max(0,n-r.loading.first):0;if(i.advancedDateTime=Date.now()-a,i.live||null!=s&&s.live){if(i.reloaded(s),s&&this.log(`live playlist ${t} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED"}`),s&&i.fragments.length>0&&gs(s,i),!this.canLoad||!i.live)return;let a,o,l;if(i.canBlockReload&&i.endSN&&i.advanced){const t=this.hls.config.lowLatencyMode,r=i.lastPartSn,n=i.endSN,h=i.lastPartIndex,d=r===n;-1!==h?(o=d?n+1:r,l=d?t?0:h:h+1):o=n+1;const c=i.age,u=c+i.ageHeader;let f=Math.min(u-i.partTarget,1.5*i.targetduration);if(f>0){if(s&&f>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${f} with playlist age: ${i.age}`),f=0;else{const t=Math.floor(f/i.targetduration);if(o+=t,void 0!==l){l+=Math.round(f%i.targetduration/i.partTarget)}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${c.toFixed(2)}s goal: ${f} skip sn ${t} to part ${l}`)}i.tuneInGoal=f}if(a=this.getDeliveryDirectives(i,e.deliveryDirectives,o,l),t||!d)return void this.loadPlaylist(a)}else(i.canBlockReload||i.canSkipUntil)&&(a=this.getDeliveryDirectives(i,e.deliveryDirectives,o,l));const h=this.hls.mainForwardBufferInfo,d=h?h.end-h.len:0,c=function(t,e=1/0){let s=1e3*t.targetduration;if(t.updated){const i=t.fragments,r=4;if(i.length&&s*r>e){const t=1e3*i[i.length-1].duration;t<s&&(s=t)}}else s/=2;return Math.round(s)}(i,1e3*(i.edge-d));i.updated&&n>this.requestScheduled+c&&(this.requestScheduled=r.loading.start),void 0!==o&&i.canBlockReload?this.requestScheduled=r.loading.first+c-(1e3*i.partTarget||1e3):-1===this.requestScheduled||this.requestScheduled+c<n?this.requestScheduled=n:this.requestScheduled-n<=0&&(this.requestScheduled+=c);let u=this.requestScheduled-n;u=Math.max(0,u),this.log(`reload live playlist ${t} in ${Math.round(u)} ms`),this.timer=self.setTimeout((()=>this.loadPlaylist(a)),u)}else this.clearTimer()}getDeliveryDirectives(t,e,s,i){let r=ls(t);return null!=e&&e.skip&&t.deltaUpdateFailed&&(s=e.msn,i=e.part,r=ns),new hs(s,i,r)}checkRetry(t){const e=t.details,s=Es(t),i=t.errorAction,{action:r,retryCount:n=0,retryConfig:a}=i||{},o=!!i&&!!a&&(r===Ps||!i.resolved&&r===ws);if(o){var l;if(this.requestScheduled=-1,n>=a.maxNumRetry)return!1;if(s&&null!=(l=t.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{const t=Ls(a,n);this.timer=self.setTimeout((()=>this.loadPlaylist()),t),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" in ${t}ms`)}t.levelRetry=!0,i.resolved=!0}return o}}class Ns{constructor(t,e=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=s}sample(t,e){const s=Math.pow(this.alpha_,t);this.estimate_=e*(1-s)+s*this.estimate_,this.totalWeight_+=t}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}}class Us{constructor(t,e,s,i=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 Ns(t),this.fast_=new Ns(e),this.defaultTTFB_=i,this.ttfb_=new Ns(t)}update(t,e){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==t&&(this.slow_=new Ns(t,s.getEstimate(),s.getTotalWeight())),i.halfLife!==e&&(this.fast_=new Ns(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.ttfb_=new Ns(t,r.getEstimate(),r.getTotalWeight()))}sample(t,e){const s=(t=Math.max(t,this.minDelayMs_))/1e3,i=8*e/s;this.fast_.sample(s,i),this.slow_.sample(s,i)}sampleTTFB(t){const e=t/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(s,Math.max(t,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}destroy(){}}const Bs={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},$s={};function Gs(t,e,s,i,r,n){const a=t.audioCodec?t.audioGroups:null,o=null==n?void 0:n.audioCodec,l=null==n?void 0:n.channels,h=l?parseInt(l):o?1/0:2;let d=null;if(null!=a&&a.length)try{d=1===a.length&&a[0]?e.groups[a[0]].channels:a.reduce(((t,s)=>{if(s){const i=e.groups[s];if(!i)throw new Error(`Audio track group ${s} not found`);Object.keys(i.channels).forEach((e=>{t[e]=(t[e]||0)+i.channels[e]}))}return t}),{2:0})}catch(t){return!0}return void 0!==t.videoCodec&&(t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(i,30)||"SDR"!==t.videoRange&&t.videoRange!==s||t.bitrate>Math.max(r,8e6))||!!d&&D(h)&&Object.keys(d).some((t=>parseInt(t)>h))}function Ks(t,e,s){const i=t.videoCodec,r=t.audioCodec;if(!i||!r||!s)return Promise.resolve(Bs);const n={width:t.width,height:t.height,bitrate:Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)),framerate:t.frameRate||30},a=t.videoRange;"SDR"!==a&&(n.transferFunction=a.toLowerCase());const o=i.split(",").map((t=>({type:"media-source",video:A(A({},n),{},{contentType:fe(t,"video")})})));return r&&t.audioGroups&&t.audioGroups.forEach((t=>{var s;t&&(null==(s=e.groups[t])||s.tracks.forEach((e=>{if(e.groupId===t){const t=e.channels||"",s=parseFloat(t);D(s)&&s>2&&o.push.apply(o,r.split(",").map((t=>({type:"media-source",audio:{contentType:fe(t,"audio"),channels:""+s}}))))}})))})),Promise.all(o.map((t=>{const e=function(t){const{audio:e,video:s}=t,i=s||e;if(i){const t=i.contentType.split('"')[1];if(s)return`r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${t}_${Math.ceil(s.bitrate/1e5)}`;if(e)return`c${e.channels}${e.spatialRendering?"s":"n"}_${t}`}return""}(t);return $s[e]||($s[e]=s.decodingInfo(t))}))).then((t=>({supported:!t.some((t=>!t.supported)),configurations:o,decodingInfoResults:t}))).catch((t=>({supported:!1,configurations:o,decodingInfoResults:[],error:t})))}function Hs(t,e){let s=!1,i=[];return t&&(s="SDR"!==t,i=[t]),e&&(i=e.allowedVideoRanges||rs.slice(0),s=void 0!==e.preferHDR?e.preferHDR:function(){if("function"==typeof matchMedia){const t=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(t.media!==e.media)return!0===t.matches}return!1}(),i=s?i.filter((t=>"SDR"!==t)):["SDR"]),{preferHDR:s,allowedVideoRanges:i}}function Vs(t,e){N.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function Ys(t,e,s){if("attrs"in t){const s=e.indexOf(t);if(-1!==s)return s}for(let i=0;i<e.length;i++){if(Ws(t,e[i],s))return i}return-1}function Ws(t,e,s){const{groupId:i,name:r,lang:n,assocLang:a,characteristics:o,default:l}=t,h=t.forced;return(void 0===i||e.groupId===i)&&(void 0===r||e.name===r)&&(void 0===n||e.lang===n)&&(void 0===n||e.assocLang===a)&&(void 0===l||e.default===l)&&(void 0===h||e.forced===h)&&(void 0===o||function(t,e=""){const s=t.split(","),i=e.split(",");return s.length===i.length&&!s.some((t=>-1===i.indexOf(t)))}(o,e.characteristics))&&(void 0===s||s(t,e))}function js(t,e){const{audioCodec:s,channels:i}=t;return!(void 0!==s&&(e.audioCodec||"").substring(0,4)!==s.substring(0,4)||void 0!==i&&i!==(e.channels||"2"))}function qs(t,e,s){for(let i=e;i;i--)if(s(t[i]))return i;for(let i=e+1;i<t.length;i++)if(s(t[i]))return i;return-1}class Xs{constructor(){this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(t){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}var zs="NOT_LOADED",Qs="APPENDING",Js="PARTIAL",Zs="OK";class ti{constructor(t){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=t,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(w.BUFFER_APPENDED,this.onBufferAppended,this),t.on(w.FRAG_BUFFERED,this.onFragBuffered,this),t.on(w.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:t}=this;t.off(w.BUFFER_APPENDED,this.onBufferAppended,this),t.off(w.FRAG_BUFFERED,this.onFragBuffered,this),t.off(w.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(t,e){const s=this.activePartLists[e];if(s)for(let e=s.length;e--;){const i=s[e];if(!i)break;const r=i.end;if(i.start<=t&&null!==r&&t<=r)return i}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){const{fragments:s}=this,i=Object.keys(s);for(let r=i.length;r--;){const n=s[i[r]];if((null==n?void 0:n.body.type)===e&&n.buffered){const e=n.body;if(e.start<=t&&t<=e.end)return e}}return null}detectEvictedFragments(t,e,s,i){this.timeRanges&&(this.timeRanges[t]=e);const r=(null==i?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach((i=>{const n=this.fragments[i];if(!n)return;if(r>=n.body.sn)return;if(!n.buffered&&!n.loaded)return void(n.body.type===s&&this.removeFragment(n.body));const a=n.range[t];a&&a.time.some((t=>{const s=!this.isTimeBuffered(t.startPTS,t.endPTS,e);return s&&this.removeFragment(n.body),s}))}))}detectPartialFragments(t){const e=this.timeRanges,{frag:s,part:i}=t;if(!e||"initSegment"===s.sn)return;const r=si(s),n=this.fragments[r];if(!n||n.buffered&&s.gap)return;const a=!s.relurl;if(Object.keys(e).forEach((t=>{const r=s.elementaryStreams[t];if(!r)return;const o=e[t],l=a||!0===r.partial;n.range[t]=this.getBufferedTimes(s,i,l,o)})),n.loaded=null,Object.keys(n.range).length){n.buffered=!0;(n.body.endList=s.endList||n.body.endList)&&(this.endListFragments[n.body.type]=n),ei(n)||this.removeParts(s.sn-1,s.type)}else this.removeFragment(n.body)}removeParts(t,e){const s=this.activePartLists[e];s&&(this.activePartLists[e]=s.filter((e=>e.fragment.sn>=t)))}fragBuffered(t,e){const s=si(t);let i=this.fragments[s];!i&&e&&(i=this.fragments[s]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,i.buffered=!0)}getBufferedTimes(t,e,s,i){const r={time:[],partial:s},n=t.start,a=t.end,o=t.minEndPTS||a,l=t.maxStartPTS||n;for(let t=0;t<i.length;t++){const e=i.start(t)-this.bufferPadding,s=i.end(t)+this.bufferPadding;if(l>=e&&o<=s){r.time.push({startPTS:Math.max(n,i.start(t)),endPTS:Math.min(a,i.end(t))});break}if(n<s&&a>e){const e=Math.max(n,i.start(t)),s=Math.min(a,i.end(t));s>e&&(r.partial=!0,r.time.push({startPTS:e,endPTS:s}))}else if(a<=e)break}return r}getPartialFragment(t){let e,s,i,r=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach((l=>{const h=o[l];h&&ei(h)&&(s=h.body.start-a,i=h.body.end+a,t>=s&&t<=i&&(e=Math.min(t-s,i-t),n<=e&&(r=h.body,n=e)))})),r}isEndListAppended(t){const e=this.endListFragments[t];return void 0!==e&&(e.buffered||ei(e))}getState(t){const e=si(t),s=this.fragments[e];return s?s.buffered?ei(s)?Js:Zs:Qs:zs}isTimeBuffered(t,e,s){let i,r;for(let n=0;n<s.length;n++){if(i=s.start(n)-this.bufferPadding,r=s.end(n)+this.bufferPadding,t>=i&&e<=r)return!0;if(e<=i)return!1}return!1}onFragLoaded(t,e){const{frag:s,part:i}=e;if("initSegment"===s.sn||s.bitrateTest)return;const r=i?null:e,n=si(s);this.fragments[n]={body:s,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:s,part:i,timeRanges:r}=e;if("initSegment"===s.sn)return;const n=s.type;if(i){let t=this.activePartLists[n];t||(this.activePartLists[n]=t=[]),t.push(i)}this.timeRanges=r,Object.keys(r).forEach((t=>{const e=r[t];this.detectEvictedFragments(t,e,n,i)}))}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=si(t);return!!this.fragments[e]}hasParts(t){var e;return!(null==(e=this.activePartLists[t])||!e.length)}removeFragmentsInRange(t,e,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach((n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==s||i&&!o.gap||o.start<e&&o.end>t&&(a.buffered||r)&&this.removeFragment(o)}))}removeFragment(t){const e=si(t);t.stats.loaded=0,t.clearElementaryStreamInfo();const s=this.activePartLists[t.type];if(s){const e=t.sn;this.activePartLists[t.type]=s.filter((t=>t.fragment.sn!==e))}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}}function ei(t){var e,s,i;return t.buffered&&(t.body.gap||(null==(e=t.range.video)?void 0:e.partial)||(null==(s=t.range.audio)?void 0:s.partial)||(null==(i=t.range.audiovideo)?void 0:i.partial))}function si(t){return`${t.type}_${t.level}_${t.sn}`}const ii={length:0,start:()=>0,end:()=>0};class ri{static isBuffered(t,e){try{if(t){const s=ri.getBuffered(t);for(let t=0;t<s.length;t++)if(e>=s.start(t)&&e<=s.end(t))return!0}}catch(t){}return!1}static bufferInfo(t,e,s){try{if(t){const i=ri.getBuffered(t),r=[];let n;for(n=0;n<i.length;n++)r.push({start:i.start(n),end:i.end(n)});return this.bufferedInfo(r,e,s)}}catch(t){}return{len:0,start:e,end:e,nextStart:void 0}}static bufferedInfo(t,e,s){e=Math.max(0,e),t.sort((function(t,e){const s=t.start-e.start;return s||e.end-t.end}));let i=[];if(s)for(let e=0;e<t.length;e++){const r=i.length;if(r){const n=i[r-1].end;t[e].start-n<s?t[e].end>n&&(i[r-1].end=t[e].end):i.push(t[e])}else i.push(t[e])}else i=t;let r,n=0,a=e,o=e;for(let t=0;t<i.length;t++){const l=i[t].start,h=i[t].end;if(e+s>=l&&e<h)a=l,o=h,n=o-e;else if(e+s<l){r=l;break}}return{len:n,start:a||0,end:o||0,nextStart:r}}static getBuffered(t){try{return t.buffered}catch(t){return N.log("failed to get media.buffered",t),ii}}}class ni{constructor(t,e,s,i=0,r=-1,n=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=t,this.sn=e,this.id=s,this.size=i,this.part=r,this.partial=n}}function ai(t,e){for(let i=0,r=t.length;i<r;i++){var s;if((null==(s=t[i])?void 0:s.cc)===e)return t[i]}return null}function oi(t,e){if(t){const s=t.start+e;t.start=t.startPTS=s,t.endPTS=s+t.duration}}function li(t,e){const s=e.fragments;for(let e=0,i=s.length;e<i;e++)oi(s[e],t);e.fragmentHint&&oi(e.fragmentHint,t),e.alignedSliding=!0}function hi(t,e,s){e&&(!function(t,e,s){if(function(t,e,s){return!(!e||!(s.endCC>s.startCC||t&&t.cc<s.startCC))}(t,s,e)){const t=function(t,e){const s=t.fragments,i=e.fragments;if(!i.length||!s.length)return void N.log("No fragments to align");const r=ai(s,i[0].cc);if(r&&(!r||r.startPTS))return r;N.log("No frag in previous level to align on")}(s,e);t&&D(t.start)&&(N.log(`Adjusting PTS using last level due to CC increase within current level ${e.url}`),li(t.start,e))}}(t,s,e),!s.alignedSliding&&e&&di(s,e),s.alignedSliding||!e||s.skippedSegments||ms(e,s))}function di(t,e){if(!t.hasProgramDateTime||!e.hasProgramDateTime)return;const s=t.fragments,i=e.fragments;if(!s.length||!i.length)return;let r,n;const a=Math.min(e.endCC,t.endCC);e.startCC<a&&t.startCC<a&&(r=ai(i,a),n=ai(s,a)),r&&n||(r=i[Math.floor(i.length/2)],n=ai(s,r.cc)||s[Math.floor(s.length/2)]);const o=r.programDateTime,l=n.programDateTime;if(!o||!l)return;li((l-o)/1e3-(n.start-r.start),t)}const ci=Math.pow(2,17);class ui{constructor(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(t,e){const s=t.url;if(!s)return Promise.reject(new mi({type:C.NETWORK_ERROR,details:P.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error("Fragment does not have a "+(s?"part list":"url")),networkDetails:null}));this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),t.gap){if(t.tagList.some((t=>"GAP"===t[0])))return void o(gi(t));t.gap=!1}const l=this.loader=t.loader=r?new r(i):new n(i),h=fi(t),d=As(i.fragLoadPolicy.default),c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:ci};t.stats=l.stats,l.load(h,c,{onSuccess:(e,s,i,r)=>{this.resetLoader(t,l);let n=e.data;i.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),a({frag:t,part:null,payload:n,networkDetails:r})},onError:(e,i,r,n)=>{this.resetLoader(t,l),o(new mi({type:C.NETWORK_ERROR,details:P.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:A({url:s,data:void 0},e),error:new Error(`HTTP Error ${e.code} ${e.text}`),networkDetails:r,stats:n}))},onAbort:(e,s,i)=>{this.resetLoader(t,l),o(new mi({type:C.NETWORK_ERROR,details:P.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:i,stats:e}))},onTimeout:(e,s,i)=>{this.resetLoader(t,l),o(new mi({type:C.NETWORK_ERROR,details:P.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:i,stats:e}))},onProgress:(s,i,r,n)=>{e&&e({frag:t,part:null,payload:r,networkDetails:n})}})}))}loadPart(t,e,s){this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap)return void o(gi(t,e));const l=this.loader=t.loader=r?new r(i):new n(i),h=fi(t,e),d=As(i.fragLoadPolicy.default),c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:ci};e.stats=l.stats,l.load(h,c,{onSuccess:(i,r,n,o)=>{this.resetLoader(t,l),this.updateStatsFromPart(t,e);const h={frag:t,part:e,payload:i.data,networkDetails:o};s(h),a(h)},onError:(s,i,r,n)=>{this.resetLoader(t,l),o(new mi({type:C.NETWORK_ERROR,details:P.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:A({url:h.url,data:void 0},s),error:new Error(`HTTP Error ${s.code} ${s.text}`),networkDetails:r,stats:n}))},onAbort:(s,i,r)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,l),o(new mi({type:C.NETWORK_ERROR,details:P.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:r,stats:s}))},onTimeout:(s,i,r)=>{this.resetLoader(t,l),o(new mi({type:C.NETWORK_ERROR,details:P.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:r,stats:s}))}})}))}updateStatsFromPart(t,e){const s=t.stats,i=e.stats,r=i.total;if(s.loaded+=i.loaded,r){const i=Math.round(t.duration/e.duration),n=Math.min(Math.round(s.loaded/r),i),a=(i-n)*Math.round(s.loaded/n);s.total=s.loaded+a}else s.total=Math.max(s.loaded,s.total);const n=s.loading,a=i.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()}}function fi(t,e=null){const s=e||t,i={frag:t,part:e,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},r=s.byteRangeStartOffset,n=s.byteRangeEndOffset;if(D(r)&&D(n)){var a;let e=r,s=n;if("initSegment"===t.sn&&"AES-128"===(null==(a=t.decryptdata)?void 0:a.method)){const t=n-r;t%16&&(s=n+(16-t%16)),0!==r&&(i.resetIV=!0,e=r-16)}i.rangeStart=e,i.rangeEnd=s}return i}function gi(t,e){const s=new Error(`GAP ${t.gap?"tag":"attribute"} found`),i={type:C.MEDIA_ERROR,details:P.FRAG_GAP,fatal:!1,frag:t,error:s,networkDetails:null};return e&&(i.part=e),(e||t).stats.aborted=!0,new mi(i)}class mi extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class pi{constructor(t,e){this.subtle=void 0,this.aesIV=void 0,this.subtle=t,this.aesIV=e}decrypt(t,e){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t)}}class yi{constructor(t,e){this.subtle=void 0,this.key=void 0,this.subtle=t,this.key=e}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}class vi{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(t){const e=new DataView(t),s=new Uint32Array(4);for(let t=0;t<4;t++)s[t]=e.getUint32(4*t);return s}initTable(){const t=this.sBox,e=this.invSBox,s=this.subMix,i=s[0],r=s[1],n=s[2],a=s[3],o=this.invSubMix,l=o[0],h=o[1],d=o[2],c=o[3],u=new Uint32Array(256);let f=0,g=0,m=0;for(m=0;m<256;m++)u[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){let s=g^g<<1^g<<2^g<<3^g<<4;s=s>>>8^255&s^99,t[f]=s,e[s]=f;const o=u[f],m=u[o],p=u[m];let y=257*u[s]^16843008*s;i[f]=y<<24|y>>>8,r[f]=y<<16|y>>>16,n[f]=y<<8|y>>>24,a[f]=y,y=16843009*p^65537*m^257*o^16843008*f,l[s]=y<<24|y>>>8,h[s]=y<<16|y>>>16,d[s]=y<<8|y>>>24,c[s]=y,f?(f=o^u[u[u[p^o]]],g^=u[u[g]]):f=g=1}}expandKey(t){const e=this.uint8ArrayToUint32Array_(t);let s=!0,i=0;for(;i<e.length&&s;)s=e[i]===this.key[i],i++;if(s)return;this.key=e;const r=this.keySize=e.length;if(4!==r&&6!==r&&8!==r)throw new Error("Invalid aes key size="+r);const n=this.ksRows=4*(r+6+1);let a,o;const l=this.keySchedule=new Uint32Array(n),h=this.invKeySchedule=new Uint32Array(n),d=this.sBox,c=this.rcon,u=this.invSubMix,f=u[0],g=u[1],m=u[2],p=u[3];let y,v;for(a=0;a<n;a++)a<r?y=l[a]=e[a]:(v=y,a%r==0?(v=v<<8|v>>>24,v=d[v>>>24]<<24|d[v>>>16&255]<<16|d[v>>>8&255]<<8|d[255&v],v^=c[a/r|0]<<24):r>6&&a%r==4&&(v=d[v>>>24]<<24|d[v>>>16&255]<<16|d[v>>>8&255]<<8|d[255&v]),l[a]=y=(l[a-r]^v)>>>0);for(o=0;o<n;o++)a=n-o,v=3&o?l[a]:l[a-4],h[o]=o<4||a<=4?v:f[d[v>>>24]]^g[d[v>>>16&255]]^m[d[v>>>8&255]]^p[d[255&v]],h[o]=h[o]>>>0}networkToHostOrderSwap(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24}decrypt(t,e,s){const i=this.keySize+6,r=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],h=a[2],d=a[3],c=this.uint8ArrayToUint32Array_(s);let u=c[0],f=c[1],g=c[2],m=c[3];const p=new Int32Array(t),y=new Int32Array(p.length);let v,T,E,S,L,A,R,b,k,D,_,I,w,C;const P=this.networkToHostOrderSwap;for(;e<p.length;){for(k=P(p[e]),D=P(p[e+1]),_=P(p[e+2]),I=P(p[e+3]),L=k^r[0],A=I^r[1],R=_^r[2],b=D^r[3],w=4,C=1;C<i;C++)v=o[L>>>24]^l[A>>16&255]^h[R>>8&255]^d[255&b]^r[w],T=o[A>>>24]^l[R>>16&255]^h[b>>8&255]^d[255&L]^r[w+1],E=o[R>>>24]^l[b>>16&255]^h[L>>8&255]^d[255&A]^r[w+2],S=o[b>>>24]^l[L>>16&255]^h[A>>8&255]^d[255&R]^r[w+3],L=v,A=T,R=E,b=S,w+=4;v=n[L>>>24]<<24^n[A>>16&255]<<16^n[R>>8&255]<<8^n[255&b]^r[w],T=n[A>>>24]<<24^n[R>>16&255]<<16^n[b>>8&255]<<8^n[255&L]^r[w+1],E=n[R>>>24]<<24^n[b>>16&255]<<16^n[L>>8&255]<<8^n[255&A]^r[w+2],S=n[b>>>24]<<24^n[L>>16&255]<<16^n[A>>8&255]<<8^n[255&R]^r[w+3],y[e]=P(v^u),y[e+1]=P(S^f),y[e+2]=P(E^g),y[e+3]=P(T^m),u=k,f=D,g=_,m=I,e+=4}return y.buffer}}class Ti{constructor(t,{removePKCS7Padding:e=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.useSoftware=t.enableSoftwareAES,this.removePKCS7Padding=e,e)try{const t=self.crypto;t&&(this.subtle=t.subtle||t.webkitSubtle)}catch(t){}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(){const{currentResult:t,remainderData:e}=this;if(!t||e)return this.reset(),null;const s=new Uint8Array(t);return this.reset(),this.removePKCS7Padding?function(t){const e=t.byteLength,s=e&&new DataView(t.buffer).getUint8(e-1);return s?ut(t,0,e-s):t}(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,e,s){return this.useSoftware?new Promise(((i,r)=>{this.softwareDecrypt(new Uint8Array(t),e,s);const n=this.flush();n?i(n.buffer):r(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(t),e,s)}softwareDecrypt(t,e,s){const{currentIV:i,currentResult:r,remainderData:n}=this;this.logOnce("JS AES decrypt"),n&&(t=Xt(n,t),this.remainderData=null);const a=this.getValidChunk(t);if(!a.length)return null;i&&(s=i);let o=this.softwareDecrypter;o||(o=this.softwareDecrypter=new vi),o.expandKey(e);const l=r;return this.currentResult=o.decrypt(a.buffer,0,s),this.currentIV=ut(a,-16).buffer,l||null}webCryptoDecrypt(t,e,s){if(this.key!==e||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,e,s));this.key=e,this.fastAesKey=new yi(this.subtle,e)}return this.fastAesKey.expandKey().then((e=>{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new pi(this.subtle,new Uint8Array(s)).decrypt(t.buffer,e)})).catch((i=>(N.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${i.name}: ${i.message}`),this.onWebCryptoError(t,e,s))))}onWebCryptoError(t,e,s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,s);const i=this.flush();if(i)return i.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(t){let e=t;const s=t.length-t.length%16;return s!==t.length&&(e=ut(t,0,s),this.remainderData=ut(t,s)),e}logOnce(t){this.logEnabled&&(N.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const Ei=function(t){let e="";const s=t.length;for(let i=0;i<s;i++)e+=`[${t.start(i).toFixed(3)}-${t.end(i).toFixed(3)}]`;return e},Si="STOPPED",Li="IDLE",Ai="KEY_LOADING",Ri="FRAG_LOADING",bi="FRAG_LOADING_WAITING_RETRY",ki="WAITING_TRACK",Di="PARSING",_i="PARSED",Ii="ENDED",wi="ERROR",Ci="WAITING_INIT_PTS",Pi="WAITING_LEVEL";class xi extends Xs{constructor(t,e,s,i,r){super(),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=Si,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.loadedmetadata=!1,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.onvseeking=null,this.onvended=null,this.logPrefix="",this.log=void 0,this.warn=void 0,this.playlistType=r,this.logPrefix=i,this.log=N.log.bind(N,`${i}:`),this.warn=N.warn.bind(N,`${i}:`),this.hls=t,this.fragmentLoader=new ui(t.config),this.keyLoader=s,this.fragmentTracker=e,this.config=t.config,this.decrypter=new Ti(t.config),t.on(w.MANIFEST_LOADED,this.onManifestLoaded,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const t=this.fragCurrent;null!=t&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=Si}_streamEnded(t,e){if(e.live||t.nextStart||!t.end||!this.media)return!1;const s=e.partList;if(null!=s&&s.length){const t=s[s.length-1];return ri.isBuffered(this.media,t.start+t.duration/2)}const i=e.fragments[e.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(i)}getLevelDetails(){var t;if(this.levels&&null!==this.levelLastLoaded)return null==(t=this.levelLastLoaded)?void 0:t.details}onMediaAttached(t,e){const s=this.media=this.mediaBuffer=e.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),s.addEventListener("seeking",this.onvseeking),s.addEventListener("ended",this.onvended);const i=this.config;this.levels&&i.autoStartLoad&&this.state===Si&&this.startLoad(i.startPosition)}onMediaDetaching(){const t=this.media;null!=t&&t.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),t&&this.onvseeking&&this.onvended&&(t.removeEventListener("seeking",this.onvseeking),t.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.keyLoader&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}onMediaSeeking(){const{config:t,fragCurrent:e,media:s,mediaBuffer:i,state:r}=this,n=s?s.currentTime:0,a=ri.bufferInfo(i||s,n,t.maxBufferHole);if(this.log(`media seeking to ${D(n)?n.toFixed(3):n}, state: ${r}`),this.state===Ii)this.resetLoadingState();else if(e){const s=t.maxFragLookUpTolerance,i=e.start-s,r=e.start+e.duration+s;if(!a.len||r<a.start||i>a.end){const t=n>r;(n<i||t)&&(t&&e.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),e.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}s&&(this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0),this.lastCurrentTime=n),this.loadedmetadata||a.len||(this.nextLoadPosition=this.startPosition=n),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(t,e){this.startTimeOffset=e.startTimeOffset,this.initPTS=[]}onHandlerDestroying(){this.hls.off(w.MANIFEST_LOADED,this.onManifestLoaded,this),this.stopLoad(),super.onHandlerDestroying(),this.hls=null}onHandlerDestroyed(){this.state=Si,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(t,e,s){this._loadFragForPlayback(t,e,s)}_loadFragForPlayback(t,e,s){this._doFragLoad(t,e,s,(e=>{if(this.fragContextChanged(t))return this.warn(`Fragment ${t.sn}${e.part?" p: "+e.part.index:""} of level ${t.level} was dropped during download.`),void this.fragmentTracker.removeFragment(t);t.stats.chunkCount++,this._handleFragmentLoadProgress(e)})).then((e=>{if(!e)return;const s=this.state;this.fragContextChanged(t)?(s===Ri||!this.fragCurrent&&s===Di)&&(this.fragmentTracker.removeFragment(t),this.state=Li):("payload"in e&&(this.log(`Loaded fragment ${t.sn} of level ${t.level}`),this.hls.trigger(w.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e))})).catch((e=>{this.state!==Si&&this.state!==wi&&(this.warn(`Frag error: ${(null==e?void 0:e.message)||e}`),this.resetFragmentLoading(t))}))}clearTrackerIfNeeded(t){var e;const{fragmentTracker:s}=this;if(s.getState(t)===Qs){const e=t.type,i=this.getFwdBufferInfo(this.mediaBuffer,e),r=Math.max(t.duration,i?i.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?t.sn-n.sn:0)||this.reduceMaxBufferLength(r,t.duration))&&s.removeFragment(t)}else 0===(null==(e=this.mediaBuffer)?void 0:e.buffered.length)?s.removeAllFragments():s.hasParts(t.type)&&(s.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),s.getState(t)===Js&&s.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const e=t.fragments[t.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}flushMainBuffer(t,e,s=null){if(!(t-e))return;const i={startOffset:t,endOffset:e,type:s};this.hls.trigger(w.BUFFER_FLUSHING,i)}_loadInitSegment(t,e){this._doFragLoad(t,e).then((e=>{if(!e||this.fragContextChanged(t)||!this.levels)throw new Error("init load aborted");return e})).then((e=>{const{hls:s}=this,{payload:i}=e,r=t.decryptdata;if(i&&i.byteLength>0&&null!=r&&r.key&&r.iv&&"AES-128"===r.method){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer).catch((e=>{throw s.trigger(w.ERROR,{type:C.MEDIA_ERROR,details:P.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e})).then((i=>{const r=self.performance.now();return s.trigger(w.FRAG_DECRYPTED,{frag:t,payload:i,stats:{tstart:n,tdecrypt:r}}),e.payload=i,this.completeInitSegmentLoad(e)}))}return this.completeInitSegmentLoad(e)})).catch((e=>{this.state!==Si&&this.state!==wi&&(this.warn(e),this.resetFragmentLoading(t))}))}completeInitSegmentLoad(t){const{levels:e}=this;if(!e)throw new Error("init load aborted, missing levels");const s=t.frag.stats;this.state=Li,t.frag.data=new Uint8Array(t.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}fragContextChanged(t){const{fragCurrent:e}=this;return!t||!e||t.sn!==e.sn||t.level!==e.level}fragBufferedComplete(t,e){var s,i,r,n;const a=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.playlistType===Ne?"level":"track"} ${t.level} (frag:[${(null!=(s=t.startPTS)?s:NaN).toFixed(3)}-${(null!=(i=t.endPTS)?i:NaN).toFixed(3)}] > buffer:${a?Ei(ri.getBuffered(a)):"(detached)"})`),"initSegment"!==t.sn){var o;if(t.type!==Be){const e=t.elementaryStreams;if(!Object.keys(e).some((t=>!!e[t])))return void(this.state=Li)}const e=null==(o=this.levels)?void 0:o[t.level];null!=e&&e.fragmentError&&(this.log(`Resetting level fragment error count of ${e.fragmentError} on frag buffered`),e.fragmentError=0)}this.state=Li,a&&(!this.loadedmetadata&&t.type==Ne&&a.buffered.length&&(null==(r=this.fragCurrent)?void 0:r.sn)===(null==(n=this.fragPrevious)?void 0:n.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const{frag:s,part:i,partsLoaded:r}=t,n=!r||0===r.length||r.some((t=>!t)),a=new ni(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!n);e.flush(a)}_handleFragmentLoadProgress(t){}_doFragLoad(t,e,s=null,i){var r;const n=null==e?void 0:e.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=null;if(!t.encrypted||null!=(r=t.decryptdata)&&r.key?!t.encrypted&&n.encryptedFragments.length&&this.keyLoader.loadClear(t,n.encryptedFragments):(this.log(`Loading key for ${t.sn} of [${n.startSN}-${n.endSN}], ${"[stream-controller]"===this.logPrefix?"level":"track"} ${t.level}`),this.state=Ai,this.fragCurrent=t,a=this.keyLoader.load(t).then((t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(w.KEY_LOADED,t),this.state===Ai&&(this.state=Li),t})),this.hls.trigger(w.KEY_LOADING,{frag:t}),null===this.fragCurrent&&(a=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))),s=Math.max(t.start,s||0),this.config.lowLatencyMode&&"initSegment"!==t.sn){const r=n.partList;if(r&&i){s>t.end&&n.fragmentHint&&(t=n.fragmentHint);const o=this.getNextPart(r,t,s);if(o>-1){const l=r[o];let h;return this.log(`Loading part sn: ${t.sn} p: ${l.index} cc: ${t.cc} of playlist [${n.startSN}-${n.endSN}] parts [0-${o}-${r.length-1}] ${"[stream-controller]"===this.logPrefix?"level":"track"}: ${t.level}, target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=Ri,h=a?a.then((s=>!s||this.fragContextChanged(s.frag)?null:this.doFragPartsLoad(t,l,e,i))).catch((t=>this.handleFragLoadError(t))):this.doFragPartsLoad(t,l,e,i).catch((t=>this.handleFragLoadError(t))),this.hls.trigger(w.FRAG_LOADING,{frag:t,part:l,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):h}if(!t.url||this.loadedEndOfParts(r,s))return Promise.resolve(null)}}this.log(`Loading fragment ${t.sn} cc: ${t.cc} ${n?"of ["+n.startSN+"-"+n.endSN+"] ":""}${"[stream-controller]"===this.logPrefix?"level":"track"}: ${t.level}, target: ${parseFloat(s.toFixed(3))}`),D(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=Ri;const o=this.config.progressive;let l;return l=o&&a?a.then((e=>!e||this.fragContextChanged(null==e?void 0:e.frag)?null:this.fragmentLoader.load(t,i))).catch((t=>this.handleFragLoadError(t))):Promise.all([this.fragmentLoader.load(t,o?i:void 0),a]).then((([t])=>(!o&&t&&i&&i(t),t))).catch((t=>this.handleFragLoadError(t))),this.hls.trigger(w.FRAG_LOADING,{frag:t,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):l}doFragPartsLoad(t,e,s,i){return new Promise(((r,n)=>{var a;const o=[],l=null==(a=s.details)?void 0:a.partList,h=e=>{this.fragmentLoader.loadPart(t,e,i).then((i=>{o[e.index]=i;const n=i.part;this.hls.trigger(w.FRAG_LOADED,i);const a=ys(s,t.sn,e.index+1)||vs(l,t.sn,e.index+1);if(!a)return r({frag:t,part:n,partsLoaded:o});h(a)})).catch(n)};h(e)}))}handleFragLoadError(t){if("data"in t){const e=t.data;t.data&&e.details===P.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):this.hls.trigger(w.ERROR,e)}else this.hls.trigger(w.ERROR,{type:C.OTHER_ERROR,details:P.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==Di)return void(this.fragCurrent||this.state===Si||this.state===wi||(this.state=Li));const{frag:s,part:i,level:r}=e,n=self.performance.now();s.stats.parsing.end=n,i&&(i.stats.parsing.end=n),this.updateLevelTiming(s,i,r,t.partial)}getCurrentContext(t){const{levels:e,fragCurrent:s}=this,{level:i,sn:r,part:n}=t;if(null==e||!e[i])return this.warn(`Levels object was unset while buffering fragment ${r} of level ${i}. The current chunk will not be buffered.`),null;const a=e[i],o=n>-1?ys(a,r,n):null,l=o?o.fragment:function(t,e,s){if(null==t||!t.details)return null;const i=t.details;let r=i.fragments[e-i.startSN];return r||(r=i.fragmentHint,r&&r.sn===e?r:e<i.startSN&&s&&s.sn===e?s:null)}(a,r,s);return l?(s&&s!==l&&(l.stats=s.stats),{frag:l,part:o,level:a}):null}bufferFragmentData(t,e,s,i,r){var n;if(!t||this.state!==Di)return;const{data1:a,data2:o}=t;let l=a;if(a&&o&&(l=Xt(a,o)),null==(n=l)||!n.length)return;const h={type:t.type,frag:e,part:s,chunkMeta:i,parent:e.type,data:l};if(this.hls.trigger(w.BUFFER_APPENDING,h),t.dropped&&t.independent&&!s){if(r)return;this.flushBufferGap(e)}}flushBufferGap(t){const e=this.media;if(!e)return;if(!ri.isBuffered(e,e.currentTime))return void this.flushMainBuffer(0,t.start);const s=e.currentTime,i=ri.bufferInfo(e,s,0),r=t.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*r),a=Math.max(Math.min(t.start-n,i.end-n),s+n);t.start-a>n&&this.flushMainBuffer(a,t.start)}getFwdBufferInfo(t,e){const s=this.getLoadPosition();return D(s)?this.getFwdBufferInfoAtPos(t,s,e):null}getFwdBufferInfoAtPos(t,e,s){const{config:{maxBufferHole:i}}=this,r=ri.bufferInfo(t,e,i);if(0===r.len&&void 0!==r.nextStart){const n=this.fragmentTracker.getBufferedFrag(e,s);if(n&&r.nextStart<n.end)return ri.bufferInfo(t,e,Math.max(r.nextStart,i))}return r}getMaxBufferLength(t){const{config:e}=this;let s;return s=t?Math.max(8*e.maxBufferSize/t,e.maxBufferLength):e.maxBufferLength,Math.min(s,e.maxMaxBufferLength)}reduceMaxBufferLength(t,e){const s=this.config,i=Math.max(Math.min(t-e,s.maxBufferLength),e),r=Math.max(t-3*e,s.maxMaxBufferLength/2,i);return r>=i&&(s.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0)}getAppendedFrag(t,e=Ne){const s=this.fragmentTracker.getAppendedFrag(t,Ne);return s&&"fragment"in s?s.fragment:s}getNextFragment(t,e){const s=e.fragments,i=s.length;if(!i)return null;const{config:r}=this,n=s[0].start;let a;if(e.live){const o=r.initialLiveManifestSize;if(i<o)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${o})`),null;(!e.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||t<n)&&(a=this.getInitialLiveFragment(e,s),this.startPosition=this.nextLoadPosition=a?this.hls.liveSyncPosition||a.start:t)}else t<=n&&(a=s[0]);if(!a){const s=r.lowLatencyMode?e.partEnd:e.fragmentEnd;a=this.getFragmentAtPosition(t,s,e)}return this.mapToInitFragWhenRequired(a)}isLoopLoading(t,e){const s=this.fragmentTracker.getState(t);return(s===Zs||s===Js&&!!t.gap)&&this.nextLoadPosition>e}getNextFragmentLoopLoading(t,e,s,i,r){const n=t.gap,a=this.getNextFragment(this.nextLoadPosition,e);if(null===a)return a;if(t=a,n&&t&&!t.gap&&s.nextStart){const e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i);if(null!==e&&s.len+e.len>=r)return this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${t.sn}`),null}return t}mapToInitFragWhenRequired(t){return null==t||!t.initSegment||null!=t&&t.initSegment.data||this.bitrateTest?t:t.initSegment}getNextPart(t,e,s){let i=-1,r=!1,n=!0;for(let a=0,o=t.length;a<o;a++){const o=t[a];if(n=n&&!o.independent,i>-1&&s<o.start)break;const l=o.loaded;l?i=-1:(r||o.independent||n)&&o.fragment===e&&(i=a),r=l}return i}loadedEndOfParts(t,e){const s=t[t.length-1];return s&&e>s.start&&s.loaded}getInitialLiveFragment(t,e){const s=this.fragPrevious;let i=null;if(s){if(t.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),i=function(t,e,s){if(null===e||!Array.isArray(t)||!t.length||!D(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;s=s||0;for(let i=0;i<t.length;++i){const r=t[i];if(_s(e,s,r))return r}return null}(e,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){const r=s.sn+1;if(r>=t.startSN&&r<=t.endSN){const n=e[r-t.startSN];s.cc===n.cc&&(i=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=function(t,e){return bs(t,(t=>t.cc<e?1:t.cc>e?-1:0))}(e,s.cc),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const e=this.hls.liveSyncPosition;null!==e&&(i=this.getFragmentAtPosition(e,this.bitrateTest?t.fragmentEnd:t.edge,t))}return i}getFragmentAtPosition(t,e,s){const{config:i}=this;let{fragPrevious:r}=this,{fragments:n,endSN:a}=s;const{fragmentHint:o}=s,{maxFragLookUpTolerance:l}=i,h=s.partList,d=!!(i.lowLatencyMode&&null!=h&&h.length&&o);let c;if(d&&o&&!this.bitrateTest&&(n=n.concat(o),a=o.sn),t<e){c=ks(r,n,t,t>e-l?0:l)}else c=n[n.length-1];if(c){const t=c.sn-s.startSN,e=this.fragmentTracker.getState(c);if((e===Zs||e===Js&&c.gap)&&(r=c),r&&c.sn===r.sn&&(!d||h[0].fragment.sn>c.sn)){if(r&&c.level===r.level){const e=n[t+1];c=c.sn<a&&this.fragmentTracker.getState(e)!==Zs?e:null}}}return c}synchronizeToLiveEdge(t){const{config:e,media:s}=this;if(!s)return;const i=this.hls.liveSyncPosition,r=s.currentTime,n=t.fragments[0].start,a=t.edge,o=r>=n-e.maxFragLookUpTolerance&&r<=a;if(null!==i&&s.duration>i&&(r<i||!o)){const n=void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;(!o&&s.readyState<4||r<a-n)&&(this.loadedmetadata||(this.nextLoadPosition=i),s.readyState&&(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${i.toFixed(3)}`),s.currentTime=i))}}alignPlaylists(t,e,s){const i=t.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const r=t.fragments[0].start,n=!e,a=t.alignedSliding&&D(r);if(n||!a&&!r){const{fragPrevious:r}=this;hi(r,s,t);const n=t.fragments[0].start;return this.log(`Live playlist sliding: ${n.toFixed(2)} start-sn: ${e?e.startSN:"na"}->${t.startSN} prev-sn: ${r?r.sn:"na"} fragments: ${i}`),n}return r}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)}setStartPosition(t,e){let s=this.startPosition;if(s<e&&(s=-1),-1===s||-1===this.lastCurrentTime){const i=null!==this.startTimeOffset,r=i?this.startTimeOffset:t.startTimeOffset;null!==r&&D(r)?(s=e+r,r<0&&(s+=t.totalduration),s=Math.min(Math.max(e,s),e+t.totalduration),this.log(`Start time offset ${r} found in ${i?"multivariant":"media"} playlist, adjust startPosition to ${s}`),this.startPosition=s):t.live?s=this.hls.liveSyncPosition||e:this.startPosition=s=0,this.lastCurrentTime=s}this.nextLoadPosition=s}getLoadPosition(){const{media:t}=this;let e=0;return this.loadedmetadata&&t?e=t.currentTime:this.nextLoadPosition&&(e=this.nextLoadPosition),e}handleFragLoadAborted(t,e){this.transmuxer&&"initSegment"!==t.sn&&t.stats.aborted&&(this.warn(`Fragment ${t.sn}${e?" part "+e.index:""} of level ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){this.fragCurrent&&(this.fragContextChanged(t)||this.state===bi)||(this.state=Li)}onFragmentOrKeyLoadError(t,e){if(e.chunkMeta&&!e.frag){const t=this.getCurrentContext(e.chunkMeta);t&&(e.frag=t.frag)}const s=e.frag;if(!s||s.type!==t||!this.levels)return;var i;if(this.fragContextChanged(s))return void this.warn(`Frag load error must match current frag to retry ${s.url} > ${null==(i=this.fragCurrent)?void 0:i.url}`);const r=e.details===P.FRAG_GAP;r&&this.fragmentTracker.fragBuffered(s,!0);const n=e.errorAction,{action:a,retryCount:o=0,retryConfig:l}=n||{};if(n&&a===Ps&&l){this.resetStartWhenNotLoaded(this.levelLastLoaded);const i=Ls(l,o);this.warn(`Fragment ${s.sn} of ${t} ${s.level} errored with ${e.details}, retrying loading ${o+1}/${l.maxNumRetry} in ${i}ms`),n.resolved=!0,this.retryDate=self.performance.now()+i,this.state=bi}else if(l&&n){if(this.resetFragmentErrors(t),!(o<l.maxNumRetry))return void N.warn(`${e.details} reached or exceeded max retry (${o})`);r||a===Cs||(n.resolved=!0)}else(null==n?void 0:n.action)===ws?this.state=Pi:this.state=wi;this.tickImmediate()}reduceLengthAndFlushBuffer(t){if(this.state===Di||this.state===_i){const e=t.frag,s=t.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len,(null==e?void 0:e.duration)||10);const n=!r;return n&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${s} buffer`),e&&(this.fragmentTracker.removeFragment(e),this.nextLoadPosition=e.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(t){t===Ue&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==Si&&(this.state=Li)}afterBufferFlushed(t,e,s){if(!t)return;const i=ri.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,i,s),this.state===Ii&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=Li}resetStartWhenNotLoaded(t){if(!this.loadedmetadata){this.startFragRequested=!1;const e=t?t.details:null;null!=e&&e.live?(this.startPosition=-1,this.setStartPosition(e,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.warn(`The loading context changed while buffering fragment ${t.sn} of level ${t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,e,s,i){var r;const n=s.details;if(!n)return void this.warn("level.details undefined");if(!Object.keys(t.elementaryStreams).reduce(((e,r)=>{const a=t.elementaryStreams[r];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${t.sn} ${r} duration reliably (${o})`),e||!1;const l=i?0:fs(n,t,a.startPTS,a.endPTS,a.startDTS,a.endDTS);return this.hls.trigger(w.LEVEL_PTS_UPDATED,{details:n,level:s,drift:l,type:r,frag:t,start:a.startPTS,end:a.endPTS}),!0}return e}),!1)&&null===(null==(r=this.transmuxer)?void 0:r.error)){const e=new Error(`Found no media in fragment ${t.sn} of level ${t.level} resetting transmuxer to fallback to playlist timing`);if(0===s.fragmentError&&(s.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)),this.warn(e.message),this.hls.trigger(w.ERROR,{type:C.MEDIA_ERROR,details:P.FRAG_PARSING_ERROR,fatal:!1,error:e,frag:t,reason:`Found no media in msn ${t.sn} of level "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=_i,this.hls.trigger(w.FRAG_PARSED,{frag:t,part:e})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(t){"demuxerWorker"===t.event&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`))}get state(){return this._state}}class Fi{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:e}=this;let s;return t.length?(s=1===t.length?t[0]:function(t,e){const s=new Uint8Array(e);let i=0;for(let e=0;e<t.length;e++){const r=t[e];s.set(r,i),i+=r.length}return s}(t,e),this.reset(),s):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}function Mi(t="",e=9e4){return{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Oi{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(t,e,s,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(t){this.initPTS=t,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(t,e){return!1}appendFrame(t,e,s){}demux(t,e){this.cachedData&&(t=Xt(this.cachedData,t),this.cachedData=null);let s,i=mt(t,0),r=i?i.length:0;const n=this._audioTrack,a=this._id3Track,o=i?vt(i):void 0,l=t.length;for((null===this.basePTS||0===this.frameIndex&&D(o))&&(this.basePTS=Ni(o,e,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),i&&i.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:qe,duration:Number.POSITIVE_INFINITY});r<l;){if(this.canParse(t,r)){const e=this.appendFrame(n,t,r);e?(this.frameIndex++,this.lastPTS=e.sample.pts,r+=e.length,s=r):r=l}else yt(t,r)?(i=mt(t,r),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:qe,duration:Number.POSITIVE_INFINITY}),r+=i.length,s=r):r++;if(r===l&&s!==l){const e=ut(t,s);this.cachedData?this.cachedData=Xt(this.cachedData,e):this.cachedData=e}}return{audioTrack:n,videoTrack:Mi(),id3Track:a,textTrack:Mi()}}demuxSampleAes(t,e,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(t){const e=this.cachedData;return e&&(this.cachedData=null,this.demux(e,0)),{audioTrack:this._audioTrack,videoTrack:Mi(),id3Track:this._id3Track,textTrack:Mi()}}destroy(){}}const Ni=(t,e,s)=>{if(D(t))return 90*t;return 9e4*e+(s?9e4*s.baseTime/s.timescale:0)};function Ui(t,e){return 255===t[e]&&240==(246&t[e+1])}function Bi(t,e){return 1&t[e+1]?7:9}function $i(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function Gi(t,e){return e+1<t.length&&Ui(t,e)}function Ki(t,e){if(Gi(t,e)){const s=Bi(t,e);if(e+s>=t.length)return!1;const i=$i(t,e);if(i<=s)return!1;const r=e+i;return r===t.length||Gi(t,r)}return!1}function Hi(t,e,s,i,r){if(!t.samplerate){const n=function(t,e,s,i){let r,n,a,o;const l=navigator.userAgent.toLowerCase(),h=i,d=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];r=1+((192&e[s+2])>>>6);const c=(60&e[s+2])>>>2;if(!(c>d.length-1))return a=(1&e[s+2])<<2,a|=(192&e[s+3])>>>6,N.log(`manifest codec:${i}, ADTS type:${r}, samplingIndex:${c}`),/firefox/i.test(l)?c>=6?(r=5,o=new Array(4),n=c-3):(r=2,o=new Array(2),n=c):-1!==l.indexOf("android")?(r=2,o=new Array(2),n=c):(r=5,o=new Array(4),i&&(-1!==i.indexOf("mp4a.40.29")||-1!==i.indexOf("mp4a.40.5"))||!i&&c>=6?n=c-3:((i&&-1!==i.indexOf("mp4a.40.2")&&(c>=6&&1===a||/vivaldi/i.test(l))||!i&&1===a)&&(r=2,o=new Array(2)),n=c)),o[0]=r<<3,o[0]|=(14&c)>>1,o[1]|=(1&c)<<7,o[1]|=a<<3,5===r&&(o[1]|=(14&n)>>1,o[2]=(1&n)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:d[c],channelCount:a,codec:"mp4a.40."+r,manifestCodec:h};{const e=new Error(`invalid ADTS sampling index:${c}`);t.emit(w.ERROR,w.ERROR,{type:C.MEDIA_ERROR,details:P.FRAG_PARSING_ERROR,fatal:!0,error:e,reason:e.message})}}(e,s,i,r);if(!n)return;t.config=n.config,t.samplerate=n.samplerate,t.channelCount=n.channelCount,t.codec=n.codec,t.manifestCodec=n.manifestCodec,N.log(`parsed codec:${t.codec}, rate:${n.samplerate}, channels:${n.channelCount}`)}}function Vi(t){return 9216e4/t}function Yi(t,e,s,i,r){const n=i+r*Vi(t.samplerate),a=function(t,e){const s=Bi(t,e);if(e+s<=t.length){const i=$i(t,e)-s;if(i>0)return{headerLength:s,frameLength:i}}}(e,s);let o;if(a){const{frameLength:i,headerLength:r}=a,l=r+i,h=Math.max(0,s+l-e.length);h?(o=new Uint8Array(l-r),o.set(e.subarray(s+r,e.length),0)):o=e.subarray(s+r,s+l);const d={unit:o,pts:n};return h||t.samples.push(d),{sample:d,length:l,missing:h}}const l=e.length-s;o=new Uint8Array(l),o.set(e.subarray(s,e.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}let Wi=null;const ji=[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],qi=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Xi=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],zi=[0,1,1,4];function Qi(t,e,s,i,r){if(s+24>e.length)return;const n=Ji(e,s);if(n&&s+n.frameLength<=e.length){const a=i+r*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:e.subarray(s,s+n.frameLength),pts:a,dts:a};return t.config=[],t.channelCount=n.channelCount,t.samplerate=n.sampleRate,t.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function Ji(t,e){const s=t[e+1]>>3&3,i=t[e+1]>>1&3,r=t[e+2]>>4&15,n=t[e+2]>>2&3;if(1!==s&&0!==r&&15!==r&&3!==n){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*ji[14*(3===s?3-i:3===i?3:4)+r-1],h=qi[3*(3===s?0:2===s?1:2)+n],d=3===o?1:2,c=Xi[s][i],u=zi[i],f=8*c*u,g=Math.floor(c*l/h+a)*u;if(null===Wi){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Wi=t?parseInt(t[1]):0}return!!Wi&&Wi<=87&&2===i&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:h,channelCount:d,frameLength:g,samplesPerFrame:f}}}function Zi(t,e){return!(255!==t[e]||224&~t[e+1]||!(6&t[e+1]))}function tr(t,e){return e+1<t.length&&Zi(t,e)}function er(t,e){if(e+1<t.length&&Zi(t,e)){const s=4,i=Ji(t,e);let r=s;null!=i&&i.frameLength&&(r=i.frameLength);const n=e+r;return n===t.length||tr(t,n)}return!1}const sr=/\/emsg[-/]ID3/i;const ir=(t,e)=>{let s=0,i=5;e+=i;const r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=t[e];const o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<<l,r[0]=(a[0]&n[0])>>l,s=s?s<<o|r[0]:r[0],e+=1,i-=o}return s};class rr extends Oi{constructor(t){super(),this.observer=void 0,this.observer=t}resetInitSegment(t,e,s,i){super.resetInitSegment(t,e,s,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}}canParse(t,e){return e+64<t.length}appendFrame(t,e,s){const i=nr(t,e,s,this.basePTS,this.frameIndex);if(-1!==i){return{sample:t.samples[t.samples.length-1],length:i,missing:0}}}static probe(t){if(!t)return!1;const e=mt(t,0);if(!e)return!1;const s=e.length;return 11===t[s]&&119===t[s+1]&&void 0!==vt(e)&&ir(t,s)<16}}function nr(t,e,s,i,r){if(s+8>e.length)return-1;if(11!==e[s]||119!==e[s+1])return-1;const n=e[s+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&e[s+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+n];if(s+l>e.length)return-1;const h=e[s+6]>>5;let d=0;2===h?d+=2:(1&h&&1!==h&&(d+=2),4&h&&(d+=2));const c=(e[s+6]<<8|e[s+7])>>12-d&1,u=[2,1,2,3,3,4,4,5][h]+c,f=e[s+5]>>3,g=7&e[s+5],m=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|h<<3|c<<2|o>>4,o<<4&224]),p=i+r*(1536/a*9e4),y=e.subarray(s,s+l);return t.config=m,t.channelCount=u,t.samplerate=a,t.samples.push({unit:y,pts:p}),l}class ar{constructor(){this.VideoSample=null}createVideoSample(t,e,s,i){return{key:t,frame:!1,pts:e,dts:s,units:[],debug:i,length:0}}getLastNalUnit(t){var e;let s,i=this.VideoSample;if(i&&0!==i.units.length||(i=t[t.length-1]),null!=(e=i)&&e.units){const t=i.units;s=t[t.length-1]}return s}pushAccessUnit(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){const s=e.samples,i=s.length;if(!i)return void e.dropped++;{const e=s[i-1];t.pts=e.pts,t.dts=e.dts}}e.samples.push(t)}t.debug.length&&N.log(t.pts+"/"+t.dts+":"+t.debug)}}class or{constructor(t){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const t=this.data,e=this.bytesAvailable,s=t.byteLength-e,i=new Uint8Array(4),r=Math.min(4,e);if(0===r)throw new Error("no bytes available");i.set(t.subarray(s,s+r)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*r,this.bytesAvailable-=r}skipBits(t){let e;t=Math.min(t,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(e=(t-=this.bitsAvailable)>>3,t-=e<<3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)}readBits(t){let e=Math.min(this.bitsAvailable,t);const s=this.word>>>32-e;if(t>32&&N.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0)this.word<<=e;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return e=t-e,e>0&&this.bitsAvailable?s<<e|this.readBits(e):s}skipLZ(){let t;for(t=0;t<this.bitsAvailable;++t)if(this.word&2147483648>>>t)return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const t=this.skipLZ();return this.readBits(t+1)-1}readEG(){const t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}skipScalingList(t){let e,s=8,i=8;for(let r=0;r<t;r++)0!==i&&(e=this.readEG(),i=(s+e+256)%256),s=0===i?s:i}readSPS(){let t,e,s,i=0,r=0,n=0,a=0;const o=this.readUByte.bind(this),l=this.readBits.bind(this),h=this.readUEG.bind(this),d=this.readBoolean.bind(this),c=this.skipBits.bind(this),u=this.skipEG.bind(this),f=this.skipUEG.bind(this),g=this.skipScalingList.bind(this);o();const m=o();if(l(5),c(3),o(),f(),100===m||110===m||122===m||244===m||44===m||83===m||86===m||118===m||128===m){const t=h();if(3===t&&c(1),f(),f(),c(1),d())for(e=3!==t?8:12,s=0;s<e;s++)d()&&g(s<6?16:64)}f();const p=h();if(0===p)h();else if(1===p)for(c(1),u(),u(),t=h(),s=0;s<t;s++)u();f(),c(1);const y=h(),v=h(),T=l(1);0===T&&c(1),c(1),d()&&(i=h(),r=h(),n=h(),a=h());let E=[1,1];if(d()&&d()){switch(o()){case 1:E=[1,1];break;case 2:E=[12,11];break;case 3:E=[10,11];break;case 4:E=[16,11];break;case 5:E=[40,33];break;case 6:E=[24,11];break;case 7:E=[20,11];break;case 8:E=[32,11];break;case 9:E=[80,33];break;case 10:E=[18,11];break;case 11:E=[15,11];break;case 12:E=[64,33];break;case 13:E=[160,99];break;case 14:E=[4,3];break;case 15:E=[3,2];break;case 16:E=[2,1];break;case 255:E=[o()<<8|o(),o()<<8|o()]}}return{width:Math.ceil(16*(y+1)-2*i-2*r),height:(2-T)*(v+1)*16-(T?2:4)*(n+a),pixelRatio:E}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class lr extends ar{parseAVCPES(t,e,s,i,r){const n=this.parseAVCNALu(t,s.data);let a,o=this.VideoSample,l=!1;s.data=null,o&&n.length&&!t.audFound&&(this.pushAccessUnit(o,t),o=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts,"")),n.forEach((i=>{var n;switch(i.type){case 1:{let e=!1;a=!0;const r=i.data;if(l&&r.length>4){const t=new or(r).readSliceType();2!==t&&4!==t&&7!==t&&9!==t||(e=!0)}var h;if(e)null!=(h=o)&&h.frame&&!o.key&&(this.pushAccessUnit(o,t),o=this.VideoSample=null);o||(o=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts,"")),o.frame=!0,o.key=e;break}case 5:a=!0,null!=(n=o)&&n.frame&&!o.key&&(this.pushAccessUnit(o,t),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts,"")),o.key=!0,o.frame=!0;break;case 6:a=!0,Jt(i.data,1,s.pts,e.samples);break;case 7:{var d,c;a=!0,l=!0;const e=i.data,s=new or(e).readSPS();if(!t.sps||t.width!==s.width||t.height!==s.height||(null==(d=t.pixelRatio)?void 0:d[0])!==s.pixelRatio[0]||(null==(c=t.pixelRatio)?void 0:c[1])!==s.pixelRatio[1]){t.width=s.width,t.height=s.height,t.pixelRatio=s.pixelRatio,t.sps=[e],t.duration=r;const i=e.subarray(1,4);let n="avc1.";for(let t=0;t<3;t++){let e=i[t].toString(16);e.length<2&&(e="0"+e),n+=e}t.codec=n}break}case 8:a=!0,t.pps=[i.data];break;case 9:a=!0,t.audFound=!0,o&&this.pushAccessUnit(o,t),o=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts,"");break;case 12:a=!0;break;default:a=!1,o&&(o.debug+="unknown NAL "+i.type+" ")}if(o&&a){o.units.push(i)}})),i&&o&&(this.pushAccessUnit(o,t),this.VideoSample=null)}parseAVCNALu(t,e){const s=e.byteLength;let i=t.naluState||0;const r=i,n=[];let a,o,l,h=0,d=-1,c=0;for(-1===i&&(d=0,c=31&e[0],i=0,h=1);h<s;)if(a=e[h++],i)if(1!==i)if(a)if(1===a){if(o=h-i-1,d>=0){const t={data:e.subarray(d,o),type:c};n.push(t)}else{const s=this.getLastNalUnit(t.samples);s&&(r&&h<=4-r&&s.state&&(s.data=s.data.subarray(0,s.data.byteLength-r)),o>0&&(s.data=Xt(s.data,e.subarray(0,o)),s.state=0))}h<s?(l=31&e[h],d=h,c=l,i=0):i=-1}else i=0;else i=3;else i=a?0:2;else i=a?0:1;if(d>=0&&i>=0){const t={data:e.subarray(d,s),type:c,state:i};n.push(t)}if(0===n.length){const s=this.getLastNalUnit(t.samples);s&&(s.data=Xt(s.data,e))}return t.naluState=i,n}}class hr{constructor(t,e,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Ti(e,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(t,e,s){const i=t[e].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then((r=>{const n=new Uint8Array(r);i.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(t,e+1,s)}))}decryptAacSamples(t,e,s){for(;;e++){if(e>=t.length)return void s();if(!(t[e].unit.length<32)&&(this.decryptAacSample(t,e,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const e=16*Math.floor((t.length-48)/160)+16,s=new Int8Array(e);let i=0;for(let e=32;e<t.length-16;e+=160,i+=16)s.set(t.subarray(e,e+16),i);return s}getAvcDecryptedUnit(t,e){const s=new Uint8Array(e);let i=0;for(let e=32;e<t.length-16;e+=160,i+=16)t.set(s.subarray(i,i+16),e);return t}decryptAvcSample(t,e,s,i,r){const n=Zt(r.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then((a=>{r.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(t,e,s+1,i)}))}decryptAvcSamples(t,e,s,i){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,s=0){if(e>=t.length)return void i();const r=t[e].units;for(;!(s>=r.length);s++){const n=r[s];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(t,e,s,i,n),this.decrypter.isSync())))return}}}}const dr=188;class cr{constructor(t,e,s){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=t,this.config=e,this.typeSupported=s,this.videoParser=new lr}static probe(t){const e=cr.syncOffset(t);return e>0&&N.warn(`MPEG2-TS detected but first sync word found @ offset ${e}`),-1!==e}static syncOffset(t){const e=t.length;let s=Math.min(940,e-dr)+1,i=0;for(;i<s;){let r=!1,n=-1,a=0;for(let o=i;o<e;o+=dr){if(71!==t[o]||e-o!==dr&&71!==t[o+dr]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(s=Math.min(n+18612,t.length-dr)+1)),r||(r=0===ur(t,o)),r&&a>1&&(0===n&&a>2||o+dr>s))return n}i++}return-1}static createTrack(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:xt[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}}resetInitSegment(t,e,s,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=cr.createTrack("video"),this._audioTrack=cr.createTrack("audio",i),this._id3Track=cr.createTrack("id3"),this._txtTrack=cr.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=s,this._duration=i}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:e,_id3Track:s}=this;t&&(t.pesData=null),e&&(e.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,e,s=!1,i=!1){let r;s||(this.sampleAes=null);const n=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let h=n.pid,d=n.pesData,c=a.pid,u=o.pid,f=a.pesData,g=o.pesData,m=null,p=this.pmtParsed,y=this._pmtId,v=t.length;if(this.remainderData&&(v=(t=Xt(this.remainderData,t)).length,this.remainderData=null),v<dr&&!i)return this.remainderData=t,{audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};const T=Math.max(0,cr.syncOffset(t));v-=(v-T)%dr,v<t.byteLength&&!i&&(this.remainderData=new Uint8Array(t.buffer,v,t.buffer.byteLength-v));let E=0;for(let e=T;e<v;e+=dr)if(71===t[e]){const i=!!(64&t[e+1]),v=ur(t,e);let E;if((48&t[e+3])>>4>1){if(E=e+5+t[e+4],E===e+dr)continue}else E=e+4;switch(v){case h:i&&(d&&(r=yr(d))&&this.videoParser.parseAVCPES(n,l,r,!1,this._duration),d={data:[],size:0}),d&&(d.data.push(t.subarray(E,e+dr)),d.size+=e+dr-E);break;case c:if(i){if(f&&(r=yr(f)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,r);break;case"mp3":this.parseMPEGPES(a,r);break;case"ac3":this.parseAC3PES(a,r)}f={data:[],size:0}}f&&(f.data.push(t.subarray(E,e+dr)),f.size+=e+dr-E);break;case u:i&&(g&&(r=yr(g))&&this.parseID3PES(o,r),g={data:[],size:0}),g&&(g.data.push(t.subarray(E,e+dr)),g.size+=e+dr-E);break;case 0:i&&(E+=t[E]+1),y=this._pmtId=fr(t,E);break;case y:{i&&(E+=t[E]+1);const r=gr(t,E,this.typeSupported,s,this.observer);h=r.videoPid,h>0&&(n.pid=h,n.segmentCodec=r.segmentVideoCodec),c=r.audioPid,c>0&&(a.pid=c,a.segmentCodec=r.segmentAudioCodec),u=r.id3Pid,u>0&&(o.pid=u),null===m||p||(N.warn(`MPEG-TS PMT found at ${e} after unknown PID '${m}'. Backtracking to sync byte @${T} to parse all TS packets.`),m=null,e=T-188),p=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=v}}else E++;E>0&&mr(this.observer,new Error(`Found ${E} TS packet/s that do not start with 0x47`)),n.pesData=d,a.pesData=f,o.pesData=g;const S={audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};return i&&this.extractRemainingSamples(S),S}flush(){const{remainderData:t}=this;let e;return this.remainderData=null,e=t?this.demux(t,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e}extractRemainingSamples(t){const{audioTrack:e,videoTrack:s,id3Track:i,textTrack:r}=t,n=s.pesData,a=e.pesData,o=i.pesData;let l;if(n&&(l=yr(n))?(this.videoParser.parseAVCPES(s,r,l,!0,this._duration),s.pesData=null):s.pesData=n,a&&(l=yr(a))){switch(e.segmentCodec){case"aac":this.parseAACPES(e,l);break;case"mp3":this.parseMPEGPES(e,l);break;case"ac3":this.parseAC3PES(e,l)}e.pesData=null}else null!=a&&a.size&&N.log("last AAC PES packet truncated,might overlap between fragments"),e.pesData=a;o&&(l=yr(o))?(this.parseID3PES(i,l),i.pesData=null):i.pesData=o}demuxSampleAes(t,e,s){const i=this.demux(t,s,!0,!this.config.progressive),r=this.sampleAes=new hr(this.observer,this.config,e);return this.decrypt(i,r)}decrypt(t,e){return new Promise((s=>{const{audioTrack:i,videoTrack:r}=t;i.samples&&"aac"===i.segmentCodec?e.decryptAacSamples(i.samples,0,(()=>{r.samples?e.decryptAvcSamples(r.samples,0,0,(()=>{s(t)})):s(t)})):r.samples&&e.decryptAvcSamples(r.samples,0,0,(()=>{s(t)}))}))}destroy(){this._duration=0}parseAACPES(t,e){let s=0;const i=this.aacOverFlow;let r,n,a,o=e.data;if(i){this.aacOverFlow=null;const e=i.missing,r=i.sample.unit.byteLength;if(-1===e)o=Xt(i.sample.unit,o);else{const n=r-e;i.sample.unit.set(o.subarray(0,e),n),t.samples.push(i.sample),s=i.missing}}for(r=s,n=o.length;r<n-1&&!Gi(o,r);r++);if(r!==s){let t;const e=r<n-1;if(t=e?`AAC PES did not start with ADTS header,offset:${r}`:"No ADTS header found in AAC PES",mr(this.observer,new Error(t),e),!e)return}if(Hi(t,this.observer,o,r,this.audioCodec),void 0!==e.pts)a=e.pts;else{if(!i)return void N.warn("[tsdemuxer]: AAC PES unknown PTS");{const e=Vi(t.samplerate);a=i.sample.pts+e}}let l,h=0;for(;r<n;){if(l=Yi(t,o,r,a,h),r+=l.length,l.missing){this.aacOverFlow=l;break}for(h++;r<n-1&&!Gi(o,r);r++);}}parseMPEGPES(t,e){const s=e.data,i=s.length;let r=0,n=0;const a=e.pts;if(void 0!==a)for(;n<i;)if(tr(s,n)){const e=Qi(t,s,n,a,r);if(!e)break;n+=e.length,r++}else n++;else N.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(t,e){{const s=e.data,i=e.pts;if(void 0===i)return void N.warn("[tsdemuxer]: AC3 PES unknown PTS");const r=s.length;let n,a=0,o=0;for(;o<r&&(n=nr(t,s,o,i,a++))>0;)o+=n}}parseID3PES(t,e){if(void 0===e.pts)return void N.warn("[tsdemuxer]: ID3 PES unknown PTS");const s=k({},e,{type:this._videoTrack?ze:qe,duration:Number.POSITIVE_INFINITY});t.samples.push(s)}}function ur(t,e){return((31&t[e+1])<<8)+t[e+2]}function fr(t,e){return(31&t[e+10])<<8|t[e+11]}function gr(t,e,s,i,r){const n={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},a=e+3+((15&t[e+1])<<8|t[e+2])-4;for(e+=12+((15&t[e+10])<<8|t[e+11]);e<a;){const a=ur(t,e),o=(15&t[e+3])<<8|t[e+4];switch(t[e]){case 207:if(!i){pr("ADTS AAC");break}case 15:-1===n.audioPid&&(n.audioPid=a);break;case 21:-1===n.id3Pid&&(n.id3Pid=a);break;case 219:if(!i){pr("H.264");break}case 27:-1===n.videoPid&&(n.videoPid=a,n.segmentVideoCodec="avc");break;case 3:case 4:s.mpeg||s.mp3?-1===n.audioPid&&(n.audioPid=a,n.segmentAudioCodec="mp3"):N.log("MPEG audio found, not supported in this browser");break;case 193:if(!i){pr("AC-3");break}case 129:s.ac3?-1===n.audioPid&&(n.audioPid=a,n.segmentAudioCodec="ac3"):N.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===n.audioPid&&o>0){let i=e+5,r=o;for(;r>2;){if(106===t[i])!0!==s.ac3?N.log("AC-3 audio found, not supported in this browser for now"):(n.audioPid=a,n.segmentAudioCodec="ac3");const e=t[i+1]+2;i+=e,r-=e}}break;case 194:case 135:return mr(r,new Error("Unsupported EC-3 in M2TS found")),n;case 36:return mr(r,new Error("Unsupported HEVC in M2TS found")),n}e+=o+5}return n}function mr(t,e,s){N.warn(`parsing error: ${e.message}`),t.emit(w.ERROR,w.ERROR,{type:C.MEDIA_ERROR,details:P.FRAG_PARSING_ERROR,fatal:!1,levelRetry:s,error:e,reason:e.message})}function pr(t){N.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function yr(t){let e,s,i,r,n,a=0;const o=t.data;if(!t||0===t.size)return null;for(;o[0].length<19&&o.length>1;)o[0]=Xt(o[0],o[1]),o.splice(1,1);e=o[0];if(1===(e[0]<<16)+(e[1]<<8)+e[2]){if(s=(e[4]<<8)+e[5],s&&s>t.size-6)return null;const l=e[7];192&l&&(r=536870912*(14&e[9])+4194304*(255&e[10])+16384*(254&e[11])+128*(255&e[12])+(254&e[13])/2,64&l?(n=536870912*(14&e[14])+4194304*(255&e[15])+16384*(254&e[16])+128*(255&e[17])+(254&e[18])/2,r-n>54e5&&(N.warn(`${Math.round((r-n)/9e4)}s delta between PTS and DTS, align them`),r=n)):n=r),i=e[8];let h=i+9;if(t.size<=h)return null;t.size-=h;const d=new Uint8Array(t.size);for(let t=0,s=o.length;t<s;t++){e=o[t];let s=e.byteLength;if(h){if(h>s){h-=s;continue}e=e.subarray(h),s-=h,h=0}d.set(e,a),a+=s}return s&&(s-=i+3),{data:d,pts:r,dts:n,len:s}}return null}class vr{static getSilentFrame(t,e){if("mp4a.40.2"===t){if(1===e)return new Uint8Array([0,200,0,128,35,128]);if(2===e)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===e)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===e)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===e)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])}}}const Tr=Math.pow(2,32)-1;class Er{static init(){let t;for(t in Er.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},Er.types)Er.types.hasOwnProperty(t)&&(Er.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);const e=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),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]);Er.HDLR_TYPES={video:e,audio:s};const i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);Er.STTS=Er.STSC=Er.STCO=r,Er.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Er.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Er.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Er.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);Er.FTYP=Er.box(Er.types.ftyp,n,o,n,a),Er.DINF=Er.box(Er.types.dinf,Er.box(Er.types.dref,i))}static box(t,...e){let s=8,i=e.length;const r=i;for(;i--;)s+=e[i].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=255&s,n.set(t,4),i=0,s=8;i<r;i++)n.set(e[i],s),s+=e[i].byteLength;return n}static hdlr(t){return Er.box(Er.types.hdlr,Er.HDLR_TYPES[t])}static mdat(t){return Er.box(Er.types.mdat,t)}static mdhd(t,e){e*=t;const s=Math.floor(e/(Tr+1)),i=Math.floor(e%(Tr+1));return Er.box(Er.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,s>>24,s>>16&255,s>>8&255,255&s,i>>24,i>>16&255,i>>8&255,255&i,85,196,0,0]))}static mdia(t){return Er.box(Er.types.mdia,Er.mdhd(t.timescale,t.duration),Er.hdlr(t.type),Er.minf(t))}static mfhd(t){return Er.box(Er.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}static minf(t){return"audio"===t.type?Er.box(Er.types.minf,Er.box(Er.types.smhd,Er.SMHD),Er.DINF,Er.stbl(t)):Er.box(Er.types.minf,Er.box(Er.types.vmhd,Er.VMHD),Er.DINF,Er.stbl(t))}static moof(t,e,s){return Er.box(Er.types.moof,Er.mfhd(t),Er.traf(s,e))}static moov(t){let e=t.length;const s=[];for(;e--;)s[e]=Er.trak(t[e]);return Er.box.apply(null,[Er.types.moov,Er.mvhd(t[0].timescale,t[0].duration)].concat(s).concat(Er.mvex(t)))}static mvex(t){let e=t.length;const s=[];for(;e--;)s[e]=Er.trex(t[e]);return Er.box.apply(null,[Er.types.mvex,...s])}static mvhd(t,e){e*=t;const s=Math.floor(e/(Tr+1)),i=Math.floor(e%(Tr+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,s>>24,s>>16&255,s>>8&255,255&s,i>>24,i>>16&255,i>>8&255,255&i,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 Er.box(Er.types.mvhd,r)}static sdtp(t){const e=t.samples||[],s=new Uint8Array(4+e.length);let i,r;for(i=0;i<e.length;i++)r=e[i].flags,s[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return Er.box(Er.types.sdtp,s)}static stbl(t){return Er.box(Er.types.stbl,Er.stsd(t),Er.box(Er.types.stts,Er.STTS),Er.box(Er.types.stsc,Er.STSC),Er.box(Er.types.stsz,Er.STSZ),Er.box(Er.types.stco,Er.STCO))}static avc1(t){let e,s,i,r=[],n=[];for(e=0;e<t.sps.length;e++)s=t.sps[e],i=s.byteLength,r.push(i>>>8&255),r.push(255&i),r=r.concat(Array.prototype.slice.call(s));for(e=0;e<t.pps.length;e++)s=t.pps[e],i=s.byteLength,n.push(i>>>8&255),n.push(255&i),n=n.concat(Array.prototype.slice.call(s));const a=Er.box(Er.types.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|t.sps.length].concat(r).concat([t.pps.length]).concat(n))),o=t.width,l=t.height,h=t.pixelRatio[0],d=t.pixelRatio[1];return Er.box(Er.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,o>>8&255,255&o,l>>8&255,255&l,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]),a,Er.box(Er.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Er.box(Er.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,d>>24,d>>16&255,d>>8&255,255&d])))}static esds(t){const e=t.config.length;return new Uint8Array([0,0,0,0,3,23+e,0,1,0,4,15+e,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([e]).concat(t.config).concat([6,1,2]))}static audioStsd(t){const e=t.samplerate;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,e>>8&255,255&e,0,0])}static mp4a(t){return Er.box(Er.types.mp4a,Er.audioStsd(t),Er.box(Er.types.esds,Er.esds(t)))}static mp3(t){return Er.box(Er.types[".mp3"],Er.audioStsd(t))}static ac3(t){return Er.box(Er.types["ac-3"],Er.audioStsd(t),Er.box(Er.types.dac3,t.config))}static stsd(t){return"audio"===t.type?"mp3"===t.segmentCodec&&"mp3"===t.codec?Er.box(Er.types.stsd,Er.STSD,Er.mp3(t)):"ac3"===t.segmentCodec?Er.box(Er.types.stsd,Er.STSD,Er.ac3(t)):Er.box(Er.types.stsd,Er.STSD,Er.mp4a(t)):Er.box(Er.types.stsd,Er.STSD,Er.avc1(t))}static tkhd(t){const e=t.id,s=t.duration*t.timescale,i=t.width,r=t.height,n=Math.floor(s/(Tr+1)),a=Math.floor(s%(Tr+1));return Er.box(Er.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a,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,i>>8&255,255&i,0,0,r>>8&255,255&r,0,0]))}static traf(t,e){const s=Er.sdtp(t),i=t.id,r=Math.floor(e/(Tr+1)),n=Math.floor(e%(Tr+1));return Er.box(Er.types.traf,Er.box(Er.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i])),Er.box(Er.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,n>>24,n>>16&255,n>>8&255,255&n])),Er.trun(t,s.length+16+20+8+16+8+8),s)}static trak(t){return t.duration=t.duration||4294967295,Er.box(Er.types.trak,Er.tkhd(t),Er.mdia(t))}static trex(t){const e=t.id;return Er.box(Er.types.trex,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,e){const s=t.samples||[],i=s.length,r=12+16*i,n=new Uint8Array(r);let a,o,l,h,d,c;for(e+=8+r,n.set(["video"===t.type?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,255&i,e>>>24&255,e>>>16&255,e>>>8&255,255&e],0),a=0;a<i;a++)o=s[a],l=o.duration,h=o.size,d=o.flags,c=o.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,h>>>24&255,h>>>16&255,h>>>8&255,255&h,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,61440&d.degradPrio,15&d.degradPrio,c>>>24&255,c>>>16&255,c>>>8&255,255&c],12+16*a);return Er.box(Er.types.trun,n)}static initSegment(t){Er.types||Er.init();const e=Er.moov(t);return Xt(Er.FTYP,e)}}Er.types=void 0,Er.HDLR_TYPES=void 0,Er.STTS=void 0,Er.STSC=void 0,Er.STCO=void 0,Er.STSZ=void 0,Er.VMHD=void 0,Er.SMHD=void 0,Er.STSD=void 0,Er.FTYP=void 0,Er.DINF=void 0;function Sr(t,e,s=1,i=!1){const r=t*e*s;return i?Math.round(r):r}function Lr(t,e=!1){return Sr(t,1e3,1/9e4,e)}let Ar,Rr=null,br=null;class kr{constructor(t,e,s,i=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=t,this.config=e,this.typeSupported=s,this.ISGenerated=!1,null===Rr){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Rr=t?parseInt(t[1]):0}if(null===br){const t=navigator.userAgent.match(/Safari\/(\d+)/i);br=t?parseInt(t[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){N.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=t}resetNextTimestamp(){N.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){N.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let e=!1;const s=t.reduce(((t,s)=>{const i=s.pts-t;return i<-4294967296?(e=!0,Dr(t,s.pts)):i>0?t:s.pts}),t[0].pts);return e&&N.debug("PTS rollover detected"),s}remux(t,e,s,i,r,n,a,o){let l,h,d,c,u,f,g=r,m=r;const p=t.pid>-1,y=e.pid>-1,v=e.samples.length,T=t.samples.length>0,E=a&&v>0||v>1;if((!p||T)&&(!y||E)||this.ISGenerated||a){if(this.ISGenerated){var S,L,A,R;const t=this.videoTrackConfig;!t||e.width===t.width&&e.height===t.height&&(null==(S=e.pixelRatio)?void 0:S[0])===(null==(L=t.pixelRatio)?void 0:L[0])&&(null==(A=e.pixelRatio)?void 0:A[1])===(null==(R=t.pixelRatio)?void 0:R[1])||this.resetInitSegment()}else d=this.generateIS(t,e,r,n);const s=this.isVideoContiguous;let i,a=-1;if(E&&(a=function(t){for(let e=0;e<t.length;e++)if(t[e].key)return e;return-1}(e.samples),!s&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,a>0){N.warn(`[mp4-remuxer]: Dropped ${a} out of ${v} video samples due to a missing keyframe`);const t=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(a),e.dropped+=a,m+=(e.samples[0].pts-t)/e.inputTimeScale,i=m}else-1===a&&(N.warn(`[mp4-remuxer]: No keyframe found out of ${v} video samples`),f=!1);if(this.ISGenerated){if(T&&E){const s=this.getVideoStartPts(e.samples),i=(Dr(t.samples[0].pts,s)-s)/e.inputTimeScale;g+=Math.max(0,i),m+=Math.max(0,-i)}if(T){if(t.samplerate||(N.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),d=this.generateIS(t,e,r,n)),h=this.remuxAudio(t,g,this.isAudioContiguous,n,y||E||o===Ue?m:void 0),E){const i=h?h.endPTS-h.startPTS:0;e.inputTimeScale||(N.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),d=this.generateIS(t,e,r,n)),l=this.remuxVideo(e,m,s,i)}}else E&&(l=this.remuxVideo(e,m,s,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=i)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(u=_r(s,r,this._initPTS,this._initDTS)),i.samples.length&&(c=Ir(i,r,this._initPTS))),{audio:h,video:l,initSegment:d,independent:f,text:c,id3:u}}generateIS(t,e,s,i){const r=t.samples,n=e.samples,a=this.typeSupported,o={},l=this._initPTS;let h,d,c,u=!l||i,f="audio/mp4";if(u&&(h=d=1/0),t.config&&r.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",t.codec=""):a.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3"}o.audio={id:"audio",container:f,codec:t.codec,initSegment:"mp3"===t.segmentCodec&&a.mpeg?new Uint8Array(0):Er.initSegment([t]),metadata:{channelCount:t.channelCount}},u&&(c=t.inputTimeScale,l&&c===l.timescale?u=!1:h=d=r[0].pts-Math.round(c*s))}if(e.sps&&e.pps&&n.length){if(e.timescale=e.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:Er.initSegment([e]),metadata:{width:e.width,height:e.height}},u)if(c=e.inputTimeScale,l&&c===l.timescale)u=!1;else{const t=this.getVideoStartPts(n),e=Math.round(c*s);d=Math.min(d,Dr(n[0].dts,t)-e),h=Math.min(h,t-e)}this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,u?(this._initPTS={baseTime:h,timescale:c},this._initDTS={baseTime:d,timescale:c}):h=c=void 0,{tracks:o,initPTS:h,timescale:c}}remuxVideo(t,e,s,i){const r=t.inputTimeScale,n=t.samples,a=[],o=n.length,l=this._initPTS;let h,d,c=this.nextAvcDts,u=8,f=this.videoSampleDuration,g=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,p=!1;if(!s||null===c){const t=e*r,i=n[0].pts-Dr(n[0].dts,n[0].pts);Rr&&null!==c&&Math.abs(t-i-c)<15e3?s=!0:c=t-i}const y=l.baseTime*r/l.timescale;for(let t=0;t<o;t++){const e=n[t];e.pts=Dr(e.pts-y,c),e.dts=Dr(e.dts-y,c),e.dts<n[t>0?t-1:t].dts&&(p=!0)}p&&n.sort((function(t,e){const s=t.dts-e.dts,i=t.pts-e.pts;return s||i})),h=n[0].dts,d=n[n.length-1].dts;const v=d-h,T=v?Math.round(v/(o-1)):f||t.inputTimeScale/30;if(s){const t=h-c,s=t>T,i=t<-1;if((s||i)&&(s?N.warn(`AVC: ${Lr(t,!0)} ms (${t}dts) hole between fragments detected at ${e.toFixed(3)}`):N.warn(`AVC: ${Lr(-t,!0)} ms (${t}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!i||c>=n[0].pts||Rr)){h=c;const e=n[0].pts-t;if(s)n[0].dts=h,n[0].pts=e;else for(let s=0;s<n.length&&!(n[s].dts>e);s++)n[s].dts-=t,n[s].pts-=t;N.log(`Video: Initial PTS/DTS adjusted: ${Lr(e,!0)}/${Lr(h,!0)}, delta: ${Lr(t,!0)} ms`)}}h=Math.max(0,h);let E=0,S=0,L=h;for(let t=0;t<o;t++){const e=n[t],s=e.units,i=s.length;let r=0;for(let t=0;t<i;t++)r+=s[t].data.length;S+=r,E+=i,e.length=r,e.dts<L?(e.dts=L,L+=T/4|0||1):L=e.dts,g=Math.min(e.pts,g),m=Math.max(e.pts,m)}d=n[o-1].dts;const A=S+4*E+8;let R;try{R=new Uint8Array(A)}catch(t){return void this.observer.emit(w.ERROR,w.ERROR,{type:C.MUX_ERROR,details:P.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:A,reason:`fail allocating video mdat ${A}`})}const b=new DataView(R.buffer);b.setUint32(0,A),R.set(Er.types.mdat,4);let D=!1,_=Number.POSITIVE_INFINITY,I=Number.POSITIVE_INFINITY,x=Number.NEGATIVE_INFINITY,F=Number.NEGATIVE_INFINITY;for(let t=0;t<o;t++){const e=n[t],s=e.units;let l,h=0;for(let t=0,e=s.length;t<e;t++){const e=s[t],i=e.data,r=e.data.byteLength;b.setUint32(u,r),u+=4,R.set(i,u),u+=r,h+=4+r}if(t<o-1)f=n[t+1].dts-e.dts,l=n[t+1].pts-e.pts;else{const s=this.config,a=t>0?e.dts-n[t-1].dts:T;if(l=t>0?e.pts-n[t-1].pts:T,s.stretchShortVideoTrack&&null!==this.nextAudioPts){const t=Math.floor(s.maxBufferHole*r),n=(i?g+i*r:this.nextAudioPts)-e.pts;n>t?(f=n-a,f<0?f=a:D=!0,N.log(`[mp4-remuxer]: It is approximately ${n/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=a}else f=a}const d=Math.round(e.pts-e.dts);_=Math.min(_,f),x=Math.max(x,f),I=Math.min(I,l),F=Math.max(F,l),a.push(new wr(e.key,f,h,d))}if(a.length)if(Rr){if(Rr<70){const t=a[0].flags;t.dependsOn=2,t.isNonSync=0}}else if(br&&F-I<x-_&&T/x<.025&&0===a[0].cts){N.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let t=h;for(let e=0,s=a.length;e<s;e++){const i=t+a[e].duration,r=t+a[e].cts;if(e<s-1){const t=i+a[e+1].cts;a[e].duration=t-r}else a[e].duration=e?a[e-1].duration:T;a[e].cts=0,t=i}}f=D||!f?T:f,this.nextAvcDts=c=d+f,this.videoSampleDuration=f,this.isVideoContiguous=!0;const M={data1:Er.moof(t.sequenceNumber++,h,k({},t,{samples:a})),data2:R,startPTS:g/r,endPTS:(m+f)/r,startDTS:h/r,endDTS:c/r,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:t.dropped};return t.samples=[],t.dropped=0,M}getSamplesPerFrame(t){switch(t.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(t,e,s,i,r){const n=t.inputTimeScale,a=n/(t.samplerate?t.samplerate:n),o=this.getSamplesPerFrame(t),l=o*a,h=this._initPTS,d="mp3"===t.segmentCodec&&this.typeSupported.mpeg,c=[],u=void 0!==r;let f=t.samples,g=d?0:8,m=this.nextAudioPts||-1;const p=e*n,y=h.baseTime*n/h.timescale;if(this.isAudioContiguous=s=s||f.length&&m>0&&(i&&Math.abs(p-m)<9e3||Math.abs(Dr(f[0].pts-y,p)-m)<20*l),f.forEach((function(t){t.pts=Dr(t.pts-y,p)})),!s||m<0){if(f=f.filter((t=>t.pts>=0)),!f.length)return;m=0===r?0:i&&!u?Math.max(0,p):f[0].pts}if("aac"===t.segmentCodec){const e=this.config.maxAudioFramesDrift;for(let s=0,i=m;s<f.length;s++){const r=f[s],a=r.pts,o=a-i,h=Math.abs(1e3*o/n);if(o<=-e*l&&u)0===s&&(N.warn(`Audio frame @ ${(a/n).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*o/n)} ms.`),this.nextAudioPts=m=i=a);else if(o>=e*l&&h<1e4&&u){let e=Math.round(o/l);i=a-e*l,i<0&&(e--,i+=l),0===s&&(this.nextAudioPts=m=i),N.warn(`[mp4-remuxer]: Injecting ${e} audio frame @ ${(i/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n<e;n++){const e=Math.max(i,0);let n=vr.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);n||(N.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),n=r.unit.subarray()),f.splice(s,0,{unit:n,pts:e}),i+=l,s++}}r.pts=i,i+=l}}let v,T=null,E=null,S=0,L=f.length;for(;L--;)S+=f[L].unit.byteLength;for(let e=0,i=f.length;e<i;e++){const i=f[e],r=i.unit;let n=i.pts;if(null!==E){c[e-1].duration=Math.round((n-E)/a)}else{if(s&&"aac"===t.segmentCodec&&(n=m),T=n,!(S>0))return;S+=g;try{v=new Uint8Array(S)}catch(t){return void this.observer.emit(w.ERROR,w.ERROR,{type:C.MUX_ERROR,details:P.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:S,reason:`fail allocating audio mdat ${S}`})}if(!d){new DataView(v.buffer).setUint32(0,S),v.set(Er.types.mdat,4)}}v.set(r,g);const l=r.byteLength;g+=l,c.push(new wr(!0,o,l,0)),E=n}const A=c.length;if(!A)return;const R=c[c.length-1];this.nextAudioPts=m=E+a*R.duration;const b=d?new Uint8Array(0):Er.moof(t.sequenceNumber++,T/a,k({},t,{samples:c}));t.samples=[];const D=T/n,_=m/n,I={data1:b,data2:v,startPTS:D,endPTS:_,startDTS:D,endDTS:_,type:"audio",hasAudio:!0,hasVideo:!1,nb:A};return this.isAudioContiguous=!0,I}remuxEmptyAudio(t,e,s,i){const r=t.inputTimeScale,n=r/(t.samplerate?t.samplerate:r),a=this.nextAudioPts,o=this._initDTS,l=9e4*o.baseTime/o.timescale,h=(null!==a?a:i.startDTS*r)+l,d=i.endDTS*r+l,c=1024*n,u=Math.ceil((d-h)/c),f=vr.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);if(N.warn("[mp4-remuxer]: remux empty Audio"),!f)return void N.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");const g=[];for(let t=0;t<u;t++){const e=h+t*c;g.push({unit:f,pts:e,dts:e})}return t.samples=g,this.remuxAudio(t,e,s,!1)}}function Dr(t,e){let s;if(null===e)return t;for(s=e<t?-8589934592:8589934592;Math.abs(t-e)>4294967296;)t+=s;return t}function _r(t,e,s,i){const r=t.samples.length;if(!r)return;const n=t.inputTimeScale;for(let a=0;a<r;a++){const r=t.samples[a];r.pts=Dr(r.pts-s.baseTime*n/s.timescale,e*n)/n,r.dts=Dr(r.dts-i.baseTime*n/i.timescale,e*n)/n}const a=t.samples;return t.samples=[],{samples:a}}function Ir(t,e,s){const i=t.samples.length;if(!i)return;const r=t.inputTimeScale;for(let n=0;n<i;n++){const i=t.samples[n];i.pts=Dr(i.pts-s.baseTime*r/s.timescale,e*r)/r}t.samples.sort(((t,e)=>t.pts-e.pts));const n=t.samples;return t.samples=[],{samples:n}}class wr{constructor(t,e,s,i){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=e,this.size=s,this.cts=i,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1}}}function Cr(t,e){const s=null==t?void 0:t.codec;if(s&&s.length>4)return s;if(e===V){if("ec-3"===s||"ac-3"===s||"alac"===s)return s;if("fLaC"===s||"Opus"===s){return ve(s,!1)}const t="mp4a.40.5";return N.info(`Parsed audio codec "${s}" or audio object type not handled. Using "${t}"`),t}return N.warn(`Unhandled video codec "${s}"`),"hvc1"===s||"hev1"===s?"hvc1.1.6.L120.90":"av01"===s?"av01.0.04M.08":"avc1.42e01e"}try{Ar=self.performance.now.bind(self.performance)}catch(t){N.debug("Unable to use Performance API on this environment"),Ar=null==tt?void 0:tt.Date.now}const Pr=[{demux:class{constructor(t,e){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=e}resetTimeStamp(){}resetInitSegment(t,e,s,i){const r=this.videoTrack=Mi("video",1),n=this.audioTrack=Mi("audio",1),a=this.txtTrack=Mi("text",1);if(this.id3Track=Mi("id3",1),this.timeOffset=0,null==t||!t.byteLength)return;const o=Kt(t);if(o.video){const{id:t,timescale:e,codec:s}=o.video;r.id=t,r.timescale=a.timescale=e,r.codec=s}if(o.audio){const{id:t,timescale:e,codec:s}=o.audio;n.id=t,n.timescale=e,n.codec=s}a.id=xt.text,r.sampleDuration=0,r.duration=n.duration=i}resetContiguity(){this.remainderData=null}static probe(t){return function(t){const e=t.byteLength;for(let s=0;s<e;){const i=Ot(t,s);if(i>8&&109===t[s+4]&&111===t[s+5]&&111===t[s+6]&&102===t[s+7])return!0;s=i>1?s+i:e}return!1}(t)}demux(t,e){this.timeOffset=e;let s=t;const i=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=Xt(this.remainderData,t));const e=function(t){const e={valid:null,remainder:null},s=$t(t,["moof"]);if(s.length<2)return e.remainder=t,e;const i=s[s.length-1];return e.valid=ut(t,0,i.byteOffset-8),e.remainder=ut(t,i.byteOffset-8),e}(s);this.remainderData=e.remainder,i.samples=e.valid||new Uint8Array}else i.samples=s;const n=this.extractID3Track(i,e);return r.samples=zt(e,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const t=this.timeOffset,e=this.videoTrack,s=this.txtTrack;e.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(e,this.timeOffset);return s.samples=zt(t,e),{videoTrack:e,audioTrack:Mi(),id3Track:i,textTrack:Mi()}}extractID3Track(t,e){const s=this.id3Track;if(t.samples.length){const i=$t(t.samples,["emsg"]);i&&i.forEach((t=>{const i=function(t){const e=t[0];let s="",i="",r=0,n=0,a=0,o=0,l=0,h=0;if(0===e){for(;"\0"!==Ft(t.subarray(h,h+1));)s+=Ft(t.subarray(h,h+1)),h+=1;for(s+=Ft(t.subarray(h,h+1)),h+=1;"\0"!==Ft(t.subarray(h,h+1));)i+=Ft(t.subarray(h,h+1)),h+=1;i+=Ft(t.subarray(h,h+1)),h+=1,r=Ot(t,12),n=Ot(t,16),o=Ot(t,20),l=Ot(t,24),h=28}else if(1===e){h+=4,r=Ot(t,h),h+=4;const e=Ot(t,h);h+=4;const n=Ot(t,h);for(h+=4,a=2**32*e+n,_(a)||(a=Number.MAX_SAFE_INTEGER,N.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Ot(t,h),h+=4,l=Ot(t,h),h+=4;"\0"!==Ft(t.subarray(h,h+1));)s+=Ft(t.subarray(h,h+1)),h+=1;for(s+=Ft(t.subarray(h,h+1)),h+=1;"\0"!==Ft(t.subarray(h,h+1));)i+=Ft(t.subarray(h,h+1)),h+=1;i+=Ft(t.subarray(h,h+1)),h+=1}return{schemeIdUri:s,value:i,timeScale:r,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:t.subarray(h,t.byteLength)}}(t);if(sr.test(i.schemeIdUri)){const t=D(i.presentationTime)?i.presentationTime/i.timeScale:e+i.presentationTimeDelta/i.timeScale;let r=4294967295===i.eventDuration?Number.POSITIVE_INFINITY:i.eventDuration/i.timeScale;r<=.001&&(r=Number.POSITIVE_INFINITY);const n=i.payload;s.samples.push({data:n,len:n.byteLength,dts:t,pts:t,type:ze,duration:r})}}))}return s}demuxSampleAes(t,e,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}},remux:class{constructor(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null}destroy(){}resetTimeStamp(t){this.initPTS=t,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(t,e,s,i){this.audioCodec=e,this.videoCodec=s,this.generateInitSegment(function(t,e){if(!t||!e)return t;const s=e.keyId;s&&e.isCommonEncryption&&$t(t,["moov","trak"]).forEach((t=>{const e=$t(t,["mdia","minf","stbl","stsd"])[0].subarray(8);let i=$t(e,["enca"]);const r=i.length>0;r||(i=$t(e,["encv"])),i.forEach((t=>{$t(r?t.subarray(28):t.subarray(78),["sinf"]).forEach((t=>{const e=jt(t);if(e){const t=e.subarray(8,24);t.some((t=>0!==t))||(N.log(`[eme] Patching keyId in 'enc${r?"a":"v"}>sinf>>tenc' box: ${wt(t)} -> ${wt(s)}`),e.set(s,8))}}))}))}));return t}(t,i)),this.emitInitSegment=!0}generateInitSegment(t){let{audioCodec:e,videoCodec:s}=this;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const i=this.initData=Kt(t);i.audio&&(e=Cr(i.audio,V)),i.video&&(s=Cr(i.video,Y));const r={};i.audio&&i.video?r.audiovideo={container:"video/mp4",codec:e+","+s,initSegment:t,id:"main"}:i.audio?r.audio={container:"audio/mp4",codec:e,initSegment:t,id:"audio"}:i.video?r.video={container:"video/mp4",codec:s,initSegment:t,id:"main"}:N.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=r}remux(t,e,s,i,r,n){var a,o;let{initPTS:l,lastEndTime:h}=this;const d={audio:void 0,video:void 0,text:i,id3:s,initSegment:void 0};D(h)||(h=this.lastEndTime=r||0);const c=e.samples;if(null==c||!c.length)return d;const u={initPTS:void 0,timescale:1};let f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(c),f=this.initData),null==(o=f)||!o.length)return N.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),d;this.emitInitSegment&&(u.tracks=this.initTracks,this.emitInitSegment=!1);const g=function(t,e){let s=0,i=0,r=0;const n=$t(t,["moof","traf"]);for(let t=0;t<n.length;t++){const a=n[t],o=$t(a,["tfhd"])[0],l=e[Ot(o,4)];if(!l)continue;const h=l.default,d=Ot(o,0)|(null==h?void 0:h.flags);let c=null==h?void 0:h.duration;8&d&&(c=Ot(o,2&d?12:8));const u=l.timescale||9e4,f=$t(a,["trun"]);for(let t=0;t<f.length;t++)s=qt(f[t]),!s&&c&&(s=c*Ot(f[t],4)),l.type===Y?i+=s/u:l.type===V&&(r+=s/u)}if(0===i&&0===r){let e=1/0,s=0,i=0;const r=$t(t,["sidx"]);for(let t=0;t<r.length;t++){const n=Gt(r[t]);if(null!=n&&n.references){e=Math.min(e,n.earliestPresentationTime/n.timescale);const t=n.references.reduce(((t,e)=>t+e.info.duration||0),0);s=Math.max(s,t+n.earliestPresentationTime/n.timescale),i=s-e}}if(i&&D(i))return i}return i||r}(c,f),m=function(t,e){return $t(e,["moof","traf"]).reduce(((e,s)=>{const i=$t(s,["tfdt"])[0],r=i[0],n=$t(s,["tfhd"]).reduce(((e,s)=>{const n=Ot(s,4),a=t[n];if(a){let t=Ot(i,4);if(1===r){if(t===Ct)return N.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),e;t*=Ct+1,t+=Ot(i,8)}const s=t/(a.timescale||9e4);if(D(s)&&(null===e||s<e))return s}return e}),null);return null!==n&&D(n)&&(null===e||n<e)?n:e}),null)}(f,c),p=null===m?r:m;(function(t,e,s,i){if(null===t)return!0;const r=Math.max(i,1),n=e-t.baseTime/t.timescale;return Math.abs(n-s)>r}(l,p,r,g)||u.timescale!==l.timescale&&n)&&(u.initPTS=p-r,l&&1===l.timescale&&N.warn("Adjusting initPTS by "+(u.initPTS-l.baseTime)),this.initPTS=l={baseTime:u.initPTS,timescale:1});const y=t?p-l.baseTime/l.timescale:h,v=y+g;!function(t,e,s){$t(e,["moof","traf"]).forEach((e=>{$t(e,["tfhd"]).forEach((i=>{const r=Ot(i,4),n=t[r];if(!n)return;const a=n.timescale||9e4;$t(e,["tfdt"]).forEach((t=>{const e=t[0],i=s*a;if(i){let s=Ot(t,4);if(0===e)s-=i,s=Math.max(s,0),Bt(t,4,s);else{s*=Math.pow(2,32),s+=Ot(t,8),s-=i,s=Math.max(s,0);const e=Math.floor(s/(Ct+1)),r=Math.floor(s%(Ct+1));Bt(t,4,e),Bt(t,8,r)}}}))}))}))}(f,c,l.baseTime/l.timescale),g>0?this.lastEndTime=v:(N.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const T=!!f.audio,E=!!f.video;let S="";T&&(S+="audio"),E&&(S+="video");const L={data1:c,startPTS:y,startDTS:y,endPTS:v,endDTS:v,type:S,hasAudio:T,hasVideo:E,nb:1,dropped:0};return d.audio="audio"===L.type?L:void 0,d.video="audio"!==L.type?L:void 0,d.initSegment=u,d.id3=_r(s,r,l,l),i.samples.length&&(d.text=Ir(i,r,l)),d}}},{demux:cr,remux:kr},{demux:class extends Oi{constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.observer=t,this.config=e}resetInitSegment(t,e,s,i){super.resetInitSegment(t,e,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=mt(t,0);let s=(null==e?void 0:e.length)||0;if(er(t,s))return!1;for(let e=t.length;s<e;s++)if(Ki(t,s))return N.log("ADTS sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return function(t,e){return e+5<t.length}(t,e)&&Ui(t,e)&&$i(t,e)<=t.length-e}(t,e)}appendFrame(t,e,s){Hi(t,this.observer,e,s,t.manifestCodec);const i=Yi(t,e,s,this.basePTS,this.frameIndex);if(i&&0===i.missing)return i}},remux:kr},{demux:class extends Oi{resetInitSegment(t,e,s,i){super.resetInitSegment(t,e,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=mt(t,0);let s=(null==e?void 0:e.length)||0;if(e&&11===t[s]&&119===t[s+1]&&void 0!==vt(e)&&ir(t,s)<=16)return!1;for(let e=t.length;s<e;s++)if(er(t,s))return N.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return Zi(t,e)&&4<=t.length-e}(t,e)}appendFrame(t,e,s){if(null!==this.basePTS)return Qi(t,e,s,this.basePTS,this.frameIndex)}},remux:kr}];Pr.splice(2,0,{demux:rr,remux:kr});class xr{constructor(t,e,s,i,r){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=t,this.typeSupported=e,this.config=s,this.vendor=i,this.id=r}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,s,i){const r=s.transmuxing;r.executeStart=Ar();let n=new Uint8Array(t);const{currentTransmuxState:a,transmuxConfig:o}=this;i&&(this.currentTransmuxState=i);const{contiguous:l,discontinuity:h,trackSwitch:d,accurateTimeOffset:c,timeOffset:u,initSegmentChange:f}=i||a,{audioCodec:g,videoCodec:m,defaultInitPts:p,duration:y,initSegmentData:v}=o,T=function(t,e){let s=null;t.byteLength>0&&null!=(null==e?void 0:e.key)&&null!==e.iv&&null!=e.method&&(s=e);return s}(n,e);if(T&&"AES-128"===T.method){const t=this.getDecrypter();if(!t.isSync())return this.decryptionPromise=t.webCryptoDecrypt(n,T.key.buffer,T.iv.buffer).then((t=>{const e=this.push(t,null,s);return this.decryptionPromise=null,e})),this.decryptionPromise;{let e=t.softwareDecrypt(n,T.key.buffer,T.iv.buffer);if(s.part>-1&&(e=t.flush()),!e)return r.executeEnd=Ar(),Fr(s);n=new Uint8Array(e)}}const E=this.needsProbing(h,d);if(E){const t=this.configureTransmuxer(n);if(t)return N.warn(`[transmuxer] ${t.message}`),this.observer.emit(w.ERROR,w.ERROR,{type:C.MEDIA_ERROR,details:P.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),r.executeEnd=Ar(),Fr(s)}(h||d||f||E)&&this.resetInitSegment(v,g,m,y,e),(h||f||E)&&this.resetInitialTimestamp(p),l||this.resetContiguity();const S=this.transmux(n,T,u,c,s),L=this.currentTransmuxState;return L.contiguous=!0,L.discontinuity=!1,L.trackSwitch=!1,r.executeEnd=Ar(),S}flush(t){const e=t.transmuxing;e.executeStart=Ar();const{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return r.then((()=>this.flush(t)));const n=[],{timeOffset:a}=i;if(s){const e=s.flush();e&&n.push(this.push(e,null,t))}const{demuxer:o,remuxer:l}=this;if(!o||!l)return e.executeEnd=Ar(),[Fr(t)];const h=o.flush(a);return Mr(h)?h.then((e=>(this.flushRemux(n,e,t),n))):(this.flushRemux(n,h,t),n)}flushRemux(t,e,s){const{audioTrack:i,videoTrack:r,id3Track:n,textTrack:a}=e,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;N.log(`[transmuxer.ts]: Flushed fragment ${s.sn}${s.part>-1?" p: "+s.part:""} of level ${s.level}`);const h=this.remuxer.remux(i,r,n,a,l,o,!0,this.id);t.push({remuxResult:h,chunkMeta:s}),s.transmuxing.executeEnd=Ar()}resetInitialTimestamp(t){const{demuxer:e,remuxer:s}=this;e&&s&&(e.resetTimeStamp(t),s.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:e}=this;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())}resetInitSegment(t,e,s,i,r){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(t,e,s,i),a.resetInitSegment(t,e,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,e,s,i,r){let n;return n=e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,s,i,r):this.transmuxUnencrypted(t,s,i,r),n}transmuxUnencrypted(t,e,s,i){const{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(t,e,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,n,a,o,e,s,!1,this.id),chunkMeta:i}}transmuxSampleAes(t,e,s,i,r){return this.demuxer.demuxSampleAes(t,e,s).then((t=>({remuxResult:this.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,s,i,!1,this.id),chunkMeta:r})))}configureTransmuxer(t){const{config:e,observer:s,typeSupported:i,vendor:r}=this;let n;for(let e=0,s=Pr.length;e<s;e++){var a;if(null!=(a=Pr[e].demux)&&a.probe(t)){n=Pr[e];break}}if(!n)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,l=this.remuxer,h=n.remux,d=n.demux;l&&l instanceof h||(this.remuxer=new h(s,e,i,r)),o&&o instanceof d||(this.demuxer=new d(s,e,i),this.probe=d.probe)}needsProbing(t,e){return!this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new Ti(this.config)),t}}const Fr=t=>({remuxResult:{},chunkMeta:t});function Mr(t){return"then"in t&&t.then instanceof Function}class Or{constructor(t,e,s,i,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=e,this.initSegmentData=s,this.duration=i,this.defaultInitPts=r||null}}class Nr{constructor(t,e,s,i,r,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=t,this.contiguous=e,this.accurateTimeOffset=s,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=n}}var Ur={exports:{}};!function(t){var e=Object.prototype.hasOwnProperty,s="~";function i(){}function r(t,e,s){this.fn=t,this.context=e,this.once=s||!1}function n(t,e,i,n,a){if("function"!=typeof i)throw new TypeError("The listener must be a function");var o=new r(i,n||t,a),l=s?s+e:e;return t._events[l]?t._events[l].fn?t._events[l]=[t._events[l],o]:t._events[l].push(o):(t._events[l]=o,t._eventsCount++),t}function a(t,e){0==--t._eventsCount?t._events=new i:delete t._events[e]}function o(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(s=!1)),o.prototype.eventNames=function(){var t,i,r=[];if(0===this._eventsCount)return r;for(i in t=this._events)e.call(t,i)&&r.push(s?i.slice(1):i);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},o.prototype.listeners=function(t){var e=s?s+t:t,i=this._events[e];if(!i)return[];if(i.fn)return[i.fn];for(var r=0,n=i.length,a=new Array(n);r<n;r++)a[r]=i[r].fn;return a},o.prototype.listenerCount=function(t){var e=s?s+t:t,i=this._events[e];return i?i.fn?1:i.length:0},o.prototype.emit=function(t,e,i,r,n,a){var o=s?s+t:t;if(!this._events[o])return!1;var l,h,d=this._events[o],c=arguments.length;if(d.fn){switch(d.once&&this.removeListener(t,d.fn,void 0,!0),c){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,e),!0;case 3:return d.fn.call(d.context,e,i),!0;case 4:return d.fn.call(d.context,e,i,r),!0;case 5:return d.fn.call(d.context,e,i,r,n),!0;case 6:return d.fn.call(d.context,e,i,r,n,a),!0}for(h=1,l=new Array(c-1);h<c;h++)l[h-1]=arguments[h];d.fn.apply(d.context,l)}else{var u,f=d.length;for(h=0;h<f;h++)switch(d[h].once&&this.removeListener(t,d[h].fn,void 0,!0),c){case 1:d[h].fn.call(d[h].context);break;case 2:d[h].fn.call(d[h].context,e);break;case 3:d[h].fn.call(d[h].context,e,i);break;case 4:d[h].fn.call(d[h].context,e,i,r);break;default:if(!l)for(u=1,l=new Array(c-1);u<c;u++)l[u-1]=arguments[u];d[h].fn.apply(d[h].context,l)}}return!0},o.prototype.on=function(t,e,s){return n(this,t,e,s,!1)},o.prototype.once=function(t,e,s){return n(this,t,e,s,!0)},o.prototype.removeListener=function(t,e,i,r){var n=s?s+t:t;if(!this._events[n])return this;if(!e)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn!==e||r&&!o.once||i&&o.context!==i||a(this,n);else{for(var l=0,h=[],d=o.length;l<d;l++)(o[l].fn!==e||r&&!o[l].once||i&&o[l].context!==i)&&h.push(o[l]);h.length?this._events[n]=1===h.length?h[0]:h:a(this,n)}return this},o.prototype.removeAllListeners=function(t){var e;return t?(e=s?s+t:t,this._events[e]&&a(this,e)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=s,o.EventEmitter=o,t.exports=o}(Ur);var Br=g(Ur.exports);class $r{constructor(t,e,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0;const r=t.config;this.hls=t,this.id=e,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;const n=(t,e)=>{(e=e||{}).frag=this.frag,e.id=this.id,t===w.ERROR&&(this.error=e.error),this.hls.trigger(t,e)};this.observer=new Br,this.observer.on(w.FRAG_DECRYPTED,n),this.observer.on(w.ERROR,n);const a=he(r.preferManagedMediaSource)||{isTypeSupported:()=>!1},o={mpeg:a.isTypeSupported("audio/mpeg"),mp3:a.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:a.isTypeSupported('audio/mp4; codecs="ac-3"')};if(this.useWorker&&"undefined"!=typeof Worker){if(r.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{r.workerPath?(N.log(`loading Web Worker ${r.workerPath} for "${e}"`),this.workerContext=function(t){const e=new self.URL(t,self.location.href).href;return{worker:new self.Worker(e),scriptURL:e}}(r.workerPath)):(N.log(`injecting Web Worker for "${e}"`),this.workerContext=function(){const t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),e=self.URL.createObjectURL(t);return{worker:new self.Worker(e),objectURL:e}}()),this.onwmsg=t=>this.onWorkerMessage(t);const{worker:t}=this.workerContext;t.addEventListener("message",this.onwmsg),t.onerror=t=>{const s=new Error(`${t.message} (${t.filename}:${t.lineno})`);r.enableWorker=!1,N.warn(`Error in "${e}" Web Worker, fallback to inline`),this.hls.trigger(w.ERROR,{type:C.OTHER_ERROR,details:P.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:s})},t.postMessage({cmd:"init",typeSupported:o,vendor:"",id:e,config:JSON.stringify(r)})}catch(t){N.warn(`Error setting up "${e}" Web Worker, fallback to inline`,t),this.resetWorker(),this.error=null,this.transmuxer=new xr(this.observer,o,r,"",e)}return}}this.transmuxer=new xr(this.observer,o,r,"",e)}resetWorker(){if(this.workerContext){const{worker:t,objectURL:e}=this.workerContext;e&&self.URL.revokeObjectURL(e),t.removeEventListener("message",this.onwmsg),t.onerror=null,t.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(t,e,s,i,r,n,a,o,l,h){var d,c;l.transmuxing.start=self.performance.now();const{transmuxer:u}=this,f=n?n.start:r.start,g=r.decryptdata,m=this.frag,p=!(m&&r.cc===m.cc),y=!(m&&l.level===m.level),v=m?l.sn-m.sn:-1,T=this.part?l.part-this.part.index:-1,E=0===v&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),S=!y&&(1===v||0===v&&(1===T||E&&T<=0)),L=self.performance.now();(y||v||0===r.stats.parsing.start)&&(r.stats.parsing.start=L),!n||!T&&S||(n.stats.parsing.start=L);const A=!(m&&(null==(d=r.initSegment)?void 0:d.url)===(null==(c=m.initSegment)?void 0:c.url)),R=new Nr(p,S,o,y,f,A);if(!S||p||A){N.log(`[transmuxer-interface, ${r.type}]: Starting new transmux session for sn: ${l.sn} p: ${l.part} level: ${l.level} id: ${l.id}\n discontinuity: ${p}\n trackSwitch: ${y}\n contiguous: ${S}\n accurateTimeOffset: ${o}\n timeOffset: ${f}\n initSegmentChange: ${A}`);const t=new Or(s,i,e,a,h);this.configureTransmuxer(t)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:t,decryptdata:g,chunkMeta:l,state:R},t instanceof ArrayBuffer?[t]:[]);else if(u){const e=u.push(t,g,l,R);Mr(e)?(u.async=!0,e.then((t=>{this.handleTransmuxComplete(t)})).catch((t=>{this.transmuxerError(t,l,"transmuxer-interface push error")}))):(u.async=!1,this.handleTransmuxComplete(e))}}flush(t){t.transmuxing.start=self.performance.now();const{transmuxer:e}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:t});else if(e){let s=e.flush(t);Mr(s)||e.async?(Mr(s)||(s=Promise.resolve(s)),s.then((e=>{this.handleFlushResult(e,t)})).catch((e=>{this.transmuxerError(e,t,"transmuxer-interface flush error")}))):this.handleFlushResult(s,t)}}transmuxerError(t,e,s){this.hls&&(this.error=t,this.hls.trigger(w.ERROR,{type:C.MEDIA_ERROR,details:P.FRAG_PARSING_ERROR,chunkMeta:e,frag:this.frag||void 0,fatal:!1,error:t,err:t,reason:s}))}handleFlushResult(t,e){t.forEach((t=>{this.handleTransmuxComplete(t)})),this.onFlush(e)}onWorkerMessage(t){const e=t.data;if(null==e||!e.event)return void N.warn("worker message received with no "+(e?"event name":"data"));const s=this.hls;if(this.hls)switch(e.event){case"init":{var i;const t=null==(i=this.workerContext)?void 0:i.objectURL;t&&self.URL.revokeObjectURL(t);break}case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;case"workerLog":N[e.data.logType]&&N[e.data.logType](e.data.message);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.id=this.id,s.trigger(e.event,e.data)}}configureTransmuxer(t){const{transmuxer:e}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:t}):e&&e.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}function Gr(t,e){if(t.length!==e.length)return!1;for(let s=0;s<t.length;s++)if(!Kr(t[s].attrs,e[s].attrs))return!1;return!0}function Kr(t,e,s){const i=t["STABLE-RENDITION-ID"];return i&&!s?i===e["STABLE-RENDITION-ID"]:!(s||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some((s=>t[s]!==e[s]))}function Hr(t,e){return e.label.toLowerCase()===t.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(t.lang||"").toLowerCase())}class Vr{constructor(t){this.buffered=void 0;const e=(e,s,i)=>{if((s>>>=0)>i-1)throw new DOMException(`Failed to execute '${e}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${i})`);return t[s][e]};this.buffered={get length(){return t.length},end:s=>e("end",s,t.length),start:s=>e("start",s,t.length)}}}class Yr{constructor(t){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=t}append(t,e,s){const i=this.queues[e];i.push(t),1!==i.length||s||this.executeNext(e)}insertAbort(t,e){this.queues[e].unshift(t),this.executeNext(e)}appendBlocker(t){let e;const s=new Promise((t=>{e=t})),i={execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(i,t),s}executeNext(t){const e=this.queues[t];if(e.length){const s=e[0];try{s.execute()}catch(e){N.warn(`[buffer-operation-queue]: Exception executing "${t}" SourceBuffer operation: ${e}`),s.onError(e);const i=this.buffers[t];null!=i&&i.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){this.queues[t].shift(),this.executeNext(t)}current(t){return this.queues[t][0]}}const Wr=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;function jr(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach((e=>{t.removeChild(e)}))}const qr={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},Xr=t=>String.fromCharCode(qr[t]||t),zr=15,Qr=100,Jr={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Zr={17:2,18:4,21:6,22:8,23:10,19:13,20:15},tn={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},en={25:2,26:4,29:6,30:8,31:10,27:13,28:15},sn=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class rn{constructor(){this.time=null,this.verboseLevel=0}log(t,e){if(this.verboseLevel>=t){const s="function"==typeof e?e():e;N.log(`${this.time} [${t}] ${s}`)}}}const nn=function(t){const e=[];for(let s=0;s<t.length;s++)e.push(t[s].toString(16));return e};class an{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(t){const e=["foreground","underline","italics","background","flash"];for(let s=0;s<e.length;s++){const i=e[s];t.hasOwnProperty(i)&&(this[i]=t[i])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(t){return this.foreground===t.foreground&&this.underline===t.underline&&this.italics===t.italics&&this.background===t.background&&this.flash===t.flash}copy(t){this.foreground=t.foreground,this.underline=t.underline,this.italics=t.italics,this.background=t.background,this.flash=t.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class on{constructor(){this.uchar=" ",this.penState=new an}reset(){this.uchar=" ",this.penState.reset()}setChar(t,e){this.uchar=t,this.penState.copy(e)}setPenState(t){this.penState.copy(t)}equals(t){return this.uchar===t.uchar&&this.penState.equals(t.penState)}copy(t){this.uchar=t.uchar,this.penState.copy(t.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}}class ln{constructor(t){this.chars=[],this.pos=0,this.currPenState=new an,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Qr;t++)this.chars.push(new on);this.logger=t}equals(t){for(let e=0;e<Qr;e++)if(!this.chars[e].equals(t.chars[e]))return!1;return!0}copy(t){for(let e=0;e<Qr;e++)this.chars[e].copy(t.chars[e])}isEmpty(){let t=!0;for(let e=0;e<Qr;e++)if(!this.chars[e].isEmpty()){t=!1;break}return t}setCursor(t){this.pos!==t&&(this.pos=t),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Qr&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Qr)}moveCursor(t){const e=this.pos+t;if(t>1)for(let t=this.pos+1;t<e+1;t++)this.chars[t].setPenState(this.currPenState);this.setCursor(e)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(t){t>=144&&this.backSpace();const e=Xr(t);this.pos>=Qr?this.logger.log(0,(()=>"Cannot insert "+t.toString(16)+" ("+e+") at position "+this.pos+". Skipping it!")):(this.chars[this.pos].setChar(e,this.currPenState),this.moveCursor(1))}clearFromPos(t){let e;for(e=t;e<Qr;e++)this.chars[e].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const t=[];let e=!0;for(let s=0;s<Qr;s++){const i=this.chars[s].uchar;" "!==i&&(e=!1),t.push(i)}return e?"":t.join("")}setPenStyles(t){this.currPenState.setStyles(t);this.chars[this.pos].setPenState(this.currPenState)}}class hn{constructor(t){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let e=0;e<zr;e++)this.rows.push(new ln(t));this.logger=t}reset(){for(let t=0;t<zr;t++)this.rows[t].clear();this.currRow=14}equals(t){let e=!0;for(let s=0;s<zr;s++)if(!this.rows[s].equals(t.rows[s])){e=!1;break}return e}copy(t){for(let e=0;e<zr;e++)this.rows[e].copy(t.rows[e])}isEmpty(){let t=!0;for(let e=0;e<zr;e++)if(!this.rows[e].isEmpty()){t=!1;break}return t}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(t){this.rows[this.currRow].insertChar(t)}setPen(t){this.rows[this.currRow].setPenStyles(t)}moveCursor(t){this.rows[this.currRow].moveCursor(t)}setCursor(t){this.logger.log(2,"setCursor: "+t);this.rows[this.currRow].setCursor(t)}setPAC(t){this.logger.log(2,(()=>"pacData = "+JSON.stringify(t)));let e=t.row-1;if(this.nrRollUpRows&&e<this.nrRollUpRows-1&&(e=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==e){for(let t=0;t<zr;t++)this.rows[t].clear();const t=this.currRow+1-this.nrRollUpRows,s=this.lastOutputScreen;if(s){const i=s.rows[t].cueStartTime,r=this.logger.time;if(null!==i&&null!==r&&i<r)for(let i=0;i<this.nrRollUpRows;i++)this.rows[e-this.nrRollUpRows+i+1].copy(s.rows[t+i])}}this.currRow=e;const s=this.rows[this.currRow];if(null!==t.indent){const e=t.indent,i=Math.max(e-1,0);s.setCursor(t.indent),t.color=s.chars[i].penState.foreground}const i={foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:!1};this.setPen(i)}setBkgData(t){this.logger.log(2,(()=>"bkgData = "+JSON.stringify(t))),this.backSpace(),this.setPen(t),this.insertChar(32)}setRollUpRows(t){this.nrRollUpRows=t}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,(()=>this.getDisplayText()));const t=this.currRow+1-this.nrRollUpRows,e=this.rows.splice(t,1)[0];e.clear(),this.rows.splice(this.currRow,0,e),this.logger.log(2,"Rolling up")}getDisplayText(t){t=t||!1;const e=[];let s="",i=-1;for(let s=0;s<zr;s++){const r=this.rows[s].getTextString();r&&(i=s+1,t?e.push("Row "+i+": '"+r+"'"):e.push(r.trim()))}return e.length>0&&(s=t?"["+e.join(" | ")+"]":e.join("\n")),s}getTextAndFormat(){return this.rows}}class dn{constructor(t,e,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=t,this.outputFilter=e,this.mode=null,this.verbose=0,this.displayedMemory=new hn(s),this.nonDisplayedMemory=new hn(s),this.lastOutputScreen=new hn(s),this.currRollUpRow=this.displayedMemory.rows[14],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[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(t){this.outputFilter=t}setPAC(t){this.writeScreen.setPAC(t)}setBkgData(t){this.writeScreen.setBkgData(t)}setMode(t){t!==this.mode&&(this.mode=t,this.logger.log(2,(()=>"MODE="+t)),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=t)}insertChars(t){for(let e=0;e<t.length;e++)this.writeScreen.insertChar(t[e]);const e=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,(()=>e+": "+this.writeScreen.getDisplayText(!0))),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,(()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0))),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(t){this.logger.log(2,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){const t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,(()=>"DISP: "+this.displayedMemory.getDisplayText()))}this.outputDataUpdate(!0)}ccTO(t){this.logger.log(2,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)}ccMIDROW(t){const e={flash:!1};if(e.underline=t%2==1,e.italics=t>=46,e.italics)e.foreground="white";else{const s=Math.floor(t/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];e.foreground=i[s]}this.logger.log(2,"MIDROW: "+JSON.stringify(e)),this.writeScreen.setPen(e)}outputDataUpdate(t=!1){const e=this.logger.time;null!==e&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:e):this.cueStartTime=e,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))}}class cn{constructor(t,e,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const i=this.logger=new rn;this.channels=[null,new dn(t,e,i),new dn(t+1,s,i)]}getHandler(t){return this.channels[t].getHandler()}setHandler(t,e){this.channels[t].setHandler(e)}addData(t,e){this.logger.time=t;for(let t=0;t<e.length;t+=2){const s=127&e[t],i=127&e[t+1];let r=!1,n=null;if(0===s&&0===i)continue;this.logger.log(3,(()=>"["+nn([e[t],e[t+1]])+"] -> ("+nn([s,i])+")"));const a=this.cmdHistory;if(s>=16&&s<=31){if(fn(s,i,a)){un(null,null,a),this.logger.log(3,(()=>"Repeated command ("+nn([s,i])+") is dropped"));continue}un(s,i,this.cmdHistory),r=this.parseCmd(s,i),r||(r=this.parseMidrow(s,i)),r||(r=this.parsePAC(s,i)),r||(r=this.parseBackgroundAttributes(s,i))}else un(null,null,a);if(!r&&(n=this.parseChars(s,i),n)){const t=this.currentChannel;if(t&&t>0){this.channels[t].insertChars(n)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}r||n||this.logger.log(2,(()=>"Couldn't parse cleaned data "+nn([s,i])+" orig: "+nn([e[t],e[t+1]])))}}parseCmd(t,e){if(!((20===t||28===t||21===t||29===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=33&&e<=35))return!1;const s=20===t||21===t||23===t?1:2,i=this.channels[s];return 20===t||21===t||28===t||29===t?32===e?i.ccRCL():33===e?i.ccBS():34===e?i.ccAOF():35===e?i.ccAON():36===e?i.ccDER():37===e?i.ccRU(2):38===e?i.ccRU(3):39===e?i.ccRU(4):40===e?i.ccFON():41===e?i.ccRDC():42===e?i.ccTR():43===e?i.ccRTD():44===e?i.ccEDM():45===e?i.ccCR():46===e?i.ccENM():47===e&&i.ccEOC():i.ccTO(e-32),this.currentChannel=s,!0}parseMidrow(t,e){let s=0;if((17===t||25===t)&&e>=32&&e<=47){if(s=17===t?1:2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[s];return!!i&&(i.ccMIDROW(e),this.logger.log(3,(()=>"MIDROW ("+nn([t,e])+")")),!0)}return!1}parsePAC(t,e){let s;if(!((t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127)&&!((16===t||24===t)&&e>=64&&e<=95))return!1;const i=t<=23?1:2;s=e>=64&&e<=95?1===i?Jr[t]:tn[t]:1===i?Zr[t]:en[t];const r=this.channels[i];return!!r&&(r.setPAC(this.interpretPAC(s,e)),this.currentChannel=i,!0)}interpretPAC(t,e){let s;const i={color:null,italics:!1,indent:null,underline:!1,row:t};return s=e>95?e-96:e-64,i.underline=!(1&~s),s<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((s-16)/2),i}parseChars(t,e){let s,i=null,r=null;if(t>=25?(s=2,r=t-8):(s=1,r=t),r>=17&&r<=19){let t;t=17===r?e+80:18===r?e+112:e+144,this.logger.log(2,(()=>"Special char '"+Xr(t)+"' in channel "+s)),i=[t]}else t>=32&&t<=127&&(i=0===e?[t]:[t,e]);return i&&this.logger.log(3,(()=>"Char codes = "+nn(i).join(","))),i}parseBackgroundAttributes(t,e){if(!((16===t||24===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=45&&e<=47))return!1;let s;const i={};16===t||24===t?(s=Math.floor((e-32)/2),i.background=sn[s],e%2==1&&(i.background=i.background+"_semi")):45===e?i.background="transparent":(i.foreground="black",47===e&&(i.underline=!0));const r=t<=23?1:2;return this.channels[r].setBkgData(i),!0}reset(){for(let t=0;t<Object.keys(this.channels).length;t++){const e=this.channels[t];e&&e.reset()}un(null,null,this.cmdHistory)}cueSplitAtTime(t){for(let e=0;e<this.channels.length;e++){const s=this.channels[e];s&&s.cueSplitAtTime(t)}}}function un(t,e,s){s.a=t,s.b=e}function fn(t,e,s){return s.a===t&&s.b===e}class gn{constructor(t,e){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=e}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(t,e,s){(null===this.startTime||this.startTime>t)&&(this.startTime=t),this.endTime=e,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var mn=function(){if(null!=tt&&tt.VTTCue)return self.VTTCue;const t=["","lr","rl"],e=["start","middle","end","left","right"];function s(t,e){if("string"!=typeof e)return!1;if(!Array.isArray(t))return!1;const s=e.toLowerCase();return!!~t.indexOf(s)&&s}function i(t){return s(e,t)}function r(t,...e){let s=1;for(;s<arguments.length;s++){const e=arguments[s];for(const s in e)t[s]=e[s]}return t}function n(e,n,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let h="",d=!1,c=e,u=n,f=a,g=null,m="",p=!0,y="auto",v="start",T=50,E="middle",S=50,L="middle";Object.defineProperty(o,"id",r({},l,{get:function(){return h},set:function(t){h=""+t}})),Object.defineProperty(o,"pauseOnExit",r({},l,{get:function(){return d},set:function(t){d=!!t}})),Object.defineProperty(o,"startTime",r({},l,{get:function(){return c},set:function(t){if("number"!=typeof t)throw new TypeError("Start time must be set to a number.");c=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",r({},l,{get:function(){return u},set:function(t){if("number"!=typeof t)throw new TypeError("End time must be set to a number.");u=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",r({},l,{get:function(){return f},set:function(t){f=""+t,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",r({},l,{get:function(){return g},set:function(t){g=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",r({},l,{get:function(){return m},set:function(e){const i=function(e){return s(t,e)}(e);if(!1===i)throw new SyntaxError("An invalid or illegal string was specified.");m=i,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",r({},l,{get:function(){return p},set:function(t){p=!!t,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",r({},l,{get:function(){return y},set:function(t){if("number"!=typeof t&&"auto"!==t)throw new SyntaxError("An invalid number or illegal string was specified.");y=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",r({},l,{get:function(){return v},set:function(t){const e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");v=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",r({},l,{get:function(){return T},set:function(t){if(t<0||t>100)throw new Error("Position must be between 0 and 100.");T=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",r({},l,{get:function(){return E},set:function(t){const e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",r({},l,{get:function(){return S},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");S=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",r({},l,{get:function(){return L},set:function(t){const e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");L=e,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class pn{decode(t,e){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function yn(t){function e(t,e,s,i){return 3600*(0|t)+60*(0|e)+(0|s)+parseFloat(i||0)}const s=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return s?parseFloat(s[2])>59?e(s[2],s[3],0,s[4]):e(s[1],s[2],s[3],s[4]):null}class vn{constructor(){this.values=Object.create(null)}set(t,e){this.get(t)||""===e||(this.values[t]=e)}get(t,e,s){return s?this.has(t)?this.values[t]:e[s]:this.has(t)?this.values[t]:e}has(t){return t in this.values}alt(t,e,s){for(let i=0;i<s.length;++i)if(e===s[i]){this.set(t,e);break}}integer(t,e){/^-?\d+$/.test(e)&&this.set(t,parseInt(e,10))}percent(t,e){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(e)){const s=parseFloat(e);if(s>=0&&s<=100)return this.set(t,s),!0}return!1}}function Tn(t,e,s,i){const r=i?t.split(i):[t];for(const t in r){if("string"!=typeof r[t])continue;const i=r[t].split(s);if(2!==i.length)continue;e(i[0],i[1])}}const En=new mn(0,0,""),Sn="middle"===En.align?"middle":"center";function Ln(t,e,s){const i=t;function r(){const e=yn(t);if(null===e)throw new Error("Malformed timestamp: "+i);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function n(){t=t.replace(/^\s+/,"")}if(n(),e.startTime=r(),n(),"--\x3e"!==t.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);t=t.slice(3),n(),e.endTime=r(),n(),function(t,e){const i=new vn;Tn(t,(function(t,e){let r;switch(t){case"region":for(let r=s.length-1;r>=0;r--)if(s[r].id===e){i.set(t,s[r].region);break}break;case"vertical":i.alt(t,e,["rl","lr"]);break;case"line":r=e.split(","),i.integer(t,r[0]),i.percent(t,r[0])&&i.set("snapToLines",!1),i.alt(t,r[0],["auto"]),2===r.length&&i.alt("lineAlign",r[1],["start",Sn,"end"]);break;case"position":r=e.split(","),i.percent(t,r[0]),2===r.length&&i.alt("positionAlign",r[1],["start",Sn,"end","line-left","line-right","auto"]);break;case"size":i.percent(t,e);break;case"align":i.alt(t,e,["start",Sn,"end","left","right"])}}),/:/,/\s/),e.region=i.get("region",null),e.vertical=i.get("vertical","");let r=i.get("line","auto");"auto"===r&&-1===En.line&&(r=-1),e.line=r,e.lineAlign=i.get("lineAlign","start"),e.snapToLines=i.get("snapToLines",!0),e.size=i.get("size",100),e.align=i.get("align",Sn);let n=i.get("position","auto");"auto"===n&&50===En.position&&(n="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=n}(t,e)}function An(t){return t.replace(/<br(?: \/)?>/gi,"\n")}class Rn{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new pn,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(t){const e=this;function s(){let t=e.buffer,s=0;for(t=An(t);s<t.length&&"\r"!==t[s]&&"\n"!==t[s];)++s;const i=t.slice(0,s);return"\r"===t[s]&&++s,"\n"===t[s]&&++s,e.buffer=t.slice(s),i}t&&(e.buffer+=e.decoder.decode(t,{stream:!0}));try{let t="";if("INITIAL"===e.state){if(!/\r\n|\n/.test(e.buffer))return this;t=s();const i=t.match(/^()?WEBVTT([ \t].*)?$/);if(null==i||!i[0])throw new Error("Malformed WebVTT signature.");e.state="HEADER"}let i=!1;for(;e.buffer;){if(!/\r\n|\n/.test(e.buffer))return this;switch(i?i=!1:t=s(),e.state){case"HEADER":/:/.test(t)?Tn(t,(function(t,e){}),/:/):t||(e.state="ID");continue;case"NOTE":t||(e.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(t)){e.state="NOTE";break}if(!t)continue;if(e.cue=new mn(0,0,""),e.state="CUE",-1===t.indexOf("--\x3e")){e.cue.id=t;continue}case"CUE":if(!e.cue){e.state="BADCUE";continue}try{Ln(t,e.cue,e.regionList)}catch(t){e.cue=null,e.state="BADCUE";continue}e.state="CUETEXT";continue;case"CUETEXT":{const s=-1!==t.indexOf("--\x3e");if(!t||s&&(i=!0)){e.oncue&&e.cue&&e.oncue(e.cue),e.cue=null,e.state="ID";continue}if(null===e.cue)continue;e.cue.text&&(e.cue.text+="\n"),e.cue.text+=t}continue;case"BADCUE":t||(e.state="ID")}}}catch(t){"CUETEXT"===e.state&&e.cue&&e.oncue&&e.oncue(e.cue),e.cue=null,e.state="INITIAL"===e.state?"BADWEBVTT":"BADCUE"}return this}flush(){const t=this;try{if((t.cue||"HEADER"===t.state)&&(t.buffer+="\n\n",t.parse()),"INITIAL"===t.state||"BADWEBVTT"===t.state)throw new Error("Malformed WebVTT signature.")}catch(e){t.onparsingerror&&t.onparsingerror(e)}return t.onflush&&t.onflush(),this}}const bn=/\r\n|\n\r|\n|\r/g,kn=function(t,e,s=0){return t.slice(s,s+e.length)===e},Dn=function(t){let e=5381,s=t.length;for(;s;)e=33*e^t.charCodeAt(--s);return(e>>>0).toString()};function _n(t,e,s){return Dn(t.toString())+Dn(e.toString())+Dn(s)}function In(t,e,s,i,r,n,a){const o=new Rn,l=Dt(new Uint8Array(t)).trim().replace(bn,"\n").split("\n"),h=[],d=e?function(t,e=1){return Sr(t,9e4,1/e)}(e.baseTime,e.timescale):0;let c,u="00:00.000",f=0,g=0,m=!0;o.oncue=function(t){const n=s[i];let a=s.ccOffset;const o=(f-d)/9e4;if(null!=n&&n.new&&(void 0!==g?a=s.ccOffset=n.start:function(t,e,s){let i=t[e],r=t[i.prevCC];if(!r||!r.new&&i.new)return t.ccOffset=t.presentationOffset=i.start,void(i.new=!1);for(;null!=(n=r)&&n.new;){var n;t.ccOffset+=i.start-r.start,i.new=!1,i=r,r=t[i.prevCC]}t.presentationOffset=s}(s,i,o)),o){if(!e)return void(c=new Error("Missing initPTS for VTT MPEGTS"));a=o-s.presentationOffset}const l=t.endTime-t.startTime,u=Dr(9e4*(t.startTime+a-g),9e4*r)/9e4;t.startTime=Math.max(u,0),t.endTime=Math.max(u+l,0);const m=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(m)),t.id||(t.id=_n(t.startTime,t.endTime,m)),t.endTime>0&&h.push(t)},o.onparsingerror=function(t){c=t},o.onflush=function(){c?a(c):n(h)},l.forEach((t=>{if(m){if(kn(t,"X-TIMESTAMP-MAP=")){m=!1,t.slice(16).split(",").forEach((t=>{kn(t,"LOCAL:")?u=t.slice(6):kn(t,"MPEGTS:")&&(f=parseInt(t.slice(7)))}));try{g=function(t){let e=parseInt(t.slice(-3));const s=parseInt(t.slice(-6,-4)),i=parseInt(t.slice(-9,-7)),r=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!(D(e)&&D(s)&&D(i)&&D(r)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return e+=1e3*s,e+=6e4*i,e+=36e5*r,e}(u)/1e3}catch(t){c=t}return}""===t&&(m=!1)}o.parse(t+"\n")})),o.flush()}const wn="stpp.ttml.im1t",Cn=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Pn=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,xn={left:"start",center:"center",right:"end",start:"start",end:"end"};function Fn(t,e,s,i){const r=$t(new Uint8Array(t),["mdat"]);if(0===r.length)return void i(new Error("Could not parse IMSC1 mdat"));const n=r.map((t=>Dt(t))),a=function(t,e,s=1,i=!1){return Sr(t,e,1/s,i)}(e.baseTime,1,e.timescale);try{n.forEach((t=>s(function(t,e){const s=(new DOMParser).parseFromString(t,"text/xml"),i=s.getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(r).reduce(((t,e)=>(t[e]=i.getAttribute(`ttp:${e}`)||r[e],t)),{}),a="preserve"!==i.getAttribute("xml:space"),o=On(Mn(i,"styling","style")),l=On(Mn(i,"layout","region")),h=Mn(i,"body","[begin]");return[].map.call(h,(t=>{const s=Nn(t,a);if(!s||!t.hasAttribute("begin"))return null;const i=$n(t.getAttribute("begin"),n),r=$n(t.getAttribute("dur"),n);let h=$n(t.getAttribute("end"),n);if(null===i)throw Bn(t);if(null===h){if(null===r)throw Bn(t);h=i+r}const d=new mn(i-e,h-e,s);d.id=_n(d.startTime,d.endTime,d.text);const c=function(t,e,s){const i="http://www.w3.org/ns/ttml#styling";let r=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;a&&s.hasOwnProperty(a)&&(r=s[a]);return n.reduce(((s,n)=>{const a=Un(e,i,n)||Un(t,i,n)||Un(r,i,n);return a&&(s[n]=a),s}),{})}(l[t.getAttribute("region")],o[t.getAttribute("style")],o),{textAlign:u}=c;if(u){const t=xn[u];t&&(d.lineAlign=t),d.align=u}return k(d,c),d})).filter((t=>null!==t))}(t,a))))}catch(t){i(t)}}function Mn(t,e,s){const i=t.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(s)):[]}function On(t){return t.reduce(((t,e)=>{const s=e.getAttribute("xml:id");return s&&(t[s]=e),t}),{})}function Nn(t,e){return[].slice.call(t.childNodes).reduce(((t,s,i)=>{var r;return"br"===s.nodeName&&i?t+"\n":null!=(r=s.childNodes)&&r.length?Nn(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent}),"")}function Un(t,e,s){return t&&t.hasAttributeNS(e,s)?t.getAttributeNS(e,s):null}function Bn(t){return new Error(`Could not parse ttml timestamp ${t}`)}function $n(t,e){if(!t)return null;let s=yn(t);return null===s&&(Cn.test(t)?s=function(t,e){const s=Cn.exec(t),i=(0|s[4])+(0|s[5])/e.subFrameRate;return 3600*(0|s[1])+60*(0|s[2])+(0|s[3])+i/e.frameRate}(t,e):Pn.test(t)&&(s=function(t,e){const s=Pn.exec(t),i=Number(s[1]);switch(s[2]){case"h":return 3600*i;case"m":return 60*i;case"ms":return 1e3*i;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}(t,e))),s}function Gn(t){return t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles"}function Kn(t,e){return!!t&&t.kind===Gn(e)&&Hr(e,t)}class Hn{constructor(t){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:t}=this;t.on(w.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(w.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(w.MANIFEST_PARSED,this.onManifestParsed,this),t.on(w.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(w.BUFFER_CODECS,this.onBufferCodecs,this),t.on(w.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(w.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(w.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(w.MANIFEST_PARSED,this.onManifestParsed,this),t.off(w.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(w.BUFFER_CODECS,this.onBufferCodecs,this),t.off(w.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,e){const s=this.hls.levels[e.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(t,e){this.media=e.media instanceof HTMLVideoElement?e.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(t,e){const s=this.hls;this.restrictedLevels=[],this.firstLevel=e.firstLevel,s.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onLevelsUpdated(t,e){this.timer&&D(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,e){this.hls.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const t=this.hls.levels;if(t.length){const e=this.hls,s=this.getMaxLevel(t.length-1);s!==this.autoLevelCapping&&N.log(`Setting autoLevelCapping to ${s}: ${t[s].height}p@${t[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),e.autoLevelCapping=s,e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}}getMaxLevel(t){const e=this.hls.levels;if(!e.length)return-1;const s=e.filter(((e,s)=>this.isLevelAllowed(e)&&s<=t));return this.clientRect=null,Hn.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;const t=this.media,e={width:0,height:0};if(t){const s=t.getBoundingClientRect();e.width=s.width,e.height=s.height,e.width||e.height||(e.width=s.right-s.left||t.width||0,e.height=s.bottom-s.top||t.height||0)}return this.clientRect=e,e}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch(t){}return t}isLevelAllowed(t){return!this.restrictedLevels.some((e=>t.bitrate===e.bitrate&&t.width===e.width&&t.height===e.height))}static getMaxLevelByMediaSize(t,e,s){if(null==t||!t.length)return-1;let i=t.length-1;const r=Math.max(e,s);for(let e=0;e<t.length;e+=1){const s=t[e];if((s.width>=r||s.height>=r)&&(n=s,!(a=t[e+1])||n.width!==a.width||n.height!==a.height)){i=e;break}}var n,a;return i}}const Vn="[eme]";class Yn{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=Yn.CDMCleanupPromise?[Yn.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=N.debug.bind(N,Vn),this.log=N.log.bind(N,Vn),this.warn=N.warn.bind(N,Vn),this.error=N.error.bind(N,Vn),this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(w.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(w.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(w.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(w.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(w.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(w.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(t){const{drmSystems:e,widevineLicenseUrl:s}=this.config,i=e[t];if(i)return i.licenseUrl;if(t===et.WIDEVINE&&s)return s;throw new Error(`no license server URL configured for key-system "${t}"`)}getServerCertificateUrl(t){const{drmSystems:e}=this.config,s=e[t];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const e=this.hls.levels,s=(t,e,s)=>!!t&&s.indexOf(t)===e,i=e.map((t=>t.audioCodec)).filter(s),r=e.map((t=>t.videoCodec)).filter(s);return i.length+r.length===0&&r.push("avc1.42e01e"),new Promise(((e,s)=>{const n=t=>{const a=t.shift();this.getMediaKeysPromise(a,i,r).then((t=>e({keySystem:a,mediaKeys:t}))).catch((e=>{t.length?n(t):s(e instanceof Wn?e:new Wn({type:C.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_NO_ACCESS,error:e,fatal:!0},e.message))}))};n(t)}))}requestMediaKeySystemAccess(t,e){const{requestMediaKeySystemAccessFunc:s}=this.config;if("function"!=typeof s){let t=`Configured requestMediaKeySystemAccess is not a function ${s}`;return null===dt&&"http:"===self.location.protocol&&(t=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(t))}return s(t,e)}getMediaKeysPromise(t,e,s){const i=function(t,e,s,i){let r;switch(t){case et.FAIRPLAY:r=["cenc","sinf"];break;case et.WIDEVINE:case et.PLAYREADY:r=["cenc"];break;case et.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${t}`)}return function(t,e,s,i){return[{initDataTypes:t,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map((t=>({contentType:`audio/mp4; codecs="${t}"`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null}))),videoCapabilities:s.map((t=>({contentType:`video/mp4; codecs="${t}"`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null})))}]}(r,e,s,i)}(t,e,s,this.config.drmSystemOptions),r=this.keySystemAccessPromises[t];let n=null==r?void 0:r.keySystemAccess;if(!n){this.log(`Requesting encrypted media "${t}" key-system access with config: ${JSON.stringify(i)}`),n=this.requestMediaKeySystemAccess(t,i);const e=this.keySystemAccessPromises[t]={keySystemAccess:n};return n.catch((e=>{this.log(`Failed to obtain access to key-system "${t}": ${e}`)})),n.then((s=>{this.log(`Access for key-system "${s.keySystem}" obtained`);const i=this.fetchServerCertificate(t);return this.log(`Create media-keys for "${t}"`),e.mediaKeys=s.createMediaKeys().then((e=>(this.log(`Media-keys created for "${t}"`),i.then((s=>s?this.setMediaKeysServerCertificate(e,t,s):e))))),e.mediaKeys.catch((e=>{this.error(`Failed to create media-keys for "${t}"}: ${e}`)})),e.mediaKeys}))}return n.then((()=>r.mediaKeys))}createMediaKeySessionContext({decryptdata:t,keySystem:e,mediaKeys:s}){this.log(`Creating key-system session "${e}" keyId: ${wt(t.keyId||[])}`);const i=s.createSession(),r={decryptdata:t,keySystem:e,mediaKeys:s,mediaKeysSession:i,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(t){const e=t.decryptdata;if(e.pssh){const s=this.createMediaKeySessionContext(t),i=this.getKeyIdString(e),r="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(s,r,e.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}getKeyIdString(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(null===t.keyId)throw new Error("keyId is null");return wt(t.keyId)}updateKeySession(t,e){var s;const i=t.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyID ${wt((null==(s=t.decryptdata)?void 0:s.keyId)||[])}\n } (data length: ${e?e.byteLength:e})`),i.update(e)}selectKeySystemFormat(t){const e=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)),this.keyFormatPromise}getKeyFormatPromise(t){return new Promise(((e,s)=>{const i=ht(this.config),r=t.map(at).filter((t=>!!t&&-1!==i.indexOf(t)));return this.getKeySystemSelectionPromise(r).then((({keySystem:t})=>{const i=lt(t);i?e(i):s(new Error(`Unable to find format for key-system "${t}"`))})).catch(s)}))}loadKey(t){const e=t.keyInfo.decryptdata,s=this.getKeyIdString(e),i=`(keyId: ${s} format: "${e.keyFormat}" method: ${e.method} uri: ${e.uri})`;this.log(`Starting session for key ${i}`);let r=this.keyIdToKeySessionPromise[s];return r||(r=this.keyIdToKeySessionPromise[s]=this.getKeySystemForKeyPromise(e).then((({keySystem:s,mediaKeys:r})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${i}`),this.attemptSetMediaKeys(s,r).then((()=>{this.throwIfDestroyed();const t=this.createMediaKeySessionContext({keySystem:s,mediaKeys:r,decryptdata:e});return this.generateRequestWithPreferredKeySession(t,"cenc",e.pssh,"playlist-key")}))))),r.catch((t=>this.handleError(t)))),r}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t){this.hls&&(this.error(t.message),t instanceof Wn?this.hls.trigger(w.ERROR,t.data):this.hls.trigger(w.ERROR,{type:C.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0}))}getKeySystemForKeyPromise(t){const e=this.getKeyIdString(t),s=this.keyIdToKeySessionPromise[e];if(!s){const e=at(t.keyFormat),s=e?[e]:ht(this.config);return this.attemptKeySystemAccess(s)}return s}getKeySystemSelectionPromise(t){if(t.length||(t=ht(this.config)),0===t.length)throw new Wn({type:C.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}_onMediaEncrypted(t){const{initDataType:e,initData:s}=t;if(this.debug(`"${t.type}" event: init data type: "${e}"`),null===s)return;let i,r;if("sinf"===e&&this.config.drmSystems[et.FAIRPLAY]){const t=Ft(new Uint8Array(s));try{const e=Q(JSON.parse(t).sinf),s=jt(new Uint8Array(e));if(!s)return;i=s.subarray(8,24),r=et.FAIRPLAY}catch(t){return void this.warn('Failed to parse sinf "encrypted" event message initData')}}else{const t=function(t){if(!(t instanceof ArrayBuffer)||t.byteLength<32)return null;const e={version:0,systemId:"",kids:null,data:null},s=new DataView(t),i=s.getUint32(0);if(t.byteLength!==i&&i>44)return null;if(1886614376!==s.getUint32(4))return null;if(e.version=s.getUint32(8)>>>24,e.version>1)return null;e.systemId=wt(new Uint8Array(t,12,16));const r=s.getUint32(28);if(0===e.version){if(i-32<r)return null;e.data=new Uint8Array(t,32,r)}else if(1===e.version){e.kids=[];for(let s=0;s<r;s++)e.kids.push(new Uint8Array(t,32+16*s,16))}return e}(s);if(null===t)return;0===t.version&&t.systemId===ot&&t.data&&(i=t.data.subarray(8,24)),r=function(t){if(t===ot)return et.WIDEVINE}(t.systemId)}if(!r||!i)return;const n=wt(i),{keyIdToKeySessionPromise:a,mediaKeySessions:o}=this;let l=a[n];for(let t=0;t<o.length;t++){const r=o[t],h=r.decryptdata;if(h.pssh||!h.keyId)continue;const d=wt(h.keyId);if(n===d||-1!==h.uri.replace(/-/g,"").indexOf(n)){l=a[d],delete a[d],h.pssh=new Uint8Array(s),h.keyId=i,l=a[n]=l.then((()=>this.generateRequestWithPreferredKeySession(r,e,s,"encrypted-event-key-match")));break}}l||(l=a[n]=this.getKeySystemSelectionPromise([r]).then((({keySystem:t,mediaKeys:r})=>{var a;this.throwIfDestroyed();const o=new se("ISO-23001-7",n,null!=(a=lt(t))?a:"");return o.pssh=new Uint8Array(s),o.keyId=i,this.attemptSetMediaKeys(t,r).then((()=>{this.throwIfDestroyed();const i=this.createMediaKeySessionContext({decryptdata:o,keySystem:t,mediaKeys:r});return this.generateRequestWithPreferredKeySession(i,e,s,"encrypted-event-no-match")}))}))),l.catch((t=>this.handleError(t)))}_onWaitingForKey(t){this.log(`"${t.type}" event`)}attemptSetMediaKeys(t,e){const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const i=Promise.all(s).then((()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(e)}));return this.setMediaKeysQueue.push(i),i.then((()=>{this.log(`Media-keys set for "${t}"`),s.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter((t=>-1===s.indexOf(t)))}))}generateRequestWithPreferredKeySession(t,e,s,i){var r,n;const a=null==(r=this.config.drmSystems)||null==(n=r[t.keySystem])?void 0:n.generateRequest;if(a)try{const i=a.call(this.hls,e,s,t);if(!i)throw new Error("Invalid response from configured generateRequest filter");e=i.initDataType,s=t.decryptdata.pssh=i.initData?new Uint8Array(i.initData):null}catch(t){var o;if(this.warn(t.message),null!=(o=this.hls)&&o.config.debug)throw t}if(null===s)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(t);const l=this.getKeyIdString(t.decryptdata);this.log(`Generating key-session request for "${i}": ${l} (init data type: ${e} length: ${s?s.byteLength:null})`);const h=new Br,d=t._onmessage=e=>{const s=t.mediaKeysSession;if(!s)return void h.emit("error",new Error("invalid state"));const{messageType:i,message:r}=e;this.log(`"${i}" message event for session "${s.sessionId}" message size: ${r.byteLength}`),"license-request"===i||"license-renewal"===i?this.renewLicense(t,r).catch((t=>{this.handleError(t),h.emit("error",t)})):"license-release"===i?t.keySystem===et.FAIRPLAY&&(this.updateKeySession(t,Z("acknowledged")),this.removeSession(t)):this.warn(`unhandled media key message type "${i}"`)},c=t._onkeystatuseschange=e=>{if(!t.mediaKeysSession)return void h.emit("error",new Error("invalid state"));this.onKeyStatusChange(t);const s=t.keyStatus;h.emit("keyStatus",s),"expired"===s&&(this.warn(`${t.keySystem} expired for key ${l}`),this.renewKeySession(t))};t.mediaKeysSession.addEventListener("message",d),t.mediaKeysSession.addEventListener("keystatuseschange",c);const u=new Promise(((t,e)=>{h.on("error",e),h.on("keyStatus",(s=>{s.startsWith("usable")?t():"output-restricted"===s?e(new Wn({type:C.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===s?e(new Wn({type:C.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${s}"`)):"expired"===s?e(new Error("key expired while generating request")):this.warn(`unhandled key status change "${s}"`)}))}));return t.mediaKeysSession.generateRequest(e,s).then((()=>{var e;this.log(`Request generated for key-session "${null==(e=t.mediaKeysSession)?void 0:e.sessionId}" keyId: ${l}`)})).catch((t=>{throw new Wn({type:C.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_NO_SESSION,error:t,fatal:!1},`Error generating key-session request: ${t}`)})).then((()=>u)).catch((e=>{throw h.removeAllListeners(),this.removeSession(t),e})).then((()=>(h.removeAllListeners(),t)))}onKeyStatusChange(t){t.mediaKeysSession.keyStatuses.forEach(((e,s)=>{this.log(`key status change "${e}" for keyStatuses keyId: ${wt("buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s))} session keyId: ${wt(new Uint8Array(t.decryptdata.keyId||[]))} uri: ${t.decryptdata.uri}`),t.keyStatus=e}))}fetchServerCertificate(t){const e=this.config,s=new(0,e.loader)(e),i=this.getServerCertificateUrl(t);return i?(this.log(`Fetching server certificate for "${t}"`),new Promise(((r,n)=>{const a={responseType:"arraybuffer",url:i},o=e.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(t,e,s,i)=>{r(t.data)},onError:(e,s,r,o)=>{n(new Wn({type:C.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:A({url:a.url,data:void 0},e)},`"${t}" certificate request failed (${i}). Status: ${e.code} (${e.text})`))},onTimeout:(e,s,r)=>{n(new Wn({type:C.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:{url:a.url,data:void 0}},`"${t}" certificate request timed out (${i})`))},onAbort:(t,e,s)=>{n(new Error("aborted"))}};s.load(a,l,h)}))):Promise.resolve()}setMediaKeysServerCertificate(t,e,s){return new Promise(((i,r)=>{t.setServerCertificate(s).then((r=>{this.log(`setServerCertificate ${r?"success":"not supported by CDM"} (${null==s?void 0:s.byteLength}) on "${e}"`),i(t)})).catch((t=>{r(new Wn({type:C.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:t,fatal:!0},t.message))}))}))}renewLicense(t,e){return this.requestLicense(t,new Uint8Array(e)).then((e=>this.updateKeySession(t,new Uint8Array(e)).catch((t=>{throw new Wn({type:C.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:t,fatal:!0},t.message)}))))}unpackPlayReadyKeyMessage(t,e){const s=String.fromCharCode.apply(null,new Uint16Array(e.buffer));if(!s.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),e;const i=(new DOMParser).parseFromString(s,"application/xml"),r=i.querySelectorAll("HttpHeader");if(r.length>0){let e;for(let s=0,i=r.length;s<i;s++){var n,a;e=r[s];const i=null==(n=e.querySelector("name"))?void 0:n.textContent,o=null==(a=e.querySelector("value"))?void 0:a.textContent;i&&o&&t.setRequestHeader(i,o)}}const o=i.querySelector("Challenge"),l=null==o?void 0:o.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return Z(atob(l))}setupLicenseXHR(t,e,s,i){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then((()=>{if(!s.decryptdata)throw new Error("Key removed");return r.call(this.hls,t,e,s,i)})).catch((n=>{if(!s.decryptdata)throw n;return t.open("POST",e,!0),r.call(this.hls,t,e,s,i)})).then((s=>{t.readyState||t.open("POST",e,!0);return{xhr:t,licenseChallenge:s||i}})):(t.open("POST",e,!0),Promise.resolve({xhr:t,licenseChallenge:i}))}requestLicense(t,e){const s=this.config.keyLoadPolicy.default;return new Promise(((i,r)=>{const n=this.getLicenseServerUrl(t.keySystem);this.log(`Sending license request to URL: ${n}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return r(new Error("invalid state"));if(4===a.readyState)if(200===a.status){this._requestLicenseFailureCount=0;let e=a.response;this.log(`License received ${e instanceof ArrayBuffer?e.byteLength:e}`);const s=this.config.licenseResponseCallback;if(s)try{e=s.call(this.hls,a,n,t)}catch(t){this.error(t)}i(e)}else{const o=s.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)r(new Wn({type:C.KEY_SYSTEM_ERROR,details:P.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:{url:n,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${n}). Status: ${a.status} (${a.statusText})`));else{const s=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${s} attempts left`),this.requestLicense(t,e).then(i,r)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=a,this.setupLicenseXHR(a,n,t,e).then((({xhr:e,licenseChallenge:s})=>{t.keySystem==et.PLAYREADY&&(s=this.unpackPlayReadyKeyMessage(e,s)),e.send(s)}))}))}onMediaAttached(t,e){if(!this.config.emeEnabled)return;const s=e.media;this.media=s,s.addEventListener("encrypted",this.onMediaEncrypted),s.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const t=this.media,e=this.mediaKeySessions;t&&(t.removeEventListener("encrypted",this.onMediaEncrypted),t.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},se.clearKeyUriToKeyIdMap();const s=e.length;Yn.CDMCleanupPromise=Promise.all(e.map((t=>this.removeSession(t))).concat(null==t?void 0:t.setMediaKeys(null).catch((t=>{this.log(`Could not clear media keys: ${t}`)})))).then((()=>{s&&(this.log("finished closing key sessions and clearing media keys"),e.length=0)})).catch((t=>{this.log(`Could not close sessions and clear media keys: ${t}`)}))}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(t,{sessionKeys:e}){if(e&&this.config.emeEnabled&&!this.keyFormatPromise){const t=e.reduce(((t,e)=>(-1===t.indexOf(e.keyFormat)&&t.push(e.keyFormat),t)),[]);this.log(`Selecting key-system from session-keys ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)}}removeSession(t){const{mediaKeysSession:e,licenseXhr:s}=t;if(e){this.log(`Remove licenses and keys and close session ${e.sessionId}`),t._onmessage&&(e.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(e.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const i=this.mediaKeySessions.indexOf(t);return i>-1&&this.mediaKeySessions.splice(i,1),e.remove().catch((t=>{this.log(`Could not remove session: ${t}`)})).then((()=>e.close())).catch((t=>{this.log(`Could not close session: ${t}`)}))}}}Yn.CDMCleanupPromise=void 0;class Wn extends Error{constructor(t,e){super(e),this.data=void 0,t.error||(t.error=new Error(e)),this.data=t,t.err=t.error}}var jn,qn,Xn;!function(t){t.MANIFEST="m",t.AUDIO="a",t.VIDEO="v",t.MUXED="av",t.INIT="i",t.CAPTION="c",t.TIMED_TEXT="tt",t.KEY="k",t.OTHER="o"}(jn||(jn={})),function(t){t.DASH="d",t.HLS="h",t.SMOOTH="s",t.OTHER="o"}(qn||(qn={})),function(t){t.OBJECT="CMCD-Object",t.REQUEST="CMCD-Request",t.SESSION="CMCD-Session",t.STATUS="CMCD-Status"}(Xn||(Xn={}));const zn={[Xn.OBJECT]:["br","d","ot","tb"],[Xn.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[Xn.SESSION]:["cid","pr","sf","sid","st","v"],[Xn.STATUS]:["bs","rtp"]};class Qn{constructor(t,e){this.value=void 0,this.params=void 0,Array.isArray(t)&&(t=t.map((t=>t instanceof Qn?t:new Qn(t)))),this.value=t,this.params=e}}class Jn{constructor(t){this.description=void 0,this.description=t}}function Zn(t,e,s,i){return new Error(`failed to ${t} "${r=e,Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":"object"==typeof r?JSON.stringify(r):String(r)}" as ${s}`,{cause:i});var r}const ta="Bare Item";const ea=/[\x00-\x1f\x7f]+/;function sa(t,e,s){return Zn("serialize",t,e,s)}function ia(t){if(!1===ArrayBuffer.isView(t))throw sa(t,"Byte Sequence");return`:${e=t,btoa(String.fromCharCode(...e))}:`;var e}function ra(t){if(function(t){return t<-999999999999999||999999999999999<t}(t))throw sa(t,"Integer");return t.toString()}function na(t,e){if(t<0)return-na(-t,e);const s=Math.pow(10,e);if(Math.abs(t*s%1-.5)<Number.EPSILON){const e=Math.floor(t*s);return(e%2==0?e:e+1)/s}return Math.round(t*s)/s}function aa(t){const e=na(t,3);if(Math.floor(Math.abs(e)).toString().length>12)throw sa(t,"Decimal");const s=e.toString();return s.includes(".")?s:`${s}.0`}function oa(t){const e=(s=t).description||s.toString().slice(7,-1);var s;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e))throw sa(e,"Token");return e}function la(t){switch(typeof t){case"number":if(!D(t))throw sa(t,ta);return Number.isInteger(t)?ra(t):aa(t);case"string":return function(t){if(ea.test(t))throw sa(t,"String");return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(t);case"symbol":return oa(t);case"boolean":return function(t){if("boolean"!=typeof t)throw sa(t,"Boolean");return t?"?1":"?0"}(t);case"object":if(t instanceof Date)return function(t){return`@${ra(t.getTime()/1e3)}`}(t);if(t instanceof Uint8Array)return ia(t);if(t instanceof Jn)return oa(t);default:throw sa(t,ta)}}function ha(t){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(t))throw sa(t,"Key");return t}function da(t){return null==t?"":Object.entries(t).map((([t,e])=>!0===e?`;${ha(t)}`:`;${ha(t)}=${la(e)}`)).join("")}function ca(t){return t instanceof Qn?`${la(t.value)}${da(t.params)}`:la(t)}function ua(t,e={whitespace:!0}){if("object"!=typeof t)throw sa(t,"Dict");const s=t instanceof Map?t.entries():Object.entries(t),i=null!=e&&e.whitespace?" ":"";return Array.from(s).map((([t,e])=>{e instanceof Qn==!1&&(e=new Qn(e));let s=ha(t);var i;return!0===e.value?s+=da(e.params):(s+="=",Array.isArray(e.value)?s+=`(${(i=e).value.map(ca).join(" ")})${da(i.params)}`:s+=ca(e)),s})).join(`,${i}`)}const fa=t=>Math.round(t),ga=t=>100*fa(t/100),ma={br:fa,d:fa,bl:ga,dl:ga,mtp:ga,nor:(t,e)=>(null!=e&&e.baseUrl&&(t=function(t,e){const s=new URL(t),i=new URL(e);if(s.origin!==i.origin)return t;const r=s.pathname.split("/").slice(1),n=i.pathname.split("/").slice(1,-1);for(;r[0]===n[0];)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")}(t,e.baseUrl)),encodeURIComponent(t)),rtp:ga,tb:fa};function pa(t,e){const s={};if(null==t||"object"!=typeof t)return s;const i=Object.keys(t).sort(),r=k({},ma,null==e?void 0:e.formatters),n=null==e?void 0:e.filter;return i.forEach((i=>{if(null!=n&&n(i))return;let a=t[i];const o=r[i];o&&(a=o(a,e)),"v"===i&&1===a||"pr"==i&&1===a||(t=>"number"==typeof t?D(t):null!=t&&""!==t&&!1!==t)(a)&&((t=>"ot"===t||"sf"===t||"st"===t)(i)&&"string"==typeof a&&(a=new Jn(a)),s[i]=a)})),s}function ya(t,e={}){return t?function(t,e){return ua(t,e)}(pa(t,e),k({whitespace:!1},e)):""}function va(t,e,s){return k(t,function(t,e={}){if(!t)return{};const s=Object.entries(t),i=Object.entries(zn).concat(Object.entries((null==e?void 0:e.customHeaderMap)||{})),r=s.reduce(((t,e)=>{var s;const[r,n]=e,a=(null==(s=i.find((t=>t[1].includes(r))))?void 0:s[0])||Xn.REQUEST;return null!=t[a]||(t[a]={}),t[a][r]=n,t}),{});return Object.entries(r).reduce(((t,[s,i])=>(t[s]=ya(i,e),t)),{})}(e,s))}const Ta=/CMCD=[^&#]+/;function Ea(t,e,s){const i=function(t,e={}){if(!t)return"";const s=ya(t,e);return`CMCD=${encodeURIComponent(s)}`}(e,s);if(!i)return t;if(Ta.test(t))return t.replace(Ta,i);const r=t.includes("?")?"&":"?";return`${t}${r}${i}`}function Sa(t,e,s,i){t&&Object.keys(e).forEach((r=>{const n=t.filter((t=>t.groupId===r)).map((t=>{const n=k({},t);return n.details=void 0,n.attrs=new $(n.attrs),n.url=n.attrs.URI=La(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",s),n.groupId=n.attrs["GROUP-ID"]=e[r],n.attrs["PATHWAY-ID"]=i,n}));t.push(...n)}))}function La(t,e,s,i){const{HOST:r,PARAMS:n,[s]:a}=i;let o;e&&(o=null==a?void 0:a[e],o&&(t=o));const l=new self.URL(t);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach((t=>{t&&l.searchParams.set(t,n[t])})),l.href}const Aa=/^age:\s*[\d.]+\s*$/im;class Ra{constructor(t){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=t&&t.xhrSetup||null,this.stats=new H,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,4!==t.readyState&&(this.stats.aborted=!0,t.abort()))}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(t,e,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=s,this.loadInternal()}loadInternal(){const{config:t,context:e}=this;if(!t||!e)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then((()=>{if(this.loader===s&&!this.stats.aborted)return r(s,e.url)})).catch((t=>{if(this.loader===s&&!this.stats.aborted)return s.open("GET",e.url,!0),r(s,e.url)})).then((()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,e,t)})).catch((t=>{this.callbacks.onError({code:s.status,text:t.message},e,s,i)})):this.openAndSendXhr(s,e,t)}openAndSendXhr(t,e,s){t.readyState||t.open("GET",e.url,!0);const i=e.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=s.loadPolicy;if(i)for(const e in i)t.setRequestHeader(e,i[e]);e.rangeEnd&&t.setRequestHeader("Range","bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=e.responseType,self.clearTimeout(this.requestTimeout),s.timeout=r&&D(r)?r:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),t.send()}readystatechange(){const{context:t,loader:e,stats:s}=this;if(!t||!e)return;const i=e.readyState,r=this.config;if(!s.aborted&&i>=2&&(0===s.loading.first&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;const i=e.status,n="text"!==e.responseType;if(i>=200&&i<300&&(n&&e.response||null!==e.responseText)){s.loading.end=Math.max(self.performance.now(),s.loading.first);const r=n?e.response:e.responseText,a="arraybuffer"===e.responseType?r.byteLength:r.length;if(s.loaded=s.total=a,s.bwEstimate=8e3*s.total/(s.loading.end-s.loading.first),!this.callbacks)return;const o=this.callbacks.onProgress;if(o&&o(s,t,r,e),!this.callbacks)return;const l={url:e.responseURL,data:r,code:i};this.callbacks.onSuccess(l,s,t,e)}else{const n=r.loadPolicy.errorRetry;Rs(n,s.retry,!1,{url:t.url,data:void 0,code:i})?this.retry(n):(N.error(`${i} while loading ${t.url}`),this.callbacks.onError({code:i,text:e.statusText},t,e,s))}}}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry;if(Rs(t,this.stats.retry,!0))this.retry(t);else{var e;N.warn(`timeout while loading ${null==(e=this.context)?void 0:e.url}`);const t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.loader))}}retry(t){const{context:e,stats:s}=this;this.retryDelay=Ls(t,s.retry),s.retry++,N.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==e?void 0:e.url}, retrying ${s.retry}/${t.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(t){const e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)}getCacheAge(){let t=null;if(this.loader&&Aa.test(this.loader.getAllResponseHeaders())){const e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.loader&&new RegExp(`^${t}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null}}const ba=/(\d+)-(\d+)\/(\d+)/;class ka{constructor(t){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=t.fetchSetup||Da,this.controller=new self.AbortController,this.stats=new H}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 t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(t,e,s){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();const r=function(t,e){const s={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(k({},t.headers))};t.rangeEnd&&s.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1));return s}(t,this.controller.signal),n=s.onProgress,a="arraybuffer"===t.responseType,o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:h}=e.loadPolicy;this.context=t,this.config=e,this.callbacks=s,this.request=this.fetchSetup(t,r),self.clearTimeout(this.requestTimeout),e.timeout=l&&D(l)?l:h,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),s.onTimeout(i,t,this.response)}),e.timeout),self.fetch(this.request).then((r=>{this.response=this.loader=r;const o=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=h,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),s.onTimeout(i,t,this.response)}),h-(o-i.loading.start)),!r.ok){const{status:t,statusText:e}=r;throw new _a(e||"fetch, bad network response",t,r)}return i.loading.first=o,i.total=function(t){const e=t.get("Content-Range");if(e){const t=function(t){const e=ba.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}(e);if(D(t))return t}const s=t.get("Content-Length");if(s)return parseInt(s)}(r.headers)||i.total,n&&D(e.highWaterMark)?this.loadProgressively(r,i,t,e.highWaterMark,n):a?r.arrayBuffer():"json"===t.responseType?r.json():r.text()})).then((r=>{const a=this.response;if(!a)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const l=r[o];l&&(i.loaded=i.total=l);const h={url:a.url,data:r,code:a.status};n&&!D(e.highWaterMark)&&n(i,t,r,a),s.onSuccess(h,i,t,a)})).catch((e=>{if(self.clearTimeout(this.requestTimeout),i.aborted)return;const r=e&&e.code||0,n=e?e.message:null;s.onError({code:r,text:n},t,e?e.details:null,i)}))}getCacheAge(){let t=null;if(this.response){const e=this.response.headers.get("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,e,s,i=0,r){const n=new Fi,a=t.body.getReader(),o=()=>a.read().then((a=>{if(a.done)return n.dataLength&&r(e,s,n.flush(),t),Promise.resolve(new ArrayBuffer(0));const l=a.value,h=l.length;return e.loaded+=h,h<i||n.dataLength?(n.push(l),n.dataLength>=i&&r(e,s,n.flush(),t)):r(e,s,l,t),o()})).catch((()=>Promise.reject()));return o()}}function Da(t,e){return new self.Request(t.url,e)}class _a extends Error{constructor(t,e,s){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=s}}const Ia=/\s/,wa={newCue(t,e,s,i){const r=[];let n,a,o,l,h;const d=self.VTTCue||self.TextTrackCue;for(let u=0;u<i.rows.length;u++)if(n=i.rows[u],o=!0,l=0,h="",!n.isEmpty()){var c;for(let t=0;t<n.chars.length;t++)Ia.test(n.chars[t].uchar)&&o?l++:(h+=n.chars[t].uchar,o=!1);n.cueStartTime=e,e===s&&(s+=1e-4),l>=16?l--:l++;const i=An(h.trim()),f=_n(e,s,i);null!=t&&null!=(c=t.cues)&&c.getCueById(f)||(a=new d(e,s,i),a.id=f,a.line=u+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),r.push(a))}return t&&r.length&&(r.sort(((t,e)=>"auto"===t.line||"auto"===e.line?0:t.line>8&&e.line>8?e.line-t.line:t.line-e.line)),r.forEach((e=>Ve(t,e)))),r}},Ca=A(A({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:6e7,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:Ra,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class{constructor(t){this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this._abandonRulesCheck=()=>{const{fragCurrent:t,partCurrent:e,hls:s}=this,{autoLevelEnabled:i,media:r}=s;if(!t||!r)return;const n=performance.now(),a=e?e.stats:t.stats,o=e?e.duration:t.duration,l=n-a.loading.start,h=s.minAutoLevel;if(a.aborted||a.loaded&&a.loaded===a.total||t.level<=h)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!i||r.paused||!r.playbackRate||!r.readyState)return;const d=s.mainForwardBufferInfo;if(null===d)return;const c=this.bwEstimator.getEstimateTTFB(),u=Math.abs(r.playbackRate);if(l<=Math.max(c,o/(2*u)*1e3))return;const f=d.len/u,g=a.loading.first?a.loading.first-a.loading.start:-1,m=a.loaded&&g>-1,p=this.getBwEstimate(),y=s.levels,v=y[t.level],T=a.total||Math.max(a.loaded,Math.round(o*v.averageBitrate/8));let E=m?l-g:l;E<1&&m&&(E=Math.min(l,8*a.loaded/p));const S=m?1e3*a.loaded/E:0,L=S?(T-a.loaded)/S:8*T/p+c/1e3;if(L<=f)return;const A=S?8*S:p;let R,b=Number.POSITIVE_INFINITY;for(R=t.level-1;R>h;R--){const t=y[R].maxBitrate;if(b=this.getTimeToLoadFrag(c/1e3,A,o*t,!y[R].details),b<f)break}if(b>=L)return;if(b>10*o)return;s.nextLoadLevel=s.nextAutoLevel=R,m?this.bwEstimator.sample(l-Math.min(c,g),a.loaded):this.bwEstimator.sampleTTFB(l);const k=y[R].maxBitrate;this.getBwEstimate()*this.hls.config.abrBandWidthUpFactor>k&&this.resetEstimator(k),this.clearTimer(),N.warn(`[abr] Fragment ${t.sn}${e?" part "+e.index:""} of level ${t.level} is loading too slowly;\n Time to underbuffer: ${f.toFixed(3)} s\n Estimated load time for current fragment: ${L.toFixed(3)} s\n Estimated load time for down switch fragment: ${b.toFixed(3)} s\n TTFB estimate: ${0|g} ms\n Current BW estimate: ${D(p)?0|p:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${R} @ ${0|k} bps`),s.trigger(w.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:e,stats:a})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){t&&(N.log(`setting initial bwe to ${t}`),this.hls.config.abrEwmaDefaultEstimate=t),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const t=this.hls.config;return new Us(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(w.MANIFEST_LOADING,this.onManifestLoading,this),t.on(w.FRAG_LOADING,this.onFragLoading,this),t.on(w.FRAG_LOADED,this.onFragLoaded,this),t.on(w.FRAG_BUFFERED,this.onFragBuffered,this),t.on(w.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(w.LEVEL_LOADED,this.onLevelLoaded,this),t.on(w.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(w.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(w.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(w.MANIFEST_LOADING,this.onManifestLoading,this),t.off(w.FRAG_LOADING,this.onFragLoading,this),t.off(w.FRAG_LOADED,this.onFragLoaded,this),t.off(w.FRAG_BUFFERED,this.onFragBuffered,this),t.off(w.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(w.LEVEL_LOADED,this.onLevelLoaded,this),t.off(w.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(w.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(w.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(t,e){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(t,e){const s=e.frag;if(!this.ignoreFragment(s)){var i;if(!s.bitrateTest)this.fragCurrent=s,this.partCurrent=null!=(i=e.part)?i:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(t,e){this.clearTimer()}onError(t,e){if(!e.fatal)switch(e.details){case P.BUFFER_ADD_CODEC_ERROR:case P.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case P.FRAG_LOAD_TIMEOUT:{const t=e.frag,{fragCurrent:s,partCurrent:i}=this;if(t&&s&&t.sn===s.sn&&t.level===s.level){const e=performance.now(),s=i?i.stats:t.stats,r=e-s.loading.start,n=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&n>-1){const t=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(r-Math.min(t,n),s.loaded)}else this.bwEstimator.sampleTTFB(r)}break}}}getTimeToLoadFrag(t,e,s,i){return t+s/e+(i?this.lastLevelLoadSec:0)}onLevelLoaded(t,e){const s=this.hls.config,{loading:i}=e.stats,r=i.end-i.start;D(r)&&(this.lastLevelLoadSec=r/1e3),e.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD)}onFragLoaded(t,{frag:e,part:s}){const i=s?s.stats:e.stats;if(e.type===Ne&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(e)){if(this.clearTimer(),e.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const t=s?s.duration:e.duration,r=this.hls.levels[e.level],n=(r.loaded?r.loaded.bytes:0)+i.loaded,a=(r.loaded?r.loaded.duration:0)+t;r.loaded={bytes:n,duration:a},r.realBitrate=Math.round(8*n/a)}if(e.bitrateTest){const t={stats:i,frag:e,part:s,id:e.type};this.onFragBuffered(w.FRAG_BUFFERED,t),e.bitrateTest=!1}else this.lastLoadedFragLevel=e.level}}onFragBuffered(t,e){const{frag:s,part:i}=e,r=null!=i&&i.stats.loaded?i.stats:s.stats;if(r.aborted)return;if(this.ignoreFragment(s))return;const n=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==Ne||"initSegment"===t.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:t,minAutoLevel:e}=this.hls,s=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,r=this.findBestLevel(s,e,t,0,i,1,1);if(r>-1)return r;const n=this.hls.firstLevel,a=Math.min(Math.max(n,e),t);return N.warn(`[abr] Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const t=this.forcedAutoLevel,e=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(!(-1===t||e&&s&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return t;const i=e&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==t){const e=this.hls.levels;if(e.length>Math.max(t,i)&&e[t].loadError<=e[i].loadError)return t}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:s}=this,{maxAutoLevel:i,config:r,minAutoLevel:n}=s,a=e?e.duration:t?t.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let h=r.abrBandWidthFactor,d=r.abrBandWidthUpFactor;if(l){const t=this.findBestLevel(o,n,i,l,0,h,d);if(t>=0)return t}let c=a?Math.min(a,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const t=this.bitrateTestDelay;if(t){c=(a?Math.min(a,r.maxLoadingDelay):r.maxLoadingDelay)-t,N.info(`[abr] bitrate test took ${Math.round(1e3*t)}ms, set first fragment max fetchDuration to ${Math.round(1e3*c)} ms`),h=d=1}}const u=this.findBestLevel(o,n,i,l,c,h,d);if(N.info(`[abr] ${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${u}`),u>-1)return u;const f=s.levels[n],g=s.levels[s.loadLevel];return(null==f?void 0:f.bitrate)<(null==g?void 0:g.bitrate)?n:s.loadLevel}getStarvationDelay(){const t=this.hls,e=t.media;if(!e)return 1/0;const s=e&&0!==e.playbackRate?Math.abs(e.playbackRate):1,i=t.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(t,e,s,i,r,n,a){var o;const l=i+r,h=this.lastLoadedFragLevel,d=-1===h?this.hls.firstLevel:h,{fragCurrent:c,partCurrent:u}=this,{levels:f,allAudioTracks:g,loadLevel:m,config:p}=this.hls;if(1===f.length)return 0;const y=f[d],v=!(null==y||null==(o=y.details)||!o.live),T=-1===m||-1===h;let E,S="SDR",L=(null==y?void 0:y.frameRate)||0;const{audioPreference:A,videoPreference:R}=p,b=this.audioTracksByGroup||(this.audioTracksByGroup=function(t){return t.reduce(((t,e)=>{let s=t.groups[e.groupId];s||(s=t.groups[e.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(e);const i=e.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||e.default,s.hasAutoSelect=s.hasAutoSelect||e.autoselect,s.hasDefault&&(t.hasDefaultAudio=!0),s.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}(g));if(T){if(-1!==this.firstSelection)return this.firstSelection;const i=this.codecTiers||(this.codecTiers=function(t,e,s,i){return t.slice(s,i+1).reduce(((t,s)=>{if(!s.codecSet)return t;const i=s.audioGroups;let r=t[s.codecSet];r||(t[s.codecSet]=r={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!i,fragmentError:0}),r.minBitrate=Math.min(r.minBitrate,s.bitrate);const n=Math.min(s.height,s.width);return r.minHeight=Math.min(r.minHeight,n),r.minFramerate=Math.min(r.minFramerate,s.frameRate),r.maxScore=Math.max(r.maxScore,s.score),r.fragmentError+=s.fragmentError,r.videoRanges[s.videoRange]=(r.videoRanges[s.videoRange]||0)+1,i&&i.forEach((t=>{if(!t)return;const s=e.groups[t];s&&(r.hasDefaultAudio=r.hasDefaultAudio||e.hasDefaultAudio?s.hasDefault:s.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(s.channels).forEach((t=>{r.channels[t]=(r.channels[t]||0)+s.channels[t]})))})),t}),{})}(f,b,e,s)),r=function(t,e,s,i,r){const n=Object.keys(t),a=null==i?void 0:i.channels,o=null==i?void 0:i.audioCodec,l=a&&2===parseInt(a);let h=!0,d=!1,c=1/0,u=1/0,f=1/0,g=0,m=[];const{preferHDR:p,allowedVideoRanges:y}=Hs(e,r);for(let e=n.length;e--;){const s=t[n[e]];h=s.channels[2]>0,c=Math.min(c,s.minHeight),u=Math.min(u,s.minFramerate),f=Math.min(f,s.minBitrate);const i=y.filter((t=>s.videoRanges[t]>0));i.length>0&&(d=!0,m=i)}c=D(c)?c:0,u=D(u)?u:0;const v=Math.max(1080,c),T=Math.max(30,u);return f=D(f)?f:s,s=Math.max(f,s),d||(e=void 0,m=[]),{codecSet:n.reduce(((e,i)=>{const r=t[i];if(i===e)return e;if(r.minBitrate>s)return Vs(i,`min bitrate of ${r.minBitrate} > current estimate of ${s}`),e;if(!r.hasDefaultAudio)return Vs(i,"no renditions with default or auto-select sound found"),e;if(o&&i.indexOf(o.substring(0,4))%5!=0)return Vs(i,`audio codec preference "${o}" not found`),e;if(a&&!l){if(!r.channels[a])return Vs(i,`no renditions with ${a} channel sound found (channels options: ${Object.keys(r.channels)})`),e}else if((!o||l)&&h&&0===r.channels[2])return Vs(i,"no renditions with stereo sound found"),e;return r.minHeight>v?(Vs(i,`min resolution of ${r.minHeight} > maximum of ${v}`),e):r.minFramerate>T?(Vs(i,`min framerate of ${r.minFramerate} > maximum of ${T}`),e):m.some((t=>r.videoRanges[t]>0))?r.maxScore<g?(Vs(i,`max score of ${r.maxScore} < selected max of ${g}`),e):e&&(me(i)>=me(e)||r.fragmentError>t[e].fragmentError)?e:(g=r.maxScore,i):(Vs(i,`no variants with VIDEO-RANGE of ${JSON.stringify(m)} found`),e)}),void 0),videoRanges:m,preferHDR:p,minFramerate:u,minBitrate:f}}(i,S,t,A,R),{codecSet:n,videoRanges:a,minFramerate:o,minBitrate:l,preferHDR:h}=r;E=n,S=h?a[a.length-1]:a[0],L=o,t=Math.max(t,l),N.log(`[abr] picked start tier ${JSON.stringify(r)}`)}else E=null==y?void 0:y.codecSet,S=null==y?void 0:y.videoRange;const k=u?u.duration:c?c.duration:0,_=this.bwEstimator.getEstimateTTFB()/1e3,I=[];for(let o=s;o>=e;o--){var w;const e=f[o],c=o>d;if(!e)continue;if(p.useMediaCapabilities&&!e.supportedResult&&!e.supportedPromise){const s=navigator.mediaCapabilities;"function"==typeof(null==s?void 0:s.decodingInfo)&&Gs(e,b,S,L,t,A)?(e.supportedPromise=Ks(e,b,s),e.supportedPromise.then((t=>{if(!this.hls)return;e.supportedResult=t;const s=this.hls.levels,i=s.indexOf(e);t.error?N.warn(`[abr] MediaCapabilities decodingInfo error: "${t.error}" for level ${i} ${JSON.stringify(t)}`):t.supported||(N.warn(`[abr] Unsupported MediaCapabilities decodingInfo result for level ${i} ${JSON.stringify(t)}`),i>-1&&s.length>1&&(N.log(`[abr] Removing unsupported level ${i}`),this.hls.removeLevel(i)))}))):e.supportedResult=Bs}if(E&&e.codecSet!==E||S&&e.videoRange!==S||c&&L>e.frameRate||!c&&L>0&&L<e.frameRate||e.supportedResult&&(null==(w=e.supportedResult.decodingInfoResults)||!w[0].smooth)){I.push(o);continue}const g=e.details,R=(u?null==g?void 0:g.partTarget:null==g?void 0:g.averagetargetduration)||k;let C;C=c?a*t:n*t;const P=k&&i>=2*k&&0===r?f[o].averageBitrate:f[o].maxBitrate,x=this.getTimeToLoadFrag(_,C,P*R,void 0===g);if(C>=P&&(o===h||0===e.loadError&&0===e.fragmentError)&&(x<=_||!D(x)||v&&!this.bitrateTestDelay||x<l)){const t=this.forcedAutoLevel;return o===m||-1!==t&&t===m||(I.length&&N.trace(`[abr] Skipped level(s) ${I.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${f[I[0]].codecs}" ${f[I[0]].videoRange}; not compatible with "${y.codecs}" ${S}`),N.info(`[abr] switch candidate:${d}->${o} adjustedbw(${Math.round(C)})-bitrate=${Math.round(C-P)} ttfb:${_.toFixed(1)} avgDuration:${R.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${x.toFixed(1)} firstSelection:${T} codecSet:${E} videoRange:${S} hls.loadLevel:${m}`)),T&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(t){const{maxAutoLevel:e,minAutoLevel:s}=this.hls,i=Math.min(Math.max(t,s),e);this._nextAutoLevel!==i&&(this.nextAutoLevelKey="",this._nextAutoLevel=i)}},bufferController:class{constructor(t){this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendSource=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this.log=void 0,this.warn=void 0,this.error=void 0,this._onEndStreaming=t=>{this.hls&&this.hls.pauseBuffering()},this._onStartStreaming=t=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=()=>{const{media:t,mediaSource:e}=this;this.log("Media source opened"),t&&(t.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(w.MEDIA_ATTACHED,{media:t,mediaSource:e})),e&&e.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:t,_objectUrl:e}=this;t!==e&&N.error(`Media element src was set while attaching MediaSource (${e} > ${t})`)},this.hls=t;const e="[buffer-controller]";var s;this.appendSource=(s=he(t.config.preferManagedMediaSource),"undefined"!=typeof self&&s===self.ManagedMediaSource),this.log=N.log.bind(N,e),this.warn=N.warn.bind(N,e),this.error=N.error.bind(N,e),this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.hls=null}registerListeners(){const{hls:t}=this;t.on(w.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(w.MANIFEST_LOADING,this.onManifestLoading,this),t.on(w.MANIFEST_PARSED,this.onManifestParsed,this),t.on(w.BUFFER_RESET,this.onBufferReset,this),t.on(w.BUFFER_APPENDING,this.onBufferAppending,this),t.on(w.BUFFER_CODECS,this.onBufferCodecs,this),t.on(w.BUFFER_EOS,this.onBufferEos,this),t.on(w.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(w.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(w.FRAG_PARSED,this.onFragParsed,this),t.on(w.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:t}=this;t.off(w.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(w.MANIFEST_LOADING,this.onManifestLoading,this),t.off(w.MANIFEST_PARSED,this.onManifestParsed,this),t.off(w.BUFFER_RESET,this.onBufferReset,this),t.off(w.BUFFER_APPENDING,this.onBufferAppending,this),t.off(w.BUFFER_CODECS,this.onBufferCodecs,this),t.off(w.BUFFER_EOS,this.onBufferEos,this),t.off(w.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(w.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(w.FRAG_PARSED,this.onFragParsed,this),t.off(w.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new Yr(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.appendErrors={audio:0,video:0,audiovideo:0},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(t,e){let s=2;(e.audio&&!e.video||!e.altAudio)&&(s=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=s,this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(t,e){const s=this.media=e.media,i=he(this.appendSource);if(s&&i){var r;const t=this.mediaSource=new i;this.log(`created media source: ${null==(r=t.constructor)?void 0:r.name}`),t.addEventListener("sourceopen",this._onMediaSourceOpen),t.addEventListener("sourceended",this._onMediaSourceEnded),t.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.addEventListener("startstreaming",this._onStartStreaming),t.addEventListener("endstreaming",this._onEndStreaming));const e=this._objectUrl=self.URL.createObjectURL(t);if(this.appendSource)try{s.removeAttribute("src");const i=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||i&&t instanceof i,jr(s),function(t,e){const s=self.document.createElement("source");s.type="video/mp4",s.src=e,t.appendChild(s)}(s,e),s.load()}catch(t){s.src=e}else s.src=e;s.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:t,mediaSource:e,_objectUrl:s}=this;if(e){if(this.log("media source detaching"),"open"===e.readyState)try{e.endOfStream()}catch(t){this.warn(`onMediaDetaching: ${t.message} while calling endOfStream`)}this.onBufferReset(),e.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("sourceended",this._onMediaSourceEnded),e.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.removeEventListener("startstreaming",this._onStartStreaming),e.removeEventListener("endstreaming",this._onEndStreaming)),t&&(t.removeEventListener("emptied",this._onMediaEmptied),s&&self.URL.revokeObjectURL(s),this.mediaSrc===s?(t.removeAttribute("src"),this.appendSource&&jr(t),t.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(w.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach((t=>{this.resetBuffer(t)})),this._initSourceBuffer()}resetBuffer(t){const e=this.sourceBuffer[t];try{var s;if(e)this.removeBufferListeners(t),this.sourceBuffer[t]=void 0,null!=(s=this.mediaSource)&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(e)}catch(e){this.warn(`onBufferReset ${t}`,e)}}onBufferCodecs(t,e){const s=this.getSourceBufferTypes().length,i=Object.keys(e);if(i.forEach((t=>{if(s){const s=this.tracks[t];if(s&&"function"==typeof s.buffer.changeType){var i;const{id:r,codec:n,levelCodec:a,container:o,metadata:l}=e[t],h=Te(s.codec,s.levelCodec),d=null==h?void 0:h.replace(Wr,"$1");let c=Te(n,a);const u=null==(i=c)?void 0:i.replace(Wr,"$1");if(c&&d!==u){"audio"===t.slice(0,5)&&(c=ve(c,this.appendSource));const e=`${o};codecs=${c}`;this.appendChangeType(t,e),this.log(`switching codec ${h} to ${c}`),this.tracks[t]={buffer:s.buffer,codec:n,container:o,levelCodec:a,metadata:l,id:r}}}}else this.pendingTracks[t]=e[t]})),s)return;const r=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==r&&(this.log(`${r} bufferCodec event(s) expected ${i.join(",")}`),this.bufferCodecEventsExpected=r),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks()}appendChangeType(t,e){const{operationQueue:s}=this,i={execute:()=>{const i=this.sourceBuffer[t];i&&(this.log(`changing ${t} sourceBuffer type to ${e}`),i.changeType(e)),s.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn(`Failed to change ${t} SourceBuffer type`,e)}};s.append(i,t,!!this.pendingTracks[t])}onBufferAppending(t,e){const{hls:s,operationQueue:i,tracks:r}=this,{data:n,type:a,frag:o,part:l,chunkMeta:h}=e,d=h.buffering[a],c=self.performance.now();d.start=c;const u=o.stats.buffering,f=l?l.stats.buffering:null;0===u.start&&(u.start=c),f&&0===f.start&&(f.start=c);const g=r.audio;let m=!1;"audio"===a&&"audio/mpeg"===(null==g?void 0:g.container)&&(m=!this.lastMpegAudioChunk||1===h.id||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);const p=o.start,y={execute:()=>{if(d.executeStart=self.performance.now(),m){const t=this.sourceBuffer[a];if(t){const e=p-t.timestampOffset;Math.abs(e)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${p} (delta: ${e}) sn: ${o.sn})`),t.timestampOffset=p)}}this.appendExecutor(n,a)},onStart:()=>{},onComplete:()=>{const t=self.performance.now();d.executeEnd=d.end=t,0===u.first&&(u.first=t),f&&0===f.first&&(f.first=t);const{sourceBuffer:e}=this,s={};for(const t in e)s[t]=ri.getBuffered(e[t]);this.appendErrors[a]=0,"audio"===a||"video"===a?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(w.BUFFER_APPENDED,{type:a,frag:o,part:l,chunkMeta:h,parent:o.type,timeRanges:s})},onError:t=>{const e={type:C.MEDIA_ERROR,parent:o.type,details:P.BUFFER_APPEND_ERROR,sourceBufferName:a,frag:o,part:l,chunkMeta:h,error:t,err:t,fatal:!1};if(t.code===DOMException.QUOTA_EXCEEDED_ERR)e.details=P.BUFFER_FULL_ERROR;else{const t=++this.appendErrors[a];e.details=P.BUFFER_APPEND_ERROR,this.warn(`Failed ${t}/${s.config.appendErrorMaxRetry} times to append segment in "${a}" sourceBuffer`),t>=s.config.appendErrorMaxRetry&&(e.fatal=!0)}s.trigger(w.ERROR,e)}};i.append(y,a,!!this.pendingTracks[a])}onBufferFlushing(t,e){const{operationQueue:s}=this,i=t=>({execute:this.removeExecutor.bind(this,t,e.startOffset,e.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(w.BUFFER_FLUSHED,{type:t})},onError:e=>{this.warn(`Failed to remove from ${t} SourceBuffer`,e)}});e.type?s.append(i(e.type),e.type):this.getSourceBufferTypes().forEach((t=>{s.append(i(t),t)}))}onFragParsed(t,e){const{frag:s,part:i}=e,r=[],n=i?i.elementaryStreams:s.elementaryStreams;n[W]?r.push("audiovideo"):(n[V]&&r.push("audio"),n[Y]&&r.push("video"));0===r.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers((()=>{const t=self.performance.now();s.stats.buffering.end=t,i&&(i.stats.buffering.end=t);const e=i?i.stats:s.stats;this.hls.trigger(w.FRAG_BUFFERED,{frag:s,part:i,stats:e,id:s.type})}),r)}onFragChanged(t,e){this.trimBuffers()}onBufferEos(t,e){this.getSourceBufferTypes().reduce(((t,s)=>{const i=this.sourceBuffer[s];return!i||e.type&&e.type!==s||(i.ending=!0,i.ended||(i.ended=!0,this.log(`${s} sourceBuffer now EOS`))),t&&!(i&&!i.ended)}),!0)&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers((()=>{this.getSourceBufferTypes().forEach((t=>{const e=this.sourceBuffer[t];e&&(e.ending=!1)}));const{mediaSource:t}=this;t&&"open"===t.readyState?(this.log("Calling mediaSource.endOfStream()"),t.endOfStream()):t&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${t.readyState}`)})))}onLevelUpdated(t,{details:e}){e.fragments.length&&(this.details=e,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}trimBuffers(){const{hls:t,details:e,media:s}=this;if(!s||null===e)return;if(!this.getSourceBufferTypes().length)return;const i=t.config,r=s.currentTime,n=e.levelTargetDuration,a=e.live&&null!==i.liveBackBufferLength?i.liveBackBufferLength:i.backBufferLength;if(D(a)&&a>0){const t=Math.max(a,n),e=Math.floor(r/n)*n-t;this.flushBackBuffer(r,n,e)}if(D(i.frontBufferFlushThreshold)&&i.frontBufferFlushThreshold>0){const t=Math.max(i.maxBufferLength,i.frontBufferFlushThreshold),e=Math.max(t,n),s=Math.floor(r/n)*n+e;this.flushFrontBuffer(r,n,s)}}flushBackBuffer(t,e,s){const{details:i,sourceBuffer:r}=this;this.getSourceBufferTypes().forEach((n=>{const a=r[n];if(a){const r=ri.getBuffered(a);if(r.length>0&&s>r.start(0)){if(this.hls.trigger(w.BACK_BUFFER_REACHED,{bufferEnd:s}),null!=i&&i.live)this.hls.trigger(w.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(a.ended&&r.end(r.length-1)-t<2*e)return void this.log(`Cannot flush ${n} back buffer while SourceBuffer is in ended state`);this.hls.trigger(w.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:n})}}}))}flushFrontBuffer(t,e,s){const{sourceBuffer:i}=this;this.getSourceBufferTypes().forEach((r=>{const n=i[r];if(n){const i=ri.getBuffered(n),a=i.length;if(a<2)return;const o=i.start(a-1),l=i.end(a-1);if(s>o||t>=o&&t<=l)return;if(n.ended&&t-l<2*e)return void this.log(`Cannot flush ${r} front buffer while SourceBuffer is in ended state`);this.hls.trigger(w.BUFFER_FLUSHING,{startOffset:o,endOffset:1/0,type:r})}}))}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||"open"!==this.mediaSource.readyState)return;const{details:t,hls:e,media:s,mediaSource:i}=this,r=t.fragments[0].start+t.totalduration,n=s.duration,a=D(i.duration)?i.duration:0;t.live&&e.config.liveDurationInfinity?(i.duration=1/0,this.updateSeekableRange(t)):(r>a&&r>n||!D(n))&&(this.log(`Updating Media Source duration to ${r.toFixed(3)}`),i.duration=r)}updateSeekableRange(t){const e=this.mediaSource,s=t.fragments;if(s.length&&t.live&&null!=e&&e.setLiveSeekableRange){const i=Math.max(0,s[0].start),r=Math.max(i,i+t.totalduration);this.log(`Media Source duration is set to ${e.duration}. Setting seekable range to ${i}-${r}.`),e.setLiveSeekableRange(i,r)}}checkPendingTracks(){const{bufferCodecEventsExpected:t,operationQueue:e,pendingTracks:s}=this,i=Object.keys(s).length;if(i&&(!t||2===i||"audiovideo"in s)){this.createSourceBuffers(s),this.pendingTracks={};const t=this.getSourceBufferTypes();if(t.length)this.hls.trigger(w.BUFFER_CREATED,{tracks:this.tracks}),t.forEach((t=>{e.executeNext(t)}));else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(w.ERROR,{type:C.MEDIA_ERROR,details:P.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}}createSourceBuffers(t){const{sourceBuffer:e,mediaSource:s}=this;if(!s)throw Error("createSourceBuffers called when mediaSource was null");for(const r in t)if(!e[r]){var i;const n=t[r];if(!n)throw Error(`source buffer exists for track ${r}, however track does not`);let a=-1===(null==(i=n.levelCodec)?void 0:i.indexOf(","))?n.levelCodec:n.codec;a&&"audio"===r.slice(0,5)&&(a=ve(a,this.appendSource));const o=`${n.container};codecs=${a}`;this.log(`creating sourceBuffer(${o})`);try{const t=e[r]=s.addSourceBuffer(o),i=r;this.addBufferListener(i,"updatestart",this._onSBUpdateStart),this.addBufferListener(i,"updateend",this._onSBUpdateEnd),this.addBufferListener(i,"error",this._onSBUpdateError),this.appendSource&&this.addBufferListener(i,"bufferedchange",((t,e)=>{const s=e.removedRanges;null!=s&&s.length&&this.hls.trigger(w.BUFFER_FLUSHED,{type:r})})),this.tracks[r]={buffer:t,codec:a,container:n.container,levelCodec:n.levelCodec,metadata:n.metadata,id:n.id}}catch(t){this.error(`error while trying to add sourceBuffer: ${t.message}`),this.hls.trigger(w.ERROR,{type:C.MEDIA_ERROR,details:P.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:r,mimeType:o})}}}get mediaSrc(){var t,e;const s=(null==(t=this.media)||null==(e=t.querySelector)?void 0:e.call(t,"source"))||this.media;return null==s?void 0:s.src}_onSBUpdateStart(t){const{operationQueue:e}=this;e.current(t).onStart()}_onSBUpdateEnd(t){var e;if("closed"===(null==(e=this.mediaSource)?void 0:e.readyState))return void this.resetBuffer(t);const{operationQueue:s}=this;s.current(t).onComplete(),s.shiftAndExecuteNext(t)}_onSBUpdateError(t,e){var s;const i=new Error(`${t} SourceBuffer error. MediaSource readyState: ${null==(s=this.mediaSource)?void 0:s.readyState}`);this.error(`${i}`,e),this.hls.trigger(w.ERROR,{type:C.MEDIA_ERROR,details:P.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:i,fatal:!1});const r=this.operationQueue.current(t);r&&r.onError(i)}removeExecutor(t,e,s){const{media:i,mediaSource:r,operationQueue:n,sourceBuffer:a}=this,o=a[t];if(!i||!r||!o)return this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),void n.shiftAndExecuteNext(t);const l=D(i.duration)?i.duration:1/0,h=D(r.duration)?r.duration:1/0,d=Math.max(0,e),c=Math.min(s,l,h);c>d&&(!o.ending||o.ended)?(o.ended=!1,this.log(`Removing [${d},${c}] from the ${t} SourceBuffer`),o.remove(d,c)):n.shiftAndExecuteNext(t)}appendExecutor(t,e){const s=this.sourceBuffer[e];if(s)s.ended=!1,s.appendBuffer(t);else if(!this.pendingTracks[e])throw new Error(`Attempting to append to the ${e} SourceBuffer, but it does not exist`)}blockBuffers(t,e=this.getSourceBufferTypes()){if(!e.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve().then(t);const{operationQueue:s}=this,i=e.map((t=>s.appendBlocker(t)));Promise.all(i).then((()=>{t(),e.forEach((t=>{const e=this.sourceBuffer[t];null!=e&&e.updating||s.shiftAndExecuteNext(t)}))}))}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(t,e,s){const i=this.sourceBuffer[t];if(!i)return;const r=s.bind(this,t);this.listeners[t].push({event:e,listener:r}),i.addEventListener(e,r)}removeBufferListeners(t){const e=this.sourceBuffer[t];e&&this.listeners[t].forEach((t=>{e.removeEventListener(t.event,t.listener)}))}},capLevelController:Hn,errorController:class{constructor(t){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=t,this.log=N.log.bind(N,"[info]:"),this.warn=N.warn.bind(N,"[warning]:"),this.error=N.error.bind(N,"[error]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(w.ERROR,this.onError,this),t.on(w.MANIFEST_LOADING,this.onManifestLoading,this),t.on(w.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(w.ERROR,this.onError,this),t.off(w.ERROR,this.onErrorOut,this),t.off(w.MANIFEST_LOADING,this.onManifestLoading,this),t.off(w.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){return(null==t?void 0:t.type)===Ne?t.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(t,e){var s,i;if(e.fatal)return;const r=this.hls,n=e.context;switch(e.details){case P.FRAG_LOAD_ERROR:case P.FRAG_LOAD_TIMEOUT:case P.KEY_LOAD_ERROR:case P.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case P.FRAG_PARSING_ERROR:if(null!=(s=e.frag)&&s.gap)return void(e.errorAction={action:Is,flags:xs});case P.FRAG_GAP:case P.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=ws);case P.LEVEL_EMPTY_ERROR:case P.LEVEL_PARSING_ERROR:{var a,o;const t=e.parent===Ne?e.level:r.loadLevel;e.details===P.LEVEL_EMPTY_ERROR&&null!=(a=e.context)&&null!=(o=a.levelDetails)&&o.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,t):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t))}return;case P.LEVEL_LOAD_ERROR:case P.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==n?void 0:n.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,n.level)));case P.AUDIO_TRACK_LOAD_ERROR:case P.AUDIO_TRACK_LOAD_TIMEOUT:case P.SUBTITLE_LOAD_ERROR:case P.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){const t=r.levels[r.loadLevel];if(t&&(n.type===Me&&t.hasAudioGroup(n.groupId)||n.type===Oe&&t.hasSubtitleGroup(n.groupId)))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,r.loadLevel),e.errorAction.action=ws,void(e.errorAction.flags=Fs)}return;case P.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const t=r.levels[r.loadLevel],s=null==t?void 0:t.attrs["HDCP-LEVEL"];s?e.errorAction={action:ws,flags:Ms,hdcpLevel:s}:this.keySystemError(e)}return;case P.BUFFER_ADD_CODEC_ERROR:case P.REMUX_ALLOC_ERROR:case P.BUFFER_APPEND_ERROR:return void(e.errorAction=this.getLevelSwitchAction(e,null!=(i=e.level)?i:r.loadLevel));case P.INTERNAL_EXCEPTION:case P.BUFFER_APPENDING_ERROR:case P.BUFFER_FULL_ERROR:case P.LEVEL_SWITCH_ERROR:case P.BUFFER_STALLED_ERROR:case P.BUFFER_SEEK_OVER_HOLE:case P.BUFFER_NUDGE_ON_STALL:return void(e.errorAction={action:Is,flags:xs})}e.type===C.KEY_SYSTEM_ERROR&&this.keySystemError(e)}keySystemError(t){const e=this.getVariantLevelIndex(t.frag);t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e)}getPlaylistRetryOrSwitchAction(t,e){const s=Ss(this.hls.config.playlistLoadPolicy,t),i=this.playlistError++;if(Rs(s,i,Es(t),t.response))return{action:Ps,flags:xs,retryConfig:s,retryCount:i};const r=this.getLevelSwitchAction(t,e);return s&&(r.retryConfig=s,r.retryCount=i),r}getFragRetryOrSwitchAction(t){const e=this.hls,s=this.getVariantLevelIndex(t.frag),i=e.levels[s],{fragLoadPolicy:r,keyLoadPolicy:n}=e.config,a=Ss(t.details.startsWith("key")?n:r,t),o=e.levels.reduce(((t,e)=>t+e.fragmentError),0);if(i){t.details!==P.FRAG_GAP&&i.fragmentError++;if(Rs(a,o,Es(t),t.response))return{action:Ps,flags:xs,retryConfig:a,retryCount:o}}const l=this.getLevelSwitchAction(t,s);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(t,e){const s=this.hls;null==e&&(e=s.loadLevel);const i=this.hls.levels[e];if(i){var r,n;const e=t.details;i.loadError++,e===P.BUFFER_APPEND_ERROR&&i.fragmentError++;let l=-1;const{levels:h,loadLevel:d,minAutoLevel:c,maxAutoLevel:u}=s;s.autoLevelEnabled||(s.loadLevel=-1);const f=null==(r=t.frag)?void 0:r.type,g=(f===Ue&&e===P.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&(e===P.BUFFER_ADD_CODEC_ERROR||e===P.BUFFER_APPEND_ERROR))&&h.some((({audioCodec:t})=>i.audioCodec!==t)),m="video"===t.sourceBufferName&&(e===P.BUFFER_ADD_CODEC_ERROR||e===P.BUFFER_APPEND_ERROR)&&h.some((({codecSet:t,audioCodec:e})=>i.codecSet!==t&&i.audioCodec===e)),{type:p,groupId:y}=null!=(n=t.context)?n:{};for(let s=h.length;s--;){const r=(s+d)%h.length;if(r!==d&&r>=c&&r<=u&&0===h[r].loadError){var a,o;const s=h[r];if(e===P.FRAG_GAP&&f===Ne&&t.frag){const e=h[r].details;if(e){const s=ks(t.frag,e.fragments,t.frag.start);if(null!=s&&s.gap)continue}}else{if(p===Me&&s.hasAudioGroup(y)||p===Oe&&s.hasSubtitleGroup(y))continue;if(f===Ue&&null!=(a=i.audioGroups)&&a.some((t=>s.hasAudioGroup(t)))||f===Be&&null!=(o=i.subtitleGroups)&&o.some((t=>s.hasSubtitleGroup(t)))||g&&i.audioCodec===s.audioCodec||!g&&i.audioCodec!==s.audioCodec||m&&i.codecSet===s.codecSet)continue}l=r;break}}if(l>-1&&s.loadLevel!==l)return t.levelRetry=!0,this.playlistError=0,{action:ws,flags:xs,nextAutoLevel:l}}return{action:ws,flags:Fs}}onErrorOut(t,e){var s;switch(null==(s=e.errorAction)?void 0:s.action){case Is:break;case ws:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===P.FRAG_GAP?/MediaSource readyState: ended/.test(e.error.message)&&(this.warn(`MediaSource ended after "${e.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):e.fatal=!0}e.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(t){const e=this.hls,s=t.errorAction;if(!s)return;const{flags:i,hdcpLevel:r,nextAutoLevel:n}=s;switch(i){case xs:this.switchLevel(t,n);break;case Ms:r&&(e.maxHdcpLevel=is[is.indexOf(r)-1],s.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`)}s.resolved||this.switchLevel(t,n)}switchLevel(t,e){void 0!==e&&t.errorAction&&(this.warn(`switching to level ${e} after ${t.details}`),this.hls.nextAutoLevel=e,t.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}},fpsController:class{constructor(t){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners()}setStreamController(t){this.streamController=t}registerListeners(){this.hls.on(w.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(w.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,e){const s=this.hls.config;if(s.capLevelOnFPSDrop){const t=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=t,t&&"function"==typeof t.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}checkFPS(t,e,s){const i=performance.now();if(e){if(this.lastTime){const t=i-this.lastTime,r=s-this.lastDroppedFrames,n=e-this.lastDecodedFrames,a=1e3*r/t,o=this.hls;if(o.trigger(w.FPS_DROP,{currentDropped:r,currentDecoded:n,totalDroppedFrames:s}),a>0&&r>o.config.fpsDroppedMonitoringThreshold*n){let t=o.currentLevel;N.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=t)&&(t-=1,o.trigger(w.FPS_DROP_LEVEL_CAPPING,{level:t,droppedLevel:o.currentLevel}),o.autoLevelCapping=t,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,this.lastDecodedFrames=e}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)}},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:dt,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:wa,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:class extends xi{constructor(t,e,s){super(t,e,s,"[subtitle-stream-controller]",Be),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}_registerListeners(){const{hls:t}=this;t.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(w.MANIFEST_LOADING,this.onManifestLoading,this),t.on(w.LEVEL_LOADED,this.onLevelLoaded,this),t.on(w.ERROR,this.onError,this),t.on(w.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(w.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(w.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(w.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(w.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(w.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(w.MANIFEST_LOADING,this.onManifestLoading,this),t.off(w.LEVEL_LOADED,this.onLevelLoaded,this),t.off(w.ERROR,this.onError,this),t.off(w.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(w.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(w.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(w.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(w.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(w.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(t){this.stopLoad(),this.state=Li,this.setInterval(500),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(t,e){this.mainDetails=e.details}onSubtitleFragProcessed(t,e){const{frag:s,success:i}=e;if(this.fragPrevious=s,this.state=Li,!i)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let n;const a=s.start;for(let t=0;t<r.length;t++)if(a>=r[t].start&&a<=r[t].end){n=r[t];break}const o=s.start+s.duration;n?n.end=o:(n={start:a,end:o},r.push(n)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null)}onBufferFlushing(t,e){const{startOffset:s,endOffset:i}=e;if(0===s&&i!==Number.POSITIVE_INFINITY){const t=i-1;if(t<=0)return;e.endOffsetSubtitles=Math.max(0,t),this.tracksBuffered.forEach((e=>{for(let s=0;s<e.length;)if(e[s].end<=t)e.shift();else{if(!(e[s].start<t))break;e[s].start=t,s++}})),this.fragmentTracker.removeFragmentsInRange(s,t,Be)}}onFragBuffered(t,e){var s;this.loadedmetadata||e.frag.type!==Ne||null!=(s=this.media)&&s.buffered.length&&(this.loadedmetadata=!0)}onError(t,e){const s=e.frag;(null==s?void 0:s.type)===Be&&(e.details===P.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==Si&&(this.state=Li))}onSubtitleTracksUpdated(t,{subtitleTracks:e}){this.levels&&Gr(this.levels,e)?this.levels=e.map((t=>new ds(t))):(this.tracksBuffered=[],this.levels=e.map((t=>{const e=new ds(t);return this.tracksBuffered[e.id]=[],e})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Be),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(t,e){var s;if(this.currentTrackId=e.id,null==(s=this.levels)||!s.length||-1===this.currentTrackId)return void this.clearInterval();const i=this.levels[this.currentTrackId];null!=i&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.setInterval(500)}onSubtitleTrackLoaded(t,e){var s;const{currentTrackId:i,levels:r}=this,{details:n,id:a}=e;if(!r)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=r[a];if(a>=r.length||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||null!=(s=o.details)&&s.live){const t=this.mainDetails;if(n.deltaUpdateFailed||!t)return;const e=t.fragments[0];var h;if(o.details)l=this.alignPlaylists(n,o.details,null==(h=this.levelLastLoaded)?void 0:h.details),0===l&&e&&(l=e.start,ps(n,l));else n.hasProgramDateTime&&t.hasProgramDateTime?(di(n,t),l=n.fragments[0].start):e&&(l=e.start,ps(n,l))}if(o.details=n,this.levelLastLoaded=o,a===i&&(this.startFragRequested||!this.mainDetails&&n.live||this.setStartPosition(this.mainDetails||n,l),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===Li)){ks(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}_handleFragmentLoadComplete(t){const{frag:e,payload:s}=t,i=e.decryptdata,r=this.hls;if(!this.fragContextChanged(e)&&s&&s.byteLength>0&&null!=i&&i.key&&i.iv&&"AES-128"===i.method){const t=performance.now();this.decrypter.decrypt(new Uint8Array(s),i.key.buffer,i.iv.buffer).catch((t=>{throw r.trigger(w.ERROR,{type:C.MEDIA_ERROR,details:P.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t})).then((s=>{const i=performance.now();r.trigger(w.FRAG_DECRYPTED,{frag:e,payload:s,stats:{tstart:t,tdecrypt:i}})})).catch((t=>{this.warn(`${t.name}: ${t.message}`),this.state=Li}))}}doTick(){if(this.media){if(this.state===Li){const{currentTrackId:t,levels:e}=this,s=null==e?void 0:e[t];if(!s||!e.length||!s.details)return;const{config:i}=this,r=this.getLoadPosition(),n=ri.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,i.maxBufferHole),{end:a,len:o}=n,l=this.getFwdBufferInfo(this.media,Ne),h=s.details;if(o>this.getMaxBufferLength(null==l?void 0:l.len)+h.levelTargetDuration)return;const d=h.fragments,c=d.length,u=h.edge;let f=null;const g=this.fragPrevious;if(a<u){const t=i.maxFragLookUpTolerance,e=a>u-t?0:t;f=ks(g,d,Math.max(d[0].start,a),e),!f&&g&&g.start<d[0].start&&(f=d[0])}else f=d[c-1];if(!f)return;if(f=this.mapToInitFragWhenRequired(f),"initSegment"!==f.sn){const t=d[f.sn-h.startSN-1];t&&t.cc===f.cc&&this.fragmentTracker.getState(t)===zs&&(f=t)}this.fragmentTracker.getState(f)===zs&&this.loadFragment(f,s,a)}}else this.state=Li}getMaxBufferLength(t){const e=super.getMaxBufferLength();return t?Math.max(e,t):e}loadFragment(t,e,s){this.fragCurrent=t,"initSegment"===t.sn?this._loadInitSegment(t,e):(this.startFragRequested=!0,super.loadFragment(t,e,s))}get mediaBufferTimeRanges(){return new Vr(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends Os{constructor(t){super(t,"[subtitle-track-controller]"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const e=je(this.media.textTracks);for(let s=0;s<e.length;s++)if("hidden"===e[s].mode)t=e[s];else if("showing"===e[s].mode){t=e[s];break}const s=this.findTrackForTextTrack(t);this.subtitleTrack!==s&&this.setSubtitleTrack(s)},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(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(w.MANIFEST_LOADING,this.onManifestLoading,this),t.on(w.MANIFEST_PARSED,this.onManifestParsed,this),t.on(w.LEVEL_LOADING,this.onLevelLoading,this),t.on(w.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(w.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(w.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(w.MANIFEST_LOADING,this.onManifestLoading,this),t.off(w.MANIFEST_PARSED,this.onManifestParsed,this),t.off(w.LEVEL_LOADING,this.onLevelLoading,this),t.off(w.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(w.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(w.ERROR,this.onError,this)}onMediaAttached(t,e){this.media=e.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,t)}onMediaDetaching(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId);je(this.media.textTracks).forEach((t=>{Ye(t)})),this.subtitleTrack=-1,this.media=null}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.subtitleTracks}onSubtitleTrackLoaded(t,e){const{id:s,groupId:i,details:r}=e,n=this.tracksInGroup[s];if(!n||n.groupId!==i)return void this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Subtitle track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const s=e.subtitleGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(null==i?void 0:i.length)!==(null==s?void 0:s.length)||null!=s&&s.some((t=>-1===(null==i?void 0:i.indexOf(t))))){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter((t=>!s||-1!==s.indexOf(t.groupId)));if(t.length)this.selectDefaultTrack&&!t.some((t=>t.default))&&(this.selectDefaultTrack=!1),t.forEach(((t,e)=>{t.id=e}));else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.subtitlePreference;if(!r&&e){this.selectDefaultTrack=!1;const s=Ys(e,t);if(s>-1)r=t[s];else{const t=Ys(e,this.tracks);r=this.tracks[t]}}let i=this.findTrackId(r);-1===i&&r&&(i=this.findTrackId(null));const n={subtitleTracks:t};this.log(`Updating subtitle tracks, ${t.length} track(s) found in "${null==s?void 0:s.join(",")}" group-id`),this.hls.trigger(w.SUBTITLE_TRACKS_UPDATED,n),-1!==i&&-1===this.trackId&&this.setSubtitleTrack(i)}else this.shouldReloadPlaylist(r)&&this.setSubtitleTrack(this.trackId)}findTrackId(t){const e=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i<e.length;i++){const r=e[i];if((!s||r.default)&&(s||t)&&(!t||Ws(r,t)))return i}if(t){for(let s=0;s<e.length;s++){const i=e[s];if(Kr(t.attrs,i.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<e.length;s++){const i=e[s];if(Kr(t.attrs,i.attrs,["LANGUAGE"]))return s}}return-1}findTrackForTextTrack(t){if(t){const e=this.tracksInGroup;for(let s=0;s<e.length;s++){if(Hr(e[s],t))return s}}return-1}onError(t,e){!e.fatal&&e.context&&(e.context.type!==Oe||e.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||this.checkRetry(e))}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(t){this.selectDefaultTrack=!1,this.setSubtitleTrack(t)}setSubtitleOption(t){if(this.hls.config.subtitlePreference=t,t){const e=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,e.length){const s=this.currentTrack;if(s&&Ws(t,s))return s;const i=Ys(t,this.tracksInGroup);if(i>-1){const t=this.tracksInGroup[i];return this.setSubtitleTrack(i),t}if(s)return null;{const s=Ys(t,e);if(s>-1)return e[s]}}}return null}loadPlaylist(t){super.loadPlaylist();const e=this.currentTrack;if(this.shouldLoadPlaylist(e)&&e){const s=e.id,i=e.groupId;let r=e.url;if(t)try{r=t.addDirectives(r)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}this.log(`Loading subtitle playlist for id ${s}`),this.hls.trigger(w.SUBTITLE_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null})}}toggleTrackModes(){const{media:t}=this;if(!t)return;const e=je(t.textTracks),s=this.currentTrack;let i;if(s&&(i=e.filter((t=>Hr(s,t)))[0],i||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(e).forEach((t=>{"disabled"!==t.mode&&t!==i&&(t.mode="disabled")})),i){const t=this.subtitleDisplay?"showing":"hidden";i.mode!==t&&(i.mode=t)}}setSubtitleTrack(t){const e=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=t);if(t<-1||t>=e.length||!D(t))return void this.warn(`Invalid subtitle track id: ${t}`);this.clearTimer(),this.selectDefaultTrack=!1;const s=this.currentTrack,i=e[t]||null;if(this.trackId=t,this.currentTrack=i,this.toggleTrackModes(),!i)return void this.hls.trigger(w.SUBTITLE_TRACK_SWITCH,{id:t});const r=!!i.details&&!i.details.live;if(t===this.trackId&&i===s&&r)return;this.log(`Switching to subtitle-track ${t}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));const{id:n,groupId:a="",name:o,type:l,url:h}=i;this.hls.trigger(w.SUBTITLE_TRACK_SWITCH,{id:n,groupId:a,name:o,type:l,url:h});const d=this.switchParams(i.url,null==s?void 0:s.details,i.details);this.loadPlaylist(d)}},timelineController:class{constructor(t){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},t.on(w.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(w.MANIFEST_LOADING,this.onManifestLoading,this),t.on(w.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(w.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(w.FRAG_LOADING,this.onFragLoading,this),t.on(w.FRAG_LOADED,this.onFragLoaded,this),t.on(w.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(w.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(w.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(w.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(w.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(w.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(w.MANIFEST_LOADING,this.onManifestLoading,this),t.off(w.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(w.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(w.FRAG_LOADING,this.onFragLoading,this),t.off(w.FRAG_LOADED,this.onFragLoaded,this),t.off(w.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(w.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(w.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(w.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(w.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){if(this.config.enableCEA708Captions&&(!this.cea608Parser1||!this.cea608Parser2)){const t=new gn(this,"textTrack1"),e=new gn(this,"textTrack2"),s=new gn(this,"textTrack3"),i=new gn(this,"textTrack4");this.cea608Parser1=new cn(1,t,e),this.cea608Parser2=new cn(3,s,i)}}addCues(t,e,s,i,r){let n=!1;for(let t=r.length;t--;){const i=r[t],d=(a=i[0],o=i[1],l=e,h=s,Math.min(o,h)-Math.max(a,l));if(d>=0&&(i[0]=Math.min(i[0],e),i[1]=Math.max(i[1],s),n=!0,d/(s-e)>.5))return}var a,o,l,h;if(n||r.push([e,s]),this.config.renderTextTracksNatively){const r=this.captionsTracks[t];this.Cues.newCue(r,e,s,i)}else{const r=this.Cues.newCue(null,e,s,i);this.hls.trigger(w.CUES_PARSED,{type:"captions",cues:r,track:t})}}onInitPtsFound(t,{frag:e,id:s,initPTS:i,timescale:r}){const{unparsedVttFrags:n}=this;"main"===s&&(this.initPTS[e.cc]={baseTime:i,timescale:r}),n.length&&(this.unparsedVttFrags=[],n.forEach((t=>{this.onFragLoaded(w.FRAG_LOADED,t)})))}getExistingTrack(t,e){const{media:s}=this;if(s)for(let i=0;i<s.textTracks.length;i++){const r=s.textTracks[i];if(Kn(r,{name:t,lang:e,attrs:{}}))return r}return null}createCaptionsTrack(t){this.config.renderTextTracksNatively?this.createNativeTrack(t):this.createNonNativeTrack(t)}createNativeTrack(t){if(this.captionsTracks[t])return;const{captionsProperties:e,captionsTracks:s,media:i}=this,{label:r,languageCode:n}=e[t],a=this.getExistingTrack(r,n);if(a)s[t]=a,Ye(s[t]),He(s[t],i);else{const e=this.createTextTrack("captions",r,n);e&&(e[t]=!0,s[t]=e)}}createNonNativeTrack(t){if(this.nonNativeCaptionsTracks[t])return;const e=this.captionsProperties[t];if(!e)return;const s={_id:t,label:e.label,kind:"captions",default:!!e.media&&!!e.media.default,closedCaptions:e.media};this.nonNativeCaptionsTracks[t]=s,this.hls.trigger(w.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}createTextTrack(t,e,s){const i=this.media;if(i)return i.addTextTrack(t,e,s)}onMediaAttaching(t,e){this.media=e.media,this._cleanTracks()}onMediaDetaching(){const{captionsTracks:t}=this;Object.keys(t).forEach((e=>{Ye(t[e]),delete t[e]})),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:t}=this;if(!t)return;const e=t.textTracks;if(e)for(let t=0;t<e.length;t++)Ye(e[t])}onSubtitleTracksUpdated(t,e){const s=e.subtitleTracks||[],i=s.some((t=>t.textCodec===wn));if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(Gr(this.tracks,s))return void(this.tracks=s);if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const t=this.media,e=t?je(t.textTracks):null;if(this.tracks.forEach(((t,s)=>{let i;if(e){let s=null;for(let i=0;i<e.length;i++)if(e[i]&&Kn(e[i],t)){s=e[i],e[i]=null;break}s&&(i=s)}if(i)Ye(i);else{const e=Gn(t);i=this.createTextTrack(e,t.name,t.lang),i&&(i.mode="disabled")}i&&this.textTracks.push(i)})),null!=e&&e.length){const t=e.filter((t=>null!==t)).map((t=>t.label));t.length&&N.warn(`Media element contains unused subtitle tracks: ${t.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const t=this.tracks.map((t=>({label:t.name,kind:t.type.toLowerCase(),default:t.default,subtitleTrack:t})));this.hls.trigger(w.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:t})}}}onManifestLoaded(t,e){this.config.enableCEA708Captions&&e.captions&&e.captions.forEach((t=>{const e=/(?:CC|SERVICE)([1-4])/.exec(t.instreamId);if(!e)return;const s=`textTrack${e[1]}`,i=this.captionsProperties[s];i&&(i.label=t.name,t.lang&&(i.languageCode=t.lang),i.media=t)}))}closedCaptionsForLevel(t){const e=this.hls.levels[t.level];return null==e?void 0:e.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,e){if(this.enabled&&e.frag.type===Ne){var s,i;const{cea608Parser1:t,cea608Parser2:r,lastSn:n}=this,{cc:a,sn:o}=e.frag,l=null!=(s=null==(i=e.part)?void 0:i.index)?s:-1;t&&r&&(o!==n+1||o===n&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(t.reset(),r.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(t,e){const{frag:s,payload:i}=e;if(s.type===Be)if(i.byteLength){const t=s.decryptdata,r="stats"in e;if(null==t||!t.encrypted||r){const t=this.tracks[s.level],r=this.vttCCs;r[s.cc]||(r[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),t&&t.textCodec===wn?this._parseIMSC1(s,i):this._parseVTTs(e)}}else this.hls.trigger(w.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,e){const s=this.hls;Fn(e,this.initPTS[t.cc],(e=>{this._appendCues(e,t.level),s.trigger(w.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})}),(e=>{N.log(`Failed to parse IMSC1: ${e}`),s.trigger(w.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:e})}))}_parseVTTs(t){var e;const{frag:s,payload:i}=t,{initPTS:r,unparsedVttFrags:n}=this,a=r.length-1;if(!r[s.cc]&&-1===a)return void n.push(t);const o=this.hls;In(null!=(e=s.initSegment)&&e.data?Xt(s.initSegment.data,new Uint8Array(i)):i,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,(t=>{this._appendCues(t,s.level),o.trigger(w.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})}),(e=>{const r="Missing initPTS for VTT MPEGTS"===e.message;r?n.push(t):this._fallbackToIMSC1(s,i),N.log(`Failed to parse VTT cue: ${e}`),r&&a>s.cc||o.trigger(w.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:e})}))}_fallbackToIMSC1(t,e){const s=this.tracks[t.level];s.textCodec||Fn(e,this.initPTS[t.cc],(()=>{s.textCodec=wn,this._parseIMSC1(t,e)}),(()=>{s.textCodec="wvtt"}))}_appendCues(t,e){const s=this.hls;if(this.config.renderTextTracksNatively){const s=this.textTracks[e];if(!s||"disabled"===s.mode)return;t.forEach((t=>Ve(s,t)))}else{const i=this.tracks[e];if(!i)return;const r=i.default?"default":"subtitles"+e;s.trigger(w.CUES_PARSED,{type:"subtitles",cues:t,track:r})}}onFragDecrypted(t,e){const{frag:s}=e;s.type===Be&&this.onFragLoaded(w.FRAG_LOADED,e)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,e){this.initCea608Parsers();const{cea608Parser1:s,cea608Parser2:i}=this;if(!this.enabled||!s||!i)return;const{frag:r,samples:n}=e;if(r.type!==Ne||"NONE"!==this.closedCaptionsForLevel(r))for(let t=0;t<n.length;t++){const e=n[t].bytes;if(e){const r=this.extractCea608Data(e);s.addData(n[t].pts,r[0]),i.addData(n[t].pts,r[1])}}}onBufferFlushing(t,{startOffset:e,endOffset:s,endOffsetSubtitles:i,type:r}){const{media:n}=this;if(n&&!(n.currentTime<s)){if(!r||"video"===r){const{captionsTracks:t}=this;Object.keys(t).forEach((i=>We(t[i],e,s)))}if(this.config.renderTextTracksNatively&&0===e&&void 0!==i){const{textTracks:t}=this;Object.keys(t).forEach((s=>We(t[s],e,i)))}}}extractCea608Data(t){const e=[[],[]],s=31&t[0];let i=2;for(let r=0;r<s;r++){const s=t[i++],r=127&t[i++],n=127&t[i++];if(0===r&&0===n)continue;if(!!(4&s)){const t=3&s;0!==t&&1!==t||(e[t].push(r),e[t].push(n))}}return e}},audioStreamController:class extends xi{constructor(t,e,s){super(t,e,s,"[audio-stream-controller]",Ue),this.videoBuffer=null,this.videoTrackCC=-1,this.waitingVideoCC=-1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}_registerListeners(){const{hls:t}=this;t.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(w.MANIFEST_LOADING,this.onManifestLoading,this),t.on(w.LEVEL_LOADED,this.onLevelLoaded,this),t.on(w.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(w.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(w.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(w.ERROR,this.onError,this),t.on(w.BUFFER_RESET,this.onBufferReset,this),t.on(w.BUFFER_CREATED,this.onBufferCreated,this),t.on(w.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(w.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(w.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(w.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(w.MANIFEST_LOADING,this.onManifestLoading,this),t.off(w.LEVEL_LOADED,this.onLevelLoaded,this),t.off(w.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(w.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(w.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(w.ERROR,this.onError,this),t.off(w.BUFFER_RESET,this.onBufferReset,this),t.off(w.BUFFER_CREATED,this.onBufferCreated,this),t.off(w.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(w.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(w.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(w.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(t,{frag:e,id:s,initPTS:i,timescale:r}){if("main"===s){const t=e.cc;this.initPTS[e.cc]={baseTime:i,timescale:r},this.log(`InitPTS for cc: ${t} found from main: ${i}`),this.videoTrackCC=t,this.state===Ci&&this.tick()}}startLoad(t){if(!this.levels)return this.startPosition=t,void(this.state=Si);const e=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),e>0&&-1===t?(this.log(`Override startPosition with lastCurrentTime @${e.toFixed(3)}`),t=e,this.state=Li):(this.loadedmetadata=!1,this.state=ki),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}doTick(){switch(this.state){case Li:this.doTickIdle();break;case ki:{var t;const{levels:e,trackId:s}=this,i=null==e||null==(t=e[s])?void 0:t.details;if(i){if(this.waitForCdnTuneIn(i))break;this.state=Ci}break}case bi:{var e;const t=performance.now(),s=this.retryDate;if(!s||t>=s||null!=(e=this.media)&&e.seeking){const{levels:t,trackId:e}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((null==t?void 0:t[e])||null),this.state=Li}break}case Ci:{const t=this.waitingData;if(t){const{frag:e,part:s,cache:i,complete:r}=t;if(void 0!==this.initPTS[e.cc]){this.waitingData=null,this.waitingVideoCC=-1,this.state=Ri;const t={frag:e,part:s,payload:i.flush(),networkDetails:null};this._handleFragmentLoadProgress(t),r&&super._handleFragmentLoadComplete(t)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${e.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const t=this.getLoadPosition(),s=ri.bufferInfo(this.mediaBuffer,t,this.config.maxBufferHole);Ds(s.end,this.config.maxFragLookUpTolerance,e)<0&&(this.log(`Waiting fragment cc (${e.cc}) @ ${e.start} cancelled because another fragment at ${s.end} is needed`),this.clearWaitingFragment())}}else this.state=Li}}this.onTickEnd()}clearWaitingFragment(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=Li)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:t}=this;null!=t&&t.readyState&&(this.lastCurrentTime=t.currentTime)}doTickIdle(){const{hls:t,levels:e,media:s,trackId:i}=this,r=t.config;if(!s&&(this.startFragRequested||!r.startFragPrefetch)||null==e||!e[i])return;const n=e[i],a=n.details;if(!a||a.live&&this.levelLastLoaded!==n||this.waitForCdnTuneIn(a))return void(this.state=ki);const o=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&o&&(this.bufferFlushed=!1,this.afterBufferFlushed(o,V,Ue));const l=this.getFwdBufferInfo(o,Ue);if(null===l)return;const{bufferedTrack:h,switchingTrack:d}=this;if(!d&&this._streamEnded(l,a))return t.trigger(w.BUFFER_EOS,{type:"audio"}),void(this.state=Ii);const c=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,Ne),u=l.len,f=this.getMaxBufferLength(null==c?void 0:c.len),g=a.fragments,m=g[0].start;let p=this.flushing?this.getLoadPosition():l.end;if(d&&s){const t=this.getLoadPosition();h&&!Kr(d.attrs,h.attrs)&&(p=t),a.PTSKnown&&t<m&&(l.end>m||l.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=m+.05)}if(u>=f&&!d&&p<g[g.length-1].start)return;let y=this.getNextFragment(p,a),v=!1;if(y&&this.isLoopLoading(y,p)&&(v=!!y.gap,y=this.getNextFragmentLoopLoading(y,a,l,Ne,f)),!y)return void(this.bufferFlushed=!0);const T=c&&y.start>c.end+a.targetduration;if(T||(null==c||!c.len)&&l.len){const t=this.getAppendedFrag(y.start,Ne);if(null===t)return;if(v||(v=!!t.gap||!!T&&0===c.len),T&&!v||v&&l.nextStart&&l.nextStart<t.end)return}this.loadFragment(y,n,p)}getMaxBufferLength(t){const e=super.getMaxBufferLength();return t?Math.min(Math.max(e,t),this.config.maxMaxBufferLength):e}onMediaDetaching(){this.videoBuffer=null,this.bufferFlushed=this.flushing=!1,super.onMediaDetaching()}onAudioTracksUpdated(t,{audioTracks:e}){this.resetTransmuxer(),this.levels=e.map((t=>new ds(t)))}onAudioTrackSwitching(t,e){const s=!!e.url;this.trackId=e.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?this.setInterval(100):this.resetTransmuxer(),s?(this.switchingTrack=e,this.state=Li,this.flushAudioIfNeeded(e)):(this.switchingTrack=null,this.bufferedTrack=e,this.state=Si),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=this.flushing=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}onLevelLoaded(t,e){this.mainDetails=e.details,null!==this.cachedTrackLoadedData&&(this.hls.trigger(w.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(t,e){var s;if(null==this.mainDetails)return void(this.cachedTrackLoadedData=e);const{levels:i}=this,{details:r,id:n}=e;if(!i)return void this.warn(`Audio tracks were reset while loading level ${n}`);this.log(`Audio track ${n} loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const a=i[n];let o=0;if(r.live||null!=(s=a.details)&&s.live){this.checkLiveUpdate(r);const t=this.mainDetails;if(r.deltaUpdateFailed||!t)return;var l;if(!a.details&&r.hasProgramDateTime&&t.hasProgramDateTime)di(r,t),o=r.fragments[0].start;else o=this.alignPlaylists(r,a.details,null==(l=this.levelLastLoaded)?void 0:l.details)}a.details=r,this.levelLastLoaded=a,this.startFragRequested||!this.mainDetails&&r.live||this.setStartPosition(this.mainDetails||r,o),this.state!==ki||this.waitForCdnTuneIn(r)||(this.state=Li),this.tick()}_handleFragmentLoadProgress(t){var e;const{frag:s,part:i,payload:r}=t,{config:n,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const h=l.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(s.start);const d=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let c=this.transmuxer;c||(c=this.transmuxer=new $r(this.hls,Ue,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const u=this.initPTS[s.cc],f=null==(e=s.initSegment)?void 0:e.data;if(void 0!==u){const t=!1,e=i?i.index:-1,n=-1!==e,a=new ni(s.level,s.sn,s.stats.chunkCount,r.byteLength,e,n);c.push(r,f,d,"",s,i,h.totalduration,t,a,u)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${h.startSN} ,${h.endSN}],track ${a}`);const{cache:t}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new Fi,complete:!1};t.push(new Uint8Array(r)),this.waitingVideoCC=this.videoTrackCC,this.state=Ci}}_handleFragmentLoadComplete(t){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(t,e){const s=e.tracks.audio;s&&(this.mediaBuffer=s.buffer||null),e.tracks.video&&(this.videoBuffer=e.tracks.video.buffer||null)}onFragBuffered(t,e){const{frag:s,part:i}=e;if(s.type===Ue)if(this.fragContextChanged(s))this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if("initSegment"!==s.sn){this.fragPrevious=s;const t=this.switchingTrack;t&&(this.bufferedTrack=t,this.switchingTrack=null,this.hls.trigger(w.AUDIO_TRACK_SWITCHED,A({},t)))}this.fragBufferedComplete(s,i)}else if(!this.loadedmetadata&&s.type===Ne){const t=this.videoBuffer||this.media;if(t){ri.getBuffered(t).length&&(this.loadedmetadata=!0)}}}onError(t,e){var s;if(e.fatal)this.state=wi;else switch(e.details){case P.FRAG_GAP:case P.FRAG_PARSING_ERROR:case P.FRAG_DECRYPT_ERROR:case P.FRAG_LOAD_ERROR:case P.FRAG_LOAD_TIMEOUT:case P.KEY_LOAD_ERROR:case P.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Ue,e);break;case P.AUDIO_TRACK_LOAD_ERROR:case P.AUDIO_TRACK_LOAD_TIMEOUT:case P.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==ki||(null==(s=e.context)?void 0:s.type)!==Me||(this.state=Li);break;case P.BUFFER_APPEND_ERROR:case P.BUFFER_FULL_ERROR:if(!e.parent||"audio"!==e.parent)return;if(e.details===P.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case P.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onBufferFlushing(t,{type:e}){e!==Y&&(this.flushing=!0)}onBufferFlushed(t,{type:e}){if(e!==Y){this.flushing=!1,this.bufferFlushed=!0,this.state===Ii&&(this.state=Li);const t=this.mediaBuffer||this.media;t&&(this.afterBufferFlushed(t,e,Ue),this.tick())}}_handleTransmuxComplete(t){var e;const s="audio",{hls:i}=this,{remuxResult:r,chunkMeta:n}=t,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:h}=a,{details:d}=h,{audio:c,text:u,id3:f,initSegment:g}=r;if(!this.fragContextChanged(o)&&d){if(this.state=Di,this.switchingTrack&&c&&this.completeAudioSwitch(this.switchingTrack),null!=g&&g.tracks){const t=o.initSegment||o;this._bufferInitSegment(h,g.tracks,t,n),i.trigger(w.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:s,tracks:g.tracks})}if(c){const{startPTS:t,endPTS:e,startDTS:s,endDTS:i}=c;l&&(l.elementaryStreams[V]={startPTS:t,endPTS:e,startDTS:s,endDTS:i}),o.setElementaryStreamInfo(V,t,e,s,i),this.bufferFragmentData(c,o,l,n)}if(null!=f&&null!=(e=f.samples)&&e.length){const t=k({id:s,frag:o,details:d},f);i.trigger(w.FRAG_PARSING_METADATA,t)}if(u){const t=k({id:s,frag:o,details:d},u);i.trigger(w.FRAG_PARSING_USERDATA,t)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(t,e,s,i){if(this.state!==Di)return;e.video&&delete e.video;const r=e.audio;if(!r)return;r.id="audio";const n=t.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${n}/${r.codec}]`),n&&1===n.split(",").length&&(r.levelCodec=n),this.hls.trigger(w.BUFFER_CODECS,e);const a=r.initSegment;if(null!=a&&a.byteLength){const t={type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:a};this.hls.trigger(w.BUFFER_APPENDING,t)}this.tickImmediate()}loadFragment(t,e,s){const i=this.fragmentTracker.getState(t);var r;if(this.fragCurrent=t,this.switchingTrack||i===zs||i===Js)if("initSegment"===t.sn)this._loadInitSegment(t,e);else if(null!=(r=e.details)&&r.live&&!this.initPTS[t.cc]){this.log(`Waiting for video PTS in continuity counter ${t.cc} of live stream before loading audio fragment ${t.sn} of level ${this.trackId}`),this.state=Ci;const s=this.mainDetails;s&&s.fragments[0].start!==e.details.fragments[0].start&&di(e.details,s)}else this.startFragRequested=!0,super.loadFragment(t,e,s);else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){const{media:e,bufferedTrack:s}=this,i=null==s?void 0:s.attrs,r=t.attrs;e&&i&&(i.CHANNELS!==r.CHANNELS||s.name!==t.name||s.lang!==t.lang)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null)}completeAudioSwitch(t){const{hls:e}=this;this.flushAudioIfNeeded(t),this.bufferedTrack=t,this.switchingTrack=null,e.trigger(w.AUDIO_TRACK_SWITCHED,A({},t))}},audioTrackController:class extends Os{constructor(t){super(t,"[audio-track-controller]"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:t}=this;t.on(w.MANIFEST_LOADING,this.onManifestLoading,this),t.on(w.MANIFEST_PARSED,this.onManifestParsed,this),t.on(w.LEVEL_LOADING,this.onLevelLoading,this),t.on(w.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(w.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(w.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(w.MANIFEST_LOADING,this.onManifestLoading,this),t.off(w.MANIFEST_PARSED,this.onManifestParsed,this),t.off(w.LEVEL_LOADING,this.onLevelLoading,this),t.off(w.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(w.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(w.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(t,e){this.tracks=e.audioTracks||[]}onAudioTrackLoaded(t,e){const{id:s,groupId:i,details:r}=e,n=this.tracksInGroup[s];if(!n||n.groupId!==i)return void this.warn(`Audio track with id:${s} and group:${i} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Audio track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const s=e.audioGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(null==i?void 0:i.length)!==(null==s?void 0:s.length)||null!=s&&s.some((t=>-1===(null==i?void 0:i.indexOf(t))))){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter((t=>!s||-1!==s.indexOf(t.groupId)));if(t.length)this.selectDefaultTrack&&!t.some((t=>t.default))&&(this.selectDefaultTrack=!1),t.forEach(((t,e)=>{t.id=e}));else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.audioPreference;if(!r&&e){const s=Ys(e,t,js);if(s>-1)r=t[s];else{const t=Ys(e,this.tracks);r=this.tracks[t]}}let i=this.findTrackId(r);-1===i&&r&&(i=this.findTrackId(null));const a={audioTracks:t};this.log(`Updating audio tracks, ${t.length} track(s) found in group(s): ${null==s?void 0:s.join(",")}`),this.hls.trigger(w.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==i&&-1===o)this.setAudioTrack(i);else if(t.length&&-1===o){var n;const e=new Error(`No audio track selected for current audio group-ID(s): ${null==(n=this.groupIds)?void 0:n.join(",")} track count: ${t.length}`);this.warn(e.message),this.hls.trigger(w.ERROR,{type:C.MEDIA_ERROR,details:P.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:e})}}else this.shouldReloadPlaylist(r)&&this.setAudioTrack(this.trackId)}onError(t,e){!e.fatal&&e.context&&(e.context.type!==Me||e.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||(this.requestScheduled=-1,this.checkRetry(e)))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}setAudioOption(t){const e=this.hls;if(e.config.audioPreference=t,t){const s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const i=this.currentTrack;if(i&&Ws(t,i,js))return i;const r=Ys(t,this.tracksInGroup,js);if(r>-1){const t=this.tracksInGroup[r];return this.setAudioTrack(r),t}if(i){let i=e.loadLevel;-1===i&&(i=e.firstAutoLevel);const r=function(t,e,s,i,r){const n=e[i],a=e.reduce(((t,e,s)=>{const i=e.uri;return(t[i]||(t[i]=[])).push(s),t}),{})[n.uri];a.length>1&&(i=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,h=n.codecSet.substring(0,4),d=qs(e,i,(e=>{if(e.videoRange!==o||e.frameRate!==l||e.codecSet.substring(0,4)!==h)return!1;const i=e.audioGroups,n=s.filter((t=>!i||-1!==i.indexOf(t.groupId)));return Ys(t,n,r)>-1}));return d>-1?d:qs(e,i,(e=>{const i=e.audioGroups,n=s.filter((t=>!i||-1!==i.indexOf(t.groupId)));return Ys(t,n,r)>-1}))}(t,e.levels,s,i,js);if(-1===r)return null;e.nextLoadLevel=r}if(t.channels||t.audioCodec){const e=Ys(t,s);if(e>-1)return s[e]}}}return null}setAudioTrack(t){const e=this.tracksInGroup;if(t<0||t>=e.length)return void this.warn(`Invalid audio track id: ${t}`);this.clearTimer(),this.selectDefaultTrack=!1;const s=this.currentTrack,i=e[t],r=i.details&&!i.details.live;if(t===this.trackId&&i===s&&r)return;if(this.log(`Switching to audio-track ${t} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=t,this.currentTrack=i,this.hls.trigger(w.AUDIO_TRACK_SWITCHING,A({},i)),r)return;const n=this.switchParams(i.url,null==s?void 0:s.details,i.details);this.loadPlaylist(n)}findTrackId(t){const e=this.tracksInGroup;for(let s=0;s<e.length;s++){const i=e[s];if((!this.selectDefaultTrack||i.default)&&(!t||Ws(t,i,js)))return s}if(t){const{name:s,lang:i,assocLang:r,characteristics:n,audioCodec:a,channels:o}=t;for(let t=0;t<e.length;t++){if(Ws({name:s,lang:i,assocLang:r,characteristics:n,audioCodec:a,channels:o},e[t],js))return t}for(let s=0;s<e.length;s++){const i=e[s];if(Kr(t.attrs,i.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<e.length;s++){const i=e[s];if(Kr(t.attrs,i.attrs,["LANGUAGE"]))return s}}return-1}loadPlaylist(t){const e=this.currentTrack;if(this.shouldLoadPlaylist(e)&&e){super.loadPlaylist();const s=e.id,i=e.groupId;let r=e.url;if(t)try{r=t.addDirectives(r)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}this.log(`loading audio-track playlist ${s} "${e.name}" lang:${e.lang} group:${i}`),this.clearTimer(),this.hls.trigger(w.AUDIO_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null})}}},emeController:Yn,cmcdController:class{constructor(t){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.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=t=>{try{this.apply(t,{ot:jn.MANIFEST,su:!this.initialized})}catch(t){N.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=t=>{try{const e=t.frag,s=this.hls.levels[e.level],i=this.getObjectType(e),r={d:1e3*e.duration,ot:i};i!==jn.VIDEO&&i!==jn.AUDIO&&i!=jn.MUXED||(r.br=s.bitrate/1e3,r.tb=this.getTopBandwidth(i)/1e3,r.bl=this.getBufferLength(i)),this.apply(t,r)}catch(t){N.warn("Could not generate segment CMCD data.",t)}},this.hls=t;const e=this.config=t.config,{cmcd:s}=e;null!=s&&(e.pLoader=this.createPlaylistLoader(),e.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||function(){try{return crypto.randomUUID()}catch(t){try{const t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}catch(t){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(t=>{const s=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?s:3&s|8).toString(16)}))}}}(),this.cid=s.contentId,this.useHeaders=!0===s.useHeaders,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){const t=this.hls;t.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(w.MEDIA_DETACHED,this.onMediaDetached,this),t.on(w.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(w.MEDIA_DETACHED,this.onMediaDetached,this),t.off(w.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=null}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(t,e){var s,i;this.audioBuffer=null==(s=e.tracks.audio)?void 0:s.buffer,this.videoBuffer=null==(i=e.tracks.video)?void 0:i.buffer}createData(){var t;return{v:1,sf:qn.HLS,sid:this.sid,cid:this.cid,pr:null==(t=this.media)?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,e={}){k(e,this.createData());const s=e.ot===jn.INIT||e.ot===jn.VIDEO||e.ot===jn.MUXED;this.starved&&s&&(e.bs=!0,e.su=!0,this.starved=!1),null==e.su&&(e.su=this.buffering);const{includeKeys:i}=this;i&&(e=Object.keys(e).reduce(((t,s)=>(i.includes(s)&&(t[s]=e[s]),t)),{})),this.useHeaders?(t.headers||(t.headers={}),va(t.headers,e)):t.url=Ea(t.url,e)}getObjectType(t){const{type:e}=t;return"subtitle"===e?jn.TIMED_TEXT:"initSegment"===t.sn?jn.INIT:"audio"===e?jn.AUDIO:"main"===e?this.hls.audioTracks.length?jn.VIDEO:jn.MUXED:void 0}getTopBandwidth(t){let e,s=0;const i=this.hls;if(t===jn.AUDIO)e=i.audioTracks;else{const t=i.maxAutoLevel,s=t>-1?t+1:i.levels.length;e=i.levels.slice(0,s)}for(const t of e)t.bitrate>s&&(s=t.bitrate);return s>0?s:NaN}getBufferLength(t){const e=this.hls.media,s=t===jn.AUDIO?this.audioBuffer:this.videoBuffer;if(!s||!e)return NaN;return 1e3*ri.bufferInfo(s,e.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:t}=this.config,e=this.applyPlaylistData,s=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new s(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,s,i){e(t),this.loader.load(t,s,i)}}}createFragmentLoader(){const{fLoader:t}=this.config,e=this.applyFragmentData,s=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new s(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,s,i){e(t),this.loader.load(t,s,i)}}}},contentSteeringController:class{constructor(t){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=t,this.log=N.log.bind(N,"[content-steering]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(w.MANIFEST_LOADING,this.onManifestLoading,this),t.on(w.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(w.MANIFEST_PARSED,this.onManifestParsed,this),t.on(w.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(w.MANIFEST_LOADING,this.onManifestLoading,this),t.off(w.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(w.MANIFEST_PARSED,this.onManifestParsed,this),t.off(w.ERROR,this.onError,this))}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const t=1e3*this.timeToLoad-(performance.now()-this.updated);if(t>0)return void this.scheduleRefresh(this.uri,t)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(t){const e=this.levels;e&&(this.levels=e.filter((e=>e!==t)))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(t,e){const{contentSteering:s}=e;null!==s&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks}onError(t,e){const{errorAction:s}=e;if((null==s?void 0:s.action)===ws&&s.flags===Fs){const t=this.levels;let i=this.pathwayPriority,r=this.pathwayId;if(e.context){const{groupId:s,pathwayId:i,type:n}=e.context;s&&t?r=this.getPathwayForGroupId(s,n,r):i&&(r=i)}r in this.penalizedPathways||(this.penalizedPathways[r]=performance.now()),!i&&t&&(i=t.reduce(((t,e)=>(-1===t.indexOf(e.pathwayId)&&t.push(e.pathwayId),t)),[])),i&&i.length>1&&(this.updatePathwayPriority(i),s.resolved=this.pathwayId!==r),s.resolved||N.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${r} levels: ${t?t.length:t} priorities: ${JSON.stringify(i)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(t){this.levels=t;let e=this.getLevelsForPathway(this.pathwayId);if(0===e.length){const s=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),e=this.getLevelsForPathway(s),this.pathwayId=s}return e.length!==t.length?(this.log(`Found ${e.length}/${t.length} levels in Pathway "${this.pathwayId}"`),e):t}getLevelsForPathway(t){return null===this.levels?[]:this.levels.filter((e=>t===e.pathwayId))}updatePathwayPriority(t){let e;this.pathwayPriority=t;const s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach((t=>{i-s[t]>3e5&&delete s[t]}));for(let i=0;i<t.length;i++){const r=t[i];if(r in s)continue;if(r===this.pathwayId)return;const n=this.hls.nextLoadLevel,a=this.hls.levels[n];if(e=this.getLevelsForPathway(r),e.length>0){this.log(`Setting Pathway to "${r}"`),this.pathwayId=r,Ts(e),this.hls.trigger(w.LEVELS_UPDATED,{levels:e});const t=this.hls.levels[n];a&&t&&this.levels&&(t.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&t.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${t.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(t,e,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let s=0;s<i.length;s++)if(e===Me&&i[s].hasAudioGroup(t)||e===Oe&&i[s].hasSubtitleGroup(t))return i[s].pathwayId;return s}clonePathways(t){const e=this.levels;if(!e)return;const s={},i={};t.forEach((t=>{const{ID:r,"BASE-ID":n,"URI-REPLACEMENT":a}=t;if(e.some((t=>t.pathwayId===r)))return;const o=this.getLevelsForPathway(n).map((t=>{const e=new $(t.attrs);e["PATHWAY-ID"]=r;const n=e.AUDIO&&`${e.AUDIO}_clone_${r}`,o=e.SUBTITLES&&`${e.SUBTITLES}_clone_${r}`;n&&(s[e.AUDIO]=n,e.AUDIO=n),o&&(i[e.SUBTITLES]=o,e.SUBTITLES=o);const l=La(t.uri,e["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),h=new ds({attrs:e,audioCodec:t.audioCodec,bitrate:t.bitrate,height:t.height,name:t.name,url:l,videoCodec:t.videoCodec,width:t.width});if(t.audioGroups)for(let e=1;e<t.audioGroups.length;e++)h.addGroupId("audio",`${t.audioGroups[e]}_clone_${r}`);if(t.subtitleGroups)for(let e=1;e<t.subtitleGroups.length;e++)h.addGroupId("text",`${t.subtitleGroups[e]}_clone_${r}`);return h}));e.push(...o),Sa(this.audioTracks,s,a,r),Sa(this.subtitleTracks,i,a,r)}))}loadSteeringManifest(t){const e=this.hls.config,s=e.loader;let i;this.loader&&this.loader.destroy(),this.loader=new s(e);try{i=new self.URL(t)}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${t}`)}if("data:"!==i.protocol){const t=0|(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate);i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+t)}const r={responseType:"json",url:i.href},n=e.steeringManifestLoadPolicy.default,a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(t,e,s,r)=>{this.log(`Loaded steering manifest: "${i}"`);const n=t.data;if(1!==n.VERSION)return void this.log(`Steering VERSION ${n.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=n.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=n;if(a)try{this.uri=new self.URL(a,i).href}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||s.url),o&&this.clonePathways(o);const h={steeringManifest:n,url:i.toString()};this.hls.trigger(w.STEERING_MANIFEST_LOADED,h),l&&this.updatePathwayPriority(l)},onError:(t,e,s,i)=>{if(this.log(`Error loading steering manifest: ${t.code} ${t.text} (${e.url})`),this.stopLoad(),410===t.code)return this.enabled=!1,void this.log(`Steering manifest ${e.url} no longer available`);let r=1e3*this.timeToLoad;if(429!==t.code)this.scheduleRefresh(this.uri||e.url,r);else{const t=this.loader;if("function"==typeof(null==t?void 0:t.getResponseHeader)){const e=t.getResponseHeader("Retry-After");e&&(r=1e3*parseFloat(e))}this.log(`Steering manifest ${e.url} rate limited`)}},onTimeout:(t,e,s)=>{this.log(`Timeout loading steering manifest (${e.url})`),this.scheduleRefresh(this.uri||e.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,o,l)}scheduleRefresh(t,e=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout((()=>{var e;const s=null==(e=this.hls)?void 0:e.media;!s||s.ended?this.scheduleRefresh(t,1e3*this.timeToLoad):this.loadSteeringManifest(t)}),e)}}});function Pa(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(Pa):Object.keys(t).reduce(((e,s)=>(e[s]=Pa(t[s]),e)),{}):t}function xa(t){const e=t.loader;if(e!==ka&&e!==Ra)N.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1;else{(function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1})()&&(t.loader=ka,t.progressive=!0,t.enableSoftwareAES=!0,N.log("[config]: Progressive streaming enabled, using FetchLoader"))}}let Fa;class Ma extends Os{constructor(t,e){super(t,"[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=e,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(w.MANIFEST_LOADING,this.onManifestLoading,this),t.on(w.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(w.LEVEL_LOADED,this.onLevelLoaded,this),t.on(w.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(w.FRAG_BUFFERED,this.onFragBuffered,this),t.on(w.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(w.MANIFEST_LOADING,this.onManifestLoading,this),t.off(w.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(w.LEVEL_LOADED,this.onLevelLoaded,this),t.off(w.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(w.FRAG_BUFFERED,this.onFragBuffered,this),t.off(w.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(t,e){this.resetLevels()}onManifestLoaded(t,e){const s=this.hls.config.preferManagedMediaSource,i=[],r={},n={};let a=!1,o=!1,l=!1;e.levels.forEach((t=>{var e,h;const d=t.attrs;let{audioCodec:c,videoCodec:u}=t;-1!==(null==(e=c)?void 0:e.indexOf("mp4a.40.34"))&&(Fa||(Fa=/chrome|firefox/i.test(navigator.userAgent)),Fa&&(t.audioCodec=c=void 0)),c&&(t.audioCodec=c=ve(c,s)),0===(null==(h=u)?void 0:h.indexOf("avc1"))&&(u=t.videoCodec=function(t){const e=t.split(",");for(let t=0;t<e.length;t++){const s=e[t].split(".");if(s.length>2){let i=s.shift()+".";i+=parseInt(s.shift()).toString(16),i+=("000"+parseInt(s.shift()).toString(16)).slice(-4),e[t]=i}}return e.join(",")}(u));const{width:f,height:g,unknownCodecs:m}=t;if(a||(a=!(!f||!g)),o||(o=!!u),l||(l=!!c),null!=m&&m.length||c&&!ce(c,"audio",s)||u&&!ce(u,"video",s))return;const{CODECS:p,"FRAME-RATE":y,"HDCP-LEVEL":v,"PATHWAY-ID":T,RESOLUTION:E,"VIDEO-RANGE":S}=d,L=`${`${T||"."}-`}${t.bitrate}-${E}-${y}-${p}-${S}-${v}`;if(r[L])if(r[L].uri===t.url||t.attrs["PATHWAY-ID"])r[L].addGroupId("audio",d.AUDIO),r[L].addGroupId("text",d.SUBTITLES);else{const e=n[L]+=1;t.attrs["PATHWAY-ID"]=new Array(e+1).join(".");const s=new ds(t);r[L]=s,i.push(s)}else{const e=new ds(t);r[L]=e,n[L]=1,i.push(e)}})),this.filterAndSortMediaOptions(i,e,a,o,l)}filterAndSortMediaOptions(t,e,s,i,r){let n=[],a=[],o=t;if((s||i)&&r&&(o=o.filter((({videoCodec:t,videoRange:e,width:s,height:i})=>{return(!!t||!(!s||!i))&&(!!(r=e)&&rs.indexOf(r)>-1);var r}))),0===o.length)return void Promise.resolve().then((()=>{if(this.hls){e.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(e.levels[0].attrs)}`);const t=new Error("no level with compatible codecs found in manifest");this.hls.trigger(w.ERROR,{type:C.MEDIA_ERROR,details:P.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:t,reason:t.message})}}));if(e.audioTracks){const{preferManagedMediaSource:t}=this.hls.config;n=e.audioTracks.filter((e=>!e.audioCodec||ce(e.audioCodec,"audio",t))),Oa(n)}e.subtitles&&(a=e.subtitles,Oa(a));const l=o.slice(0);o.sort(((t,e)=>{if(t.attrs["HDCP-LEVEL"]!==e.attrs["HDCP-LEVEL"])return(t.attrs["HDCP-LEVEL"]||"")>(e.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&t.height!==e.height)return t.height-e.height;if(t.frameRate!==e.frameRate)return t.frameRate-e.frameRate;if(t.videoRange!==e.videoRange)return rs.indexOf(t.videoRange)-rs.indexOf(e.videoRange);if(t.videoCodec!==e.videoCodec){const s=ge(t.videoCodec),i=ge(e.videoCodec);if(s!==i)return i-s}if(t.uri===e.uri&&t.codecSet!==e.codecSet){const s=me(t.codecSet),i=me(e.codecSet);if(s!==i)return i-s}return t.averageBitrate!==e.averageBitrate?t.averageBitrate-e.averageBitrate:0}));let h=l[0];if(this.steering&&(o=this.steering.filterParsedLevels(o),o.length!==l.length))for(let t=0;t<l.length;t++)if(l[t].pathwayId===o[0].pathwayId){h=l[t];break}this._levels=o;for(let t=0;t<o.length;t++)if(o[t]===h){var d;this._firstLevel=t;const e=h.bitrate,s=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${o.length} level(s) found, first bitrate: ${e}`),void 0===(null==(d=this.hls.userConfig)?void 0:d.abrEwmaDefaultEstimate)){const t=Math.min(e,this.hls.config.abrEwmaDefaultEstimateMax);t>s&&s===Ca.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=t)}break}const c=r&&!i,u={levels:o,audioTracks:n,subtitleTracks:a,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:r,video:i,altAudio:!c&&n.some((t=>!!t.url))};this.hls.trigger(w.MANIFEST_PARSED,u),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return 0===this._levels.length?null:this._levels}get level(){return this.currentLevelIndex}set level(t){const e=this._levels;if(0===e.length)return;if(t<0||t>=e.length){const s=new Error("invalid level idx"),i=t<0;if(this.hls.trigger(w.ERROR,{type:C.OTHER_ERROR,details:P.LEVEL_SWITCH_ERROR,level:t,fatal:i,error:s,reason:s.message}),i)return;t=Math.min(t,e.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,n=e[t],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=n,s===t&&n.details&&i&&r===a)return;this.log(`Switching to level ${t} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${s}${r?" with Pathway "+r:""}`);const o={level:t,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(w.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const t=this.switchParams(n.uri,null==i?void 0:i.details,l);this.loadPlaylist(t)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(void 0===this._startLevel){const t=this.hls.config.startLevel;return void 0!==t?t:this.hls.firstAutoLevel}return this._startLevel}set startLevel(t){this._startLevel=t}onError(t,e){!e.fatal&&e.context&&e.context.type===Fe&&e.context.level===this.level&&this.checkRetry(e)}onFragBuffered(t,{frag:e}){if(void 0!==e&&e.type===Ne){const t=e.elementaryStreams;if(!Object.keys(t).some((e=>!!t[e])))return;const s=this._levels[e.level];null!=s&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(t,e){var s;const{level:i,details:r}=e,n=this._levels[i];var a;if(!n)return this.warn(`Invalid level index ${i}`),void(null!=(a=e.deliveryDirectives)&&a.skip&&(r.deltaUpdateFailed=!0));i===this.currentLevelIndex?(0===n.fragmentError&&(n.loadError=0),this.playlistLoaded(i,e,n.details)):null!=(s=e.deliveryDirectives)&&s.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist();const e=this.currentLevelIndex,s=this.currentLevel;if(s&&this.shouldLoadPlaylist(s)){let i=s.uri;if(t)try{i=t.addDirectives(i)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}const r=s.attrs["PATHWAY-ID"];this.log(`Loading level index ${e}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""} with${r?" Pathway "+r:""} ${i}`),this.clearTimer(),this.hls.trigger(w.LEVEL_LOADING,{url:i,level:e,pathwayId:s.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}removeLevel(t){var e;const s=this._levels.filter(((e,s)=>s!==t||(this.steering&&this.steering.removeLevel(e),e===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,e.details&&e.details.fragments.forEach((t=>t.level=-1))),!1)));Ts(s),this._levels=s,this.currentLevelIndex>-1&&null!=(e=this.currentLevel)&&e.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(w.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(t,{levels:e}){this._levels=e}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:e,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==e&&(this._maxAutoLevel=e,this.hls.trigger(w.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function Oa(t){const e={};t.forEach((t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++}))}class Na{constructor(t){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=t}abort(t){for(const s in this.keyUriToKeyInfo){const i=this.keyUriToKeyInfo[s].loader;if(i){var e;if(t&&t!==(null==(e=i.context)?void 0:e.frag.type))return;i.abort()}}}detach(){for(const t in this.keyUriToKeyInfo){const e=this.keyUriToKeyInfo[t];(e.mediaKeySessionContext||e.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[t]}}destroy(){this.detach();for(const t in this.keyUriToKeyInfo){const e=this.keyUriToKeyInfo[t].loader;e&&e.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(t,e=P.KEY_LOAD_ERROR,s,i,r){return new mi({type:C.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:r,error:s,networkDetails:i})}loadClear(t,e){if(this.emeController&&this.config.emeEnabled){const{sn:s,cc:i}=t;for(let t=0;t<e.length;t++){const r=e[t];if(i<=r.cc&&("initSegment"===s||"initSegment"===r.sn||s<r.sn)){this.emeController.selectKeySystemFormat(r).then((t=>{r.setKeyFormat(t)}));break}}}}load(t){return!t.decryptdata&&t.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(t).then((e=>this.loadInternal(t,e))):this.loadInternal(t)}loadInternal(t,e){var s,i;e&&t.setKeyFormat(e);const r=t.decryptdata;if(!r){const s=new Error(e?`Expected frag.decryptdata to be defined after setting format ${e}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(t,P.KEY_LOAD_ERROR,s))}const n=r.uri;if(!n)return Promise.reject(this.createKeyLoadError(t,P.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));let a=this.keyUriToKeyInfo[n];if(null!=(s=a)&&s.decryptdata.key)return r.key=a.decryptdata.key,Promise.resolve({frag:t,keyInfo:a});var o;if(null!=(i=a)&&i.keyLoadPromise)switch(null==(o=a.mediaKeySessionContext)?void 0:o.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return a.keyLoadPromise.then((e=>(r.key=e.keyInfo.decryptdata.key,{frag:t,keyInfo:a})))}switch(a=this.keyUriToKeyInfo[n]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===r.keyFormat?this.loadKeyHTTP(a,t):this.loadKeyEME(a,t);case"AES-128":return this.loadKeyHTTP(a,t);default:return Promise.reject(this.createKeyLoadError(t,P.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(t,e){const s={frag:e,keyInfo:t};if(this.emeController&&this.config.emeEnabled){const e=this.emeController.loadKey(s);if(e)return(t.keyLoadPromise=e.then((e=>(t.mediaKeySessionContext=e,s)))).catch((e=>{throw t.keyLoadPromise=null,e}))}return Promise.resolve(s)}loadKeyHTTP(t,e){const s=this.config,i=new(0,s.loader)(s);return e.keyLoader=t.loader=i,t.keyLoadPromise=new Promise(((r,n)=>{const a={keyInfo:t,frag:e,responseType:"arraybuffer",url:t.decryptdata.uri},o=s.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(t,e,s,i)=>{const{frag:a,keyInfo:o,url:l}=s;if(!a.decryptdata||o!==this.keyUriToKeyInfo[l])return n(this.createKeyLoadError(a,P.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),i));o.decryptdata.key=a.decryptdata.key=new Uint8Array(t.data),a.keyLoader=null,o.loader=null,r({frag:a,keyInfo:o})},onError:(t,s,i,r)=>{this.resetLoader(s),n(this.createKeyLoadError(e,P.KEY_LOAD_ERROR,new Error(`HTTP Error ${t.code} loading key ${t.text}`),i,A({url:a.url,data:void 0},t)))},onTimeout:(t,s,i)=>{this.resetLoader(s),n(this.createKeyLoadError(e,P.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),i))},onAbort:(t,s,i)=>{this.resetLoader(s),n(this.createKeyLoadError(e,P.INTERNAL_ABORTED,new Error("key loading aborted"),i))}};i.load(a,l,h)}))}resetLoader(t){const{frag:e,keyInfo:s,url:i}=t,r=s.loader;e.keyLoader===r&&(e.keyLoader=null,s.loader=null),delete this.keyUriToKeyInfo[i],r&&r.destroy()}}function Ua(){return self.SourceBuffer||self.WebKitSourceBuffer}function Ba(){if(!he())return!1;const t=Ua();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}class $a{constructor(t,e,s,i){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=t,this.media=e,this.fragmentTracker=s,this.hls=i}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(t,e){const{config:s,media:i,stalled:r}=this;if(null===i)return;const{currentTime:n,seeking:a}=i,o=this.seeking&&!a,l=!this.seeking&&a;if(this.seeking=a,n!==t){if(this.moved=!0,a||(this.nudgeRetry=0),null!==r){if(this.stallReported){const t=self.performance.now()-r;N.warn(`playback not stuck anymore @${n}, after ${Math.round(t)}ms`),this.stallReported=!1}this.stalled=null}return}if(l||o)return void(this.stalled=null);if(i.paused&&!a||i.ended||0===i.playbackRate||!ri.getBuffered(i).length)return void(this.nudgeRetry=0);const h=ri.bufferInfo(i,n,0),d=h.nextStart||0;if(a){const t=h.len>2,s=!d||e&&e.start<=n||d-n>2&&!this.fragmentTracker.getPartialFragment(n);if(t||s)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var c;if(!(h.len>0)&&!d)return;const t=Math.max(d,h.start||0)-n,e=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,s=(null==e||null==(c=e.details)?void 0:c.live)?2*e.details.targetduration:2,r=this.fragmentTracker.getPartialFragment(n);if(t>0&&(t<=s||r))return void(i.paused||this._trySkipBufferHole(r))}const u=self.performance.now();if(null===r)return void(this.stalled=u);const f=u-r;if(!a&&f>=250&&(this._reportStall(h),!this.media))return;const g=ri.bufferInfo(i,n,s.maxBufferHole);this._tryFixBufferStall(g,f)}_tryFixBufferStall(t,e){const{config:s,fragmentTracker:i,media:r}=this;if(null===r)return;const n=r.currentTime,a=i.getPartialFragment(n);if(a){if(this._trySkipBufferHole(a)||!this.media)return}(t.len>s.maxBufferHole||t.nextStart&&t.nextStart-n<s.maxBufferHole)&&e>1e3*s.highBufferWatchdogPeriod&&(N.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(t){const{hls:e,media:s,stallReported:i}=this;if(!i&&s){this.stallReported=!0;const i=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${JSON.stringify(t)})`);N.warn(i.message),e.trigger(w.ERROR,{type:C.MEDIA_ERROR,details:P.BUFFER_STALLED_ERROR,fatal:!1,error:i,buffer:t.len})}}_trySkipBufferHole(t){const{config:e,hls:s,media:i}=this;if(null===i)return 0;const r=i.currentTime,n=ri.bufferInfo(i,r,0),a=r<n.start?n.start:n.nextStart;if(a){const o=n.len<=e.maxBufferHole,l=n.len>0&&n.len<1&&i.readyState<3,h=a-r;if(h>0&&(o||l)){if(h>e.maxBufferHole){const{fragmentTracker:e}=this;let s=!1;if(0===r){const t=e.getAppendedFrag(0,Ne);t&&a<t.end&&(s=!0)}if(!s){const s=t||e.getAppendedFrag(r,Ne);if(s){let t=!1,i=s.end;for(;i<a;){const s=e.getPartialFragment(i);if(!s){t=!0;break}i+=s.duration}if(t)return 0}}}const n=Math.max(a+.05,r+.1);if(N.warn(`skipping hole, adjusting currentTime from ${r} to ${n}`),this.moved=!0,this.stalled=null,i.currentTime=n,t&&!t.gap){const e=new Error(`fragment loaded with buffer holes, seeking from ${r} to ${n}`);s.trigger(w.ERROR,{type:C.MEDIA_ERROR,details:P.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:e,reason:e.message,frag:t})}return n}}return 0}_tryNudgeBuffer(){const{config:t,hls:e,media:s,nudgeRetry:i}=this;if(null===s)return;const r=s.currentTime;if(this.nudgeRetry++,i<t.nudgeMaxRetry){const n=r+(i+1)*t.nudgeOffset,a=new Error(`Nudging 'currentTime' from ${r} to ${n}`);N.warn(a.message),s.currentTime=n,e.trigger(w.ERROR,{type:C.MEDIA_ERROR,details:P.BUFFER_NUDGE_ON_STALL,error:a,fatal:!1})}else{const s=new Error(`Playhead still not moving while enough data buffered @${r} after ${t.nudgeMaxRetry} nudges`);N.error(s.message),e.trigger(w.ERROR,{type:C.MEDIA_ERROR,details:P.BUFFER_STALLED_ERROR,error:s,fatal:!0})}}}class Ga extends xi{constructor(t,e,s){super(t,e,s,"[stream-controller]",Ne),this.audioCodecSwap=!1,this.gapController=null,this.level=-1,this._forceStartLoad=!1,this.altAudio=!1,this.audioOnly=!1,this.fragPlaying=null,this.onvplaying=null,this.onvseeked=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(w.MANIFEST_LOADING,this.onManifestLoading,this),t.on(w.MANIFEST_PARSED,this.onManifestParsed,this),t.on(w.LEVEL_LOADING,this.onLevelLoading,this),t.on(w.LEVEL_LOADED,this.onLevelLoaded,this),t.on(w.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(w.ERROR,this.onError,this),t.on(w.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(w.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(w.BUFFER_CREATED,this.onBufferCreated,this),t.on(w.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(w.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(w.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(w.MANIFEST_LOADING,this.onManifestLoading,this),t.off(w.MANIFEST_PARSED,this.onManifestParsed,this),t.off(w.LEVEL_LOADED,this.onLevelLoaded,this),t.off(w.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(w.ERROR,this.onError,this),t.off(w.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(w.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(w.BUFFER_CREATED,this.onBufferCreated,this),t.off(w.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(w.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(w.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying()}startLoad(t){if(this.levels){const{lastCurrentTime:e,hls:s}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let t=s.startLevel;-1===t&&(s.config.testBandwidth&&this.levels.length>1?(t=0,this.bitrateTest=!0):t=s.firstAutoLevel),s.nextLoadLevel=t,this.level=s.loadLevel,this.loadedmetadata=!1}e>0&&-1===t&&(this.log(`Override startPosition with lastCurrentTime @${e.toFixed(3)}`),t=e),this.state=Li,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}else this._forceStartLoad=!0,this.state=Si}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Pi:{const{levels:t,level:e}=this,s=null==t?void 0:t[e],i=null==s?void 0:s.details;if(i&&(!i.live||this.levelLastLoaded===s)){if(this.waitForCdnTuneIn(i))break;this.state=Li;break}if(this.hls.nextLoadLevel!==this.level){this.state=Li;break}break}case bi:{var t;const e=self.performance.now(),s=this.retryDate;if(!s||e>=s||null!=(t=this.media)&&t.seeking){const{levels:t,level:e}=this,s=null==t?void 0:t[e];this.resetStartWhenNotLoaded(s||null),this.state=Li}}}this.state===Li&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:s,media:i}=this;if(null===e||!i&&(this.startFragRequested||!t.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const r=t.nextLoadLevel;if(null==s||!s[r])return;const n=s[r],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const t={};return this.altAudio&&(t.type="video"),this.hls.trigger(w.BUFFER_EOS,t),void(this.state=Ii)}t.loadLevel!==r&&-1===t.manualLevel&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=t.nextLoadLevel=r;const l=n.details;if(!l||this.state===Pi||l.live&&this.levelLastLoaded!==n)return this.level=r,void(this.state=Pi);const h=a.len,d=this.getMaxBufferLength(n.maxBitrate);if(h>=d)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const c=this.backtrackFragment?this.backtrackFragment.start:a.end;let u=this.getNextFragment(c,l);if(this.couldBacktrack&&!this.fragPrevious&&u&&"initSegment"!==u.sn&&this.fragmentTracker.getState(u)!==Zs){var f;const t=(null!=(f=this.backtrackFragment)?f:u).sn-l.startSN,e=l.fragments[t-1];e&&u.cc===e.cc&&(u=e,this.fragmentTracker.removeFragment(e))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(u&&this.isLoopLoading(u,c)){if(!u.gap){const t=this.audioOnly&&!this.altAudio?V:Y,e=(t===Y?this.videoBuffer:this.mediaBuffer)||this.media;e&&this.afterBufferFlushed(e,t,Ne)}u=this.getNextFragmentLoopLoading(u,l,a,Ne,d)}u&&(!u.initSegment||u.initSegment.data||this.bitrateTest||(u=u.initSegment),this.loadFragment(u,n,c))}loadFragment(t,e,s){const i=this.fragmentTracker.getState(t);this.fragCurrent=t,i===zs||i===Js?"initSegment"===t.sn?this._loadInitSegment(t,e):this.bitrateTest?(this.log(`Fragment ${t.sn} of level ${t.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(t,e)):(this.startFragRequested=!0,super.loadFragment(t,e,s)):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,Ne)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:t,media:e}=this;if(null!=e&&e.readyState){let s;const i=this.getAppendedFrag(e.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const r=this.getLevelDetails();if(null!=r&&r.live){const t=this.getMainFwdBufferInfo();if(!t||t.len<2*r.targetduration)return}if(!e.paused&&t){const e=t[this.hls.nextLoadLevel],i=this.fragLastKbps;s=i&&this.fragCurrent?this.fragCurrent.duration*e.maxBitrate/(1e3*i)+1:0}else s=0;const n=this.getBufferedFrag(e.currentTime+s);if(n){const t=this.followingBufferedFrag(n);if(t){this.abortCurrentFrag();const e=t.maxStartPTS?t.maxStartPTS:t.start,s=t.duration,i=Math.max(n.end,e+Math.min(Math.max(s-this.config.maxFragLookUpTolerance,s*(this.couldBacktrack?.5:.125)),s*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(i,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const t=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.state){case Ai:case Ri:case bi:case Di:case _i:this.state=Li}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,this.altAudio?"video":null)}onMediaAttached(t,e){super.onMediaAttached(t,e);const s=e.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),s.addEventListener("playing",this.onvplaying),s.addEventListener("seeked",this.onvseeked),this.gapController=new $a(this.config,s,this.fragmentTracker,this.hls)}onMediaDetaching(){const{media:t}=this;t&&this.onvplaying&&this.onvseeked&&(t.removeEventListener("playing",this.onvplaying),t.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){const t=this.media,e=t?t.currentTime:null;D(e)&&this.log(`Media seeked to ${e.toFixed(3)}`);const s=this.getMainFwdBufferInfo();null!==s&&0!==s.len?this.tick():this.warn(`Main forward buffer length on "seeked" event ${s?s.len:"empty"})`)}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(w.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=this.fragLastKbps=0,this.levels=this.fragPlaying=this.backtrackFragment=this.levelLastLoaded=null,this.altAudio=this.audioOnly=this.startFragRequested=!1}onManifestParsed(t,e){let s=!1,i=!1;e.levels.forEach((t=>{const e=t.audioCodec;e&&(s=s||-1!==e.indexOf("mp4a.40.2"),i=i||-1!==e.indexOf("mp4a.40.5"))})),this.audioCodecSwitch=s&&i&&!function(){var t;const e=Ua();return"function"==typeof(null==e||null==(t=e.prototype)?void 0:t.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1}onLevelLoading(t,e){const{levels:s}=this;if(!s||this.state!==Li)return;const i=s[e.level];(!i.details||i.details.live&&this.levelLastLoaded!==i||this.waitForCdnTuneIn(i.details))&&(this.state=Pi)}onLevelLoaded(t,e){var s;const{levels:i}=this,r=e.level,n=e.details,a=n.totalduration;if(!i)return void this.warn(`Levels were reset while loading level ${r}`);this.log(`Level ${r} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""}, cc [${n.startCC}, ${n.endCC}] duration:${a}`);const o=i[r],l=this.fragCurrent;!l||this.state!==Ri&&this.state!==bi||l.level!==e.level&&l.loader&&this.abortCurrentFrag();let h=0;if(n.live||null!=(s=o.details)&&s.live){var d;if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;h=this.alignPlaylists(n,o.details,null==(d=this.levelLastLoaded)?void 0:d.details)}if(o.details=n,this.levelLastLoaded=o,this.hls.trigger(w.LEVEL_UPDATED,{details:n,level:r}),this.state===Pi){if(this.waitForCdnTuneIn(n))return;this.state=Li}this.startFragRequested?n.live&&this.synchronizeToLiveEdge(n):this.setStartPosition(n,h),this.tick()}_handleFragmentLoadProgress(t){var e;const{frag:s,part:i,payload:r}=t,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const a=n[s.level],o=a.details;if(!o)return this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),void this.fragmentTracker.removeFragment(s);const l=a.videoCodec,h=o.PTSKnown||!o.live,d=null==(e=s.initSegment)?void 0:e.data,c=this._getAudioCodec(a),u=this.transmuxer=this.transmuxer||new $r(this.hls,Ne,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,g=-1!==f,m=new ni(s.level,s.sn,s.stats.chunkCount,r.byteLength,f,g),p=this.initPTS[s.cc];u.push(r,d,c,l,s,i,o.totalduration,h,m,p)}onAudioTrackSwitching(t,e){const s=this.altAudio;if(!!!e.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const t=this.fragCurrent;t&&(this.log("Switching to main audio track, cancel main fragment load"),t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const t=this.hls;s&&(t.trigger(w.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),t.trigger(w.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const s=e.id,i=!!this.hls.audioTracks[s].url;if(i){const t=this.videoBuffer;t&&this.mediaBuffer!==t&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=t)}this.altAudio=i,this.tick()}onBufferCreated(t,e){const s=e.tracks;let i,r,n=!1;for(const t in s){const e=s[t];if("main"===e.id){if(r=t,i=e,"video"===t){const e=s[t];e&&(this.videoBuffer=e.buffer)}}else n=!0}n&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:s,part:i}=e;if(s&&s.type!==Ne)return;if(this.fragContextChanged(s))return this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===_i&&(this.state=Li));const r=i?i.stats:s.stats;this.fragLastKbps=Math.round(8*r.total/(r.buffering.end-r.loading.first)),"initSegment"!==s.sn&&(this.fragPrevious=s),this.fragBufferedComplete(s,i)}onError(t,e){var s;if(e.fatal)this.state=wi;else switch(e.details){case P.FRAG_GAP:case P.FRAG_PARSING_ERROR:case P.FRAG_DECRYPT_ERROR:case P.FRAG_LOAD_ERROR:case P.FRAG_LOAD_TIMEOUT:case P.KEY_LOAD_ERROR:case P.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Ne,e);break;case P.LEVEL_LOAD_ERROR:case P.LEVEL_LOAD_TIMEOUT:case P.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==Pi||(null==(s=e.context)?void 0:s.type)!==Fe||(this.state=Li);break;case P.BUFFER_APPEND_ERROR:case P.BUFFER_FULL_ERROR:if(!e.parent||"main"!==e.parent)return;if(e.details===P.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(e)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case P.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}checkBuffer(){const{media:t,gapController:e}=this;if(t&&e&&t.readyState){if(this.loadedmetadata||!ri.getBuffered(t).length){const t=this.state!==Li?this.fragCurrent:null;e.poll(this.lastCurrentTime,t)}this.lastCurrentTime=t.currentTime}}onFragLoadEmergencyAborted(){this.state=Li,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==V||this.audioOnly&&!this.altAudio){const t=(e===Y?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(t,e,Ne),this.tick()}}onLevelsUpdated(t,e){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=e.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:t}=this;if(!t)return;const e=t.currentTime;let s=this.startPosition;if(s>=0&&e<s){if(t.seeking)return void this.log(`could not seek to ${s}, already seeking at ${e}`);const i=ri.getBuffered(t),r=(i.length?i.start(0):0)-s;r>0&&(r<this.config.maxBufferHole||r<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${r} to match buffer start`),s+=r,this.startPosition=s),this.log(`seek to target start position ${s} from current time ${e}`),t.currentTime=s}}_getAudioCodec(t){let e=this.config.defaultAudioCodec||t.audioCodec;return this.audioCodecSwap&&e&&(this.log("Swapping audio codec"),e=-1!==e.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),e}_loadBitrateTestFrag(t,e){t.bitrateTest=!0,this._doFragLoad(t,e).then((s=>{const{hls:i}=this;if(!s||this.fragContextChanged(t))return;e.fragmentError=0,this.state=Li,this.startFragRequested=!1,this.bitrateTest=!1;const r=t.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),i.trigger(w.FRAG_LOADED,s),t.bitrateTest=!1}))}_handleTransmuxComplete(t){var e;const s="main",{hls:i}=this,{remuxResult:r,chunkMeta:n}=t,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:h}=a,{video:d,text:c,id3:u,initSegment:f}=r,{details:g}=h,m=this.altAudio?void 0:r.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=Di,f){if(null!=f&&f.tracks){const t=o.initSegment||o;this._bufferInitSegment(h,f.tracks,t,n),i.trigger(w.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:s,tracks:f.tracks})}const t=f.initPTS,e=f.timescale;D(t)&&(this.initPTS[o.cc]={baseTime:t,timescale:e},i.trigger(w.INIT_PTS_FOUND,{frag:o,id:s,initPTS:t,timescale:e}))}if(d&&g&&"initSegment"!==o.sn){const t=g.fragments[o.sn-1-g.startSN],e=o.sn===g.startSN,s=!t||o.cc>t.cc;if(!1!==r.independent){const{startPTS:t,endPTS:i,startDTS:r,endDTS:a}=d;if(l)l.elementaryStreams[d.type]={startPTS:t,endPTS:i,startDTS:r,endDTS:a};else if(d.firstKeyFrame&&d.independent&&1===n.id&&!s&&(this.couldBacktrack=!0),d.dropped&&d.independent){const r=this.getMainFwdBufferInfo(),n=(r?r.end:this.getLoadPosition())+this.config.maxBufferHole,l=d.firstKeyFramePTS?d.firstKeyFramePTS:t;if(!e&&n<l-this.config.maxBufferHole&&!s)return void this.backtrack(o);s&&(o.gap=!0),o.setElementaryStreamInfo(d.type,o.start,i,o.start,a,!0)}else e&&t>2&&(o.gap=!0);o.setElementaryStreamInfo(d.type,t,i,r,a),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(d,o,l,n,e||s)}else{if(!e&&!s)return void this.backtrack(o);o.gap=!0}}if(m){const{startPTS:t,endPTS:e,startDTS:s,endDTS:i}=m;l&&(l.elementaryStreams[V]={startPTS:t,endPTS:e,startDTS:s,endDTS:i}),o.setElementaryStreamInfo(V,t,e,s,i),this.bufferFragmentData(m,o,l,n)}if(g&&null!=u&&null!=(e=u.samples)&&e.length){const t={id:s,frag:o,details:g,samples:u.samples};i.trigger(w.FRAG_PARSING_METADATA,t)}if(g&&c){const t={id:s,frag:o,details:g,samples:c.samples};i.trigger(w.FRAG_PARSING_USERDATA,t)}}}_bufferInitSegment(t,e,s,i){if(this.state!==Di)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&delete e.audio;const{audio:r,video:n,audiovideo:a}=e;if(r){let e=t.audioCodec;const s=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){e&&(e=-1!==e.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const t=r.metadata;t&&"channelCount"in t&&1!==(t.channelCount||1)&&-1===s.indexOf("firefox")&&(e="mp4a.40.5")}e&&-1!==e.indexOf("mp4a.40.5")&&-1!==s.indexOf("android")&&"audio/mpeg"!==r.container&&(e="mp4a.40.2",this.log(`Android: force audio codec to ${e}`)),t.audioCodec&&t.audioCodec!==e&&this.log(`Swapping manifest audio codec "${t.audioCodec}" for "${e}"`),r.levelCodec=e,r.id="main",this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${e||""}/${t.audioCodec||""}/${r.codec}]`)}n&&(n.levelCodec=t.videoCodec,n.id="main",this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${t.videoCodec||""}/${n.codec}]`)),a&&this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${t.codecs}/${a.codec}]`),this.hls.trigger(w.BUFFER_CODECS,e),Object.keys(e).forEach((t=>{const r=e[t].initSegment;null!=r&&r.byteLength&&this.hls.trigger(w.BUFFER_APPENDING,{type:t,data:r,frag:s,part:null,chunkMeta:i,parent:s.type})})),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,Ne)}backtrack(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=Li}checkFragmentChanged(){const t=this.media;let e=null;if(t&&t.readyState>1&&!1===t.seeking){const s=t.currentTime;if(ri.isBuffered(t,s)?e=this.getAppendedFrag(s):ri.isBuffered(t,s+.1)&&(e=this.getAppendedFrag(s+.1)),e){this.backtrackFragment=null;const t=this.fragPlaying,s=e.level;t&&e.sn===t.sn&&t.level===s||(this.fragPlaying=e,this.hls.trigger(w.FRAG_CHANGED,{frag:e}),t&&t.level===s||this.hls.trigger(w.LEVEL_SWITCHED,{level:s}))}}}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){const t=this.media;return t?this.fragPlaying||this.getAppendedFrag(t.currentTime):null}get currentProgramDateTime(){const t=this.media;if(t){const e=t.currentTime,s=this.currentFrag;if(s&&D(e)&&D(s.programDateTime)){const t=s.programDateTime+1e3*(e-s.start);return new Date(t)}}return null}get currentLevel(){const t=this.currentFrag;return t?t.level:-1}get nextBufferedFrag(){const t=this.currentFrag;return t?this.followingBufferedFrag(t):null}get forceStartLoad(){return this._forceStartLoad}}class Ka{static get version(){return"1.5.14"}static isMSESupported(){return Ba()}static isSupported(){return function(){if(!Ba())return!1;const t=he();return"function"==typeof(null==t?void 0:t.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((e=>t.isTypeSupported(fe(e,"video"))))||["mp4a.40.2","fLaC"].some((e=>t.isTypeSupported(fe(e,"audio")))))}()}static getMediaSource(){return he()}static get Events(){return w}static get ErrorTypes(){return C}static get ErrorDetails(){return P}static get DefaultConfig(){return Ka.defaultConfig?Ka.defaultConfig:Ca}static set DefaultConfig(t){Ka.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new Br,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,this.triggeringException=void 0,function(t,e){if("object"==typeof console&&!0===t||"object"==typeof t){O(t,"debug","log","info","warn","error");try{M.log(`Debug logs enabled for "${e}" in hls.js version 1.5.14`)}catch(t){M=F}}else M=F}(t.debug||!1,"Hls instance");const e=this.config=function(t,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==e.liveMaxLatencyDurationCount&&(void 0===e.liveSyncDurationCount||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==e.liveMaxLatencyDuration&&(void 0===e.liveSyncDuration||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const s=Pa(t),i=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((t=>{const r=`${"level"===t?"playlist":t}LoadPolicy`,n=void 0===e[r],a=[];i.forEach((i=>{const o=`${t}Loading${i}`,l=e[o];if(void 0!==l&&n){a.push(o);const t=s[r].default;switch(e[r]={default:t},i){case"TimeOut":t.maxLoadTimeMs=l,t.maxTimeToFirstByteMs=l;break;case"MaxRetry":t.errorRetry.maxNumRetry=l,t.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":t.errorRetry.retryDelayMs=l,t.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":t.errorRetry.maxRetryDelayMs=l,t.timeoutRetry.maxRetryDelayMs=l}}})),a.length&&N.warn(`hls.js config: "${a.join('", "')}" setting(s) are deprecated, use "${r}": ${JSON.stringify(e[r])}`)})),A(A({},s),e)}(Ka.DefaultConfig,t);this.userConfig=t,e.progressive&&xa(e);const{abrController:s,bufferController:i,capLevelController:r,errorController:n,fpsController:a}=e,o=new n(this),l=this.abrController=new s(this),h=this.bufferController=new i(this),d=this.capLevelController=new r(this),c=new a(this),u=new Ke(this),f=new es(this),g=e.contentSteeringController,m=g?new g(this):null,p=this.levelController=new Ma(this,m),y=new ti(this),v=new Na(this.config),T=this.streamController=new Ga(this,y,v);d.setStreamController(T),c.setStreamController(T);const E=[u,p,T];m&&E.splice(1,0,m),this.networkControllers=E;const S=[l,h,d,c,f,y];this.audioTrackController=this.createController(e.audioTrackController,E);const L=e.audioStreamController;L&&E.push(new L(this,y,v)),this.subtitleTrackController=this.createController(e.subtitleTrackController,E);const R=e.subtitleStreamController;R&&E.push(new R(this,y,v)),this.createController(e.timelineController,S),v.emeController=this.emeController=this.createController(e.emeController,S),this.cmcdController=this.createController(e.cmcdController,S),this.latencyController=this.createController(ss,S),this.coreComponents=S,E.push(o);const b=o.onErrorOut;"function"==typeof b&&this.on(w.ERROR,b,o)}createController(t,e){if(t){const s=new t(this);return e&&e.push(s),s}return null}on(t,e,s=this){this._emitter.on(t,e,s)}once(t,e,s=this){this._emitter.once(t,e,s)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,e,s=this,i){this._emitter.off(t,e,s,i)}listeners(t){return this._emitter.listeners(t)}emit(t,e,s){return this._emitter.emit(t,e,s)}trigger(t,e){if(this.config.debug)return this.emit(t,t,e);try{return this.emit(t,t,e)}catch(e){if(N.error("An internal error happened while handling event "+t+'. Error message: "'+e.message+'". Here is a stacktrace:',e),!this.triggeringException){this.triggeringException=!0;const s=t===w.ERROR;this.trigger(w.ERROR,{type:C.OTHER_ERROR,details:P.INTERNAL_EXCEPTION,fatal:s,event:t,error:e}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){N.log("destroy"),this.trigger(w.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach((t=>t.destroy())),this.networkControllers.length=0,this.coreComponents.forEach((t=>t.destroy())),this.coreComponents.length=0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){N.log("attachMedia"),this._media=t,this.trigger(w.MEDIA_ATTACHING,{media:t})}detachMedia(){N.log("detachMedia"),this.trigger(w.MEDIA_DETACHING,void 0),this._media=null}loadSource(t){this.stopLoad();const e=this.media,s=this.url,i=this.url=S.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,N.log(`loadSource:${i}`),e&&s&&(s!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(e)),this.trigger(w.MANIFEST_LOADING,{url:t})}startLoad(t=-1){N.log(`startLoad(${t})`),this.started=!0,this.networkControllers.forEach((e=>{e.startLoad(t)}))}stopLoad(){N.log("stopLoad"),this.started=!1,this.networkControllers.forEach((t=>{t.stopLoad()}))}resumeBuffering(){this.started&&this.networkControllers.forEach((t=>{"fragmentLoader"in t&&t.startLoad(-1)}))}pauseBuffering(){this.networkControllers.forEach((t=>{"fragmentLoader"in t&&t.stopLoad()}))}swapAudioCodec(){N.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){N.log("recoverMediaError");const t=this._media;this.detachMedia(),t&&this.attachMedia(t)}removeLevel(t){this.levelController.removeLevel(t)}get levels(){const t=this.levelController.levels;return t||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){N.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){N.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){N.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){N.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return-1===t&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){N.log(`set startLevel:${t}`),-1!==t&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const e=!!t;e!==this.config.capLevelToPlayerSize&&(e?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=e)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(N.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){(function(t){return is.indexOf(t)>-1})(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:e}}=this;if(!t)return 0;const s=t.length;for(let i=0;i<s;i++)if(t[i].maxBitrate>=e)return i;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:s}=this;let i;if(i=-1===e&&null!=t&&t.length?t.length-1:e,s)for(let e=i;e--;){const i=t[e].attrs["HDCP-LEVEL"];if(i&&i<=s)return e}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}setAudioOption(t){var e;return null==(e=this.audioTrackController)?void 0:e.setAudioOption(t)}setSubtitleOption(t){var e;return null==(e=this.subtitleTrackController)||e.setSubtitleOption(t),null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const e=this.audioTrackController;e&&(e.audioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return!!t&&t.subtitleDisplay}set subtitleDisplay(t){const e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}Ka.defaultConfig=void 0;var Ha=t.Utils.now,Va=t.Utils.listContainsIgnoreCase;t.Events.register("PLAYBACK_FRAGMENT_CHANGED"),t.Events.register("PLAYBACK_FRAGMENT_PARSING_METADATA");var Ya=function(e){function r(){var t;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,r);for(var e=arguments.length,i=new Array(e),n=0;n<e;n++)i[n]=arguments[n];return(t=s(this,r,[].concat(i))).options.hlsPlayback=h(h({},t.defaultOptions),t.options.hlsPlayback),t._timeUpdateThrottleDelay=200,t._timeUpdateFiringRate=.2,t._durationChangeMinOffset=.5,t._setInitialState(),t}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&d(t,e)}(r,e),n=r,o=[{key:"HLSJS",get:function(){return Ka}}],(a=[{key:"name",get:function(){return"hls"}},{key:"supportedVersion",get:function(){return{min:"0.11.4"}}},{key:"levels",get:function(){return this._levels||[]}},{key:"currentLevel",get:function(){return null===this._currentLevel||void 0===this._currentLevel?-1:this._currentLevel},set:function(e){this._currentLevel=e,this.trigger(t.Events.PLAYBACK_LEVEL_SWITCH_START),this.options.playback.hlsUseNextLevel?this._hls.nextLevel=this._currentLevel:this._hls.currentLevel=this._currentLevel}},{key:"isReady",get:function(){return this._isReadyState}},{key:"latency",get:function(){return this._hls.latency}},{key:"liveSyncPosition",get:function(){return this._hls.liveSyncPosition}},{key:"currentProgramDateTime",get:function(){return this._hls.playingDate}},{key:"_startTime",get:function(){return this._playbackType===t.Playback.LIVE&&"EVENT"!==this._playlistType?this._extrapolatedStartTime:this._playableRegionStartTime}},{key:"_now",get:function(){return Ha()}},{key:"_extrapolatedStartTime",get:function(){if(!this._localStartTimeCorrelation)return this._playableRegionStartTime;var t=this._localStartTimeCorrelation,e=this._now-t.local,s=(t.remote+e)/1e3;return Math.min(s,this._playableRegionStartTime+this._extrapolatedWindowDuration)}},{key:"_extrapolatedEndTime",get:function(){var t=this._playableRegionStartTime+this._playableRegionDuration;if(!this._localEndTimeCorrelation)return t;var e=this._localEndTimeCorrelation,s=this._now-e.local,i=(e.remote+s)/1e3;return Math.max(t-this._extrapolatedWindowDuration,Math.min(i,t))}},{key:"_duration",get:function(){return this._extrapolatedEndTime-this._startTime}},{key:"_extrapolatedWindowDuration",get:function(){return null===this._segmentTargetDuration?0:this._extrapolatedWindowNumSegments*this._segmentTargetDuration}},{key:"bandwidthEstimate",get:function(){return this._hls&&this._hls.bandwidthEstimate}},{key:"defaultOptions",get:function(){return{preload:!0}}},{key:"customListeners",get:function(){return this.options.hlsPlayback&&this.options.hlsPlayback.customListeners||[]}},{key:"sourceMedia",get:function(){return this.options.src}},{key:"currentTimestamp",get:function(){return this._currentFragment?(this._currentFragment.programDateTime+1e3*(this.el.currentTime-this._currentFragment.start))/1e3:null}},{key:"_setInitialState",value:function(){this._minDvrSize=void 0===this.options.hlsMinimumDvrSize?60:this.options.hlsMinimumDvrSize,this._extrapolatedWindowNumSegments=this.options.playback&&void 0!==this.options.playback.extrapolatedWindowNumSegments?this.options.playback.extrapolatedWindowNumSegments:2,this._playbackType=t.Playback.VOD,this._lastTimeUpdate={current:0,total:0,firstFragDateTime:0},this._lastTimeUpdateFiredTime=0,this._lastDuration=null,this._playableRegionStartTime=0,this._localStartTimeCorrelation=null,this._localEndTimeCorrelation=null,this._playableRegionDuration=0,this._programDateTime=0,this._durationExcludesAfterLiveSyncPoint=!1,this._segmentTargetDuration=null,this._playlistType=null,this._recoverAttemptsRemaining=this.options.hlsRecoverAttempts||16}},{key:"_setup",value:function(){this._destroyHLSInstance(),this._createHLSInstance(),this._listenHLSEvents(),this._attachHLSMedia()}},{key:"_destroyHLSInstance",value:function(){this._hls&&(this._manifestLoading=!1,this._ccIsSetup=!1,this._ccTracksUpdated=!1,this._setInitialState(),this._hls.destroy(),this._hls=null)}},{key:"_createHLSInstance",value:function(){var t=h({},this.options.playback.hlsjsConfig);this._hls=new Ka(t)}},{key:"_attachHLSMedia",value:function(){this._hls&&this._hls.attachMedia(this.el)}},{key:"_listenHLSEvents",value:function(){var t=this;this._hls&&(this._hls.once(Ka.Events.MEDIA_ATTACHED,(function(){t.options.hlsPlayback.preload&&t._hls.loadSource(t.options.src)})),this._hls.on(Ka.Events.MANIFEST_LOADING,(function(){return t._manifestLoading=!0})),this._hls.on(Ka.Events.LEVEL_LOADED,(function(e,s){return t._updatePlaybackType(e,s)})),this._hls.on(Ka.Events.LEVEL_UPDATED,(function(e,s){return t._onLevelUpdated(e,s)})),this._hls.on(Ka.Events.LEVEL_SWITCHED,(function(e,s){return t._onLevelSwitch(e,s)})),this._hls.on(Ka.Events.FRAG_CHANGED,(function(e,s){return t._onFragmentChanged(e,s)})),this._hls.on(Ka.Events.FRAG_LOADED,(function(e,s){return t._onFragmentLoaded(e,s)})),this._hls.on(Ka.Events.FRAG_BUFFERED,(function(e,s){return t._onFragmentBuffered(e,s)})),this._hls.on(Ka.Events.FRAG_PARSING_METADATA,(function(e,s){return t._onFragmentParsingMetadata(e,s)})),this._hls.on(Ka.Events.ERROR,(function(e,s){return t._onHLSJSError(e,s)})),this._hls.on(Ka.Events.SUBTITLE_TRACK_LOADED,(function(e,s){return t._onSubtitleLoaded(e,s)})),this._hls.on(Ka.Events.SUBTITLE_TRACKS_UPDATED,(function(){return t._ccTracksUpdated=!0})),this.bindCustomListeners())}},{key:"bindCustomListeners",value:function(){var t=this;this.customListeners.forEach((function(e){var s=e.eventName,i=e.once?"once":"on";s&&t._hls["".concat(i)](s,e.callback)}))}},{key:"unbindCustomListeners",value:function(){var t=this;this.customListeners.forEach((function(e){var s=e.eventName;s&&t._hls.off(s,e.callback)}))}},{key:"_onFragmentParsingMetadata",value:function(e,s){this.trigger(t.Events.Custom.PLAYBACK_FRAGMENT_PARSING_METADATA,{evt:e,data:s})}},{key:"render",value:function(){return this._ready(),c(r,"render",this,3)([])}},{key:"_ready",value:function(){this._isReadyState||(!this._hls&&this._setup(),this._isReadyState=!0,this.trigger(t.Events.PLAYBACK_READY,this.name))}},{key:"_recover",value:function(e,s,i){if(this._recoveredDecodingError)if(this._recoveredAudioCodecError){t.Log.error("hlsjs: failed to recover",{evt:e,data:s}),i.level=t.PlayerError.Levels.FATAL;var r=this.createError(i);this.trigger(t.Events.PLAYBACK_ERROR,r),this.stop()}else this._recoveredAudioCodecError=!0,this._hls.swapAudioCodec(),this._hls.recoverMediaError(),this.play();else this._recoveredDecodingError=!0,this._hls.recoverMediaError(),this.play()}},{key:"_setupSrc",value:function(t){}},{key:"_startTimeUpdateTimer",value:function(){var t=this;this._timeUpdateTimer||(this._timeUpdateTimer=setInterval((function(){t._onDurationChange(),t._onTimeUpdate()}),100))}},{key:"_stopTimeUpdateTimer",value:function(){this._timeUpdateTimer&&(clearInterval(this._timeUpdateTimer),this._timeUpdateTimer=null)}},{key:"getProgramDateTime",value:function(){return this._programDateTime}},{key:"getDuration",value:function(){return this._duration}},{key:"getCurrentTime",value:function(){return Math.max(0,this.el.currentTime-this._startTime)}},{key:"getStartTimeOffset",value:function(){return this._startTime}},{key:"seekPercentage",value:function(t){var e=t>0?this._duration*(t/100):this._duration;this.seek(e)}},{key:"seek",value:function(e){e<0&&(t.Log.warn("Attempt to seek to a negative time. Resetting to live point. Use seekToLivePoint() to seek to the live point."),e=this.getDuration()),e+=this._startTime,this.el.currentTime=e}},{key:"seekToLivePoint",value:function(){this.seek(this.getDuration())}},{key:"_updateSettings",value:function(){this._playbackType===t.Playback.VOD?this.settings.left=["playpause","position","duration"]:this.dvrEnabled?this.settings.left=["playpause"]:this.settings.left=["playstop"],this.settings.seekEnabled=this.isSeekEnabled(),this.trigger(t.Events.PLAYBACK_SETTINGSUPDATE)}},{key:"_onHLSJSError",value:function(e,s){var i,r={code:"".concat(s.type,"_").concat(s.details),description:"".concat(this.name," error: type: ").concat(s.type,", details: ").concat(s.details),raw:s};if(s.response&&(r.description+=", response: ".concat(JSON.stringify(s.response))),s.fatal)if(this._recoverAttemptsRemaining>0)switch(this._recoverAttemptsRemaining-=1,s.type){case Ka.ErrorTypes.NETWORK_ERROR:switch(s.details){case Ka.ErrorDetails.MANIFEST_LOAD_ERROR:case Ka.ErrorDetails.MANIFEST_LOAD_TIMEOUT:case Ka.ErrorDetails.MANIFEST_PARSING_ERROR:case Ka.ErrorDetails.LEVEL_LOAD_ERROR:case Ka.ErrorDetails.LEVEL_LOAD_TIMEOUT:t.Log.error("hlsjs: unrecoverable network fatal error.",{evt:e,data:s}),i=this.createError(r),this.trigger(t.Events.PLAYBACK_ERROR,i),this.stop();break;default:t.Log.warn("hlsjs: trying to recover from network error.",{evt:e,data:s}),r.level=t.PlayerError.Levels.WARN,this._hls.startLoad()}break;case Ka.ErrorTypes.MEDIA_ERROR:t.Log.warn("hlsjs: trying to recover from media error.",{evt:e,data:s}),r.level=t.PlayerError.Levels.WARN,this._recover(e,s,r);break;default:t.Log.error("hlsjs: could not recover from error.",{evt:e,data:s}),i=this.createError(r),this.trigger(t.Events.PLAYBACK_ERROR,i),this.stop()}else t.Log.error("hlsjs: could not recover from error after maximum number of attempts.",{evt:e,data:s}),i=this.createError(r),this.trigger(t.Events.PLAYBACK_ERROR,i),this.stop();else{if(this.options.playback.triggerFatalErrorOnResourceDenied&&this._keyIsDenied(s))return t.Log.error("hlsjs: could not load decrypt key.",{evt:e,data:s}),i=this.createError(r),this.trigger(t.Events.PLAYBACK_ERROR,i),void this.stop();r.level=t.PlayerError.Levels.WARN,t.Log.warn("hlsjs: non-fatal error occurred",{evt:e,data:s})}}},{key:"_keyIsDenied",value:function(t){return t.type===Ka.ErrorTypes.NETWORK_ERROR&&t.details===Ka.ErrorDetails.KEY_LOAD_ERROR&&t.response&&t.response.code>=400}},{key:"_onTimeUpdate",value:function(){var e={current:this.getCurrentTime(),total:this.getDuration(),firstFragDateTime:this.getProgramDateTime()};this._shouldThrottleTimeUpdate(e)||(this._lastTimeUpdate=e,this._lastTimeUpdateFiredTime=this._now,this.trigger(t.Events.PLAYBACK_TIMEUPDATE,e,this.name))}},{key:"_shouldThrottleTimeUpdate",value:function(t){var e=Math.abs(t.current-this._lastTimeUpdate.current)<this._timeUpdateFiringRate,s=Math.abs(t.total-this._lastTimeUpdate.total)<this._durationChangeMinOffset,i=t.firstFragDateTime===this._lastTimeUpdate.firstFragDateTime,r=e&&s&&i,n=this._now-this._lastTimeUpdateFiredTime<this._timeUpdateThrottleDelay;return r&&n}},{key:"_onDurationChange",value:function(){var t=this.getDuration();Math.abs(this._lastDuration-t)<this._durationChangeMinOffset||(this._lastDuration=t,c(r,"_onDurationChange",this,3)([]))}},{key:"_onProgress",value:function(){if(this.el.buffered.length){for(var e=[],s=0,i=0;i<this.el.buffered.length;i++)e=[].concat(u(e),[{start:Math.max(0,this.el.buffered.start(i)-this._playableRegionStartTime),end:Math.max(0,this.el.buffered.end(i)-this._playableRegionStartTime)}]),this.el.currentTime>=e[i].start&&this.el.currentTime<=e[i].end&&(s=i);var r={start:e[s].start,current:e[s].end,total:this.getDuration()};this.trigger(t.Events.PLAYBACK_PROGRESS,r,e)}}},{key:"load",value:function(t){this._stopTimeUpdateTimer(),this.options.src=t,this._setup()}},{key:"play",value:function(){!this._hls&&this._setup(),!this._manifestLoading&&!this.options.hlsPlayback.preload&&this._hls.loadSource(this.options.src),c(r,"play",this,3)([]),this._startTimeUpdateTimer()}},{key:"pause",value:function(){this._hls&&this.el.pause()}},{key:"stop",value:function(){this._stopTimeUpdateTimer(),this._hls&&c(r,"stop",this,3)([]),this._destroyHLSInstance()}},{key:"destroy",value:function(){this._stopTimeUpdateTimer(),this._destroyHLSInstance(),c(r,"destroy",this,3)([])}},{key:"_updatePlaybackType",value:function(e,s){this._playbackType=s.details.live?t.Playback.LIVE:t.Playback.VOD,this._onLevelUpdated(e,s),this._ccTracksUpdated&&this._playbackType===t.Playback.LIVE&&this.hasClosedCaptionsTracks&&this._onSubtitleLoaded()}},{key:"_fillLevels",value:function(){this._levels=this._hls.levels.map((function(t,e){return{id:e,level:t,label:"".concat(t.bitrate/1e3,"Kbps")}})),this.trigger(t.Events.PLAYBACK_LEVELS_AVAILABLE,this._levels)}},{key:"_onLevelUpdated",value:function(e,s){this._segmentTargetDuration=s.details.targetduration,this._playlistType=s.details.type||null;var i=!1,r=!1,n=s.details.fragments,a=this._playableRegionStartTime,o=this._playableRegionDuration;if(0!==n.length){if(n[0].rawProgramDateTime&&(this._programDateTime=n[0].rawProgramDateTime),this._playableRegionStartTime!==n[0].start&&(i=!0,this._playableRegionStartTime=n[0].start),i)if(this._localStartTimeCorrelation){var l=this._localStartTimeCorrelation,h=this._now-l.local,d=(l.remote+h)/1e3;d<n[0].start?this._localStartTimeCorrelation={local:this._now,remote:1e3*n[0].start}:d>a+this._extrapolatedWindowDuration&&(this._localStartTimeCorrelation={local:this._now,remote:1e3*Math.max(n[0].start,a+this._extrapolatedWindowDuration)})}else this._localStartTimeCorrelation={local:this._now,remote:1e3*(n[0].start+this._extrapolatedWindowDuration/2)};var c=s.details.totalduration;if(this._playbackType===t.Playback.LIVE){var u=s.details.targetduration*((this.options.playback.hlsjsConfig||{}).liveSyncDurationCount||Ka.DefaultConfig.liveSyncDurationCount);u<=c?(c-=u,this._durationExcludesAfterLiveSyncPoint=!0):this._durationExcludesAfterLiveSyncPoint=!1}c!==this._playableRegionDuration&&(r=!0,this._playableRegionDuration=c);var f=n[0].start+c,g=a+o;if(f!==g)if(this._localEndTimeCorrelation){var m=this._localEndTimeCorrelation,p=this._now-m.local,y=(m.remote+p)/1e3;y>f?this._localEndTimeCorrelation={local:this._now,remote:1e3*f}:y<f-this._extrapolatedWindowDuration?this._localEndTimeCorrelation={local:this._now,remote:1e3*(f-this._extrapolatedWindowDuration)}:y>g&&(this._localEndTimeCorrelation={local:this._now,remote:1e3*g})}else this._localEndTimeCorrelation={local:this._now,remote:1e3*f};r&&this._onDurationChange(),i&&this._onProgress()}}},{key:"_onFragmentChanged",value:function(e,s){this._currentFragment=s.frag,this.trigger(t.Events.Custom.PLAYBACK_FRAGMENT_CHANGED,s)}},{key:"_onFragmentLoaded",value:function(e,s){this.trigger(t.Events.PLAYBACK_FRAGMENT_LOADED,s)}},{key:"_onFragmentBuffered",value:function(e,s){this.trigger(t.Events.PLAYBACK_FRAGMENT_BUFFERED,s)}},{key:"_onSubtitleLoaded",value:function(){if(!this._ccIsSetup){this.trigger(t.Events.PLAYBACK_SUBTITLE_AVAILABLE);var e=this._playbackType===t.Playback.LIVE?-1:this.closedCaptionsTrackId;this.closedCaptionsTrackId=e,this._ccIsSetup=!0}}},{key:"_onLevelSwitch",value:function(e,s){this.levels.length||this._fillLevels(),this.trigger(t.Events.PLAYBACK_LEVEL_SWITCH_END),this.trigger(t.Events.PLAYBACK_LEVEL_SWITCH,s);var i=this._hls.levels[s.level];i&&(this.highDefinition=i.height>=720||i.bitrate/1e3>=2e3,this.trigger(t.Events.PLAYBACK_HIGHDEFINITIONUPDATE,this.highDefinition),this.trigger(t.Events.PLAYBACK_BITRATE,{height:i.height,width:i.width,bandwidth:i.bitrate,bitrate:i.bitrate,level:s.level}))}},{key:"dvrEnabled",get:function(){return this._durationExcludesAfterLiveSyncPoint&&this._duration>=this._minDvrSize&&this.getPlaybackType()===t.Playback.LIVE}},{key:"getPlaybackType",value:function(){return this._playbackType}},{key:"isSeekEnabled",value:function(){return this._playbackType===t.Playback.VOD||this.dvrEnabled}}])&&i(n.prototype,a),o&&i(n,o),Object.defineProperty(n,"prototype",{writable:!1}),n;var n,a,o}(t.HTML5Video);return Ya.canPlay=function(t,e){var s=t.split("?")[0].match(/.*\.(.*)$/)||[],i=s.length>1&&"m3u8"===s[1].toLowerCase()||Va(e,["application/vnd.apple.mpegurl","application/x-mpegURL"]);return!(!Ka.isSupported()||!i)},Ya}(core);
|
|
2
2
|
//# sourceMappingURL=hlsjs-playback.min.js.map
|