@clappr/player 0.14.2 → 0.14.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/clappr.js +23786 -19457
- package/dist/clappr.js.map +1 -1
- package/dist/clappr.min.js +1 -1
- package/dist/clappr.min.js.map +1 -1
- package/dist/clappr.plainhtml5.js +22 -22
- package/dist/clappr.plainhtml5.min.js +1 -1
- package/dist/clappr.plainhtml5.min.js.map +1 -1
- package/package.json +4 -4
package/dist/clappr.min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).Clappr=e()}(this,function(){"use strict";function t(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var n=i.call(t,e);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function e(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),i.push.apply(i,n)}return i}function i(i){for(var n=1;n<arguments.length;n++){var r=null!=arguments[n]?arguments[n]:{};n%2?e(Object(r),!0).forEach(function(e){t(i,e,r[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(i,Object.getOwnPropertyDescriptors(r)):e(Object(r)).forEach(function(t){Object.defineProperty(i,t,Object.getOwnPropertyDescriptor(r,t))})}return i}function n(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,n=Array(e);i<e;i++)n[i]=t[i];return n}function r(t,e,i){return e=u(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,f()?Reflect.construct(e,i||[],u(t).constructor):e.apply(t,i))}function s(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function a(t,e){for(var i=0;i<e.length;i++){var n=e[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,E(n.key),n)}}function o(t,e,i){return e&&a(t.prototype,e),i&&a(t,i),Object.defineProperty(t,"prototype",{writable:!1}),t}function l(t,e){var i="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!i){if(Array.isArray(t)||(i=b(t))||e){i&&(t=i);var n=0,r=function(){};return{s:r,n:function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:r}}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 h(t,e,i){return(e=E(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function c(){return c="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(t,e,i){var n=function(t,e){for(;!{}.hasOwnProperty.call(t,e)&&null!==(t=u(t)););return t}(t,e);if(n){var r=Object.getOwnPropertyDescriptor(n,e);return r.get?r.get.call(arguments.length<3?t:i):r.value}},c.apply(null,arguments)}function u(t){return u=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},u(t)}function d(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&&m(t,e)}function f(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(f=function(){return!!t})()}function g(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),i.push.apply(i,n)}return i}function p(t){for(var e=1;e<arguments.length;e++){var i=null!=arguments[e]?arguments[e]:{};e%2?g(Object(i),!0).forEach(function(e){h(t,e,i[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):g(Object(i)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))})}return t}function m(t,e){return m=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},m(t,e)}function v(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 n,r,s,a,o=[],l=!0,h=!1;try{if(s=(i=i.call(t)).next,0===e){if(Object(i)!==i)return;l=!1}else for(;!(l=(n=s.call(i)).done)&&(o.push(n.value),o.length!==e);l=!0);}catch(t){h=!0,r=t}finally{try{if(!l&&null!=i.return&&(a=i.return(),Object(a)!==a))return}finally{if(h)throw r}}return o}}(t,e)||b(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 y(t,e,i,n){var r=c(u(t.prototype),e,i);return"function"==typeof r?function(t){return r.apply(i,t)}:r}function A(t){return function(t){if(Array.isArray(t))return n(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||b(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 E(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var n=i.call(t,e);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t,"string");return"symbol"==typeof e?e:e+""}function T(t){return T="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},T(t)}function b(t,e){if(t){if("string"==typeof t)return n(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)?n(t,e):void 0}}var S,k=function(){var t,e,i,n,r,s,a=[],o=a.concat,l=a.filter,h=a.slice,c=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+(?!\w))[^>]*>/,p=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,m=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)(?![\w:])(?:"[^"]*"|'[^']*'|\/(?!>)|[^>"'\/])*)\/>/gi,v=/^(?:body|html)$/i,y=/([A-Z])/g,A=["val","css","html","text","data","width","height","offset"],E=c.createElement("table"),T=c.createElement("tr"),b={tr:c.createElement("tbody"),tbody:E,thead:E,tfoot:E,td:T,th:T,"*":c.createElement("div")},S=/complete|loaded|interactive/,k=/^[\w-]*$/,_={},L=_.toString,I={},R=c.createElement("div"),C={tabindex:"tabIndex",readonly:"readOnly",for:"htmlFor",class:"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},P=Array.isArray||function(t){return t instanceof Array};function D(t){return null==t?String(t):_[L.call(t)]||"object"}function w(t){return"function"==D(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"==D(t)}function N(t){return M(t)&&!O(t)&&Object.getPrototypeOf(t)==Object.prototype}function F(t){var e=!!t&&"length"in t&&t.length,n=i.type(t);return"function"!=n&&!O(t)&&("array"==n||0===e||"number"==typeof e&&e>0&&e-1 in t)}function B(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 U(t){return t in d?d[t]:d[t]=new RegExp("(^|\\s)"+t+"(\\s|$)")}function $(t,e){return"number"!=typeof e||f[B(t)]?e:e+"px"}function G(t){return"children"in t?h.call(t.children):i.map(t.childNodes,function(t){if(1==t.nodeType)return t})}function V(t,e){var i,n=t?t.length:0;for(i=0;i<n;i++)this[i]=t[i];this.length=n,this.selector=e||""}function K(i,n,r){for(e in n)r&&(N(n[e])||P(n[e]))?(N(n[e])&&!N(i[e])&&(i[e]={}),P(n[e])&&!P(i[e])&&(i[e]=[]),K(i[e],n[e],r)):n[e]!==t&&(i[e]=n[e])}function H(t,e){return null==e?i(t):i(t).filter(e)}function Y(t,e,i,n){return w(e)?e.call(t,i,n):e}function j(t,e,i){null==i?t.removeAttribute(e):t.setAttribute(e,i)}function W(e,i){var n=e.className||"",r=n&&n.baseVal!==t;if(i===t)return r?n.baseVal:n;r?n.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,n=t.childNodes.length;i<n;i++)q(t.childNodes[i],e)}return I.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 n,r=t.parentNode,s=!r;return s&&(r=R).appendChild(t),n=~I.qsa(r,e).indexOf(t),s&&R.removeChild(t),n},r=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})},I.fragment=function(e,n,r){var s,a,o,l;return(l=p.exec(e))&&(s=i(c.createElement(l[1]))),s||(e.replace&&(e=e.replace(m,"<$1></$2>")),n===t&&(n=(l=g.exec(e))&&l[1]),Object.prototype.hasOwnProperty.call(b,n)||(n="*"),(o=b[n]).innerHTML=""+e,s=i.each(h.call(o.childNodes),function(){o.removeChild(this)})),N(r)&&(a=i(s),i.each(r,function(t,e){A.indexOf(t)>-1?a[t](e):a.attr(t,e)})),s},I.Z=function(t,e){return new V(t,e)},I.isZ=function(t){return t instanceof I.Z},I.init=function(e,n){var r,s,a;if(!e)return I.Z();if("string"==typeof e)if("<"==(e=e.trim())[0]&&(s=g.exec(e)))r=I.fragment(e,s[1],n),e=null;else{if(n!==t)return i(n).find(e);r=I.qsa(c,e)}else{if(w(e))return i(c).ready(e);if(I.isZ(e))return e;if(P(e))a=e,r=l.call(a,function(t){return null!=t});else if(M(e))r=[e],e=null;else if(s=g.exec(e))r=I.fragment(e.trim(),s[1],n),e=null;else{if(n!==t)return i(n).find(e);r=I.qsa(c,e)}}return I.Z(r,e)},(i=function(t,e){return I.init(t,e)}).extend=function(t){var e,i=h.call(arguments,1);return"boolean"==typeof t&&(e=t,t=i.shift()),i.forEach(function(i){K(t,i,e)}),t},I.qsa=function(t,e){var i,n="#"==e[0],r=!n&&"."==e[0],s=n||r?e.slice(1):e,a=k.test(s);return t.getElementById&&a&&n?(i=t.getElementById(s))?[i]:[]:1!==t.nodeType&&9!==t.nodeType&&11!==t.nodeType?[]:h.call(a&&!n&&t.getElementsByClassName?r?t.getElementsByClassName(s):t.getElementsByTagName(e):t.querySelectorAll(e))},i.contains=c.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=D,i.isFunction=w,i.isWindow=O,i.isArray=P,i.isPlainObject=N,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=r,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 n,r,s,a,o=[];if(F(t))for(r=0;r<t.length;r++)null!=(n=e(t[r],r))&&o.push(n);else for(s in t)null!=(n=e(t[s],s))&&o.push(n);return(a=o).length>0?i.fn.concat.apply([],a):a},i.each=function(t,e){var i,n;if(F(t)){for(i=0;i<t.length;i++)if(!1===e.call(t[i],i,t[i]))return t}else for(n in t)if(!1===e.call(t[n],n,t[n]))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:I.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]=I.isZ(e)?e.toArray():e;return o.apply(I.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(h.apply(this,arguments))},ready:function(t){return S.test(c.readyState)&&c.body?t(i):c.addEventListener("DOMContentLoaded",function(){t(i)},!1),this},get:function(e){return e===t?h.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 w(t)?this.not(this.not(t)):i(l.call(this,function(e){return I.matches(e,t)}))},add:function(t,e){return i(s(this.concat(i(t,e))))},is:function(t){return this.length>0&&I.matches(this[0],t)},not:function(e){var n=[];if(w(e)&&e.call!==t)this.each(function(t){e.call(this,t)||n.push(this)});else{var r="string"==typeof e?this.filter(e):F(e)&&w(e.item)?h.call(e):i(e);this.forEach(function(t){r.indexOf(t)<0&&n.push(t)})}return i(n)},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(I.qsa(this[0],t)):this.map(function(){return I.qsa(this,t)}):i()},closest:function(t,e){var n=[],r="object"==typeof t&&i(t);return this.each(function(i,s){for(;s&&!(r?r.indexOf(s)>=0:I.matches(s,t));)s=s!==e&&!x(s)&&s.parentNode;s&&n.indexOf(s)<0&&n.push(s)}),i(n)},parents:function(t){for(var e=[],n=this;n.length>0;)n=i.map(n,function(t){if((t=t.parentNode)&&!x(t)&&e.indexOf(t)<0)return e.push(t),t});return H(e,t)},parent:function(t){return H(s(this.pluck("parentNode")),t)},children:function(t){return H(this.map(function(){return G(this)}),t)},contents:function(){return this.map(function(){return this.contentDocument||h.call(this.childNodes)})},siblings:function(t){return H(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=c.createElement(t),c.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=w(t);if(this[0]&&!e)var n=i(t).get(0),r=n.parentNode||this.length>1;return this.each(function(s){i(this).wrapAll(e?t.call(this,s):r?n.cloneNode(!0):n)})},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=w(t);return this.each(function(n){var r=i(this),s=r.contents(),a=e?t.call(this,n):t;s.length?s.wrapAll(a):r.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 n=i(this);(e===t?"none"==n.css("display"):e)?n.show():n.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 n=this.innerHTML;i(this).empty().append(Y(this,t,e,n))}):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,n){var r;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,n,t,this.getAttribute(i)))}):0 in this&&1==this[0].nodeType&&null!=(r=this[0].getAttribute(i))?r: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=C[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=C[t]||t,this.each(function(){delete this[t]})},data:function(e,i){var n="data-"+e.replace(y,"-$1").toLowerCase(),r=1 in arguments?this.attr(n,i):this.attr(n);return null!==r?z(r):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 n=i(this),r=Y(this,t,e,n.offset()),s=n.offsetParent().offset(),a={top:r.top-s.top,left:r.left-s.left};"static"==n.css("position")&&(a.position="relative"),n.css(a)});if(!this.length)return null;if(c.documentElement!==this[0]&&!i.contains(c.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,n){if(arguments.length<2){var s=this[0];if("string"==typeof t){if(!s)return;return s.style[r(t)]||getComputedStyle(s,"").getPropertyValue(t)}if(P(t)){if(!s)return;var a={},o=getComputedStyle(s,"");return i.each(t,function(t,e){a[e]=s.style[r(e)]||o.getPropertyValue(e)}),a}}var l="";if("string"==D(t))n||0===n?l=B(t)+":"+$(t,n):this.each(function(){this.style.removeProperty(B(t))});else for(e in t)t[e]||0===t[e]?l+=B(e)+":"+$(e,t[e])+";":this.each(function(){this.style.removeProperty(B(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))},U(t))},addClass:function(t){return t?this.each(function(e){if("className"in this){n=[];var r=W(this);Y(this,t,e,r).split(/\s+/g).forEach(function(t){i(this).hasClass(t)||n.push(t)},this),n.length&&W(this,r+(r?" ":"")+n.join(" "))}}):this},removeClass:function(e){return this.each(function(i){if("className"in this){if(e===t)return W(this,"");n=W(this),Y(this,e,i,n).split(/\s+/g).forEach(function(t){n=n.replace(U(t)," ")}),W(this,n.trim())}})},toggleClass:function(e,n){return e?this.each(function(r){var s=i(this);Y(this,e,r,W(this)).split(/\s+/g).forEach(function(e){(n===t?!s.hasClass(e):n)?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(),n=this.offset(),r=v.test(e[0].nodeName)?{top:0,left:0}:e.offset();return n.top-=parseFloat(i(t).css("margin-top"))||0,n.left-=parseFloat(i(t).css("margin-left"))||0,r.top+=parseFloat(i(e[0]).css("border-top-width"))||0,r.left+=parseFloat(i(e[0]).css("border-left-width"))||0,{top:n.top-r.top,left:n.left-r.left}}},offsetParent:function(){return this.map(function(){for(var t=this.offsetParent||c.body;t&&!v.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 n=e.replace(/./,function(t){return t[0].toUpperCase()});i.fn[e]=function(r){var s,a=this[0];return r===t?O(a)?a["inner"+n]:x(a)?a.documentElement["scroll"+n]:(s=this.offset())&&s[e]:this.each(function(t){(a=i(this)).css(e,Y(this,r,t,a[e]()))})}}),["after","prepend","before","append"].forEach(function(e,n){var r=n%2;i.fn[e]=function(){var e,s,a=i.map(arguments,function(n){var r=[];return"array"==(e=D(n))?(n.forEach(function(e){return e.nodeType!==t?r.push(e):i.zepto.isZ(e)?r=r.concat(e.get()):void(r=r.concat(I.fragment(e)))}),r):"object"==e||null==n?n:I.fragment(n)}),o=this.length>1;return a.length<1?this:this.each(function(t,e){s=r?e:e.parentNode,e=0==n?e.nextSibling:1==n?e.firstChild:2==n?e:null;var l=i.contains(c.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[r?e+"To":"insert"+(n?"Before":"After")]=function(t){return i(t)[e](this),this}}),I.Z.prototype=V.prototype=i.fn,I.uniq=s,I.deserializeValue=z,i.zepto=I,i}();window.Zepto=k,void 0===window.$&&(window.$=k),function(t){var e,i,n=+new Date,r=window.document,s=/^(?:text|application)\/javascript/i,a=/^(?:text|application)\/xml/i,o="application/json",l="text/html",h=/^\s*$/,c=r.createElement("a");function u(e,i,n,s){if(e.global)return function(e,i,n){var r=t.Event(i);return t(e).trigger(r,n),!r.isDefaultPrevented()}(i||r,n,s)}function d(t,e){var i=e.context;if(!1===e.beforeSend.call(i,t,e)||!1===u(e,i,"ajaxBeforeSend",[t,e]))return!1;u(e,i,"ajaxSend",[t,e])}function f(t,e,i,n){var r=i.context,s="success";i.success.call(r,t,s,e),n&&n.resolveWith(r,[t,s,e]),u(i,r,"ajaxSuccess",[e,i,t]),p(s,e,i)}function g(t,e,i,n,r){var s=n.context;n.error.call(s,i,e,t),r&&r.rejectWith(s,[i,e,t]),u(n,s,"ajaxError",[i,n,t||e]),p(e,i,n)}function p(e,i,n){var r=n.context;n.complete.call(r,i,e),u(n,r,"ajaxComplete",[i,n]),function(e){e.global&&! --t.active&&u(e,null,"ajaxStop")}(n)}function m(){}function v(t,e){return""==e?t:(t+"&"+e).replace(/[&?]{1,2}/,"?")}function y(e,i,n,r){return t.isFunction(i)&&(r=n,n=i,i=void 0),t.isFunction(n)||(r=n,n=void 0),{url:e,data:i,success:n,dataType:r}}c.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"+n++,h=r.createElement("script"),c=window[l],u=function(e){t(h).triggerHandler("error",e||"abort")},p={abort:u};if(i&&i.promise(p),t(h).on("load error",function(n,r){clearTimeout(a),t(h).off().remove(),"error"!=n.type&&s?f(s[0],p,e,i):g(null,r||"error",p,e,i),window[l]=c,s&&t.isFunction(c)&&c(s[0]),c=s=void 0}),!1===d(p,e))return u("abort"),p;window[l]=function(){s=arguments};var m=e.url.indexOf("?"),v=m>-1?e.url.lastIndexOf("=?"):-1;return h.src=v>m+1?e.url.slice(0,v+1)+l+e.url.slice(v+2):e.url,r.head.appendChild(h),e.timeout>0&&(a=setTimeout(function(){u("timeout")},e.timeout)),p},t.ajaxSettings={type:"GET",beforeSend:m,success:m,error:m,complete:m,context:null,global:!0,xhr:function(){return new window.XMLHttpRequest},accepts:{script:"text/javascript, application/javascript, application/x-javascript",json:o,xml:"application/xml, text/xml",html:l,text:"text/plain"},crossDomain:!1,timeout:0,processData:!0,cache:!0,dataFilter:m},t.ajax=function(n){var p,y,A=t.extend({},n||{}),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++&&u(e,null,"ajaxStart")}(A),A.crossDomain||((p=r.createElement("a")).href=A.url,p.href=p.href,A.crossDomain=c.protocol+"//"+c.host!=p.protocol+"//"+p.host),A.url||(A.url=window.location.toString()),(y=A.url.indexOf("#"))>-1&&(A.url=A.url.slice(0,y)),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,b=/\?.+=\?/.test(A.url);if(b&&(T="jsonp"),!1!==A.cache&&(n&&!0===n.cache||"script"!=T&&"jsonp"!=T)||(A.url=v(A.url,"_="+Date.now())),"jsonp"==T)return b||(A.url=v(A.url,A.jsonp?A.jsonp+"=?":!1===A.jsonp?"":"callback=?")),t.ajaxJSONP(A,E);var S,k=A.accepts[T],_={},L=function(t,e){_[t.toLowerCase()]=[t,e]},I=/^([\w-]+:)\/\//.test(A.url)?RegExp.$1:window.location.protocol,R=A.xhr(),C=R.setRequestHeader;if(E&&E.promise(R),A.crossDomain||L("X-Requested-With","XMLHttpRequest"),L("Accept",k||"*/*"),(k=A.mimeType||k)&&(k.indexOf(",")>-1&&(k=k.split(",",2)[0]),R.overrideMimeType&&R.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(R.setRequestHeader=L,R.onreadystatechange=function(){if(4==R.readyState){R.onreadystatechange=m,clearTimeout(S);var e,i=!1;if(R.status>=200&&R.status<300||304==R.status||0==R.status&&"file:"==I){if(T=T||function(t){return t&&(t=t.split(";",2)[0]),t&&(t==l?"html":t==o?"json":s.test(t)?"script":a.test(t)&&"xml")||"text"}(A.mimeType||R.getResponseHeader("content-type")),"arraybuffer"==R.responseType||"blob"==R.responseType)e=R.response;else{e=R.responseText;try{e=function(t,e,i){if(i.dataFilter==m)return t;var n=i.context;return i.dataFilter.call(n,t,e)}(e,T,A),"script"==T?(0,eval)(e):"xml"==T?e=R.responseXML:"json"==T&&(e=h.test(e)?null:t.parseJSON(e))}catch(t){i=t}if(i)return g(i,"parsererror",R,A,E)}f(e,R,A,E)}else g(R.statusText||null,R.status?"error":"abort",R,A,E)}},!1===d(R,A))return R.abort(),g(null,"abort",R,A,E),R;var P=!("async"in A)||A.async;if(R.open(A.type,A.url,P,A.username,A.password),A.xhrFields)for(i in A.xhrFields)R[i]=A.xhrFields[i];for(i in _)C.apply(R,_[i]);return A.timeout>0&&(S=setTimeout(function(){R.onreadystatechange=m,R.abort(),g(null,"timeout",R,A,E)},A.timeout)),R.send(A.data?A.data:null),R},t.get=function(){return t.ajax(y.apply(null,arguments))},t.post=function(){var e=y.apply(null,arguments);return e.type="POST",t.ajax(e)},t.getJSON=function(){var e=y.apply(null,arguments);return e.dataType="json",t.ajax(e)},t.fn.load=function(e,i,n){if(!this.length)return this;var r,s=this,a=e.split(/\s/),o=y(e,i,n),l=o.success;return a.length>1&&(o.url=a[0],r=a[1]),o.success=function(e){if(r){var i=t("<div>").html(e);i.find("script").remove(),s.html(i.find(r))}else s.html(e);l&&l.apply(s,arguments)},t.ajax(o),this};var A=encodeURIComponent;function E(e,i,n,r){var s,a=t.isArray(i),o=t.isPlainObject(i);t.each(i,function(i,l){s=t.type(l),r&&(i=n?r:r+"["+(o||"object"==s||"array"==s?i:"")+"]"),!r&&a?e.add(l.name,l.value):"array"==s||!n&&"object"==s?E(e,l,n,i):e.add(i,l)})}t.param=function(e,i){var n=[];return n.add=function(e,i){t.isFunction(i)&&(i=i()),null==i&&(i=""),this.push(A(e)+"="+A(i))},E(n,e,i),n.join("&").replace(/%20/g,"+")}}(k),(S=k).Callbacks=function(t){t=S.extend({},t);var e,i,n,r,s,a,o=[],l=!t.once&&[],h=function(u){for(e=t.memory&&u,i=!0,a=r||0,r=0,s=o.length,n=!0;o&&a<s;++a)if(!1===o[a].apply(u[0],u[1])&&t.stopOnFalse){e=!1;break}n=!1,o&&(l?l.length&&h(l.shift()):e?o.length=0:c.disable())},c={add:function(){if(o){var i=o.length,a=function(e){S.each(e,function(e,i){"function"==typeof i?t.unique&&c.has(i)||o.push(i):i&&i.length&&"string"!=typeof i&&a(i)})};a(arguments),n?s=o.length:e&&(r=i,h(e))}return this},remove:function(){return o&&S.each(arguments,function(t,e){for(var i;(i=S.inArray(e,o,i))>-1;)o.splice(i,1),n&&(i<=s&&--s,i<=a&&--a)}),this},has:function(t){return!(!o||!(t?S.inArray(t,o)>-1:o.length))},empty:function(){return s=o.length=0,this},disable:function(){return o=l=e=void 0,this},disabled:function(){return!o},lock:function(){return l=void 0,e||c.disable(),this},locked:function(){return!l},fireWith:function(t,e){return!o||i&&!l||(e=[t,(e=e||[]).slice?e.slice():e],n?l.push(e):h(e)),this},fire:function(){return c.fireWith(this,arguments)},fired:function(){return!!i}};return c},function(t){var e=Array.prototype.slice;function i(e){var n=[["resolve","done",t.Callbacks({once:1,memory:1}),"resolved"],["reject","fail",t.Callbacks({once:1,memory:1}),"rejected"],["notify","progress",t.Callbacks({memory:1})]],r="pending",s={state:function(){return r},always:function(){return a.done(arguments).fail(arguments),this},then:function(){var e=arguments;return i(function(i){t.each(n,function(n,r){var o=t.isFunction(e[n])&&e[n];a[r[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 n=this===s?i.promise():this,a=o?[e]:arguments;i[r[0]+"With"](n,a)}})}),e=null}).promise()},promise:function(e){return null!=e?t.extend(e,s):s}},a={};return t.each(n,function(t,e){var i=e[2],o=e[3];s[e[1]]=i.add,o&&i.add(function(){r=o},n[1^t][2].disable,n[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(n){var r,s,a,o=e.call(arguments),l=o.length,h=0,c=1!==l||n&&t.isFunction(n.promise)?l:0,u=1===c?n:i(),d=function(t,i,n){return function(s){i[t]=this,n[t]=arguments.length>1?e.call(arguments):s,n===r?u.notifyWith(i,n):--c||u.resolveWith(i,n)}};if(l>1)for(r=new Array(l),s=new Array(l),a=new Array(l);h<l;++h)o[h]&&t.isFunction(o[h].promise)?o[h].promise().done(d(h,a,o)).fail(u.reject).progress(d(h,s,r)):--c;return c||u.resolveWith(a,o),u.promise()},t.Deferred=i}(k),function(t){var e,i=1,n=Array.prototype.slice,r=t.isFunction,s=function(t){return"string"==typeof t},a=Object.create(null),o={},l="onfocusin"in window,h={focus:"focusin",blur:"focusout"},c={mouseenter:"mouseover",mouseleave:"mouseout"};function u(t){var e=t._zid;return"number"!=typeof e&&(t._zid=e=i++),e}function d(t,e,i,n){if((e=f(e)).ns)var r=(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||r.test(t.ns))&&(!i||u(t.fn)===u(i))&&(!n||t.sel==n)})}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 h||!!e}function p(t){return c[t]||l&&h[t]||t}function m(i,n,r,s,o,l,h){var d=u(i),m=a[d]||(a[d]=[]);n.split(/\s/).forEach(function(n){if("ready"==n)return t(document).ready(r);var a=f(n);a.fn=r,a.sel=o,a.e in c&&(r=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||r;a.proxy=function(t){if(!(t=b(t)).isImmediatePropagationStopped()){t.data=s;var n=u.apply(i,t._args==e?[t]:[t].concat(t._args));return!1===n&&(t.preventDefault(),t.stopPropagation()),n}},a.i=m.length,m.push(a),"addEventListener"in i&&i.addEventListener(p(a.e),a.proxy,g(a,h))})}function v(t,e,i,n,r){var s=u(t);(e||"").split(/\s/).forEach(function(e){d(t,e,i,n).forEach(function(e){delete a[s][e.i],"removeEventListener"in t&&t.removeEventListener(p(e.e),e.proxy,g(e,r))})})}o.click=o.mousedown=o.mouseup=o.mousemove="MouseEvents",t.event={add:m,remove:v},t.proxy=function(e,i){var a=2 in arguments&&n.call(arguments,2);if(r(e)){var o=function(){return e.apply(i,a?a.concat(n.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,n){return this.on(t,e,i,n,1)};var y=function(){return!0},A=function(){return!1},E=/^([A-Z]|returnValue$|layer[XY]$|webkitMovement[XY]$)/,T={preventDefault:"isDefaultPrevented",stopImmediatePropagation:"isImmediatePropagationStopped",stopPropagation:"isPropagationStopped"};function b(i,n){return!n&&i.isDefaultPrevented||(n||(n=i),t.each(T,function(t,e){var r=n[t];i[t]=function(){return this[e]=y,r&&r.apply(n,arguments)},i[e]=A}),(n.defaultPrevented!==e?n.defaultPrevented:"returnValue"in n?!1===n.returnValue:n.getPreventDefault&&n.getPreventDefault())&&(i.isDefaultPrevented=y)),i}function S(t){var i,n={originalEvent:t};for(i in t)E.test(i)||t[i]===e||(n[i]=t[i]);return b(n,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,h){var c,u,d=this;return i&&!s(i)?(t.each(i,function(t,e){d.on(t,a,o,e,h)}),d):(s(a)||r(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,r){h&&(c=function(t){return v(r,t.type,l),l.apply(this,arguments)}),a&&(u=function(e){var i,s=t(e.target).closest(a,r).get(0);if(s&&s!==r)return i=t.extend(S(e),{currentTarget:s,liveFired:r}),(c||l).apply(s,[i].concat(n.call(arguments,1)))}),m(r,i,l,o,a,u||c)}))},t.fn.off=function(i,n,a){var o=this;return i&&!s(i)?(t.each(i,function(t,e){o.off(t,n,e)}),o):(s(n)||r(a)||!1===a||(a=n,n=e),!1===a&&(a=A),o.each(function(){v(this,i,a,n)}))},t.fn.trigger=function(e,i){return(e=s(e)||t.isPlainObject(e)?t.Event(e):b(e))._args=i,this.each(function(){e.type in h&&"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 n,r;return this.each(function(a,o){(n=S(s(e)?t.Event(e):e))._args=i,n.target=o,t.each(d(o,e.type||e),function(t,e){if(r=e.proxy(n),n.isImmediatePropagationStopped())return!1})}),r},"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]||(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"),n=!0;if(e)for(var r in e)"bubbles"==r?n=!!e[r]:i[r]=e[r];return i.initEvent(t,n,!0),b(i)}}(k),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,n=e.matches;function r(e){return!(!(e=t(e)).width()&&!e.height())&&"none"!==e.css("display")}var s=t.expr[":"]={visible:function(){if(r(this))return this},hidden:function(){if(!r(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,n){if(t(this).text().indexOf(n)>-1)return this},has:function(t,i,n){if(e.qsa(this,n).length)return this}},a=new RegExp("(.*):(\\w+)(?:\\(([^)]+)\\))?$\\s*"),o=/^\s*>/,l="Zepto"+ +new Date;function h(t,e){t=t.replace(/=#\]/g,'="#"]');var i,n,r=a.exec(t);if(r&&r[2]in s&&(i=s[r[2]],n=r[3],t=r[1],n)){var o=Number(n);n=isNaN(o)?n.replace(/^["']|["']$/g,""):o}return e(t,i,n)}e.qsa=function(n,r){return h(r,function(s,a,h){try{var c;!s&&a?s="*":o.test(s)&&(c=t(n).addClass(l),s="."+l+" "+s);var u=i(n,s)}catch(t){throw console.error("error performing selector: %o",r),t}finally{c&&c.removeClass(l)}return a?e.uniq(t.map(u,function(t,e){return a.call(t,e,u,h)})):u})},e.matches=function(t,e){return h(e,function(e,i,r){return(!e||n(t,e))&&(!i||i.call(t,null,r)===t)})}}(k),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 n=arguments[1],r=0;r<i;){var s=e[r];if(t.call(n,s,r,e))return s;r++}}}),Object.entries||(Object.entries=function(t){for(var e=Object.keys(t),i=e.length,n=new Array(i);i--;)n[i]=[e[i],t[e[i]]];return n}),Object.values||(Object.values=function(t){for(var e=Object.keys(t),i=e.length,n=new Array(i);i--;)n[i]=t[e[i]];return n}),"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),n=1;n<arguments.length;n++){var r=arguments[n];if(null!=r)for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(i[s]=r[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 n=arguments[1],r=0;r<i;){var s=e[r];if(t.call(n,s,r,e))return r;r++}return-1},configurable:!0,writable:!0});var _,L,I,R={mp4:"data:video/mp4;base64,AAAAHGZ0eXBpc29tAAACAGlzb21pc28ybXA0MQAAAAhmcmVlAAAC721kYXQhEAUgpBv/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA3pwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcCEQBSCkG//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADengAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcAAAAsJtb292AAAAbG12aGQAAAAAAAAAAAAAAAAAAAPoAAAALwABAAABAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAB7HRyYWsAAABcdGtoZAAAAAMAAAAAAAAAAAAAAAIAAAAAAAAALwAAAAAAAAAAAAAAAQEAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAACRlZHRzAAAAHGVsc3QAAAAAAAAAAQAAAC8AAAAAAAEAAAAAAWRtZGlhAAAAIG1kaGQAAAAAAAAAAAAAAAAAAKxEAAAIAFXEAAAAAAAtaGRscgAAAAAAAAAAc291bgAAAAAAAAAAAAAAAFNvdW5kSGFuZGxlcgAAAAEPbWluZgAAABBzbWhkAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAADTc3RibAAAAGdzdHNkAAAAAAAAAAEAAABXbXA0YQAAAAAAAAABAAAAAAAAAAAAAgAQAAAAAKxEAAAAAAAzZXNkcwAAAAADgICAIgACAASAgIAUQBUAAAAAAfQAAAHz+QWAgIACEhAGgICAAQIAAAAYc3R0cwAAAAAAAAABAAAAAgAABAAAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAIAAAABAAAAHHN0c3oAAAAAAAAAAAAAAAIAAAFzAAABdAAAABRzdGNvAAAAAAAAAAEAAAAsAAAAYnVkdGEAAABabWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWRpcmFwcGwAAAAAAAAAAAAAAAAtaWxzdAAAACWpdG9vAAAAHWRhdGEAAAABAAAAAExhdmY1Ni40MC4xMDE="},C=[{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.]*)"}],P=[{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"}],D={},w=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]))},O=function(t,e,i){var n="["===e.substr(0,1)?new RegExp(e,"g"):e,r=t.split(n,2);"."!==e&&(t=t.replace(new RegExp(e,"g"),".")),i.fullVersion=t,r&&r[0]&&(i.majorVersion=parseInt(r[0])),r&&r[1]&&(i.minorVersion=parseInt(r[1]))},x=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);D.isEdge=/Edg|EdgiOS|EdgA/i.test(navigator.userAgent),D.isChrome=/Chrome|CriOS/i.test(navigator.userAgent)&&!D.isEdge,D.isSafari=/Safari/i.test(navigator.userAgent)&&!D.isChrome&&!D.isEdge,D.isFirefox=/Firefox/i.test(navigator.userAgent),D.isLegacyIE=!!window.ActiveXObject,D.isIE=D.isLegacyIE||/trident.*rv:1\d/i.test(navigator.userAgent),D.isIE11=/trident.*rv:11/i.test(navigator.userAgent),D.isChromecast=D.isChrome&&/CrKey/i.test(navigator.userAgent),D.isMobile=/Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone|IEMobile|Mobile Safari|Opera Mini/i.test(navigator.userAgent),D.isiOS=/iPad|iPhone|iPod/i.test(navigator.userAgent),D.isAndroid=/Android/i.test(navigator.userAgent),D.isWindowsPhone=/Windows Phone/i.test(navigator.userAgent),D.isWin8App=/MSAppHost/i.test(navigator.userAgent),D.isWiiU=/WiiU/i.test(navigator.userAgent),D.isPS4=/PlayStation 4/i.test(navigator.userAgent),D.hasLocalstorage=function(){try{return localStorage.setItem("clappr","clappr"),localStorage.removeItem("clappr"),!0}catch(t){return!1}}(),D.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)}}(),D.name=x.name,D.version=x.version,D.userAgent=navigator.userAgent,D.data=function(){var t,e={},i=D.userAgent.toLowerCase(),n=l(C);try{for(n.s();!(t=n.n()).done;){var r=t.value,s=new RegExp(r.identifier.toLowerCase()).exec(i);if(null!=s&&s[1]){if(e.name=r.name,e.group=r.group,r.versionIdentifier){var a=new RegExp(r.versionIdentifier.toLowerCase()).exec(i);null!=a&&a[1]&&w(a[1],e)}else w(s[1],e);break}}}catch(t){n.e(t)}finally{n.f()}return e}(),D.os=function(){var t,e={},i=D.userAgent.toLowerCase(),n=l(P);try{for(n.s();!(t=n.n()).done;){var r=t.value,s=new RegExp(r.identifier.toLowerCase()).exec(i);if(null!=s){if(e.name=r.name,e.group=r.group,r.version)O(r.version,r.versionSeparator?r.versionSeparator:".",e);else if(s[1])O(s[1],r.versionSeparator?r.versionSeparator:".",e);else if(r.versionIdentifier){var a=new RegExp(r.versionIdentifier.toLowerCase()).exec(i);null!=a&&a[1]&&O(a[1],r.versionSeparator?r.versionSeparator:".",e)}break}}}catch(t){n.e(t)}finally{n.f()}return e}(),D.isWindows=/^Windows$/i.test(D.os.group),D.isMacOS=/^Mac OS$/i.test(D.os.group),D.isLinux=/^Linux$/i.test(D.os.group),D.viewport=((_={}).width=k(window).width(),_.height=k(window).height(),_),D.device=(L=D.userAgent,(I=/\((iP(?:hone|ad|od))?(?:[^;]*; ){0,2}([^)]+(?=\)))/.exec(L))&&(I[1]||I[2])||""),void 0!==window.orientation&&function(){switch(window.orientation){case-90:case 90:D.viewport.orientation="landscape";break;default:D.viewport.orientation="portrait"}}();var M={},N=[],F=(window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||function(t){window.setTimeout(t,1e3/60)}).bind(window),B=(window.cancelAnimationFrame||window.mozCancelAnimationFrame||window.webkitCancelAnimationFrame||window.clearTimeout).bind(window);function U(t,e){if(e)for(var i in e){var n=Object.getOwnPropertyDescriptor(e,i);n?Object.defineProperty(t,i,n):t[i]=e[i]}return t}function $(t,e){var i=function(t){function i(){var t;s(this,i);for(var n=arguments.length,a=new Array(n),o=0;o<n;o++)a[o]=arguments[o];return t=r(this,i,[].concat(a)),e.initialize&&e.initialize.apply(t,a),t}return d(i,t),o(i)}(t);return U(i.prototype,e),i}var G={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)}},V=function(){return o(function t(){s(this,t)},null,[{key:"_defaultConfig",value:function(){return{volume:{value:100,parse:parseInt}}}},{key:"_defaultValueFor",value:function(t){try{return this._defaultConfig()[t].parse(this._defaultConfig()[t].value)}catch(t){return}}},{key:"_createKeyspace",value:function(t){return"clappr.".concat(document.domain,".").concat(t)}},{key:"restore",value:function(t){return D.hasLocalstorage&&localStorage[this._createKeyspace(t)]?this._defaultConfig()[t].parse(localStorage[this._createKeyspace(t)]):this._defaultValueFor(t)}},{key:"persist",value:function(t,e){if(D.hasLocalstorage)try{return localStorage[this._createKeyspace(t)]=e,!0}catch(t){return!1}}}])}(),K=function(){return o(function t(){s(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,n=/([^&=]+)=?([^&]*)/g,r=function(t){return decodeURIComponent(t.replace(i," "))},s={};e=n.exec(t);)s[r(e[1]).toLowerCase()]=r(e[2]);return s}}])}();function H(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"t",e=0,i=K.params[t]||K.hashParams[t]||"",n=i.match(/[0-9]+[hms]+/g)||[];if(n.length>0){var r={h:3600,m:60,s:1};n.forEach(function(t){if(t){var i=t[t.length-1],n=parseInt(t.slice(0,t.length-1),10);e+=n*r[i]}})}else i&&(e=parseInt(i,10));return e}function Y(t){return M[t]||(M[t]=0),t+ ++M[t]}function j(t){return t-parseFloat(t)+1>=0}function W(){var t=document.getElementsByTagName("script");return t.length?t[t.length-1].src:""}function z(){return window.navigator&&window.navigator.language}function q(t,e){var i=(e=Object.assign({inline:!1,muted:!1,timeout:250,type:"video",source:R.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 n=i.play(),r=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(r),t(e,i)};void 0!==n?n.then(function(){return s(!0)}).catch(function(t){return s(!1,t)}):s(!0)}var X=function(){return o(function t(){s(this,t)},null,[{key:"configure",value:function(t){this.options=k.extend(!0,this.options,t)}},{key:"create",value:function(t){return this.options.recycleVideo&&"video"===t&&N.length>0?N.shift():document.createElement(t)}},{key:"garbage",value:function(t){this.options.recycleVideo&&"VIDEO"===t.tagName.toUpperCase()&&(k(t).children().remove(),Object.values(t.attributes).forEach(function(e){return t.removeAttribute(e.name)}),N.push(t))}}])}();X.options={recycleVideo:!1};var Q=function(){return o(function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:500;s(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],n=(new Date).getTime(),r=n-this.lastTime;r<this.delay&&r>0&&(e(),i&&t.preventDefault()),this.lastTime=n}}])}(),Z={Config:V,Fullscreen:G,QueryString:K,DomRecycler:X,assign:U,extend:$,formatTime:function(t,e){if(!isFinite(t))return"--:--";t*=1e3;var i=(t=parseInt(t/1e3))%60,n=(t=parseInt(t/60))%60,r=(t=parseInt(t/60))%24,s=parseInt(t/24),a="";return s&&s>0&&(a+=s+":",r<1&&(a+="00:")),(r&&r>0||e)&&(a+=("0"+r).slice(-2)+":"),a+=("0"+n).slice(-2)+":",(a+=("0"+i).slice(-2)).trim()},seekStringToSeconds:H,uniqueId:Y,currentScriptUrl:W,isNumber:j,requestAnimationFrame:F,cancelAnimationFrame:B,getBrowserLanguage:z,now:function(){return window.performance&&window.performance.now?performance.now():Date.now()},removeArrayItem:function(t,e){var i=t.indexOf(e);i>=0&&t.splice(i,1)},listContainsIgnoreCase:function(t,e){return void 0!==t&&void 0!==e&&void 0!==e.find(function(e){return t.toLowerCase()===e.toLowerCase()})},canAutoPlayMedia:q,Media:R,DoubleEventHandler:Q},J="font-weight: bold; font-size: 13px;",tt="color: #ff8000;"+J,et="color: #ff0000;"+J,it=["color: #0000ff;"+J,"color: #006600;"+J,tt,et,et],nt=["debug","info","warn","error","disabled"],rt=function(){return o(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;s(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 "+nt[this.level],tt)}},{key:"log",value:function(t,e,i){if(!(e<this.level||this.EXCLUDE_LIST.indexOf(i[0])>=0)){i||(i=t,t=null);var n=it[e],r="";t&&(r="["+t+"]"),window.console&&window.console.log&&window.console.log.apply(console,["%c["+nt[e]+"]"+r,n].concat(i))}}}])}();rt.LEVEL_DEBUG=0,rt.LEVEL_INFO=1,rt.LEVEL_WARN=2,rt.LEVEL_ERROR=3,rt.getInstance=function(){return void 0===this._instance&&(this._instance=new this),this._instance},rt.setLevel=function(t){this.getInstance().level=t},rt.debug=function(){this.getInstance().debug.apply(this.getInstance(),arguments)},rt.info=function(){this.getInstance().info.apply(this.getInstance(),arguments)},rt.warn=function(){this.getInstance().warn.apply(this.getInstance(),arguments)},rt.error=function(){this.getInstance().error.apply(this.getInstance(),arguments)};var st=Array.prototype.slice,at=/\s+/,ot=function(t,e,i,n){if(!i)return!0;if("object"===T(i)){for(var r in i)t[e].apply(t,[r,i[r]].concat(n));return!1}if(at.test(i)){for(var s=i.split(at),a=0,o=s.length;a<o;a++)t[e].apply(t,[s[a]].concat(n));return!1}return!0},lt=function(t,e,i,n){var r,s=-1,a=t.length,o=e[0],l=e[1],h=e[2];!function c(){try{switch(e.length){case 0:for(;++s<a;)(r=t[s]).callback.call(r.ctx);return;case 1:for(;++s<a;)(r=t[s]).callback.call(r.ctx,o);return;case 2:for(;++s<a;)(r=t[s]).callback.call(r.ctx,o,l);return;case 3:for(;++s<a;)(r=t[s]).callback.call(r.ctx,o,l,h);return;default:for(;++s<a;)(r=t[s]).callback.apply(r.ctx,e);return}}catch(t){rt.error.apply(rt,[i,"error on event",n,"trigger","-",t]),c()}}()},ht=function(){function t(){s(this,t)}return o(t,[{key:"on",value:function(t,e,i){return ot(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 n=this;if(!ot(this,"once",t,[e,i])||!e)return this;var r=function(){n.off(t,r),e.apply(this,arguments)};return r._callback=e,this.on(t,r,i)}},{key:"off",value:function(t,e,i){var n,r,s,a,o,l,h;if(!this._events||!ot(this,"off",t,[e,i]))return this;if(!t&&!e&&!i)return this._events=void 0,this;var c=t?[t]:Object.keys(this._events);for(a=0,o=c.length;a<o;a++)if(t=c[a],s=this._events[t]){if(this._events[t]=n=[],e||i)for(l=0,h=s.length;l<h;l++)r=s[l],(e&&e!==r.callback&&e!==r.callback._callback||i&&i!==r.context)&&n.push(r);n.length||delete this._events[t]}return this}},{key:"trigger",value:function(t){var e=this.name||this.constructor.name;if(rt.debug.apply(rt,[e].concat(Array.prototype.slice.call(arguments))),!this._events)return this;var i=st.call(arguments,1);if(!ot(this,"trigger",t,i))return this;var n=this._events[t],r=this._events.all;return n&<(n,i,e,t),r&<(r,arguments,e,t),this}},{key:"stopListening",value:function(t,e,i){var n=this._listeningTo;if(!n)return this;var r=!e&&!i;for(var s in i||"object"!==T(e)||(i=this),t&&((n={})[t._listenId]=t),n)(t=n[s]).off(e,i,this),(r||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[0].toUpperCase()+t.slice(1)}).join(""):rt.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]})}}])}();ht.prototype.listenTo=function(t,e,i){return(this._listeningTo||(this._listeningTo={}))[t._listenId||(t._listenId=Y("l"))]=t,i||"object"!==T(e)||(i=this),t.on(e,i,this),this},ht.prototype.listenToOnce=function(t,e,i){return(this._listeningTo||(this._listeningTo={}))[t._listenId||(t._listenId=Y("l"))]=t,i||"object"!==T(e)||(i=this),t.once(e,i,this),this},ht.PLAYER_READY="ready",ht.PLAYER_RESIZE="resize",ht.PLAYER_FULLSCREEN="fullscreen",ht.PLAYER_PLAY="play",ht.PLAYER_PAUSE="pause",ht.PLAYER_STOP="stop",ht.PLAYER_ENDED="ended",ht.PLAYER_SEEK="seek",ht.PLAYER_ERROR="playererror",ht.ERROR="error",ht.PLAYER_TIMEUPDATE="timeupdate",ht.PLAYER_VOLUMEUPDATE="volumeupdate",ht.PLAYER_SUBTITLE_AVAILABLE="subtitleavailable",ht.PLAYBACK_PIP_ENTER="playback:picture-in-picture:enter",ht.PLAYBACK_PIP_EXIT="playback:picture-in-picture:exit",ht.PLAYBACK_PROGRESS="playback:progress",ht.PLAYBACK_TIMEUPDATE="playback:timeupdate",ht.PLAYBACK_READY="playback:ready",ht.PLAYBACK_BUFFERING="playback:buffering",ht.PLAYBACK_BUFFERFULL="playback:bufferfull",ht.PLAYBACK_SETTINGSUPDATE="playback:settingsupdate",ht.PLAYBACK_LOADEDMETADATA="playback:loadedmetadata",ht.PLAYBACK_HIGHDEFINITIONUPDATE="playback:highdefinitionupdate",ht.PLAYBACK_BITRATE="playback:bitrate",ht.PLAYBACK_LEVELS_AVAILABLE="playback:levels:available",ht.PLAYBACK_LEVEL_SWITCH_START="playback:levels:switch:start",ht.PLAYBACK_LEVEL_SWITCH_END="playback:levels:switch:end",ht.PLAYBACK_PLAYBACKSTATE="playback:playbackstate",ht.PLAYBACK_DVR="playback:dvr",ht.PLAYBACK_MEDIACONTROL_DISABLE="playback:mediacontrol:disable",ht.PLAYBACK_MEDIACONTROL_ENABLE="playback:mediacontrol:enable",ht.PLAYBACK_ENDED="playback:ended",ht.PLAYBACK_PLAY_INTENT="playback:play:intent",ht.PLAYBACK_PLAY="playback:play",ht.PLAYBACK_PAUSE="playback:pause",ht.PLAYBACK_SEEK="playback:seek",ht.PLAYBACK_SEEKED="playback:seeked",ht.PLAYBACK_STOP="playback:stop",ht.PLAYBACK_ERROR="playback:error",ht.PLAYBACK_STATS_ADD="playback:stats:add",ht.PLAYBACK_FRAGMENT_LOADED="playback:fragment:loaded",ht.PLAYBACK_FRAGMENT_BUFFERED="playback:fragment:buffered",ht.PLAYBACK_LEVEL_SWITCH="playback:level:switch",ht.PLAYBACK_SUBTITLE_AVAILABLE="playback:subtitle:available",ht.PLAYBACK_SUBTITLE_CHANGED="playback:subtitle:changed",ht.PLAYBACK_AUDIO_AVAILABLE="playback:audio:available",ht.PLAYBACK_AUDIO_CHANGED="playback:audio:changed",ht.PLAYBACK_RESIZE="playback:resize",ht.CORE_CONTAINERS_CREATED="core:containers:created",ht.CORE_ACTIVE_CONTAINER_CHANGED="core:active:container:changed",ht.CORE_OPTIONS_WILL_CHANGE="core:options:will:change",ht.CORE_OPTIONS_CHANGE="core:options:change",ht.CORE_READY="core:ready",ht.CORE_FULLSCREEN="core:fullscreen",ht.CORE_RESIZE="core:resize",ht.CORE_SCREEN_ORIENTATION_CHANGED="core:screen:orientation:changed",ht.CORE_MOUSE_MOVE="core:mousemove",ht.CORE_MOUSE_LEAVE="core:mouseleave",ht.CONTAINER_PLAYBACKSTATE="container:playbackstate",ht.CONTAINER_PLAYBACKDVRSTATECHANGED="container:dvr",ht.CONTAINER_BITRATE="container:bitrate",ht.CONTAINER_STATS_REPORT="container:stats:report",ht.CONTAINER_DESTROYED="container:destroyed",ht.CONTAINER_READY="container:ready",ht.CONTAINER_RESIZE="container:resize",ht.CONTAINER_ERROR="container:error",ht.CONTAINER_LOADEDMETADATA="container:loadedmetadata",ht.CONTAINER_SUBTITLE_AVAILABLE="container:subtitle:available",ht.CONTAINER_SUBTITLE_CHANGED="container:subtitle:changed",ht.CONTAINER_AUDIO_AVAILABLE="container:audio:available",ht.CONTAINER_AUDIO_CHANGED="container:audio:changed",ht.CONTAINER_TIMEUPDATE="container:timeupdate",ht.CONTAINER_PROGRESS="container:progress",ht.CONTAINER_PLAY="container:play",ht.CONTAINER_STOP="container:stop",ht.CONTAINER_PAUSE="container:pause",ht.CONTAINER_ENDED="container:ended",ht.CONTAINER_CLICK="container:click",ht.CONTAINER_DBLCLICK="container:dblclick",ht.CONTAINER_CONTEXTMENU="container:contextmenu",ht.CONTAINER_MOUSE_ENTER="container:mouseenter",ht.CONTAINER_MOUSE_LEAVE="container:mouseleave",ht.CONTAINER_MOUSE_UP="container:mouseup",ht.CONTAINER_MOUSE_DOWN="container:mousedown",ht.CONTAINER_PIP_ENTER="container:picture-in-picture:enter",ht.CONTAINER_PIP_EXIT="container:picture-in-picture:exit",ht.CONTAINER_SEEK="container:seek",ht.CONTAINER_SEEKED="container:seeked",ht.CONTAINER_VOLUME="container:volume",ht.CONTAINER_FULLSCREEN="container:fullscreen",ht.CONTAINER_STATE_BUFFERING="container:state:buffering",ht.CONTAINER_STATE_BUFFERFULL="container:state:bufferfull",ht.CONTAINER_SETTINGSUPDATE="container:settingsupdate",ht.CONTAINER_HIGHDEFINITIONUPDATE="container:highdefinitionupdate",ht.CONTAINER_MEDIACONTROL_SHOW="container:mediacontrol:show",ht.CONTAINER_MEDIACONTROL_HIDE="container:mediacontrol:hide",ht.CONTAINER_MEDIACONTROL_DISABLE="container:mediacontrol:disable",ht.CONTAINER_MEDIACONTROL_ENABLE="container:mediacontrol:enable",ht.CONTAINER_STATS_ADD="container:stats:add",ht.CONTAINER_OPTIONS_WILL_CHANGE="container:options:will:change",ht.CONTAINER_OPTIONS_CHANGE="container:options:change",ht.MEDIACONTROL_RENDERED="mediacontrol:rendered",ht.MEDIACONTROL_FULLSCREEN="mediacontrol:fullscreen",ht.MEDIACONTROL_SHOW="mediacontrol:show",ht.MEDIACONTROL_HIDE="mediacontrol:hide",ht.MEDIACONTROL_MOUSEMOVE_SEEKBAR="mediacontrol:mousemove:seekbar",ht.MEDIACONTROL_MOUSELEAVE_SEEKBAR="mediacontrol:mouseleave:seekbar",ht.MEDIACONTROL_PLAYING="mediacontrol:playing",ht.MEDIACONTROL_NOTPLAYING="mediacontrol:notplaying",ht.MEDIACONTROL_CONTAINERCHANGED="mediacontrol:containerchanged",ht.MEDIACONTROL_OPTIONS_CHANGE="mediacontrol:options:change";var ct=function(t){function e(){var t,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return s(this,e),(t=r(this,e,[i]))._options=i,t.uniqueId=Y("o"),t}return d(e,t),o(e,[{key:"options",get:function(){return this._options}}])}(ht),ut={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g},dt=/(.)^/,ft={"'":"'","\\":"\\","\r":"r","\n":"n","\t":"t","\u2028":"u2028","\u2029":"u2029"},gt=/\\|'|\r|\n|\t|\u2028|\u2029/g,pt={"&":"&","<":"<",">":">",'"':""","'":"'"},mt=new RegExp("[&<>\"']","g"),vt=function(t){return null===t?"":(""+t).replace(mt,function(t){return pt[t]})},yt=0,At=function(t,e){var i,n=new RegExp([(ut.escape||dt).source,(ut.interpolate||dt).source,(ut.evaluate||dt).source].join("|")+"|$","g"),r=0,s="__p+='";t.replace(n,function(e,i,n,a,o){return s+=t.slice(r,o).replace(gt,function(t){return"\\"+ft[t]}),i&&(s+="'+\n((__t=("+i+"))==null?'':escapeExpr(__t))+\n'"),n&&(s+="'+\n((__t=("+n+"))==null?'':__t)+\n'"),a&&(s+="';\n"+a+"\n__p+='"),r=o+e.length,e}),s+="';\n",ut.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["+yt+++"]";try{i=new Function(ut.variable||"obj","escapeExpr",s)}catch(t){throw t.source=s,t}if(e)return i(e,vt);var a=function(t){return i.call(this,t,vt)};return a.source="function("+(ut.variable||"obj")+"){\n"+s+"}",a};At.settings=ut;var Et={getStyleFor:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{baseUrl:""};return k('<style class="clappr-style"></style>').html(At(t.toString())(e))}},Tt=/^(\S+)\s*(.*)$/,bt=function(t){function e(t){var i;return s(this,e),(i=r(this,e,[t])).cid=Y("c"),i._ensureElement(),i.delegateEvents(),i}return d(e,t),o(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=k.zepto.isZ(t)?t:k(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 n=e.match(Tt),r=n[1],s=n[2];r+=".delegateEvents"+this.cid,""===s?this.$el.on(r,i.bind(this)):this.$el.on(r,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=k.extend(!0,{},this.attributes);this.id&&(t.id=this.id),this.className&&(t.class=this.className);var e=k(X.create(this.tagName)).attr(t);this.setElement(e,!1)}}},{key:"onResize",value:function(){return this}},{key:"resize",value:function(t){var e=j(t.width)?"".concat(t.width,"px"):"".concat(t.width),i=j(t.height)?"".concat(t.height,"px"):"".concat(t.height);return this.el.style.width=e,this.el.style.height=i,this.onResize(t),this}}])}(ct),St=function(t){function e(){var t,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;return s(this,e),(t=r(this,e,[i])).core=n,t}return d(e,t),o(e,[{key:"name",get:function(){return"error"}},{key:"createError",value:function(t){this.core?this.core.trigger(ht.ERROR,t):rt.warn(this.name,"Core is not set. Error: ",t)}}],[{key:"Levels",get:function(){return{FATAL:"FATAL",WARN:"WARN",INFO:"INFO"}}}])}(ct),kt={createError:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{useCodePrefix:!0},i=this.constructor&&this.constructor.type||"",n=this.name||i,r=this.i18n||this.core&&this.core.i18n||this.container&&this.container.i18n,s="".concat(n,":").concat(t&&t.code||"unknown"),a={description:"",level:St.Levels.FATAL,origin:n,scope:i,raw:{}},o=Object.assign({},a,t,{code:e.useCodePrefix?s:t.code});if(r&&o.level===St.Levels.FATAL&&!o.UI){var l={title:r.t("default_error_title"),message:r.t("default_error_message")};o.UI=l}return this.playerError?this.playerError.createError(o):rt.warn(n,"PlayerError is not defined. Error: ",o),o}},_t=function(t){function e(t){var i;return s(this,e),(i=r(this,e,[t.options])).core=t,i.enabled=!0,i.bindEvents(),i.render(),i}return d(e,t),o(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}}])}(bt);Object.assign(_t.prototype,kt),_t.extend=function(t){return $(_t,t)},_t.type="core";var Lt=function(t){function e(t,i,n){var a;return s(this,e),(a=r(this,e,[t]))._i18n=i,a.currentTime=0,a.volume=100,a.playback=t.playback,a.playerError=n,a.settings=k.extend(!0,{},a.playback.settings),a.isReady=!1,a.mediaControlDisabled=!1,a.plugins=[a.playback],a.dblTapHandler=new Q(500),a.clickTimer=null,a.clickDelay=200,a.actionsMetadata={},a.bindEvents(),a}return d(e,t),o(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,ht.PLAYBACK_PROGRESS,this.onProgress),this.listenTo(this.playback,ht.PLAYBACK_TIMEUPDATE,this.timeUpdated),this.listenTo(this.playback,ht.PLAYBACK_READY,this.ready),this.listenTo(this.playback,ht.PLAYBACK_BUFFERING,this.onBuffering),this.listenTo(this.playback,ht.PLAYBACK_BUFFERFULL,this.bufferfull),this.listenTo(this.playback,ht.PLAYBACK_SETTINGSUPDATE,this.settingsUpdate),this.listenTo(this.playback,ht.PLAYBACK_LOADEDMETADATA,this.loadedMetadata),this.listenTo(this.playback,ht.PLAYBACK_HIGHDEFINITIONUPDATE,this.highDefinitionUpdate),this.listenTo(this.playback,ht.PLAYBACK_BITRATE,this.updateBitrate),this.listenTo(this.playback,ht.PLAYBACK_PLAYBACKSTATE,this.playbackStateChanged),this.listenTo(this.playback,ht.PLAYBACK_DVR,this.playbackDvrStateChanged),this.listenTo(this.playback,ht.PLAYBACK_MEDIACONTROL_DISABLE,this.disableMediaControl),this.listenTo(this.playback,ht.PLAYBACK_MEDIACONTROL_ENABLE,this.enableMediaControl),this.listenTo(this.playback,ht.PLAYBACK_SEEK,this.onSeek),this.listenTo(this.playback,ht.PLAYBACK_SEEKED,this.onSeeked),this.listenTo(this.playback,ht.PLAYBACK_ENDED,this.onEnded),this.listenTo(this.playback,ht.PLAYBACK_PLAY,this.playing),this.listenTo(this.playback,ht.PLAYBACK_PAUSE,this.paused),this.listenTo(this.playback,ht.PLAYBACK_STOP,this.stopped),this.listenTo(this.playback,ht.PLAYBACK_ERROR,this.error),this.listenTo(this.playback,ht.PLAYBACK_SUBTITLE_AVAILABLE,this.subtitleAvailable),this.listenTo(this.playback,ht.PLAYBACK_SUBTITLE_CHANGED,this.subtitleChanged),this.listenTo(this.playback,ht.PLAYBACK_AUDIO_AVAILABLE,this.audioAvailable),this.listenTo(this.playback,ht.PLAYBACK_AUDIO_CHANGED,this.audioChanged),this.listenTo(this.playback,ht.PLAYBACK_PIP_ENTER,this.onEnterPiP),this.listenTo(this.playback,ht.PLAYBACK_PIP_EXIT,this.onExitPiP)}},{key:"subtitleAvailable",value:function(){this.trigger(ht.CONTAINER_SUBTITLE_AVAILABLE)}},{key:"subtitleChanged",value:function(t){this.trigger(ht.CONTAINER_SUBTITLE_CHANGED,t)}},{key:"audioAvailable",value:function(t){this.trigger(ht.CONTAINER_AUDIO_AVAILABLE,t)}},{key:"audioChanged",value:function(t){this.trigger(ht.CONTAINER_AUDIO_CHANGED,t)}},{key:"playbackStateChanged",value:function(t){this.trigger(ht.CONTAINER_PLAYBACKSTATE,t)}},{key:"playbackDvrStateChanged",value:function(t){this.settings=this.playback.settings,this.dvrInUse=t,this.trigger(ht.CONTAINER_PLAYBACKDVRSTATECHANGED,t)}},{key:"updateBitrate",value:function(t){this.trigger(ht.CONTAINER_BITRATE,t)}},{key:"statsReport",value:function(t){this.trigger(ht.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(ht.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(ht.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(ht.CONTAINER_ERROR,t,this.name)}},{key:"loadedMetadata",value:function(t){this.trigger(ht.CONTAINER_LOADEDMETADATA,t)}},{key:"timeUpdated",value:function(t){this.currentTime=t.current,this.trigger(ht.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,[ht.CONTAINER_PROGRESS].concat(e,[this.name]))}},{key:"playing",value:function(){this.trigger(ht.CONTAINER_PLAY,this.name,this.actionsMetadata.playEvent||{}),this.actionsMetadata.playEvent={}}},{key:"paused",value:function(){this.trigger(ht.CONTAINER_PAUSE,this.name,this.actionsMetadata.pauseEvent||{}),this.actionsMetadata.pauseEvent={}}},{key:"stopped",value:function(){this.trigger(ht.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(ht.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(ht.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(ht.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(ht.CONTAINER_DBLCLICK,e,e.name)})}},{key:"onContextMenu",value:function(t){this.options.chromeless&&!this.options.allowUserInteraction||this.trigger(ht.CONTAINER_CONTEXTMENU,t,this.name)}},{key:"seek",value:function(t){this.playback.seek(t)}},{key:"onSeek",value:function(t){this.trigger(ht.CONTAINER_SEEK,t,this.name)}},{key:"onSeeked",value:function(){this.trigger(ht.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(ht.CONTAINER_VOLUME,this.volume,this.name),this.playback.volume(this.volume)}},{key:"fullscreen",value:function(){this.trigger(ht.CONTAINER_FULLSCREEN,this.name)}},{key:"onBuffering",value:function(){this.trigger(ht.CONTAINER_STATE_BUFFERING,this.name)}},{key:"bufferfull",value:function(){this.trigger(ht.CONTAINER_STATE_BUFFERFULL,this.name)}},{key:"onEnterPiP",value:function(){this.trigger(ht.CONTAINER_PIP_ENTER,this.name)}},{key:"onExitPiP",value:function(){this.trigger(ht.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(ht.CONTAINER_MOUSE_ENTER)}},{key:"mouseLeave",value:function(){this.options.chromeless&&!this.options.allowUserInteraction||this.trigger(ht.CONTAINER_MOUSE_LEAVE)}},{key:"mouseUp",value:function(){this.options.chromeless&&!this.options.allowUserInteraction||this.trigger(ht.CONTAINER_MOUSE_UP)}},{key:"mouseDown",value:function(){this.options.chromeless&&!this.options.allowUserInteraction||this.trigger(ht.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(ht.CONTAINER_SETTINGSUPDATE)}},{key:"highDefinitionUpdate",value:function(t){this.trigger(ht.CONTAINER_HIGHDEFINITIONUPDATE,t)}},{key:"isHighDefinitionInUse",value:function(){return this.playback.isHighDefinitionInUse()}},{key:"disableMediaControl",value:function(){this.mediaControlDisabled||(this.mediaControlDisabled=!0,this.trigger(ht.CONTAINER_MEDIACONTROL_DISABLE))}},{key:"enableMediaControl",value:function(){this.mediaControlDisabled&&(this.mediaControlDisabled=!1,this.trigger(ht.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(ht.CONTAINER_RESIZE,t))}},{key:"onResize",value:function(t){return this.playback.resize(t),this}},{key:"configure",value:function(t,e){this.trigger(ht.CONTAINER_OPTIONS_WILL_CHANGE,e),this._options=k.extend(!0,this._options,t),this.updateStyle(),this.playback.configure(this.options),this.trigger(ht.CONTAINER_OPTIONS_CHANGE)}},{key:"render",value:function(){var t=Et.getStyleFor(".container[data-container] {\n position: absolute;\n background-color: black;\n height: 100%;\n width: 100%;\n max-width: 100%;\n}\n.container[data-container] .chromeless {\n cursor: default;\n}\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}}])}(bt);Object.assign(Lt.prototype,kt);var It=function(t){function e(t,i,n){var a;return s(this,e),(a=r(this,e,[t])).settings={},a._i18n=i,a.playerError=n,a._consented=!1,a}return d(e,t),o(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:"getFrameRate",value:function(){return null}},{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=k.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(ht.PLAYBACK_RESIZE,t),this}}])}(bt);Object.assign(It.prototype,kt),It.extend=function(t){return $(It,t)},It.canPlay=function(t,e){return!1},It.VOD="vod",It.AOD="aod",It.LIVE="live",It.NO_OP="no_op",It.type="playback";var Rt=function(t){function e(t,i,n,a){var o;return s(this,e),(o=r(this,e,[t]))._i18n=n,o.loader=i,o.playerError=a,o}return d(e,t),o(e,[{key:"options",get:function(){return this._options},set:function(t){this._options=t}},{key:"createContainers",value:function(){var t=this;return k.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,i=this.options.mimeType;"object"===T(t)?(e=t.source.toString(),t.mimeType&&(i=t.mimeType)):e=t.toString(),e.match(/^\/\//)&&(e=window.location.protocol+e);var n=p(p({},this.options),{},{src:e,mimeType:i}),r=this.findPlaybackPlugin(e,i),s=r?new r(n,this._i18n,this.playerError):new It;n=p(p({},n),{},{playback:s});var a=new Lt(n,this._i18n,this.playerError),o=k.Deferred();return o.promise(a),this.addContainerPlugins(a),this.listenToOnce(a,ht.CONTAINER_READY,function(){return o.resolve(a)}),a}},{key:"addContainerPlugins",value:function(t){this.loader.containerPlugins.forEach(function(e){t.addPlugin(new e(t))})}}])}(ct);var Ct=function(t){function e(t){var i;return s(this,e),(i=r(this,e,[t])).playerError=new St(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)},k(document).bind("fullscreenchange",i._boundFullscreenHandler),k(document).bind("MSFullscreenChange",i._boundFullscreenHandler),k(document).bind("mozfullscreenchange",i._boundFullscreenHandler),D.isMobile&&k(window).bind("resize",i._boundHandleWindowResize),i}return d(e,t),o(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 _t(this)),this._dummyMediaControl}},{key:"activeContainer",get:function(){return this._activeContainer},set:function(t){this._activeContainer=t,this.trigger(ht.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;X.configure({recycleVideo:t})}},{key:"createContainers",value:function(t){this.defer=k.Deferred(),this.defer.promise(this),this.containerFactory=new Rt(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(){D.isiOS||(this.$el.addClass("fullscreen"),this.$el.removeAttr("style"),this.previousSize={width:this.options.width,height:this.options.height},this.currentSize={width:k(window).width(),height:k(window).height()})}},{key:"setPlayerSize",value:function(){this.$el.removeClass("fullscreen"),this.currentSize=this.previousSize,this.previousSize={width:k(window).width(),height:k(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(){var e,i,n=null!==(e=t.el.clientWidth)&&void 0!==e?e:t.options.width,r=null!==(i=t.el.clientHeight)&&void 0!==i?i:t.options.height;t.triggerResize({width:n,height:r})},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(ht.CORE_RESIZE,t))}},{key:"disableResizeObserver",value:function(){this.resizeObserverInterval&&clearInterval(this.resizeObserverInterval),this.resizeObserverInterval=null}},{key:"resolveOnContainersReady",value:function(t){var e=this;k.when.apply(k,t).done(function(){e.defer.resolve(e),e.ready=!0,e.trigger(ht.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=k.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(),k(document).unbind("fullscreenchange",this._boundFullscreenHandler),k(document).unbind("MSFullscreenChange",this._boundFullscreenHandler),k(document).unbind("mozfullscreenchange",this._boundFullscreenHandler),D.isMobile&&k(window).unbind("resize",this._boundHandleWindowResize),this.stopListening(),this.undelegateEvents()}},{key:"handleFullscreenChange",value:function(){this.trigger(ht.CORE_FULLSCREEN,this.isFullscreen()),this.updateSize()}},{key:"handleWindowResize",value:function(t){var e,i,n=window.innerWidth>window.innerHeight?"landscape":"portrait";if(this._screenOrientation!==n){this._screenOrientation=n;var r=null!==(e=this.el.clientWidth)&&void 0!==e?e:this.options.width,s=null!==(i=this.el.clientHeight)&&void 0!==i?i:this.options.height;this.triggerResize({width:r,height:s}),this.trigger(ht.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,ht.CONTAINER_DESTROYED,this.removeContainer),this.containers.push(t)}},{key:"setupContainers",value:function(t){return t.forEach(this.setupContainer.bind(this)),this.trigger(ht.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=G.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=D.isiOS?this.activePlaybackEl:document;G.cancelFullscreen(e),!D.isiOS&&this.$el.removeClass("fullscreen nocursor")}else{var i=D.isiOS?this.activePlaybackEl:this.el;if(!i)return;var n=function(){!D.isiOS&&t.$el.addClass("fullscreen")};if(D.isSafari||D.isiOS)G.requestFullscreen(i),n();else{var r=G.requestFullscreen(i),s=null!=r&&"function"==typeof r.then?r:Promise.resolve();n(),s.then(function(){},function(e){setTimeout(function(){if(!t.isFullscreen()){if(t.$el.removeClass("fullscreen"),function(t){if(!t)return!1;var e=t.message||String(t);return/disallowed by permissions policy|permissions policy|fullscreen is not allowed/i.test(e)}(e))return;throw new ReferenceError(e.message||String(e))}},600)})}}}},{key:"onMouseMove",value:function(t){this.trigger(ht.CORE_MOUSE_MOVE,t)}},{key:"onMouseLeave",value:function(t){this.trigger(ht.CORE_MOUSE_LEAVE,t)}},{key:"configure",value:function(t){var e=this,i=k.extend(!0,{},this._options);this.trigger(ht.CORE_OPTIONS_WILL_CHANGE,i),this._options=k.extend(!0,this._options,t),this.configureDomRecycler();var n=t.source||t.sources;n&&this.load(n,t.mimeType||this.options.mimeType),this.trigger(ht.CORE_OPTIONS_CHANGE,t),this.containers.forEach(function(t){return t.configure(e.options,i)})}},{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=Et.getStyleFor('[data-player] {\n -webkit-touch-callout: none;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n -o-user-select: none;\n user-select: none;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n -webkit-transform: translate3d(0, 0, 0);\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 -webkit-box-sizing: border-box;\n box-sizing: border-box;\n}\n[data-player]:focus {\n outline: 0;\n}\n[data-player] * {\n -webkit-box-sizing: inherit;\n box-sizing: inherit;\n}\n[data-player] > * {\n float: none;\n max-width: none;\n}\n[data-player] > div {\n display: block;\n}\n[data-player].fullscreen {\n width: 100% !important;\n height: 100% !important;\n top: 0;\n left: 0;\n}\n[data-player].nocursor {\n cursor: none;\n}\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=Et.getStyleFor('[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}\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}}])}(bt);Object.assign(Ct.prototype,kt);var Pt,Dt,wt=function(t){function e(t){var i;return s(this,e),(i=r(this,e,[t.options])).player=t,i}return d(e,t),o(e,[{key:"loader",get:function(){return this.player.loader}},{key:"create",value:function(){return this.options.loader=this.loader,this.core=new Ct(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)}}])}(ct),Ot=/(\d+)(?:\.(\d+))?(?:\.(\d+))?/,xt=function(){function t(e,i,n){s(this,t),this.major=parseInt(e||0,10),this.minor=parseInt(i||0,10),this.patch=parseInt(n||0,10)}return o(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=v((arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").match(Ot)||[],4),i=e[1],n=e[2],r=e[3];return void 0===i?null:new t(i,n,r)}}])}(),Mt=function(t,e){return t&&e?Object.entries(t).filter(function(t){return v(t,2)[1].type===e}).reduce(function(t,e){var i=v(e,2),n=i[0],r=i[1];return t[n]=r,t},{}):{}},Nt=(Pt={plugins:{},playbacks:[]},Dt="0.16.2",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;s(this,t),this.playerId=i,this.playbackPlugins=A(Pt.playbacks);var n=t.registeredPlugins,r=n.core,a=n.container;this.containerPlugins=Object.values(a),this.corePlugins=Object.values(r),Array.isArray(e)||this.validateExternalPluginsType(e),this.addExternalPlugins(e)}return o(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)),n=[];for(var r in i)n.unshift(i[r]);return n}},{key:"addExternalPlugins",value:function(e){var i="boolean"!=typeof e.loadExternalPluginsFirst||e.loadExternalPluginsFirst,n="boolean"!=typeof e.loadExternalPlaybacksFirst||e.loadExternalPlaybacksFirst;if((e=this.groupPluginsByType(e)).playback){var r=e.playback.filter(function(e){return t.checkVersionSupport(e),!0});this.playbackPlugins=n?this.removeDups(r.concat(this.playbackPlugins)):this.removeDups(this.playbackPlugins.concat(r),!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 A(Pt.playbacks)}},{key:"registeredPlugins",get:function(){var t=Pt.plugins;return{core:Mt(t,"core"),container:Mt(t,"container")}}},{key:"checkVersionSupport",value:function(t){var e=t.prototype,i=e.supportedVersion,n=e.name;if(!i||!i.min)return rt.warn("Loader","missing version information for ".concat(n)),!1;var r=i.max?xt.parse(i.max):xt.parse(i.min).inc("minor"),s=xt.parse(i.min);return!!xt.parse(Dt).satisfies(s,r)||(rt.warn("Loader","unsupported plugin ".concat(n,": Clappr version ").concat(Dt," does not match required range [").concat(s,",").concat(r,")")),!1)}},{key:"registerPlugin",value:function(e){if(!e||!e.prototype.name)return rt.warn("Loader","missing information to register plugin: ".concat(e)),!1;t.checkVersionSupport(e);var i=Pt.plugins;if(!i)return!1;var n=i[e.prototype.name];return n&&rt.warn("Loader","overriding plugin entry: ".concat(e.prototype.name," - ").concat(n)),i[e.prototype.name]=e,!0}},{key:"registerPlayback",value:function(e){if(!e||!e.prototype.name)return!1;t.checkVersionSupport(e);var i=Pt.playbacks,n=i.findIndex(function(t){return t.prototype.name===e.prototype.name});if(n>=0){var r=i[n];i.splice(n,1),rt.warn("Loader","overriding playback entry: ".concat(r.name," - ").concat(r))}return Pt.playbacks=[e].concat(A(i)),!0}},{key:"unregisterPlugin",value:function(t){if(!t)return!1;var e=Pt.plugins;return!!e[t]&&(delete e[t],!0)}},{key:"unregisterPlayback",value:function(t){if(!t)return!1;var e=Pt.playbacks,i=e.findIndex(function(e){return e.prototype.name===t});return!(i<0||(e.splice(i,1),Pt.playbacks=e,0))}},{key:"clearPlugins",value:function(){Pt.plugins={}}},{key:"clearPlaybacks",value:function(){Pt.playbacks=[]}}])}()),Ft=W().replace(/\/[^/]+$/,""),Bt=function(t){function e(t){var i;s(this,e),i=r(this,e,[t]);var n={playerId:Y(""),persistConfig:!0,width:640,height:360,baseUrl:Ft,allowUserInteraction:D.isMobile,includeResetStyle:!0,playback:{recycleVideo:!0}};i._options=k.extend(!0,n,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 wt(i);var a=i._getParentElement(i.options);return a&&i.attachTo(a),i}return d(e,t),o(e,[{key:"loader",get:function(){return this._loader||(this._loader=new Nt(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:ht.PLAYER_READY,onResize:ht.PLAYER_RESIZE,onPlay:ht.PLAYER_PLAY,onPause:ht.PLAYER_PAUSE,onStop:ht.PLAYER_STOP,onEnded:ht.PLAYER_ENDED,onSeek:ht.PLAYER_SEEK,onError:ht.PLAYER_ERROR,onTimeUpdate:ht.PLAYER_TIMEUPDATE,onVolumeUpdate:ht.PLAYER_VOLUMEUPDATE,onSubtitleAvailable:ht.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,ht.CORE_READY,this._onReady),this.listenTo(this.core,ht.CORE_ACTIVE_CONTAINER_CHANGED,this._containerChanged),this.listenTo(this.core,ht.CORE_FULLSCREEN,this._onFullscreenChange),this.listenTo(this.core,ht.CORE_RESIZE,this._onResize),this}},{key:"_addContainerEventListeners",value:function(){var t=this.core.activeContainer;return t&&(this.listenTo(t,ht.CONTAINER_PLAY,this._onPlay),this.listenTo(t,ht.CONTAINER_PAUSE,this._onPause),this.listenTo(t,ht.CONTAINER_STOP,this._onStop),this.listenTo(t,ht.CONTAINER_ENDED,this._onEnded),this.listenTo(t,ht.CONTAINER_SEEK,this._onSeek),this.listenTo(t,ht.CONTAINER_ERROR,this._onError),this.listenTo(t,ht.CONTAINER_TIMEUPDATE,this._onTimeUpdate),this.listenTo(t,ht.CONTAINER_VOLUME,this._onVolumeUpdate),this.listenTo(t,ht.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 n=t.eventsMapping[e];n&&t.off(n,i[e])}),Object.keys(e).forEach(function(i){var n=t.eventsMapping[i];if(n){var r=e[i];(r="function"==typeof r&&r)&&t.on(n,r)}}),this}},{key:"_unregisterOptionEventListeners",value:function(){var t=this;return this.options.events?(Object.keys(this.options.events).forEach(function(e){var i=t.eventsMapping[e],n=t.options.events[e];i&&n&&t.off(i,n)}),this):this}},{key:"_containerChanged",value:function(){this.stopListening(),this._addEventListeners()}},{key:"_onReady",value:function(){this._ready=!0,this._addContainerEventListeners(),this.trigger(ht.PLAYER_READY)}},{key:"_onFullscreenChange",value:function(t){this.trigger(ht.PLAYER_FULLSCREEN,t)}},{key:"_onVolumeUpdate",value:function(t){this.trigger(ht.PLAYER_VOLUMEUPDATE,t)}},{key:"_onSubtitleAvailable",value:function(){this.trigger(ht.PLAYER_SUBTITLE_AVAILABLE)}},{key:"_onResize",value:function(t){this.trigger(ht.PLAYER_RESIZE,t)}},{key:"_onPlay",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.trigger(ht.PLAYER_PLAY,e)}},{key:"_onPause",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.trigger(ht.PLAYER_PAUSE,e)}},{key:"_onStop",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.trigger(ht.PLAYER_STOP,this.getCurrentTime(),t)}},{key:"_onEnded",value:function(){this.trigger(ht.PLAYER_ENDED)}},{key:"_onSeek",value:function(t){this.trigger(ht.PLAYER_SEEK,t)}},{key:"_onTimeUpdate",value:function(t){this.trigger(ht.PLAYER_TIMEUPDATE,t)}},{key:"_onError",value:function(t){this.trigger(ht.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._unregisterOptionEventListeners(),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:"setVolume",value:function(t){return this.core.activeContainer.setVolume(t),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()}}])}(ct);Object.assign(Bt.prototype,kt);var Ut=function(t){function e(t){var i;return s(this,e),(i=r(this,e,[t.options])).container=t,i.enabled=!0,i.bindEvents(),i}return d(e,t),o(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()}}])}(ct);Object.assign(Ut.prototype,kt),Ut.extend=function(t){return $(Ut,t)},Ut.type="container";var $t=function(t){function e(t){var i;return s(this,e),(i=r(this,e,[t.options])).core=t,i.enabled=!0,i.bindEvents(),i}return d(e,t),o(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()}}])}(ct);Object.assign($t.prototype,kt),$t.extend=function(t){return $($t,t)},$t.type="core";var Gt=function(t){function e(t){var i;return s(this,e),(i=r(this,e,[t.options])).container=t,i.enabled=!0,i.bindEvents(),i}return d(e,t),o(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(){}}])}(bt);Object.assign(Gt.prototype,kt),Gt.extend=function(t){return $(Gt,t)},Gt.type="container";var Vt={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"]};Vt.ogv=Vt.ogg,Vt["3gp"]=Vt["3gpp"];var Kt={wav:["audio/wav"],mp3:["audio/mp3",'audio/mpeg;codecs="mp3"'],aac:['audio/mp4;codecs="mp4a.40.5"'],oga:["audio/ogg"]},Ht=Object.keys(Kt).reduce(function(t,e){return[].concat(A(t),A(Kt[e]))},[]),Yt={code:"unknown",message:"unknown"},jt=function(t){function e(){var t;s(this,e);for(var i=arguments.length,n=new Array(i),a=0;a<i;a++)n[a]=arguments[a];(t=r(this,e,[].concat(n)))._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 o,l=t.options.playback,h=l.preload||(D.isSafari?"auto":t.options.preload);return t.options.poster&&("string"==typeof t.options.poster?o=t.options.poster:"string"==typeof t.options.poster.url&&(o=t.options.poster.url)),k.extend(!0,t.el,{muted:t.options.mute,defaultMuted:t.options.mute,loop:t.options.loop,poster:o,preload:h||"metadata",crossOrigin:l.crossOrigin,"x-webkit-playsinline":l.playInline}),(l.controls||t.options.useVideoTagDefaultControls)&&t.$el.attr("controls",""),l.playInline&&t.$el.attr({playsinline:"playsinline"}),l.crossOrigin&&t.$el.attr({crossorigin:l.crossOrigin}),t.settings={default:["seekbar"]},t.settings.left=["playpause","position","duration"],t.settings.right=["fullscreen","volume","hd-indicator"],l.externalTracks&&t._setupExternalTracks(l.externalTracks),t.options.autoPlay&&t.attemptAutoPlay(),t}return d(e,t),o(e,[{key:"name",get:function(){return"html5_video"}},{key:"supportedVersion",get:function(){return{min:"0.16.2"}}},{key:"tagName",get:function(){return this.isAudioOnly?"audio":"video"}},{key:"isAudioOnly",get:function(){var t=this.options.src,i=e._mimeTypesForUrl(t,Kt,this.options.mimeType);return this.options.playback&&this.options.playback.audioOnly||this.options.audioOnly||Ht.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()===It.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){y(e,"configure",this)([t]),this.el.loop=!!t.loop}},{key:"attemptAutoPlay",value:function(){var t=this;this.canAutoPlay(function(e,i){i&&rt.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};D.isMobile&&X.options.recycleVideo&&(e.element=this.el),q(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(ht.PLAYBACK_LOADEDMETADATA,{duration:t.target.duration,data:t}),this._updateSettings();var e=void 0===this._options.autoSeekFromUrl||this._options.autoSeekFromUrl;this.getPlaybackType()!==It.LIVE&&e&&this._checkInitialSeek()}},{key:"_onDurationChange",value:function(){this._updateSettings(),this._onTimeUpdate(),this._onProgress()}},{key:"_updateSettings",value:function(){this.getPlaybackType()===It.VOD||this.getPlaybackType()===It.AOD?this.settings.left=["playpause","position","duration"]:this.settings.left=["playstop"],this.settings.seekEnabled=this.isSeekEnabled(),this.trigger(ht.PLAYBACK_SETTINGSUPDATE)}},{key:"isSeekEnabled",value:function(){return isFinite(this.getDuration())}},{key:"getPlaybackType",value:function(){var t="audio"===this.tagName?It.AOD:It.VOD;return[0,void 0,1/0].indexOf(this.el.duration)>=0?It.LIVE:t}},{key:"isHighDefinitionInUse",value:function(){return!1}},{key:"consent",value:function(t){var i=this;if(this.isPlaying()||this.el._consented)y(e,"consent",this)([t]);else{var n=function(){i.el.removeEventListener("loadedmetadata",n,!1),i.el.removeEventListener("error",n,!1),i.el._consented=!0,y(e,"consent",i)([t])};this.el.addEventListener("loadedmetadata",n,!1),this.el.addEventListener("error",n,!1),this.el.load()}}},{key:"play",value:function(){var t=this;this.trigger(ht.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 rt.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(ht.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(ht.PLAYBACK_PLAY)}},{key:"_onPause",value:function(){this.dvrEnabled&&this._updateDvr(!0),this._stopPlayheadMovingChecks(),this._handleBufferingEvents(),this.trigger(ht.PLAYBACK_PAUSE)}},{key:"_onSeeking",value:function(){var t=this.getCurrentTime();this.dvrEnabled&&this._updateDvr(t<this.getDuration()-3),this.trigger(ht.PLAYBACK_SEEK,t),this._handleBufferingEvents()}},{key:"_onSeeked",value:function(){this._handleBufferingEvents(),this.trigger(ht.PLAYBACK_SEEKED)}},{key:"_onEnded",value:function(){this._handleBufferingEvents(),this.trigger(ht.PLAYBACK_ENDED,this.name)}},{key:"_onEnterPiP",value:function(){this.trigger(ht.PLAYBACK_PIP_ENTER,this.name)}},{key:"_onExitPiP",value:function(){this.trigger(ht.PLAYBACK_PIP_EXIT,this.name)}},{key:"enterPiP",value:function(){var t=this;this.el.requestPictureInPicture().then(function(){rt.info(t.name,"enter PIP success")}).catch(function(e){rt.warn(t.name,"enter PIP failed",e)})}},{key:"exitPiP",value:function(){var t=this;document.exitPictureInPicture().then(function(){rt.info(t.name,"exit PIP success")}).catch(function(e){rt.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,n=t&&e;this._playheadMovingCheckEnabled&&(n=n||t&&i),this._isBuffering!==n&&(this._isBuffering=n,n?this.trigger(ht.PLAYBACK_BUFFERING,this.name):this.trigger(ht.PLAYBACK_BUFFERFULL,this.name))}},{key:"_onError",value:function(){var t=this.el.error||Yt,e=t.code,i=t.message,n=e===Yt.code,r=this.createError({code:e,description:i,raw:this.el.error,level:n?St.Levels.WARN:St.Levels.FATAL});n?rt.warn(this.name,"HTML5 unknown error: ",r):this.trigger(ht.PLAYBACK_ERROR,r)}},{key:"destroy",value:function(){this._destroyed=!0,this._stopPlayheadMovingChecks(),this.handleTextTrackChange&&this.el.textTracks.removeEventListener("change",this.handleTextTrackChange),this.$el.off("contextmenu"),y(e,"destroy",this)([]),this.el.removeAttribute("src"),this.el.load(),this._src=null,X.garbage(this.el)}},{key:"_updateDvr",value:function(t){this.trigger(ht.PLAYBACK_DVR,t),this.trigger(ht.PLAYBACK_STATS_ADD,{dvr:t})}},{key:"seek",value:function(t){t<0&&(rt.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=H();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(ht.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(A(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 n={start:t[e].start,current:t[e].end,total:this.el.duration};this.trigger(ht.PLAYBACK_PROGRESS,n,t)}}},{key:"_typeFor",value:function(t){var i=e._mimeTypesForUrl(t,Vt,this.options.mimeType);return 0===i.length&&(i=e._mimeTypesForUrl(t,Kt,this.options.mimeType)),(i[0]||"").split(";")[0]}},{key:"_ready",value:function(){this._isReadyState||(this._isReadyState=!0,this.trigger(ht.PLAYBACK_READY,this.name))}},{key:"_checkForClosedCaptions",value:function(){if(this.isHTML5Video&&!this._ccIsSetup){if(this.hasClosedCaptionsTracks){this.trigger(ht.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(ht.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(j(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){t.track.mode="hidden"}),e&&(e.track.mode="showing"),this._ccTrackId=t,this.trigger(ht.PLAYBACK_SUBTITLE_CHANGED,{id:t})}}},{key:"template",get:function(){return At('<% 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=Et.getStyleFor("[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}}])}(It);jt._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],n=e||i&&t[i.toLowerCase()]||[];return n.constructor===Array?n:[n]},jt._canPlay=function(t,e,i,n){var r=jt._mimeTypesForUrl(i,e,n),s=document.createElement(t);return!!r.filter(function(t){return!!s.canPlayType(t).replace(/no/,"")})[0]},jt.canPlay=function(t,e){return jt._canPlay("audio",Kt,t,e)||jt._canPlay("video",Vt,t,e)};var Wt=function(t){function e(){return s(this,e),r(this,e,arguments)}return d(e,t),o(e,[{key:"name",get:function(){return"html5_audio"}},{key:"supportedVersion",get:function(){return{min:"0.16.2"}}},{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(ht.PLAYBACK_SETTINGSUPDATE)}},{key:"getPlaybackType",value:function(){return It.AOD}}])}(jt);Wt.canPlay=function(t,e){return jt._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 zt=function(t){function e(t){var i;return s(this,e),(i=r(this,e,[t])).el.src=t.src,i}return d(e,t),o(e,[{key:"name",get:function(){return"html_img"}},{key:"supportedVersion",get:function(){return{min:"0.16.2"}}},{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 It.NO_OP}},{key:"render",value:function(){var t=Et.getStyleFor("[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(ht.PLAYBACK_READY,this.name),this}},{key:"_onLoad",value:function(){this.trigger(ht.PLAYBACK_ENDED,this.name)}},{key:"_onError",value:function(t){var e="error"===t.type?"load error":"loading aborted";this.trigger(ht.PLAYBACK_ERROR,{message:e},this.name)}}])}(It);zt.canPlay=function(t){return/\.(png|jpg|jpeg|gif|bmp|tiff|pgm|pnm|webp)(|\?.*)$/i.test(t)};var qt=function(t){function e(){var t;s(this,e);for(var i=arguments.length,n=new Array(i),a=0;a<i;a++)n[a]=arguments[a];return(t=r(this,e,[].concat(n)))._noiseFrameNum=-1,t}return d(e,t),o(e,[{key:"name",get:function(){return"no_op"}},{key:"supportedVersion",get:function(){return{min:"0.16.2"}}},{key:"template",get:function(){return At("<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=Et.getStyleFor("[data-no-op] {\n position: absolute;\n height: 100%;\n width: 100%;\n text-align: center;\n}\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 -webkit-transform: translateY(-50%);\n transform: translateY(-50%);\n max-height: 100%;\n overflow: auto;\n}\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(ht.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(r){t=new Uint32Array(this.context.canvas.width*this.context.canvas.height*4);for(var i=e.data,n=0;n<i.length;n++)t[n]=i[n]}for(var r=t.length,s=6*Math.random()+4,a=0,o=0,l=0;l<r;){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=F(function(){return t._loop()}))}},{key:"destroy",value:function(){this._animationHandle&&(B(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()}}])}(It);qt.canPlay=function(t){return!0};var Xt=function(t){function e(t){var i;return s(this,e),(i=r(this,e,[t]))._initializeMessages(),i}return d(e,t),o(e,[{key:"name",get:function(){return"strings"}},{key:"supportedVersion",get:function(){return{min:"0.16.2"}}},{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||z()}},{key:"_initializeMessages",value:function(){this._messages=k.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}}])}($t),Qt=function(t){function e(){return s(this,e),r(this,e,arguments)}return d(e,t),o(e,[{key:"name",get:function(){return"sources"}},{key:"supportedVersion",get:function(){return{min:"0.16.2"}}},{key:"bindEvents",value:function(){this.listenTo(this.core,ht.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()})}}])}($t);Nt.registerPlugin(Xt),Nt.registerPlugin(Qt),Nt.registerPlayback(qt),Nt.registerPlayback(zt),Nt.registerPlayback(Wt),Nt.registerPlayback(jt);var Zt={Player:Bt,Events:ht,Browser:D,ContainerPlugin:Ut,UIContainerPlugin:Gt,CorePlugin:$t,UICorePlugin:_t,Playback:It,Container:Lt,Core:Ct,PlayerError:St,Loader:Nt,BaseObject:ct,UIObject:bt,Utils:Z,HTML5Audio:Wt,HTML5Video:jt,HTMLImg:zt,Log:rt,Styler:Et,version:"0.16.2",template:At,$:k};function Jt(t,e,i){return e=ne(e),ae(t,se()?Reflect.construct(e,i||[],ne(t).constructor):e.apply(t,i))}function te(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function ee(t,e,i){return e&&function(t,e){for(var i=0;i<e.length;i++){var n=e[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,he(n.key),n)}}(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t}function ie(){return ie="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(t,e,i){var n=function(t,e){for(;!{}.hasOwnProperty.call(t,e)&&null!==(t=ne(t)););return t}(t,e);if(n){var r=Object.getOwnPropertyDescriptor(n,e);return r.get?r.get.call(arguments.length<3?t:i):r.value}},ie.apply(null,arguments)}function ne(t){return ne=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},ne(t)}function re(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&&oe(t,e)}function se(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(se=function(){return!!t})()}function ae(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)}function oe(t,e){return oe=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},oe(t,e)}function le(t,e,i,n){var r=ie(ne(t.prototype),e,i);return"function"==typeof r?function(t){return r.apply(i,t)}:r}function he(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var n=i.call(t,e);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t,"string");return"symbol"==typeof e?e:e+""}function ce(t){return ce="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},ce(t)}var ue=function(t){function e(){return te(this,e),Jt(this,e,arguments)}return re(e,t),ee(e,[{key:"name",get:function(){return"click_to_pause"}},{key:"supportedVersion",get:function(){return{min:"0.16.2"}}},{key:"config",get:function(){return this.container.options.clickToPauseConfig||{}}},{key:"bindEvents",value:function(){this.listenTo(this.container,ht.CONTAINER_CLICK,this.click),this.listenTo(this.container,ht.CONTAINER_SETTINGSUPDATE,this.settingsUpdate)}},{key:"click",value:function(){var t=this.config.onClickPayload;(this.container.getPlaybackType()!==It.LIVE||this.container.isDvrEnabled())&&(this.container.isPlaying()?this.container.pause(t):this.container.play(t))}},{key:"settingsUpdate",value:function(){var t=this.container.getPlaybackType()!==It.LIVE||this.container.isDvrEnabled();if(t!==this.pointerEnabled){var e=t?"addClass":"removeClass";this.container.$el[e]("pointer-enabled"),this.pointerEnabled=t}}}])}(Ut),de=function(t){function e(t){var i;te(this,e),i=Jt(this,e,[t]);var n=t.options.closedCaptionsConfig;return i._title=n&&n.title?n.title:null,i._ariaLabel=n&&n.ariaLabel?n.ariaLabel:"cc-button",i._labelCb=n&&n.labelCallback&&"function"==typeof n.labelCallback?n.labelCallback:function(t){return t.name},i}return re(e,t),ee(e,[{key:"name",get:function(){return"closed_captions"}},{key:"supportedVersion",get:function(){return{min:"0.16.2"}}},{key:"template",get:function(){return At('<button type="button" class="cc-button media-control-button media-control-icon" data-cc-button aria-label="<%= ariaLabel %>"></button>\n<ul>\n <% if (title) { %>\n <li data-title><%= title %></li>\n <% }; %>\n <li><a href="#" data-cc-select="-1"><%= disabledLabel %></a></li>\n <% for (var i = 0; i < tracks.length; i++) { %>\n <li><a href="#" data-cc-select="<%= tracks[i].id %>"><%= tracks[i].label %></a></li>\n <% }; %>\n</ul>\n')}},{key:"events",get:function(){return{"click [data-cc-button]":"toggleContextMenu","click [data-cc-select]":"onTrackSelect"}}},{key:"attributes",get:function(){return{class:"cc-controls","data-cc-controls":""}}},{key:"bindEvents",value:function(){this.listenTo(this.core,ht.CORE_ACTIVE_CONTAINER_CHANGED,this.containerChanged),this.listenTo(this.core.mediaControl,ht.MEDIACONTROL_RENDERED,this.render),this.listenTo(this.core.mediaControl,ht.MEDIACONTROL_HIDE,this.hideContextMenu),this.bindContainerEvents()}},{key:"bindContainerEvents",value:function(){this.container=this.core.activeContainer,this.container&&(this.listenTo(this.container,ht.CONTAINER_SUBTITLE_AVAILABLE,this.onSubtitleAvailable),this.listenTo(this.container,ht.CONTAINER_SUBTITLE_CHANGED,this.onSubtitleChanged),this.listenTo(this.container,ht.CONTAINER_STOP,this.onContainerStop))}},{key:"onContainerStop",value:function(){this.ccAvailable(!1)}},{key:"containerChanged",value:function(){this.ccAvailable(!1),this.stopListening(),this.bindEvents()}},{key:"onSubtitleAvailable",value:function(){this.renderCcButton(),this.ccAvailable(!0)}},{key:"onSubtitleChanged",value:function(t){this.setCurrentContextMenuElement(t.id)}},{key:"onTrackSelect",value:function(t){var e=parseInt(t.target.dataset.ccSelect,10);return this.container.closedCaptionsTrackId=e,this.hideContextMenu(),t.stopPropagation(),!1}},{key:"ccAvailable",value:function(t){var e=t?"addClass":"removeClass";this.$el[e]("available")}},{key:"toggleContextMenu",value:function(){this.$el.find("ul").toggle()}},{key:"hideContextMenu",value:function(){this.$el.find("ul").hide()}},{key:"contextMenuElement",value:function(t){return this.$el.find("ul a"+(isNaN(t)?"":'[data-cc-select="'+t+'"]')).parent()}},{key:"setCurrentContextMenuElement",value:function(t){if(this._trackId!==t){this.contextMenuElement().removeClass("current"),this.contextMenuElement(t).addClass("current");var e=t>-1?"addClass":"removeClass";this.$ccButton[e]("enabled"),this._trackId=t}}},{key:"renderCcButton",value:function(){for(var t=this.container?this.container.closedCaptionsTracks:[],e=0;e<t.length;e++)t[e].label=this._labelCb(t[e]);var i=Et.getStyleFor(".cc-controls[data-cc-controls] {\n float: right;\n position: relative;\n display: none;\n}\n.cc-controls[data-cc-controls].available {\n display: block;\n}\n.cc-controls[data-cc-controls] .cc-button {\n padding: 6px !important;\n}\n.cc-controls[data-cc-controls] .cc-button.enabled {\n display: block;\n opacity: 1;\n}\n.cc-controls[data-cc-controls] .cc-button.enabled:hover {\n opacity: 1;\n text-shadow: none;\n}\n.cc-controls[data-cc-controls] > ul {\n list-style-type: none;\n position: absolute;\n bottom: 25px;\n border: 1px solid black;\n display: none;\n background-color: #e6e6e6;\n}\n.cc-controls[data-cc-controls] li {\n font-size: 10px;\n}\n.cc-controls[data-cc-controls] li[data-title] {\n background-color: #c3c2c2;\n padding: 5px;\n}\n.cc-controls[data-cc-controls] li a {\n color: #444;\n padding: 2px 10px;\n display: block;\n text-decoration: none;\n}\n.cc-controls[data-cc-controls] li a:hover {\n background-color: #555;\n color: white;\n}\n.cc-controls[data-cc-controls] li a:hover a {\n color: white;\n text-decoration: none;\n}\n.cc-controls[data-cc-controls] li.current a {\n color: #f00;\n}",{baseUrl:this.options.baseUrl});this.$el.html(this.template({ariaLabel:this._ariaLabel,disabledLabel:this.core.i18n.t("disabled"),title:this._title,tracks:t})),this.$ccButton=this.$el.find("button.cc-button[data-cc-button]"),this.$ccButton.append('<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"\n\t viewBox="0 0 49 41.8" style="enable-background:new 0 0 49 41.8;" xml:space="preserve">\n<path d="M47.1,0H3.2C1.6,0,0,1.2,0,2.8v31.5C0,35.9,1.6,37,3.2,37h11.9l3.2,1.9l4.7,2.7c0.9,0.5,2-0.1,2-1.1V37h22.1\n\tc1.6,0,1.9-1.1,1.9-2.7V2.8C49,1.2,48.7,0,47.1,0z M7.2,18.6c0-4.8,3.5-9.3,9.9-9.3c4.8,0,7.1,2.7,7.1,2.7l-2.5,4\n\tc0,0-1.7-1.7-4.2-1.7c-2.8,0-4.3,2.1-4.3,4.3c0,2.1,1.5,4.4,4.5,4.4c2.5,0,4.9-2.1,4.9-2.1l2.2,4.2c0,0-2.7,2.9-7.6,2.9\n\tC10.8,27.9,7.2,23.5,7.2,18.6z M36.9,27.9c-6.4,0-9.9-4.4-9.9-9.3c0-4.8,3.5-9.3,9.9-9.3C41.7,9.3,44,12,44,12l-2.5,4\n\tc0,0-1.7-1.7-4.2-1.7c-2.8,0-4.3,2.1-4.3,4.3c0,2.1,1.5,4.4,4.5,4.4c2.5,0,4.9-2.1,4.9-2.1l2.2,4.2C44.5,25,41.9,27.9,36.9,27.9z"/>\n</svg>'),this.$el.append(i[0])}},{key:"render",value:function(){this.renderCcButton();var t=this.core.mediaControl.$el.find("button[data-fullscreen]");return t[0]?this.$el.insertAfter(t):this.core.mediaControl.$el.find(".media-control-right-panel[data-media-control]").prepend(this.$el),this}}])}(_t),fe=function(t){function e(t){var i;return te(this,e),(i=Jt(this,e,[t])).settingsUpdate(),i}return re(e,t),ee(e,[{key:"template",get:function(){return At('<div class="live-info"><%= live %></div>\n<button type="button" class="live-button" aria-label="<%= backToLive %>"><%= backToLive %></button>\n')}},{key:"name",get:function(){return"dvr_controls"}},{key:"supportedVersion",get:function(){return{min:"0.16.2"}}},{key:"events",get:function(){return{"click .live-button":"click"}}},{key:"attributes",get:function(){return{class:"dvr-controls","data-dvr-controls":""}}},{key:"bindEvents",value:function(){this.bindCoreEvents(),this.bindContainerEvents()}},{key:"bindCoreEvents",value:function(){var t=this;this.core.mediaControl.settings?(this.listenTo(this.core.mediaControl,ht.MEDIACONTROL_CONTAINERCHANGED,this.containerChanged),this.listenTo(this.core.mediaControl,ht.MEDIACONTROL_RENDERED,this.settingsUpdate),this.listenTo(this.core,ht.CORE_OPTIONS_CHANGE,this.render)):setTimeout(function(){return t.bindCoreEvents()},100)}},{key:"bindContainerEvents",value:function(){this.core.activeContainer&&(this.listenToOnce(this.core.activeContainer,ht.CONTAINER_TIMEUPDATE,this.render),this.listenTo(this.core.activeContainer,ht.CONTAINER_PLAYBACKDVRSTATECHANGED,this.dvrChanged))}},{key:"containerChanged",value:function(){this.stopListening(),this.bindEvents()}},{key:"dvrChanged",value:function(t){this.core.getPlaybackType()===It.LIVE&&(this.settingsUpdate(),this.core.mediaControl.$el.addClass("live"),t?(this.core.mediaControl.$el.addClass("dvr"),this.core.mediaControl.$el.find(".media-control-indicator[data-position], .media-control-indicator[data-duration]").hide()):this.core.mediaControl.$el.removeClass("dvr"))}},{key:"click",value:function(){var t=this.core.mediaControl,e=t.container;e.isPlaying()||e.play(),t.$el.hasClass("dvr")&&e.seek(e.getDuration())}},{key:"settingsUpdate",value:function(){var t=this;this.stopListening(),this.core.mediaControl.$el.removeClass("live"),this.shouldRender()&&(this.render(),this.$el.click(function(){return t.click()})),this.bindEvents()}},{key:"shouldRender",value:function(){return(void 0===this.core.options.useDvrControls||!!this.core.options.useDvrControls)&&this.core.getPlaybackType()===It.LIVE}},{key:"render",value:function(){var t=Et.getStyleFor('.dvr-controls[data-dvr-controls] {\n display: inline-block;\n float: left;\n color: #fff;\n line-height: 32px;\n font-size: 10px;\n font-weight: bold;\n margin-left: 6px;\n}\n.dvr-controls[data-dvr-controls] .live-info {\n cursor: default;\n font-family: "Roboto", "Open Sans", Arial, sans-serif;\n text-transform: uppercase;\n}\n.dvr-controls[data-dvr-controls] .live-info:before {\n content: "";\n display: inline-block;\n position: relative;\n width: 7px;\n height: 7px;\n border-radius: 3.5px;\n margin-right: 3.5px;\n background-color: #ff0101;\n}\n.dvr-controls[data-dvr-controls] .live-info.disabled {\n opacity: 0.3;\n}\n.dvr-controls[data-dvr-controls] .live-info.disabled:before {\n background-color: #fff;\n}\n.dvr-controls[data-dvr-controls] .live-button {\n cursor: pointer;\n outline: none;\n display: none;\n border: 0;\n color: #fff;\n background-color: transparent;\n height: 32px;\n padding: 0;\n opacity: 0.7;\n font-family: "Roboto", "Open Sans", Arial, sans-serif;\n text-transform: uppercase;\n -webkit-transition: all 0.1s ease;\n transition: all 0.1s ease;\n}\n.dvr-controls[data-dvr-controls] .live-button:before {\n content: "";\n display: inline-block;\n position: relative;\n width: 7px;\n height: 7px;\n border-radius: 3.5px;\n margin-right: 3.5px;\n background-color: #fff;\n}\n.dvr-controls[data-dvr-controls] .live-button:hover {\n opacity: 1;\n text-shadow: rgba(255, 255, 255, 0.75) 0 0 5px;\n}\n\n.dvr .dvr-controls[data-dvr-controls] .live-info {\n display: none;\n}\n.dvr .dvr-controls[data-dvr-controls] .live-button {\n display: block;\n}\n.dvr.media-control.live[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar] {\n background-color: #005aff;\n}\n\n.media-control.live[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar] {\n background-color: #ff0101;\n}',{baseUrl:this.options.baseUrl});return this.$el.html(this.template({live:this.core.i18n.t("live"),backToLive:this.core.i18n.t("back_to_live")})),this.$el.append(t[0]),this.shouldRender()&&(this.core.mediaControl.$el.addClass("live"),this.core.mediaControl.$(".media-control-left-panel[data-media-control]").append(this.$el)),this}}])}(_t),ge=function(t){function e(){return te(this,e),Jt(this,e,arguments)}return re(e,t),ee(e,[{key:"name",get:function(){return"end_video"}},{key:"supportedVersion",get:function(){return{min:"0.16.2"}}},{key:"bindEvents",value:function(){this.listenTo(this.core,ht.CORE_ACTIVE_CONTAINER_CHANGED,this.containerChanged);var t=this.core.activeContainer;t&&(this.listenTo(t,ht.CONTAINER_ENDED,this.ended),this.listenTo(t,ht.CONTAINER_STOP,this.ended))}},{key:"containerChanged",value:function(){this.stopListening(),this.bindEvents()}},{key:"ended",value:function(){(void 0===this.core.options.exitFullscreenOnEnd||this.core.options.exitFullscreenOnEnd)&&this.core.isFullscreen()&&this.core.toggleFullscreen()}}])}($t),pe=function(t){function e(t){var i;return te(this,e),(i=Jt(this,e,[t])).options.disableErrorScreen?ae(i,i.disable()):i}return re(e,t),ee(e,[{key:"name",get:function(){return"error_screen"}},{key:"supportedVersion",get:function(){return{min:"0.16.2"}}},{key:"template",get:function(){return At('<div class="player-error-screen__content" data-error-screen>\n <% if (icon) { %>\n <div class="player-error-screen__icon" data-error-screen><%= icon %></div>\n <% } %>\n <div class="player-error-screen__title" data-error-screen><%= title %></div>\n <div class="player-error-screen__message" data-error-screen><%= message %></div>\n <div class="player-error-screen__code" data-error-screen>Error code: <%= code %></div>\n <div class="player-error-screen__reload" data-error-screen><%= reloadIcon %></div>\n</div>\n')}},{key:"container",get:function(){return this.core.getCurrentContainer()}},{key:"attributes",get:function(){return{class:"player-error-screen","data-error-screen":""}}},{key:"bindEvents",value:function(){this.listenTo(this.core,ht.ERROR,this.onError),this.listenTo(this.core,ht.CORE_ACTIVE_CONTAINER_CHANGED,this.onContainerChanged)}},{key:"bindReload",value:function(){this.reloadButton=this.$el.find(".player-error-screen__reload"),this.reloadButton&&this.reloadButton.on("click",this.reload.bind(this))}},{key:"reload",value:function(){var t=this;this.listenToOnce(this.core,ht.CORE_READY,function(){return t.container.play()}),this.core.load(this.options.sources,this.options.mimeType),this.unbindReload()}},{key:"unbindReload",value:function(){this.reloadButton&&this.reloadButton.off("click")}},{key:"onContainerChanged",value:function(){this.err=null,this.unbindReload(),this.hide()}},{key:"onError",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};t.level===St.Levels.FATAL&&(this.err=t,this.container.disableMediaControl(),this.container.stop(),this.show())}},{key:"show",value:function(){this.render(),this.$el.show()}},{key:"hide",value:function(){this.$el.hide()}},{key:"render",value:function(){if(this.err){var t=Et.getStyleFor("[data-player] .player-error-screen {\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n color: #CCCACA;\n position: absolute;\n top: 0;\n height: 100%;\n width: 100%;\n background-color: rgba(0, 0, 0, 0.7);\n z-index: 2000;\n display: -webkit-box;\n display: -ms-flexbox;\n display: flex;\n -webkit-box-orient: vertical;\n -webkit-box-direction: normal;\n -ms-flex-direction: column;\n flex-direction: column;\n -webkit-box-pack: center;\n -ms-flex-pack: center;\n justify-content: center;\n}\n[data-player] .player-error-screen__content[data-error-screen] {\n font-size: 14px;\n color: #CCCACA;\n margin-top: 45px;\n}\n[data-player] .player-error-screen__title[data-error-screen] {\n font-weight: bold;\n line-height: 30px;\n font-size: 18px;\n}\n[data-player] .player-error-screen__message[data-error-screen] {\n width: 90%;\n margin: 0 auto;\n}\n[data-player] .player-error-screen__code[data-error-screen] {\n font-size: 13px;\n margin-top: 15px;\n}\n[data-player] .player-error-screen__reload {\n cursor: pointer;\n width: 30px;\n margin: 15px auto 0 !important;\n}",{baseUrl:this.options.baseUrl});return this.$el.html(this.template({title:this.err.UI.title,message:this.err.UI.message,code:this.err.code,icon:this.err.UI.icon||"",reloadIcon:'<svg fill="#FFFFFF" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg">\n <path d="M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"/>\n <path d="M0 0h24v24H0z" fill="none"/>\n</svg>'})),this.$el.append(t[0]),this.core.$el.append(this.el),this.bindReload(),this}}}])}(_t),me='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">\n <path fill="#010101" d="M1.425.35L14.575 8l-13.15 7.65V.35z"/>\n</svg>',ve='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">\n <path fill-rule="evenodd" clip-rule="evenodd" fill="#010101" d="M1.712 14.76H6.43V1.24H1.71v13.52zm7.86-13.52v13.52h4.716V1.24H9.573z"/>\n</svg>',ye=k('link[rel="shortcut icon"]'),Ae=function(t){function e(t){var i;return te(this,e),(i=Jt(this,e,[t]))._container=null,i.configure(),i}return re(e,t),ee(e,[{key:"name",get:function(){return"favicon"}},{key:"supportedVersion",get:function(){return{min:"0.16.2"}}},{key:"oldIcon",get:function(){return ye}},{key:"configure",value:function(){this.core.options.changeFavicon?this.enabled||(this.stopListening(this.core,ht.CORE_OPTIONS_CHANGE),this.enable()):this.enabled&&(this.disable(),this.listenTo(this.core,ht.CORE_OPTIONS_CHANGE,this.configure))}},{key:"bindEvents",value:function(){this.listenTo(this.core,ht.CORE_OPTIONS_CHANGE,this.configure),this.listenTo(this.core,ht.CORE_ACTIVE_CONTAINER_CHANGED,this.containerChanged),this.core.activeContainer&&this.containerChanged()}},{key:"containerChanged",value:function(){this._container&&this.stopListening(this._container),this._container=this.core.activeContainer,this.listenTo(this._container,ht.CONTAINER_PLAY,this.setPlayIcon),this.listenTo(this._container,ht.CONTAINER_PAUSE,this.setPauseIcon),this.listenTo(this._container,ht.CONTAINER_STOP,this.resetIcon),this.listenTo(this._container,ht.CONTAINER_ENDED,this.resetIcon),this.listenTo(this._container,ht.CONTAINER_ERROR,this.resetIcon),this.resetIcon()}},{key:"disable",value:function(){le(e,"disable",this)([]),this.resetIcon()}},{key:"destroy",value:function(){le(e,"destroy",this)([]),this.resetIcon()}},{key:"createIcon",value:function(t){var e=k("<canvas/>");e[0].width=16,e[0].height=16;var i=e[0].getContext("2d");i.fillStyle="#000";var n=k(t).find("path").attr("d"),r=new Path2D(n);i.fill(r);var s=k('<link rel="shortcut icon" type="image/png"/>');return s.attr("href",e[0].toDataURL("image/png")),s}},{key:"setPlayIcon",value:function(){this.playIcon||(this.playIcon=this.createIcon(me)),this.changeIcon(this.playIcon)}},{key:"setPauseIcon",value:function(){this.pauseIcon||(this.pauseIcon=this.createIcon(ve)),this.changeIcon(this.pauseIcon)}},{key:"resetIcon",value:function(){k('link[rel="shortcut icon"]').remove(),k("head").append(this.oldIcon)}},{key:"changeIcon",value:function(t){t&&(k('link[rel="shortcut icon"]').remove(),k("head").append(t))}}])}($t),Ee=function(t){function e(t){var i;return te(this,e),(i=Jt(this,e,[t])).container.options.gaAccount&&(i.account=i.container.options.gaAccount,i.trackerName=i.container.options.gaTrackerName?i.container.options.gaTrackerName+".":"Clappr.",i.domainName=i.container.options.gaDomainName,i.currentHDState=void 0,i.embedScript()),i}return re(e,t),ee(e,[{key:"name",get:function(){return"google_analytics"}},{key:"supportedVersion",get:function(){return{min:"0.16.2"}}},{key:"embedScript",value:function(){var t=this;if(window._gat)this.addEventListeners();else{var e=document.createElement("script");e.setAttribute("type","text/javascript"),e.setAttribute("async","async"),e.setAttribute("src","//www.google-analytics.com/ga.js"),e.onload=function(){return t.addEventListeners()},document.body.appendChild(e)}}},{key:"addEventListeners",value:function(){var t=this;this.container&&(this.listenTo(this.container,ht.CONTAINER_READY,this.onReady),this.listenTo(this.container,ht.CONTAINER_PLAY,this.onPlay),this.listenTo(this.container,ht.CONTAINER_STOP,this.onStop),this.listenTo(this.container,ht.CONTAINER_PAUSE,this.onPause),this.listenTo(this.container,ht.CONTAINER_ENDED,this.onEnded),this.listenTo(this.container,ht.CONTAINER_STATE_BUFFERING,this.onBuffering),this.listenTo(this.container,ht.CONTAINER_STATE_BUFFERFULL,this.onBufferFull),this.listenTo(this.container,ht.CONTAINER_ERROR,this.onError),this.listenTo(this.container,ht.CONTAINER_PLAYBACKSTATE,this.onPlaybackChanged),this.listenTo(this.container,ht.CONTAINER_VOLUME,function(e){return t.onVolumeChanged(e)}),this.listenTo(this.container,ht.CONTAINER_SEEK,function(e){return t.onSeek(e)}),this.listenTo(this.container,ht.CONTAINER_FULL_SCREEN,this.onFullscreen),this.listenTo(this.container,ht.CONTAINER_HIGHDEFINITIONUPDATE,this.onHD),this.listenTo(this.container,ht.CONTAINER_PLAYBACKDVRSTATECHANGED,this.onDVR)),_gaq.push([this.trackerName+"_setAccount",this.account]),this.domainName&&_gaq.push([this.trackerName+"_setDomainName",this.domainName])}},{key:"onReady",value:function(){this.push(["Video","Playback",this.container.playback.name])}},{key:"onPlay",value:function(){this.push(["Video","Play",this.container.playback.src])}},{key:"onStop",value:function(){this.push(["Video","Stop",this.container.playback.src])}},{key:"onEnded",value:function(){this.push(["Video","Ended",this.container.playback.src])}},{key:"onBuffering",value:function(){this.push(["Video","Buffering",this.container.playback.src])}},{key:"onBufferFull",value:function(){this.push(["Video","Bufferfull",this.container.playback.src])}},{key:"onError",value:function(){this.push(["Video","Error",this.container.playback.src])}},{key:"onHD",value:function(t){var e=t?"ON":"OFF";e!==this.currentHDState&&(this.currentHDState=e,this.push(["Video","HD - "+e,this.container.playback.src]))}},{key:"onPlaybackChanged",value:function(t){null!==t.type&&this.push(["Video","Playback Type - "+t.type,this.container.playback.src])}},{key:"onDVR",value:function(t){var e=t?"ON":"OFF";this.push(["Interaction","DVR - "+e,this.container.playback.src])}},{key:"onPause",value:function(){this.push(["Video","Pause",this.container.playback.src])}},{key:"onSeek",value:function(){this.push(["Video","Seek",this.container.playback.src])}},{key:"onVolumeChanged",value:function(){this.push(["Interaction","Volume",this.container.playback.src])}},{key:"onFullscreen",value:function(){this.push(["Interaction","Fullscreen",this.container.playback.src])}},{key:"push",value:function(t){var e=[this.trackerName+"_trackEvent"].concat(t);_gaq.push(e)}}])}(Ut),Te=function(t){this.element=t||window.document,this.initialize()};Te.KEY_NAMES_BY_CODE={8:"backspace",9:"tab",13:"enter",16:"shift",17:"ctrl",18:"alt",20:"caps_lock",27:"esc",32:"space",37:"left",38:"up",39:"right",40:"down",48:"0",49:"1",50:"2",51:"3",52:"4",53:"5",54:"6",55:"7",56:"8",57:"9",65:"a",66:"b",67:"c",68:"d",69:"e",70:"f",71:"g",72:"h",73:"i",74:"j",75:"k",76:"l",77:"m",78:"n",79:"o",80:"p",81:"q",82:"r",83:"s",84:"t",85:"u",86:"v",87:"w",88:"x",89:"y",90:"z",112:"f1",113:"f2",114:"f3",115:"f4",116:"f5",117:"f6",118:"f7",119:"f8",120:"f9",121:"f10",122:"f11",123:"f12"},Te.KEY_CODES_BY_NAME={},function(){for(var t in Te.KEY_NAMES_BY_CODE)Object.prototype.hasOwnProperty.call(Te.KEY_NAMES_BY_CODE,t)&&(Te.KEY_CODES_BY_NAME[Te.KEY_NAMES_BY_CODE[t]]=+t)}(),Te.MODIFIERS=["shift","ctrl","alt"],Te.registerEvent=document.addEventListener?function(t,e,i){t.addEventListener(e,i,!1)}:document.attachEvent?function(t,e,i){t.attachEvent("on"+e,i)}:void 0,Te.unregisterEvent=document.removeEventListener?function(t,e,i){t.removeEventListener(e,i,!1)}:document.detachEvent?function(t,e,i){t.detachEvent("on"+e,i)}:void 0,Te.stringContains=function(t,e){return-1!==t.indexOf(e)},Te.neatString=function(t){return t.replace(/^\s+|\s+$/g,"").replace(/\s+/g," ")},Te.capitalize=function(t){return t.toLowerCase().replace(/^./,function(t){return t.toUpperCase()})},Te.isString=function(t){return Te.stringContains(Object.prototype.toString.call(t),"String")},Te.arrayIncludes=Array.prototype.indexOf?function(t,e){return-1!==t.indexOf(e)}:function(t,e){for(var i=0;i<t.length;i++)if(t[i]===e)return!0;return!1},Te.extractModifiers=function(t){var e,i;for(e=[],i=0;i<Te.MODIFIERS.length;i++)Te.stringContains(t,Te.MODIFIERS[i])&&e.push(Te.MODIFIERS[i]);return e},Te.extractKey=function(t){var e,i;for(e=Te.neatString(t).split(" "),i=0;i<e.length;i++)if(!Te.arrayIncludes(Te.MODIFIERS,e[i]))return e[i]},Te.modifiersAndKey=function(t){var e,i;return Te.stringContains(t,"any")?Te.neatString(t).split(" ").slice(0,2).join(" "):(e=Te.extractModifiers(t),(i=Te.extractKey(t))&&!Te.arrayIncludes(Te.MODIFIERS,i)&&e.push(i),e.join(" "))},Te.keyName=function(t){return Te.KEY_NAMES_BY_CODE[t+""]},Te.keyCode=function(t){return+Te.KEY_CODES_BY_NAME[t]},Te.prototype.initialize=function(){var t,e=this;for(this.lastKeyCode=-1,this.lastModifiers={},t=0;t<Te.MODIFIERS.length;t++)this.lastModifiers[Te.MODIFIERS[t]]=!1;this.keysDown={any:[]},this.keysUp={any:[]},this.downHandler=this.handler("down"),this.upHandler=this.handler("up"),Te.registerEvent(this.element,"keydown",this.downHandler),Te.registerEvent(this.element,"keyup",this.upHandler);var i="object"===ce(window.onbeforeunload)?"beforeunload":"unload";Te.registerEvent(window,i,function t(){Te.unregisterEvent(e.element,"keydown",e.downHandler),Te.unregisterEvent(e.element,"keyup",e.upHandler),Te.unregisterEvent(window,i,t)})},Te.prototype.handler=function(t){var e=this;return function(i){var n,r,s;for(i=i||window.event,e.lastKeyCode=i.keyCode,n=0;n<Te.MODIFIERS.length;n++)e.lastModifiers[Te.MODIFIERS[n]]=i[Te.MODIFIERS[n]+"Key"];for(Te.arrayIncludes(Te.MODIFIERS,Te.keyName(e.lastKeyCode))&&(e.lastModifiers[Te.keyName(e.lastKeyCode)]=!0),r=e["keys"+Te.capitalize(t)],n=0;n<r.any.length;n++)!1===r.any[n](i)&&i.preventDefault&&i.preventDefault();if(r[s=e.lastModifiersAndKey()])for(n=0;n<r[s].length;n++)!1===r[s][n](i)&&i.preventDefault&&i.preventDefault()}},Te.prototype.registerKeys=function(t,e,i){var n,r,s=this["keys"+Te.capitalize(t)];for(Te.isString(e)&&(e=[e]),n=0;n<e.length;n++)r=e[n],s[r=Te.modifiersAndKey(r+"")]?s[r].push(i):s[r]=[i];return this},Te.prototype.unregisterKeys=function(t,e,i){var n,r,s,a=this["keys"+Te.capitalize(t)];for(Te.isString(e)&&(e=[e]),n=0;n<e.length;n++)if(s=e[n],s=Te.modifiersAndKey(s+""),null===i)delete a[s];else if(a[s])for(r=0;r<a[s].length;r++)if(String(a[s][r])===String(i)){a[s].splice(r,1);break}return this},Te.prototype.off=function(t){return this.unregisterKeys("down",t,null)},Te.prototype.delegate=function(t,e,i){return null!==i||void 0!==i?this.registerKeys(t,e,i):this.unregisterKeys(t,e,i)},Te.prototype.down=function(t,e){return this.delegate("down",t,e)},Te.prototype.up=function(t,e){return this.delegate("up",t,e)},Te.prototype.lastKey=function(t){return t?this.lastModifiers[t]:Te.keyName(this.lastKeyCode)},Te.prototype.lastModifiersAndKey=function(){var t,e;for(t=[],e=0;e<Te.MODIFIERS.length;e++)this.lastKey(Te.MODIFIERS[e])&&t.push(Te.MODIFIERS[e]);return Te.arrayIncludes(t,this.lastKey())||t.push(this.lastKey()),t.join(" ")};var be={Kibo:Te},Se='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">\n <path fill-rule="evenodd" clip-rule="evenodd" fill="#010101" d="M1.712 1.24h12.6v13.52h-12.6z"/>\n</svg>',ke='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">\n <path fill-rule="evenodd" clip-rule="evenodd" fill="#010101" d="M11.5 11h-.002v1.502L7.798 10H4.5V6h3.297l3.7-2.502V4.5h.003V11zM11 4.49L7.953 6.5H5v3h2.953L11 11.51V4.49z"/>\n</svg>',_e='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">\n <path fill="#010101" d="M7.156 8L4 11.156V8.5H3V13h4.5v-1H4.844L8 8.844 7.156 8zM8.5 3v1h2.657L8 7.157 8.846 8 12 4.844V7.5h1V3H8.5z"/>\n</svg>',Le=Z.Config,Ie=Z.Fullscreen,Re=Z.formatTime,Ce=Z.extend,Pe=Z.removeArrayItem,De=function(t){function e(t){var i;return te(this,e),(i=Jt(this,e,[t])).persistConfig=i.options.persistConfig,i._previousVolumeState=null,i.currentPositionValue=null,i.currentDurationValue=null,i.keepVisible=!1,i.fullScreenOnVideoTagSupported=null,i.setInitialVolume(),i.settings={left:["play","stop","pause"],right:["volume"],default:["position","seekbar","duration"]},i.kibo=new Te(i.options.focusElement),i.bindKeyEvents(),i.container?k.isEmptyObject(i.container.settings)||(i.settings=k.extend({},i.container.settings)):i.settings={},i.userDisabled=!1,(i.container&&i.container.mediaControlDisabled||i.options.chromeless)&&i.disable(),i.stopDragHandler=function(t){return i.stopDrag(t)},i.updateDragHandler=function(t){return i.updateDrag(t)},k(document).bind("mouseup",i.stopDragHandler),k(document).bind("mousemove",i.updateDragHandler),i}return re(e,t),ee(e,[{key:"name",get:function(){return"media_control"}},{key:"supportedVersion",get:function(){return{min:"0.16.2"}}},{key:"disabled",get:function(){var t=this.container&&this.container.getPlaybackType()===It.NO_OP;return this.userDisabled||t}},{key:"container",get:function(){return this.core&&this.core.activeContainer}},{key:"playback",get:function(){return this.core&&this.core.activePlayback}},{key:"attributes",get:function(){return{class:"media-control","data-media-control":""}}},{key:"events",get:function(){return{"click [data-play]":"play","click [data-pause]":"pause","click [data-playpause]":"togglePlayPause","click [data-stop]":"stop","click [data-playstop]":"togglePlayStop","click [data-fullscreen]":"toggleFullscreen","click .bar-container[data-seekbar]":"seek","click .bar-container[data-volume]":"onVolumeClick","click .drawer-icon[data-volume]":"toggleMute","mouseenter .drawer-container[data-volume]":"showVolumeBar","mouseleave .drawer-container[data-volume]":"hideVolumeBar","mousedown .bar-container[data-volume]":"startVolumeDrag","mousemove .bar-container[data-volume]":"mousemoveOnVolumeBar","mousedown .bar-scrubber[data-seekbar]":"startSeekDrag","mousemove .bar-container[data-seekbar]":"mousemoveOnSeekBar","mouseleave .bar-container[data-seekbar]":"mouseleaveOnSeekBar","mouseenter .media-control-layer[data-controls]":"setUserKeepVisible","mouseleave .media-control-layer[data-controls]":"resetUserKeepVisible"}}},{key:"template",get:function(){return At('<div class="media-control-background" data-background></div>\n<div class="media-control-layer" data-controls>\n <% var renderBar = function(name) { %>\n <div class="bar-container" data-<%= name %>>\n <div class="bar-background" data-<%= name %>>\n <div class="bar-fill-1" data-<%= name %>></div>\n <div class="bar-fill-2" data-<%= name %>></div>\n <div class="bar-hover" data-<%= name %>></div>\n </div>\n <div class="bar-scrubber" data-<%= name %>>\n <div class="bar-scrubber-icon" data-<%= name %>></div>\n </div>\n </div>\n <% }; %>\n <% var renderSegmentedBar = function(name, segments) {\n segments = segments || 10; %>\n <div class="bar-container" data-<%= name %>>\n <% for (var i = 0; i < segments; i++) { %>\n <div class="segmented-bar-element" data-<%= name %>></div>\n <% } %>\n </div>\n <% }; %>\n <% var renderDrawer = function(name, renderContent) { %>\n <div class="drawer-container" data-<%= name %>>\n <div class="drawer-icon-container" data-<%= name %>>\n <div class="drawer-icon media-control-icon" data-<%= name %>></div>\n <span class="drawer-text" data-<%= name %>></span>\n </div>\n <% renderContent(name); %>\n </div>\n <% }; %>\n <% var renderIndicator = function(name) { %>\n <div class="media-control-indicator" data-<%= name %>></div>\n <% }; %>\n <% var renderButton = function(name) { %>\n <button type="button" class="media-control-button media-control-icon" data-<%= name %> aria-label="<%= name %>"></button>\n <% }; %>\n <% var templates = {\n bar: renderBar,\n segmentedBar: renderSegmentedBar,\n };\n var render = function(settingsList) {\n settingsList.forEach(function(setting) {\n if(setting === "seekbar") {\n renderBar(setting);\n } else if (setting === "volume") {\n renderDrawer(setting, settings.volumeBarTemplate ? templates[settings.volumeBarTemplate] : function(name) { return renderSegmentedBar(name); });\n } else if (setting === "duration" || setting === "position") {\n renderIndicator(setting);\n } else {\n renderButton(setting);\n }\n });\n }; %>\n <% if (settings.default && settings.default.length) { %>\n <div class="media-control-center-panel" data-media-control>\n <% render(settings.default); %>\n </div>\n <% } %>\n <% if (settings.left && settings.left.length) { %>\n <div class="media-control-left-panel" data-media-control>\n <% render(settings.left); %>\n </div>\n <% } %>\n <% if (settings.right && settings.right.length) { %>\n <div class="media-control-right-panel" data-media-control>\n <% render(settings.right); %>\n </div>\n <% } %>\n</div>\n')}},{key:"volume",get:function(){return this.container&&this.container.isReady?this.container.volume:this.intendedVolume}},{key:"muted",get:function(){return 0===this.volume}},{key:"getExternalInterface",value:function(){var t=this;return{setVolume:this.setVolume,getVolume:function(){return t.volume}}}},{key:"bindEvents",value:function(){var t=this;this.stopListening(),this.listenTo(this.core,ht.CORE_ACTIVE_CONTAINER_CHANGED,this.onActiveContainerChanged),this.listenTo(this.core,ht.CORE_MOUSE_MOVE,this.show),this.listenTo(this.core,ht.CORE_MOUSE_LEAVE,function(){return t.hide(t.options.hideMediaControlDelay)}),this.listenTo(this.core,ht.CORE_FULLSCREEN,this.show),this.listenTo(this.core,ht.CORE_OPTIONS_CHANGE,this.configure),this.listenTo(this.core,ht.CORE_RESIZE,this.playerResize),this.bindContainerEvents()}},{key:"bindContainerEvents",value:function(){this.container&&(this.listenTo(this.container,ht.CONTAINER_PLAY,this.changeTogglePlay),this.listenTo(this.container,ht.CONTAINER_PAUSE,this.changeTogglePlay),this.listenTo(this.container,ht.CONTAINER_STOP,this.changeTogglePlay),this.listenTo(this.container,ht.CONTAINER_DBLCLICK,this.toggleFullscreen),this.listenTo(this.container,ht.CONTAINER_TIMEUPDATE,this.onTimeUpdate),this.listenTo(this.container,ht.CONTAINER_PROGRESS,this.updateProgressBar),this.listenTo(this.container,ht.CONTAINER_SETTINGSUPDATE,this.settingsUpdate),this.listenTo(this.container,ht.CONTAINER_PLAYBACKDVRSTATECHANGED,this.settingsUpdate),this.listenTo(this.container,ht.CONTAINER_HIGHDEFINITIONUPDATE,this.highDefinitionUpdate),this.listenTo(this.container,ht.CONTAINER_MEDIACONTROL_DISABLE,this.disable),this.listenTo(this.container,ht.CONTAINER_MEDIACONTROL_ENABLE,this.enable),this.listenTo(this.container,ht.CONTAINER_ENDED,this.ended),this.listenTo(this.container,ht.CONTAINER_VOLUME,this.onVolumeChanged),this.listenTo(this.container,ht.CONTAINER_OPTIONS_CHANGE,this.setInitialVolume),"video"===this.container.playback.el.nodeName.toLowerCase()&&this.listenToOnce(this.container,ht.CONTAINER_LOADEDMETADATA,this.onLoadedMetadataOnVideoTag))}},{key:"disable",value:function(){this.userDisabled=!0,this.hide(),this.unbindKeyEvents(),this.$el.hide()}},{key:"enable",value:function(){this.options.chromeless||(this.userDisabled=!1,this.bindKeyEvents(),this.show())}},{key:"play",value:function(){this.container&&this.container.play()}},{key:"pause",value:function(){this.container&&this.container.pause()}},{key:"stop",value:function(){this.container&&this.container.stop()}},{key:"setInitialVolume",value:function(){this._previousVolumeState=null;var t=this.persistConfig?Le.restore("volume"):100,e=this.container&&this.container.options||this.options;this.setVolume(e.mute?0:t,!0)}},{key:"onVolumeChanged",value:function(){this.updateVolumeUI()}},{key:"onLoadedMetadataOnVideoTag",value:function(){var t=this.playback&&this.playback.el;!Ie.fullscreenEnabled()&&t.webkitSupportsFullscreen&&(this.fullScreenOnVideoTagSupported=!0,this.settingsUpdate())}},{key:"updateVolumeUI",value:function(){if(this.rendered){this.$volumeBarContainer.find(".bar-fill-2").css({});var t=this.$volumeBarContainer.width(),e=this.$volumeBarBackground.width(),i=(t-e)/2,n=e*this.volume/100+i;this.$volumeBarFill.css({width:"".concat(this.volume,"%")}),this.$volumeBarScrubber.css({left:n}),this.$volumeBarContainer.find(".segmented-bar-element").removeClass("fill");var r=Math.ceil(this.volume/10);this.$volumeBarContainer.find(".segmented-bar-element").slice(0,r).addClass("fill"),this.$volumeIcon.html(""),this.$volumeIcon.removeClass("muted"),this.muted?(this.$volumeIcon.append('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">\n <path fill-rule="evenodd" clip-rule="evenodd" fill="#010101" d="M9.75 11.51L6.7 9.5H3.75v-3H6.7L9.75 4.49v.664l.497.498V3.498L6.547 6H3.248v4h3.296l3.7 2.502v-2.154l-.497.5v.662zm3-5.165L12.404 6l-1.655 1.653L9.093 6l-.346.345L10.402 8 8.747 9.654l.346.347 1.655-1.653L12.403 10l.348-.346L11.097 8l1.655-1.655z"/>\n</svg>'),this.$volumeIcon.addClass("muted")):this.$volumeIcon.append(ke),this.applyButtonStyle(this.$volumeIcon)}}},{key:"changeTogglePlay",value:function(){this.$playPauseToggle.html(""),this.$playStopToggle.html(""),this.container&&this.container.isPlaying()?(this.$playPauseToggle.append(ve),this.$playStopToggle.append(Se),this.trigger(ht.MEDIACONTROL_PLAYING)):(this.$playPauseToggle.append(me),this.$playStopToggle.append(me),this.trigger(ht.MEDIACONTROL_NOTPLAYING),D.isMobile&&this.show()),this.applyButtonStyle(this.$playPauseToggle),this.applyButtonStyle(this.$playStopToggle)}},{key:"mousemoveOnSeekBar",value:function(t){if(this.settings.seekEnabled){var e=t.pageX-this.$seekBarContainer.offset().left-this.$seekBarHover.width()/2;this.$seekBarHover.css({left:e})}this.trigger(ht.MEDIACONTROL_MOUSEMOVE_SEEKBAR,t)}},{key:"mouseleaveOnSeekBar",value:function(t){this.trigger(ht.MEDIACONTROL_MOUSELEAVE_SEEKBAR,t)}},{key:"onVolumeClick",value:function(t){this.setVolume(this.getVolumeFromUIEvent(t))}},{key:"mousemoveOnVolumeBar",value:function(t){this.draggingVolumeBar&&this.setVolume(this.getVolumeFromUIEvent(t))}},{key:"playerResize",value:function(t){this.$fullscreenToggle.html("");var e=this.core.isFullscreen()?'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">\n <path fill="#010101" d="M13.5 3.344l-.844-.844L9.5 5.656V3h-1v4.5H13v-1h-2.656L13.5 3.344zM3 9.5h2.656L2.5 12.656l.844.844L6.5 10.344V13h1V8.5H3v1z"/>\n</svg>':_e;this.$fullscreenToggle.append(e),this.applyButtonStyle(this.$fullscreenToggle),0!==this.$el.find(".media-control").length&&this.$el.removeClass("w320"),(t.width<=320||this.options.hideVolumeBar)&&this.$el.addClass("w320")}},{key:"togglePlayPause",value:function(){return this.container.isPlaying()?this.container.pause():this.container.play(),!1}},{key:"togglePlayStop",value:function(){this.container.isPlaying()?this.container.stop():this.container.play()}},{key:"startSeekDrag",value:function(t){this.settings.seekEnabled&&(this.draggingSeekBar=!0,this.$el.addClass("dragging"),this.$seekBarLoaded.addClass("media-control-notransition"),this.$seekBarPosition.addClass("media-control-notransition"),this.$seekBarScrubber.addClass("media-control-notransition"),t&&t.preventDefault())}},{key:"startVolumeDrag",value:function(t){this.draggingVolumeBar=!0,this.$el.addClass("dragging"),t&&t.preventDefault()}},{key:"stopDrag",value:function(t){this.draggingSeekBar&&this.seek(t),this.$el.removeClass("dragging"),this.$seekBarLoaded.removeClass("media-control-notransition"),this.$seekBarPosition.removeClass("media-control-notransition"),this.$seekBarScrubber.removeClass("media-control-notransition dragging"),this.draggingSeekBar=!1,this.draggingVolumeBar=!1}},{key:"updateDrag",value:function(t){if(this.draggingSeekBar){t.preventDefault();var e=(t.pageX-this.$seekBarContainer.offset().left)/this.$seekBarContainer.width()*100;e=Math.min(100,Math.max(e,0)),this.setSeekPercentage(e)}else this.draggingVolumeBar&&(t.preventDefault(),this.setVolume(this.getVolumeFromUIEvent(t)))}},{key:"getVolumeFromUIEvent",value:function(t){return(t.pageX-this.$volumeBarContainer.offset().left)/this.$volumeBarContainer.width()*100}},{key:"toggleMute",value:function(){if(this.muted){var t=this._previousVolumeState;this._previousVolumeState=null;var e=null!=t&&t>0?t:100;this.setVolume(e)}else{var i=this.volume;this._previousVolumeState=i>0?i:null,this.setVolume(0)}}},{key:"setVolume",value:function(t){var e=this,i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];t=Math.min(100,Math.max(t,0)),this.intendedVolume=t,this.persistConfig&&!i&&Le.persist("volume",t);var n=function(){e.container&&e.container.isReady?e.container.setVolume(t):e.listenToOnce(e.container,ht.CONTAINER_READY,function(){e.container.setVolume(t)})};this.container?n():this.listenToOnce(this,ht.MEDIACONTROL_CONTAINERCHANGED,function(){return n()})}},{key:"toggleFullscreen",value:function(){this.trigger(ht.MEDIACONTROL_FULLSCREEN,this.name),this.container.fullscreen(),this.core.toggleFullscreen(),this.resetUserKeepVisible()}},{key:"onActiveContainerChanged",value:function(){this.fullScreenOnVideoTagSupported=null,this.bindEvents(),this.setInitialVolume(),this.changeTogglePlay(),this.bindContainerEvents(),this.settingsUpdate(),this.container&&this.container.trigger(ht.CONTAINER_PLAYBACKDVRSTATECHANGED,this.container.isDvrInUse()),this.container&&this.container.mediaControlDisabled&&this.disable(),this.trigger(ht.MEDIACONTROL_CONTAINERCHANGED)}},{key:"showVolumeBar",value:function(){this.hideVolumeId&&clearTimeout(this.hideVolumeId),this.$volumeBarContainer.removeClass("volume-bar-hide")}},{key:"hideVolumeBar",value:function(){var t=this,e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:400;this.$volumeBarContainer&&(this.draggingVolumeBar?this.hideVolumeId=setTimeout(function(){return t.hideVolumeBar()},e):(this.hideVolumeId&&clearTimeout(this.hideVolumeId),this.hideVolumeId=setTimeout(function(){return t.$volumeBarContainer.addClass("volume-bar-hide")},e)))}},{key:"ended",value:function(){this.changeTogglePlay()}},{key:"updateProgressBar",value:function(t){var e=t.start/t.total*100,i=t.current/t.total*100;this.$seekBarLoaded.css({left:"".concat(e,"%"),width:"".concat(i-e,"%")})}},{key:"onTimeUpdate",value:function(t){if(!this.draggingSeekBar){var e=t.current<0?t.total:t.current;this.currentPositionValue=e,this.currentDurationValue=t.total,this.renderSeekBar()}}},{key:"renderSeekBar",value:function(){if(null!==this.currentPositionValue&&null!==this.currentDurationValue){this.currentSeekBarPercentage=100,this.container&&(this.container.getPlaybackType()!==It.LIVE||this.container.isDvrInUse())&&(this.currentSeekBarPercentage=this.currentPositionValue/this.currentDurationValue*100),this.setSeekPercentage(this.currentSeekBarPercentage);var t=Re(this.currentPositionValue),e=Re(this.currentDurationValue);t!==this.displayedPosition&&(this.$position.text(t),this.displayedPosition=t),e!==this.displayedDuration&&(this.$duration.text(e),this.displayedDuration=e)}}},{key:"seek",value:function(t){if(this.settings.seekEnabled){var e=(t.pageX-this.$seekBarContainer.offset().left)/this.$seekBarContainer.width()*100;return e=Math.min(100,Math.max(e,0)),this.container&&this.container.seekPercentage(e),this.setSeekPercentage(e),!1}}},{key:"setKeepVisible",value:function(){this.keepVisible=!0}},{key:"resetKeepVisible",value:function(){this.keepVisible=!1}},{key:"setUserKeepVisible",value:function(){this.userKeepVisible=!0}},{key:"resetUserKeepVisible",value:function(){this.userKeepVisible=!1}},{key:"isVisible",value:function(){return!this.$el.hasClass("media-control-hide")}},{key:"show",value:function(t){var e=this;if(!this.disabled){var i=t&&t.clientX!==this.lastMouseX&&t.clientY!==this.lastMouseY;(!t||i||navigator.userAgent.match(/firefox/i))&&(clearTimeout(this.hideId),this.$el.show(),this.trigger(ht.MEDIACONTROL_SHOW,this.name),this.container&&this.container.trigger(ht.CONTAINER_MEDIACONTROL_SHOW,this.name),this.$el.removeClass("media-control-hide"),this.hideId=setTimeout(function(){return e.hide()},2e3),t&&(this.lastMouseX=t.clientX,this.lastMouseY=t.clientY));this.updateCursorStyle(!0)}}},{key:"hide",value:function(){var t=this,e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;if(this.isVisible()){var i=e||2e3;if(clearTimeout(this.hideId),this.disabled||!1!==this.options.hideMediaControl){var n=this.userKeepVisible||this.keepVisible,r=this.draggingSeekBar||this.draggingVolumeBar;if(!this.disabled&&(e||n||r))this.hideId=setTimeout(function(){return t.hide()},i);else{this.trigger(ht.MEDIACONTROL_HIDE,this.name),this.container&&this.container.trigger(ht.CONTAINER_MEDIACONTROL_HIDE,this.name),this.$el.addClass("media-control-hide"),this.hideVolumeBar(0);this.updateCursorStyle(!1)}}}}},{key:"updateCursorStyle",value:function(t){t?this.core.$el.removeClass("nocursor"):this.core.isFullscreen()&&this.core.$el.addClass("nocursor")}},{key:"settingsUpdate",value:function(){var t=this.getSettings();!t||this.fullScreenOnVideoTagSupported||Ie.fullscreenEnabled()||(t.default&&Pe(t.default,"fullscreen"),t.left&&Pe(t.left,"fullscreen"),t.right&&Pe(t.right,"fullscreen")),JSON.stringify(this.settings)!==JSON.stringify(t)&&(this.settings=t,this.render())}},{key:"getSettings",value:function(){return k.extend(!0,{},this.container&&this.container.settings)}},{key:"highDefinitionUpdate",value:function(t){this.isHD=t;var e=t?"addClass":"removeClass";this.$hdIndicator[e]("enabled")}},{key:"createCachedElements",value:function(){var t=this.$el.find(".media-control-layer");this.$duration=t.find(".media-control-indicator[data-duration]"),this.$fullscreenToggle=t.find("button.media-control-button[data-fullscreen]"),this.$playPauseToggle=t.find("button.media-control-button[data-playpause]"),this.$playStopToggle=t.find("button.media-control-button[data-playstop]"),this.$position=t.find(".media-control-indicator[data-position]"),this.$seekBarContainer=t.find(".bar-container[data-seekbar]"),this.$seekBarHover=t.find(".bar-hover[data-seekbar]"),this.$seekBarLoaded=t.find(".bar-fill-1[data-seekbar]"),this.$seekBarPosition=t.find(".bar-fill-2[data-seekbar]"),this.$seekBarScrubber=t.find(".bar-scrubber[data-seekbar]"),this.$volumeBarContainer=t.find(".bar-container[data-volume]"),this.$volumeContainer=t.find(".drawer-container[data-volume]"),this.$volumeIcon=t.find(".drawer-icon[data-volume]"),this.$volumeBarBackground=this.$el.find(".bar-background[data-volume]"),this.$volumeBarFill=this.$el.find(".bar-fill-1[data-volume]"),this.$volumeBarScrubber=this.$el.find(".bar-scrubber[data-volume]"),this.$hdIndicator=this.$el.find("button.media-control-button[data-hd-indicator]"),this.resetIndicators(),this.initializeIcons()}},{key:"resetIndicators",value:function(){this.displayedPosition=this.$position.text(),this.displayedDuration=this.$duration.text()}},{key:"initializeIcons",value:function(){var t=this.$el.find(".media-control-layer");t.find("button.media-control-button[data-play]").append(me),t.find("button.media-control-button[data-pause]").append(ve),t.find("button.media-control-button[data-stop]").append(Se),this.$playPauseToggle.append(me),this.$playStopToggle.append(me),this.$volumeIcon.append(ke),this.$fullscreenToggle.append(_e),this.$hdIndicator.append('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">\n <path fill="#010101" d="M5.375 7.062H2.637V4.26H.502v7.488h2.135V8.9h2.738v2.848h2.133V4.26H5.375v2.802zm5.97-2.81h-2.84v7.496h2.798c2.65 0 4.195-1.607 4.195-3.77v-.022c0-2.162-1.523-3.704-4.154-3.704zm2.06 3.758c0 1.21-.81 1.896-2.03 1.896h-.83V6.093h.83c1.22 0 2.03.696 2.03 1.896v.02z"/>\n</svg>')}},{key:"setSeekPercentage",value:function(t){t=Math.max(Math.min(t,100),0),this.displayedSeekBarPercentage!==t&&(this.displayedSeekBarPercentage=t,this.$seekBarPosition.removeClass("media-control-notransition"),this.$seekBarScrubber.removeClass("media-control-notransition"),this.$seekBarPosition.css({width:"".concat(t,"%")}),this.$seekBarScrubber.css({left:"".concat(t,"%")}))}},{key:"seekRelative",value:function(t){if(this.settings.seekEnabled){var e=this.container.getCurrentTime(),i=this.container.getDuration(),n=Math.min(Math.max(e+t,0),i);n=Math.min(100*n/i,100),this.container.seekPercentage(n)}}},{key:"bindKeyAndShow",value:function(t,e){var i=this;this.kibo.down(t,function(){return i.show(),e()})}},{key:"bindKeyEvents",value:function(){var t=this;if(!D.isMobile&&!this.options.disableKeyboardShortcuts){this.unbindKeyEvents(),this.kibo=new Te(this.options.focusElement||this.options.parentElement),this.bindKeyAndShow("space",function(){return t.togglePlayPause()}),this.bindKeyAndShow("left",function(){return t.seekRelative(-5)}),this.bindKeyAndShow("right",function(){return t.seekRelative(5)}),this.bindKeyAndShow("shift left",function(){return t.seekRelative(-10)}),this.bindKeyAndShow("shift right",function(){return t.seekRelative(10)}),this.bindKeyAndShow("shift ctrl left",function(){return t.seekRelative(-15)}),this.bindKeyAndShow("shift ctrl right",function(){return t.seekRelative(15)});["1","2","3","4","5","6","7","8","9","0"].forEach(function(e){t.bindKeyAndShow(e,function(){t.settings.seekEnabled&&t.container&&t.container.seekPercentage(10*e)})})}}},{key:"unbindKeyEvents",value:function(){this.kibo&&(this.kibo.off("space"),this.kibo.off("left"),this.kibo.off("right"),this.kibo.off("shift left"),this.kibo.off("shift right"),this.kibo.off("shift ctrl left"),this.kibo.off("shift ctrl right"),this.kibo.off(["1","2","3","4","5","6","7","8","9","0"]))}},{key:"parseColors",value:function(){if(this.options.mediacontrol){this.buttonsColor=this.options.mediacontrol.buttons;var t=this.options.mediacontrol.seekbar;this.$el.find(".bar-fill-2[data-seekbar]").css("background-color",t),this.$el.find(".media-control-icon svg path").css("fill",this.buttonsColor),this.$el.find(".segmented-bar-element[data-volume]").css("boxShadow","inset 2px 0 0 "+this.buttonsColor)}}},{key:"applyButtonStyle",value:function(t){this.buttonsColor&&t&&k(t).find("svg path").css("fill",this.buttonsColor)}},{key:"destroy",value:function(){k(document).unbind("mouseup",this.stopDragHandler),k(document).unbind("mousemove",this.updateDragHandler),this.unbindKeyEvents(),this.stopListening(),le(e,"destroy",this)([])}},{key:"configure",value:function(t){this.options.chromeless||t.source||t.sources?this.disable():this.enable(),this.trigger(ht.MEDIACONTROL_OPTIONS_CHANGE)}},{key:"render",value:function(){var t=this,e=this.options.hideMediaControlDelay||2e3;this.settings&&this.$el.html(this.template({settings:this.settings}));var i=Et.getStyleFor('.media-control-notransition {\n -webkit-transition: none !important;\n transition: none !important;\n}\n\n.media-control[data-media-control] {\n position: absolute;\n width: 100%;\n height: 100%;\n z-index: 9999;\n pointer-events: none;\n}\n.media-control[data-media-control].dragging {\n pointer-events: auto;\n cursor: -webkit-grabbing !important;\n cursor: grabbing !important;\n cursor: url("closed-hand.cur"), move;\n}\n.media-control[data-media-control].dragging * {\n cursor: -webkit-grabbing !important;\n cursor: grabbing !important;\n cursor: url("closed-hand.cur"), move;\n}\n.media-control[data-media-control] .media-control-background[data-background] {\n position: absolute;\n height: 40%;\n width: 100%;\n bottom: 0;\n background: -webkit-gradient(linear, left top, left bottom, from(transparent), to(rgba(0, 0, 0, 0.9)));\n background: linear-gradient(transparent, rgba(0, 0, 0, 0.9));\n will-change: transform, opacity;\n -webkit-transition: opacity 0.6s ease-out;\n transition: opacity 0.6s ease-out;\n}\n.media-control[data-media-control] .media-control-icon {\n line-height: 0;\n letter-spacing: 0;\n speak: none;\n color: #fff;\n opacity: 0.5;\n vertical-align: middle;\n text-align: left;\n -webkit-transition: all 0.1s ease;\n transition: all 0.1s ease;\n}\n.media-control[data-media-control] .media-control-icon:hover {\n color: white;\n opacity: 0.75;\n text-shadow: rgba(255, 255, 255, 0.8) 0 0 5px;\n}\n.media-control[data-media-control].media-control-hide .media-control-background[data-background] {\n opacity: 0;\n}\n.media-control[data-media-control].media-control-hide .media-control-layer[data-controls] {\n -webkit-transform: translateY(50px);\n transform: translateY(50px);\n}\n.media-control[data-media-control].media-control-hide .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar] {\n opacity: 0;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] {\n position: absolute;\n -webkit-transform: translateY(-7px);\n transform: translateY(-7px);\n bottom: 0;\n width: 100%;\n height: 32px;\n font-size: 0;\n vertical-align: middle;\n pointer-events: auto;\n -webkit-transition: bottom 0.4s ease-out;\n transition: bottom 0.4s ease-out;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .media-control-left-panel[data-media-control] {\n position: absolute;\n top: 0;\n left: 4px;\n height: 100%;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .media-control-center-panel[data-media-control] {\n height: 100%;\n text-align: center;\n line-height: 32px;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .media-control-right-panel[data-media-control] {\n position: absolute;\n top: 0;\n right: 4px;\n height: 100%;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button {\n background-color: transparent;\n border: 0;\n margin: 0 6px;\n padding: 0;\n cursor: pointer;\n display: inline-block;\n width: 32px;\n height: 100%;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button svg {\n width: 100%;\n height: 22px;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button svg path {\n fill: white;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button:focus {\n outline: none;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-play] {\n float: left;\n height: 100%;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-pause] {\n float: left;\n height: 100%;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-stop] {\n float: left;\n height: 100%;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-fullscreen] {\n float: right;\n background-color: transparent;\n border: 0;\n height: 100%;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator] {\n background-color: transparent;\n border: 0;\n cursor: default;\n display: none;\n float: right;\n height: 100%;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator].enabled {\n display: block;\n opacity: 1;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator].enabled:hover {\n opacity: 1;\n text-shadow: none;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause] {\n float: left;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop] {\n float: left;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-position], .media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration] {\n display: inline-block;\n font-size: 10px;\n color: white;\n cursor: default;\n line-height: 32px;\n position: relative;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-position] {\n margin: 0 6px 0 7px;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration]:before {\n content: "|";\n margin-right: 7px;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration] {\n color: rgba(255, 255, 255, 0.5);\n margin-right: 6px;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] {\n position: absolute;\n top: -20px;\n left: 0;\n display: inline-block;\n vertical-align: middle;\n width: 100%;\n height: 25px;\n cursor: pointer;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] {\n width: 100%;\n height: 1px;\n position: relative;\n top: 12px;\n background-color: #666666;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-1[data-seekbar] {\n position: absolute;\n top: 0;\n left: 0;\n width: 0;\n height: 100%;\n background-color: #c2c2c2;\n -webkit-transition: all 0.1s ease-out;\n transition: all 0.1s ease-out;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar] {\n position: absolute;\n top: 0;\n left: 0;\n width: 0;\n height: 100%;\n background-color: #005aff;\n -webkit-transition: all 0.1s ease-out;\n transition: all 0.1s ease-out;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-hover[data-seekbar] {\n opacity: 0;\n position: absolute;\n top: -3px;\n width: 5px;\n height: 7px;\n background-color: rgba(255, 255, 255, 0.5);\n -webkit-transition: opacity 0.1s ease;\n transition: opacity 0.1s ease;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar]:hover .bar-background[data-seekbar] .bar-hover[data-seekbar] {\n opacity: 1;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar].seek-disabled {\n cursor: default;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar].seek-disabled:hover .bar-background[data-seekbar] .bar-hover[data-seekbar] {\n opacity: 0;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar] {\n position: absolute;\n -webkit-transform: translateX(-50%);\n transform: translateX(-50%);\n top: 2px;\n left: 0;\n width: 20px;\n height: 20px;\n opacity: 1;\n -webkit-transition: all 0.1s ease-out;\n transition: all 0.1s ease-out;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar] .bar-scrubber-icon[data-seekbar] {\n position: absolute;\n left: 6px;\n top: 6px;\n width: 8px;\n height: 8px;\n border-radius: 10px;\n -webkit-box-shadow: 0 0 0 6px rgba(255, 255, 255, 0.2);\n box-shadow: 0 0 0 6px rgba(255, 255, 255, 0.2);\n background-color: white;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] {\n float: right;\n display: inline-block;\n height: 32px;\n cursor: pointer;\n margin: 0 6px;\n -webkit-box-sizing: border-box;\n box-sizing: border-box;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] {\n float: left;\n bottom: 0;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume] {\n background-color: transparent;\n border: 0;\n -webkit-box-sizing: content-box;\n box-sizing: content-box;\n width: 32px;\n height: 32px;\n opacity: 0.5;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume]:hover {\n opacity: 0.75;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume] svg {\n height: 24px;\n position: relative;\n top: 3px;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume] svg path {\n fill: white;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume].muted svg {\n margin-left: 2px;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] {\n float: left;\n position: relative;\n overflow: hidden;\n top: 6px;\n width: 42px;\n height: 18px;\n padding: 3px 0;\n -webkit-transition: width 0.2s ease-out;\n transition: width 0.2s ease-out;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-background[data-volume] {\n height: 1px;\n position: relative;\n top: 7px;\n margin: 0 3px;\n background-color: #666666;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-background[data-volume] .bar-fill-1[data-volume] {\n position: absolute;\n top: 0;\n left: 0;\n width: 0;\n height: 100%;\n background-color: #c2c2c2;\n -webkit-transition: all 0.1s ease-out;\n transition: all 0.1s ease-out;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-background[data-volume] .bar-fill-2[data-volume] {\n position: absolute;\n top: 0;\n left: 0;\n width: 0;\n height: 100%;\n background-color: #005aff;\n -webkit-transition: all 0.1s ease-out;\n transition: all 0.1s ease-out;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-background[data-volume] .bar-hover[data-volume] {\n opacity: 0;\n position: absolute;\n top: -3px;\n width: 5px;\n height: 7px;\n background-color: rgba(255, 255, 255, 0.5);\n -webkit-transition: opacity 0.1s ease;\n transition: opacity 0.1s ease;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-scrubber[data-volume] {\n position: absolute;\n -webkit-transform: translateX(-50%);\n transform: translateX(-50%);\n top: 0px;\n left: 0;\n width: 20px;\n height: 20px;\n opacity: 1;\n -webkit-transition: all 0.1s ease-out;\n transition: all 0.1s ease-out;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-scrubber[data-volume] .bar-scrubber-icon[data-volume] {\n position: absolute;\n left: 6px;\n top: 6px;\n width: 8px;\n height: 8px;\n border-radius: 10px;\n -webkit-box-shadow: 0 0 0 6px rgba(255, 255, 255, 0.2);\n box-shadow: 0 0 0 6px rgba(255, 255, 255, 0.2);\n background-color: white;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .segmented-bar-element[data-volume] {\n float: left;\n width: 4px;\n padding-left: 2px;\n height: 12px;\n opacity: 0.5;\n -webkit-box-shadow: inset 2px 0 0 white;\n box-shadow: inset 2px 0 0 white;\n -webkit-transition: -webkit-transform 0.2s ease-out;\n transition: -webkit-transform 0.2s ease-out;\n transition: transform 0.2s ease-out;\n transition: transform 0.2s ease-out, -webkit-transform 0.2s ease-out;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .segmented-bar-element[data-volume].fill {\n -webkit-box-shadow: inset 2px 0 0 #fff;\n box-shadow: inset 2px 0 0 #fff;\n opacity: 1;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .segmented-bar-element[data-volume]:nth-of-type(1) {\n padding-left: 0;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .segmented-bar-element[data-volume]:hover {\n -webkit-transform: scaleY(1.5);\n transform: scaleY(1.5);\n}\n.media-control[data-media-control].w320 .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume].volume-bar-hide {\n width: 0;\n height: 12px;\n top: 9px;\n padding: 0;\n}',{baseUrl:this.options.baseUrl});this.$el.append(i[0]),this.createCachedElements(),this.$playPauseToggle.addClass("paused"),this.$playStopToggle.addClass("stopped"),this.changeTogglePlay(),this.container&&(this.hideId=setTimeout(function(){return t.hide()},e),this.disabled&&this.hide()),D.isSafari&&D.isMobile&&(D.version<10?this.$volumeContainer.css("display","none"):this.$volumeBarContainer.css("display","none")),this.$seekBarPosition.addClass("media-control-notransition"),this.$seekBarScrubber.addClass("media-control-notransition");var n=0;return this.displayedSeekBarPercentage&&(n=this.displayedSeekBarPercentage),this.displayedSeekBarPercentage=null,this.setSeekPercentage(n),setTimeout(function(){!t.settings.seekEnabled&&t.$seekBarContainer.addClass("seek-disabled"),!D.isMobile&&!t.options.disableKeyboardShortcuts&&t.bindKeyEvents(),t.playerResize({width:t.options.width,height:t.options.height}),t.hideVolumeBar(0)},0),this.parseColors(),this.highDefinitionUpdate(this.isHD),this.core.$el.append(this.el),this.rendered=!0,this.updateVolumeUI(),this.trigger(ht.MEDIACONTROL_RENDERED),this}}])}(_t);De.extend=function(t){return Ce(De,t)};for(var we=function(t){function e(t){var i;return te(this,e),(i=Jt(this,e,[t])).hasStartedPlaying=!1,i.playRequested=!1,i.render(),setTimeout(function(){return i.update()},0),i}return re(e,t),ee(e,[{key:"name",get:function(){return"poster"}},{key:"supportedVersion",get:function(){return{min:"0.16.2"}}},{key:"template",get:function(){return At('<div class="play-wrapper" data-poster></div>\n')}},{key:"shouldRender",get:function(){var t=!(!this.options.poster||!this.options.poster.showForNoOp);return"html_img"!==this.container.playback.name&&(this.container.playback.getPlaybackType()!==It.NO_OP||t)}},{key:"attributes",get:function(){return{class:"player-poster","data-poster":""}}},{key:"events",get:function(){return{click:"clicked"}}},{key:"showOnVideoEnd",get:function(){return!this.options.poster||this.options.poster.showOnVideoEnd||void 0===this.options.poster.showOnVideoEnd}},{key:"bindEvents",value:function(){this.listenTo(this.container,ht.CONTAINER_STOP,this.onStop),this.listenTo(this.container,ht.CONTAINER_PLAY,this.onPlay),this.listenTo(this.container,ht.CONTAINER_STATE_BUFFERING,this.update),this.listenTo(this.container,ht.CONTAINER_STATE_BUFFERFULL,this.update),this.listenTo(this.container,ht.CONTAINER_OPTIONS_CHANGE,this.render),this.listenTo(this.container,ht.CONTAINER_ERROR,this.onError),this.showOnVideoEnd&&this.listenTo(this.container,ht.CONTAINER_ENDED,this.onStop)}},{key:"onError",value:function(t){this.hasFatalError=t.level===St.Levels.FATAL,this.hasFatalError&&(this.hasStartedPlaying=!1,this.playRequested=!1,this.showPlayButton())}},{key:"onPlay",value:function(){this.hasStartedPlaying=!0,this.update()}},{key:"onStop",value:function(){this.hasStartedPlaying=!1,this.playRequested=!1,this.update()}},{key:"updatePlayButton",value:function(t){!t||this.options.chromeless&&!this.options.allowUserInteraction?this.hidePlayButton():this.showPlayButton()}},{key:"showPlayButton",value:function(){this.hasFatalError&&!this.options.disableErrorScreen||(this.$playButton.show(),this.$el.addClass("clickable"))}},{key:"hidePlayButton",value:function(){this.$playButton.hide(),this.$el.removeClass("clickable")}},{key:"clicked",value:function(){if(!this.hasStartedPlaying)return this.options.chromeless&&!this.options.allowUserInteraction||(this.playRequested=!0,this.update(),this.container.playback&&(this.container.playback._consented=!0),this.container.play()),!1}},{key:"shouldHideOnPlay",value:function(){return!this.container.playback.isAudioOnly}},{key:"update",value:function(){if(this.shouldRender){var t=!this.playRequested&&!this.hasStartedPlaying&&!this.container.buffering;this.updatePlayButton(t),this.updatePoster()}}},{key:"updatePoster",value:function(){this.hasStartedPlaying?this.hidePoster():this.showPoster()}},{key:"showPoster",value:function(){this.container.disableMediaControl(),this.$el.show()}},{key:"hidePoster",value:function(){this.container.enableMediaControl(),this.shouldHideOnPlay()&&this.$el.hide()}},{key:"render",value:function(){if(this.shouldRender){var t=Et.getStyleFor(".player-poster[data-poster] {\n display: -webkit-box;\n display: -ms-flexbox;\n display: flex;\n -webkit-box-pack: center;\n -ms-flex-pack: center;\n justify-content: center;\n -webkit-box-align: center;\n -ms-flex-align: center;\n align-items: center;\n position: absolute;\n height: 100%;\n width: 100%;\n z-index: 998;\n top: 0;\n left: 0;\n background-color: transparent;\n background-size: cover;\n background-repeat: no-repeat;\n background-position: 50% 50%;\n}\n.player-poster[data-poster].clickable {\n cursor: pointer;\n}\n.player-poster[data-poster]:hover .play-wrapper[data-poster] {\n opacity: 1;\n}\n.player-poster[data-poster] .play-wrapper[data-poster] {\n width: 100%;\n height: 25%;\n margin: 0 auto;\n opacity: 0.75;\n -webkit-transition: opacity 0.1s ease;\n transition: opacity 0.1s ease;\n}\n.player-poster[data-poster] .play-wrapper[data-poster] svg {\n height: 100%;\n}\n.player-poster[data-poster] .play-wrapper[data-poster] svg path {\n fill: #fff;\n}",{baseUrl:this.options.baseUrl});if(this.$el.html(this.template()),this.$el.append(t[0]),this.options.poster&&void 0===this.options.poster.custom){var e=this.options.poster.url||this.options.poster;this.$el.css({"background-image":"url("+e+")"}),this.removeVideoElementPoster()}else this.options.poster&&(this.$el.css({background:this.options.poster.custom}),this.removeVideoElementPoster());this.container.$el.append(this.el),this.$playWrapper=this.$el.find(".play-wrapper"),this.$playWrapper.append(me),this.$playButton=this.$playWrapper.find("svg"),this.$playButton.addClass("poster-icon"),this.$playButton.attr("data-poster","");var i=this.options.mediacontrol&&this.options.mediacontrol.buttons;return i&&this.$el.find("svg path").css("fill",i),this.options.mediacontrol&&this.options.mediacontrol.buttons&&(i=this.options.mediacontrol.buttons,this.$playButton.css("color",i)),this.update(),this}}},{key:"removeVideoElementPoster",value:function(){this.container.playback&&this.container.playback.$el&&this.container.playback.$el[0]&&this.container.playback.$el[0].removeAttribute&&this.container.playback.$el[0].removeAttribute("poster")}}])}(Gt),Oe=Z.formatTime,xe=function(t){function e(t){var i;return te(this,e),(i=Jt(this,e,[t])).hoveringOverSeekBar=!1,i.hoverPosition=null,i.duration=null,i.firstFragDateTime=null,i.actualLiveTime=!!i.mediaControl.options.actualLiveTime,i.actualLiveTime&&(i.mediaControl.options.actualLiveServerTime?i.actualLiveServerTimeDiff=(new Date).getTime()-new Date(i.mediaControl.options.actualLiveServerTime).getTime():i.actualLiveServerTimeDiff=0),i}return re(e,t),ee(e,[{key:"name",get:function(){return"seek_time"}},{key:"supportedVersion",get:function(){return{min:"0.16.2"}}},{key:"template",get:function(){return At("<span data-seek-time></span>\n<span data-duration></span>\n")}},{key:"attributes",get:function(){return{class:"seek-time","data-seek-time":""}}},{key:"mediaControl",get:function(){return this.core.mediaControl}},{key:"mediaControlContainer",get:function(){return this.mediaControl.container}},{key:"isLiveStreamWithDvr",get:function(){return this.mediaControlContainer&&this.mediaControlContainer.getPlaybackType()===It.LIVE&&this.mediaControlContainer.isDvrEnabled()}},{key:"durationShown",get:function(){return this.isLiveStreamWithDvr&&!this.actualLiveTime}},{key:"useActualLiveTime",get:function(){return this.actualLiveTime&&this.isLiveStreamWithDvr}},{key:"bindEvents",value:function(){this.listenTo(this.mediaControl,ht.MEDIACONTROL_RENDERED,this.render),this.listenTo(this.mediaControl,ht.MEDIACONTROL_MOUSEMOVE_SEEKBAR,this.showTime),this.listenTo(this.mediaControl,ht.MEDIACONTROL_MOUSELEAVE_SEEKBAR,this.hideTime),this.listenTo(this.mediaControl,ht.MEDIACONTROL_CONTAINERCHANGED,this.onContainerChanged),this.mediaControlContainer&&(this.listenTo(this.mediaControlContainer,ht.CONTAINER_PLAYBACKDVRSTATECHANGED,this.update),this.listenTo(this.mediaControlContainer,ht.CONTAINER_TIMEUPDATE,this.updateDuration))}},{key:"onContainerChanged",value:function(){this.stopListening(),this.bindEvents()}},{key:"updateDuration",value:function(t){this.duration=t.total,this.firstFragDateTime=t.firstFragDateTime,this.update()}},{key:"showTime",value:function(t){this.hoveringOverSeekBar=!0,this.calculateHoverPosition(t),this.update()}},{key:"hideTime",value:function(){this.hoveringOverSeekBar=!1,this.update()}},{key:"calculateHoverPosition",value:function(t){var e=t.pageX-this.mediaControl.$seekBarContainer.offset().left;this.hoverPosition=Math.min(1,Math.max(e/this.mediaControl.$seekBarContainer.width(),0))}},{key:"getSeekTime",value:function(){var t,e,i,n;return this.useActualLiveTime?(this.firstFragDateTime?(n=new Date(this.firstFragDateTime),(i=new Date(this.firstFragDateTime)).setHours(0,0,0,0),e=(n.getTime()-i.getTime())/1e3+this.duration):(i=new Date((new Date).getTime()-this.actualLiveServerTimeDiff),e=((n=new Date(i))-i.setHours(0,0,0,0))/1e3),(t=e-this.duration+this.hoverPosition*this.duration)<0&&(t+=86400)):t=this.hoverPosition*this.duration,{seekTime:t,secondsSinceMidnight:e}}},{key:"update",value:function(){if(this.rendered)if(this.shouldBeVisible()){var t=this.getSeekTime(),e=Oe(t.seekTime,this.useActualLiveTime);if(e!==this.displayedSeekTime&&(this.$seekTimeEl.text(e),this.displayedSeekTime=e),this.durationShown){this.$durationEl.show();var i=Oe(this.actualLiveTime?t.secondsSinceMidnight:this.duration,this.actualLiveTime);i!==this.displayedDuration&&(this.$durationEl.text(i),this.displayedDuration=i)}else this.$durationEl.hide();this.$el.show();var n=this.mediaControl.$seekBarContainer.width(),r=this.$el.width(),s=this.hoverPosition*n;s-=r/2,s=Math.max(0,Math.min(s,n-r)),this.$el.css("left",s)}else this.$el.hide(),this.$el.css("left","-100%")}},{key:"shouldBeVisible",value:function(){return this.mediaControlContainer&&this.mediaControlContainer.settings.seekEnabled&&this.hoveringOverSeekBar&&null!==this.hoverPosition&&null!==this.duration}},{key:"render",value:function(){var t=Et.getStyleFor('.seek-time[data-seek-time] {\n position: absolute;\n white-space: nowrap;\n height: 20px;\n line-height: 20px;\n font-size: 0;\n left: -100%;\n bottom: 55px;\n background-color: rgba(2, 2, 2, 0.5);\n z-index: 9999;\n -webkit-transition: opacity 0.1s ease;\n transition: opacity 0.1s ease;\n}\n.seek-time[data-seek-time].hidden[data-seek-time] {\n opacity: 0;\n}\n.seek-time[data-seek-time] [data-seek-time] {\n display: inline-block;\n color: white;\n font-size: 10px;\n padding-left: 7px;\n padding-right: 7px;\n vertical-align: top;\n}\n.seek-time[data-seek-time] [data-duration] {\n display: inline-block;\n color: rgba(255, 255, 255, 0.5);\n font-size: 10px;\n padding-right: 7px;\n vertical-align: top;\n}\n.seek-time[data-seek-time] [data-duration]:before {\n content: "|";\n margin-right: 7px;\n}',{baseUrl:this.options.baseUrl});this.rendered=!0,this.displayedDuration=null,this.displayedSeekTime=null,this.$el.html(this.template()),this.$el.append(t[0]),this.$el.hide(),this.mediaControl.$el.append(this.el),this.$seekTimeEl=this.$el.find("[data-seek-time]"),this.$durationEl=this.$el.find("[data-duration]"),this.$durationEl.hide(),this.update()}}])}(_t),Me={ClickToPause:ue,ClosedCaptions:de,DVRControls:fe,EndVideo:ge,ErrorScreen:pe,Favicon:Ae,GoogleAnalytics:Ee,MediaControl:De,Poster:we,SeekTime:xe,SpinnerThreeBounce:function(t){function e(t){var i;return te(this,e),(i=Jt(this,e,[t])).template=At("<div data-bounce1></div><div data-bounce2></div><div data-bounce3></div>\n"),i.showTimeout=null,i.listenTo(i.container,ht.CONTAINER_STATE_BUFFERING,i.onBuffering),i.listenTo(i.container,ht.CONTAINER_STATE_BUFFERFULL,i.onBufferFull),i.listenTo(i.container,ht.CONTAINER_STOP,i.onStop),i.listenTo(i.container,ht.CONTAINER_ENDED,i.onStop),i.listenTo(i.container,ht.CONTAINER_ERROR,i.onStop),i.render(),i}return re(e,t),ee(e,[{key:"name",get:function(){return"spinner"}},{key:"supportedVersion",get:function(){return{min:"0.16.2"}}},{key:"attributes",get:function(){return{"data-spinner":"",class:"spinner-three-bounce"}}},{key:"onBuffering",value:function(){this.show()}},{key:"onBufferFull",value:function(){this.hide()}},{key:"onStop",value:function(){this.hide()}},{key:"show",value:function(){var t=this;null===this.showTimeout&&(this.showTimeout=setTimeout(function(){return t.$el.show()},300))}},{key:"hide",value:function(){null!==this.showTimeout&&(clearTimeout(this.showTimeout),this.showTimeout=null),this.$el.hide()}},{key:"render",value:function(){var t=Et.getStyleFor(".spinner-three-bounce[data-spinner] {\n position: absolute;\n margin: 0 auto;\n width: 70px;\n text-align: center;\n z-index: 999;\n left: 0;\n right: 0;\n margin-left: auto;\n margin-right: auto;\n /* center vertically */\n top: 50%;\n -webkit-transform: translateY(-50%);\n transform: translateY(-50%);\n}\n.spinner-three-bounce[data-spinner] > div {\n width: 18px;\n height: 18px;\n background-color: #FFFFFF;\n border-radius: 100%;\n display: inline-block;\n -webkit-animation: bouncedelay 1.4s infinite ease-in-out;\n animation: bouncedelay 1.4s infinite ease-in-out;\n /* Prevent first frame from flickering when animation starts */\n -webkit-animation-fill-mode: both;\n animation-fill-mode: both;\n}\n.spinner-three-bounce[data-spinner] [data-bounce1] {\n -webkit-animation-delay: -0.32s;\n animation-delay: -0.32s;\n}\n.spinner-three-bounce[data-spinner] [data-bounce2] {\n -webkit-animation-delay: -0.16s;\n animation-delay: -0.16s;\n}\n\n@-webkit-keyframes bouncedelay {\n 0%, 80%, 100% {\n -webkit-transform: scale(0);\n transform: scale(0);\n }\n 40% {\n -webkit-transform: scale(1);\n transform: scale(1);\n }\n}\n\n@keyframes bouncedelay {\n 0%, 80%, 100% {\n -webkit-transform: scale(0);\n transform: scale(0);\n }\n 40% {\n -webkit-transform: scale(1);\n transform: scale(1);\n }\n}",{baseUrl:this.options.baseUrl});return this.$el.html(this.template()),this.$el.append(t[0]),this.container.$el.append(this.$el),this.$el.hide(),this.container.buffering&&this.onBuffering(),this}}])}(Gt),Stats:function(t){function e(t){var i;return te(this,e),(i=Jt(this,e,[t])).setInitialAttrs(),i.reportInterval=i.options.reportInterval||5e3,i.state="IDLE",i}return re(e,t),ee(e,[{key:"name",get:function(){return"stats"}},{key:"supportedVersion",get:function(){return{min:"0.16.2"}}},{key:"bindEvents",value:function(){this.listenTo(this.container.playback,ht.PLAYBACK_PLAY,this.onPlay),this.listenTo(this.container,ht.CONTAINER_STOP,this.onStop),this.listenTo(this.container,ht.CONTAINER_ENDED,this.onStop),this.listenTo(this.container,ht.CONTAINER_DESTROYED,this.onStop),this.listenTo(this.container,ht.CONTAINER_STATE_BUFFERING,this.onBuffering),this.listenTo(this.container,ht.CONTAINER_STATE_BUFFERFULL,this.onBufferFull),this.listenTo(this.container,ht.CONTAINER_STATS_ADD,this.onStatsAdd),this.listenTo(this.container,ht.CONTAINER_BITRATE,this.onStatsAdd),this.listenTo(this.container.playback,ht.PLAYBACK_STATS_ADD,this.onStatsAdd)}},{key:"setInitialAttrs",value:function(){this.firstPlay=!0,this.startupTime=0,this.rebufferingTime=0,this.watchingTime=0,this.rebuffers=0,this.externalMetrics={}}},{key:"onPlay",value:function(){this.state="PLAYING",this.watchingTimeInit=Date.now(),this.intervalId||(this.intervalId=setInterval(this.report.bind(this),this.reportInterval))}},{key:"onStop",value:function(){clearInterval(this.intervalId),this.report(),this.intervalId=void 0,this.state="STOPPED"}},{key:"onBuffering",value:function(){this.firstPlay?this.startupTimeInit=Date.now():this.rebufferingTimeInit=Date.now(),this.state="BUFFERING",this.rebuffers++}},{key:"onBufferFull",value:function(){this.firstPlay&&this.startupTimeInit?(this.firstPlay=!1,this.startupTime=Date.now()-this.startupTimeInit,this.watchingTimeInit=Date.now()):this.rebufferingTimeInit&&(this.rebufferingTime+=this.getRebufferingTime()),this.rebufferingTimeInit=void 0,this.state="PLAYING"}},{key:"getRebufferingTime",value:function(){return Date.now()-this.rebufferingTimeInit}},{key:"getWatchingTime",value:function(){return Date.now()-this.watchingTimeInit-this.rebufferingTime}},{key:"isRebuffering",value:function(){return!!this.rebufferingTimeInit}},{key:"onStatsAdd",value:function(t){k.extend(this.externalMetrics,t)}},{key:"getStats",value:function(){var t={startupTime:this.startupTime,rebuffers:this.rebuffers,rebufferingTime:this.isRebuffering()?this.rebufferingTime+this.getRebufferingTime():this.rebufferingTime,watchingTime:this.isRebuffering()?this.getWatchingTime()-this.getRebufferingTime():this.getWatchingTime()};return k.extend(t,this.externalMetrics),t}},{key:"report",value:function(){this.container.statsReport(this.getStats())}}])}(Ut),WaterMark:function(t){function e(t){var i;return te(this,e),(i=Jt(this,e,[t])).configure(),i}return re(e,t),ee(e,[{key:"name",get:function(){return"watermark"}},{key:"supportedVersion",get:function(){return{min:"0.16.2"}}},{key:"template",get:function(){return At('<div class="clappr-watermark" data-watermark data-watermark-<%=position %>>\n<% if(typeof imageLink !== \'undefined\') { %>\n<a target="_blank" href="<%= imageLink %>">\n<% } %>\n<img src="<%= imageUrl %>">\n<% if(typeof imageLink !== \'undefined\') { %>\n</a>\n<% } %>\n</div>\n')}},{key:"bindEvents",value:function(){this.listenTo(this.container,ht.CONTAINER_PLAY,this.onPlay),this.listenTo(this.container,ht.CONTAINER_STOP,this.onStop),this.listenTo(this.container,ht.CONTAINER_OPTIONS_CHANGE,this.configure)}},{key:"configure",value:function(){this.position=this.options.position||"bottom-right",this.options.watermark?(this.imageUrl=this.options.watermark,this.imageLink=this.options.watermarkLink,this.render()):this.$el.remove()}},{key:"onPlay",value:function(){this.hidden||this.$el.show()}},{key:"onStop",value:function(){this.$el.hide()}},{key:"render",value:function(){this.$el.hide();var t=Et.getStyleFor(".clappr-watermark[data-watermark] {\n position: absolute;\n min-width: 70px;\n max-width: 200px;\n width: 12%;\n text-align: center;\n z-index: 10;\n}\n\n.clappr-watermark[data-watermark] a {\n outline: none;\n cursor: pointer;\n}\n\n.clappr-watermark[data-watermark] img {\n max-width: 100%;\n}\n\n.clappr-watermark[data-watermark-bottom-left] {\n bottom: 10px;\n left: 10px;\n}\n\n.clappr-watermark[data-watermark-bottom-right] {\n bottom: 10px;\n right: 42px;\n}\n\n.clappr-watermark[data-watermark-top-left] {\n top: 10px;\n left: 10px;\n}\n\n.clappr-watermark[data-watermark-top-right] {\n top: 10px;\n right: 37px;\n}",{baseUrl:this.options.baseUrl}),e={position:this.position,imageUrl:this.imageUrl,imageLink:this.imageLink};return this.$el.html(this.template(e)),this.$el.append(t[0]),this.container.$el.append(this.$el),this}}])}(Gt)},Ne=0,Fe=Object.values(Me);Ne<Fe.length;Ne++){var Be=Fe[Ne];Nt.registerPlugin(Be)}var Ue=Me.ClickToPause,$e=Me.ClosedCaptions,Ge=Me.DVRControls,Ve=Me.EndVideo,Ke=Me.ErrorScreen,He=Me.Favicon,Ye=Me.GoogleAnalytics,je=Me.MediaControl,We=Me.Poster,ze=Me.SeekTime,qe=Me.SpinnerThreeBounce,Xe=Me.Stats,Qe=Me.WaterMark,Ze=i(i({},Zt),{},{ClickToPause:Ue,ClosedCaptions:$e,DVRControls:Ge,EndVideo:Ve,ErrorScreen:Ke,Favicon:He,GoogleAnalytics:Ye,MediaControl:je,Poster:We,SeekTime:ze,SpinnerThreeBounce:qe,Stats:Xe,WaterMark:Qe,Vendor:be,Plugins:Me,version:"0.14.2"});const Je=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},ti=Number.isSafeInteger||function(t){return"number"==typeof t&&Math.abs(t)<=ei},ei=Number.MAX_SAFE_INTEGER||9007199254740991;let ii=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}({}),ni=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.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",t.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",t.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",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.ASSET_LIST_LOAD_ERROR="assetListLoadError",t.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",t.ASSET_LIST_PARSING_ERROR="assetListParsingError",t.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.ATTACH_MEDIA_ERROR="attachMediaError",t.UNKNOWN="unknown",t}({}),ri=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.MEDIA_ENDED="hlsMediaEnded",t.STALL_RESOLVED="hlsStallResolved",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.BUFFERED_TO_END="hlsBufferedToEnd",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.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",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_TRACK_UPDATED="hlsSubtitleTrackUpdated",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.ASSET_LIST_LOADING="hlsAssetListLoading",t.ASSET_LIST_LOADED="hlsAssetListLoaded",t.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",t.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",t.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",t.INTERSTITIAL_STARTED="hlsInterstitialStarted",t.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",t.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",t.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",t.INTERSTITIAL_ENDED="hlsInterstitialEnded",t.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",t.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",t.EVENT_CUE_ENTER="hlsEventCueEnter",t}({});var si="manifest",ai="level",oi="audioTrack",li="subtitleTrack",hi="main",ci="audio",ui="subtitle";class di{constructor(t,e=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=i}sample(t,e){const i=Math.pow(this.alpha_,t);this.estimate_=e*(1-i)+i*this.estimate_,this.totalWeight_+=t}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}}class fi{constructor(t,e,i,n=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new di(t),this.fast_=new di(e),this.defaultTTFB_=n,this.ttfb_=new di(t)}update(t,e){const{slow_:i,fast_:n,ttfb_:r}=this;i.halfLife!==t&&(this.slow_=new di(t,i.getEstimate(),i.getTotalWeight())),n.halfLife!==e&&(this.fast_=new di(e,n.getEstimate(),n.getTotalWeight())),r.halfLife!==t&&(this.ttfb_=new di(t,r.getEstimate(),r.getTotalWeight()))}sample(t,e){const i=(t=Math.max(t,this.minDelayMs_))/1e3,n=8*e/i;this.fast_.sample(i,n),this.slow_.sample(i,n)}sampleTTFB(t){const e=t/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(i,Math.max(t,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function gi(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var n=i.call(t,e);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function pi(){return pi=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var n in i)({}).hasOwnProperty.call(i,n)&&(t[n]=i[n])}return t},pi.apply(null,arguments)}function mi(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),i.push.apply(i,n)}return i}function vi(t){for(var e=1;e<arguments.length;e++){var i=null!=arguments[e]?arguments[e]:{};e%2?mi(Object(i),!0).forEach(function(e){gi(t,e,i[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):mi(Object(i)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))})}return t}class yi{constructor(t,e){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const i=`[${t}]:`;this.trace=Ai,this.debug=e.debug.bind(null,i),this.log=e.log.bind(null,i),this.warn=e.warn.bind(null,i),this.info=e.info.bind(null,i),this.error=e.error.bind(null,i)}}const Ai=function(){},Ei={trace:Ai,debug:Ai,log:Ai,warn:Ai,info:Ai,error:Ai};function Ti(){return pi({},Ei)}function bi(t,e,i){return e[t]?e[t].bind(e):function(t,e){const i=self.console[t];return i?i.bind(self.console,`${e?"["+e+"] ":""}[${t}] >`):Ai}(t,i)}const Si=Ti();const ki=Si;function _i(t=!0){if("undefined"==typeof self)return;return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Li(t,e){const i=Object.keys(t),n=Object.keys(e),r=i.length,s=n.length;return!r||!s||r===s&&!i.some(t=>-1===n.indexOf(t))}function Ii(t,e=!1){if("undefined"!=typeof TextDecoder){const i=new TextDecoder("utf-8").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 n,r,s,a="",o=0;for(;o<i;){if(n=t[o++],0===n&&e)return a;if(0!==n&&3!==n)switch(n>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(n);break;case 12:case 13:r=t[o++],a+=String.fromCharCode((31&n)<<6|63&r);break;case 14:r=t[o++],s=t[o++],a+=String.fromCharCode((15&n)<<12|(63&r)<<6|63&s)}}return a}function Ri(t){let e="";for(let i=0;i<t.length;i++){let n=t[i].toString(16);n.length<2&&(n="0"+n),e+=n}return e}function Ci(t){return Uint8Array.from(t.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function Pi(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Di,wi={exports:{}};var Oi=(Di||(Di=1,function(t){var e,i,n,r,s;e=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,r=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,s={buildAbsoluteURL:function(t,e,n){if(n=n||{},t=t.trim(),!(e=e.trim())){if(!n.alwaysNormalize)return t;var r=s.parseURL(t);if(!r)throw new Error("Error trying to parse base URL.");return r.path=s.normalizePath(r.path),s.buildURLFromParts(r)}var a=s.parseURL(e);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return n.alwaysNormalize?(a.path=s.normalizePath(a.path),s.buildURLFromParts(a)):e;var o=s.parseURL(t);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=i.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var h={scheme:o.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(h.netLoc=o.netLoc,"/"!==a.path[0]))if(a.path){var c=o.path,u=c.substring(0,c.lastIndexOf("/")+1)+a.path;h.path=s.normalizePath(u)}else h.path=o.path,a.params||(h.params=o.params,a.query||(h.query=o.query));return null===h.path&&(h.path=n.alwaysNormalize?s.normalizePath(a.path):a.path),s.buildURLFromParts(h)},parseURL:function(t){var i=e.exec(t);return i?{scheme:i[1]||"",netLoc:i[2]||"",path:i[3]||"",params:i[4]||"",query:i[5]||"",fragment:i[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(n,"");t.length!==(t=t.replace(r,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}},t.exports=s}(wi)),wi.exports);class xi{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 Mi="audio",Ni="video",Fi="audiovideo";class Bi{constructor(t){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof t&&(t={url:t}),this.base=t,function(t,e){const i=Vi(t,e);i&&(i.enumerable=!0,Object.defineProperty(t,e,i))}(this,"stats")}setByteRange(t,e){const i=t.split("@",2);let n;n=1===i.length?(null==e?void 0:e.byteRangeEndOffset)||0:parseInt(i[1]),this._byteRange=[n,parseInt(i[0])+n]}get baseurl(){return this.base.url}get byteRange(){return null===this._byteRange?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return null===this._streams&&(this._streams={[Mi]:null,[Ni]:null,[Fi]:null}),this._streams}set elementaryStreams(t){this._streams=t}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new xi),this._stats}set stats(t){this._stats=t}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Oi.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[Mi]=null,t[Ni]=null,t[Fi]=null}}function Ui(t){return"initSegment"!==t.sn}class $i extends Bi{constructor(t,e){super(e),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=t}get byteLength(){if(this.hasStats){const t=this.stats.total;if(t)return t}if(this.byteRange.length){const t=this.byteRange[0],e=this.byteRange[1];if(Je(t)&&Je(e))return e-t}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(t){this._bitrate=t}get decryptdata(){var t;const{levelkeys:e}=this;if(!e||e.NONE)return null;if(e.identity)this._decryptdata||(this._decryptdata=e.identity.getDecryptData(this.sn));else if(null==(t=this._decryptdata)||!t.keyId){const t=Object.keys(e);if(1===t.length){const i=this._decryptdata=e[t[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,e))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;const t=Je(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){var e;const t=Object.keys(this.levelkeys),i=t.length;if(i>1||1===i&&null!=(e=this.levelkeys[t[0]])&&e.encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(t){Je(t)?this._programDateTime=t:this._programDateTime=this.rawProgramDateTime=null}get ref(){return Ui(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(t){this.setStart(this.start+t)}setStart(t){this.start=t,this._ref&&(this._ref.start=t)}setDuration(t){this.duration=t,this._ref&&(this._ref.duration=t)}setKeyFormat(t){const e=this.levelkeys;if(e){var i;const n=e[t];!n||null!=(i=this._decryptdata)&&i.keyId||(this._decryptdata=n.getDecryptData(this.sn,e))}}abortRequests(){var t,e;null==(t=this.loader)||t.abort(),null==(e=this.keyLoader)||e.abort()}setElementaryStreamInfo(t,e,i,n,r,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,n),o.endDTS=Math.max(o.endDTS,r)):a[t]={startPTS:e,endPTS:i,startDTS:n,endDTS:r,partial:s}}}class Gi extends Bi{constructor(t,e,i,n,r){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.duration=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=e,this.index=n;const s=t.enumeratedString("BYTERANGE");s&&this.setByteRange(s,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)}}function Vi(t,e){const i=Object.getPrototypeOf(t);if(i){const t=Object.getOwnPropertyDescriptor(i,e);return t||Vi(i,e)}}const Ki=Math.pow(2,32)-1,Hi=[].push,Yi={video:1,audio:2,id3:3,text:4};function ji(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 zi(t,e){const i=Xi(t,e);return i<0?4294967296+i:i}function qi(t,e){let i=zi(t,e);return i*=Math.pow(2,32),i+=zi(t,e+4),i}function Xi(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function Qi(t,e){const i=[];if(!e.length)return i;const n=t.byteLength;for(let r=0;r<n;){const s=zi(t,r),a=s>1?r+s:n;if(ji(t.subarray(r+4,r+8))===e[0])if(1===e.length)i.push(t.subarray(r+8,a));else{const n=Qi(t.subarray(r+8,a),e.slice(1));n.length&&Hi.apply(i,n)}r=a}return i}function Zi(t){const e=[],i=t[0];let n=8;const r=zi(t,n);n+=4;let s=0,a=0;0===i?(s=zi(t,n),a=zi(t,n+4),n+=8):(s=qi(t,n),a=qi(t,n+8),n+=16),n+=2;let o=t.length+a;const l=Wi(t,n);n+=2;for(let i=0;i<l;i++){let i=n;const s=zi(t,i);i+=4;const a=2147483647&s;if(1===(2147483648&s)>>>31)return ki.warn("SIDX has hierarchical references (not supported)"),null;const l=zi(t,i);i+=4,e.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/r,start:o,end:o+a-1}}),o+=a,i+=4,n=i}return{earliestPresentationTime:s,timescale:r,version:i,referencesCount:l,references:e}}function Ji(t){const e=[],i=Qi(t,["moov","trak"]);for(let t=0;t<i.length;t++){const n=i[t],r=Qi(n,["tkhd"])[0];if(r){let t=r[0];const i=zi(r,0===t?12:20),s=Qi(n,["mdia","mdhd"])[0];if(s){t=s[0];const r=zi(s,0===t?12:20),a=Qi(n,["mdia","hdlr"])[0];if(a){const t=ji(a.subarray(8,12)),s={soun:Mi,vide:Ni}[t],o=tn(Qi(n,["mdia","minf","stbl","stsd"])[0]);s?(e[i]={timescale:r,type:s,stsd:o},e[s]=vi({timescale:r,id:i},o)):e[i]={timescale:r,type:t,stsd:o}}}}}return Qi(t,["moov","mvex","trex"]).forEach(t=>{const i=zi(t,4),n=e[i];n&&(n.default={duration:zi(t,12),flags:zi(t,20)})}),e}function tn(t){const e=t.subarray(8),i=e.subarray(86),n=ji(e.subarray(4,8));let r,s=n;const a="enca"===n||"encv"===n;if(a){const t=Qi(e,[n])[0];Qi(t.subarray("enca"===n?28:78),["sinf"]).forEach(t=>{const e=Qi(t,["schm"])[0];if(e){const i=ji(e.subarray(4,8));if("cbcs"===i||"cenc"===i){const e=Qi(t,["frma"])[0];e&&(s=ji(e))}}})}const o=s;switch(s){case"avc1":case"avc2":case"avc3":case"avc4":{const t=Qi(i,["avcC"])[0];t&&t.length>3&&(s+="."+rn(t[1])+rn(t[2])+rn(t[3]),r=en("avc1"===o?"dva1":"dvav",i));break}case"mp4a":{const t=Qi(e,[n])[0],i=Qi(t.subarray(28),["esds"])[0];if(i&&i.length>7){let t=4;if(3!==i[t++])break;t=nn(i,t),t+=2;const e=i[t++];if(128&e&&(t+=2),64&e&&(t+=i[t++]),4!==i[t++])break;t=nn(i,t);const n=i[t++];if(64!==n)break;if(s+="."+rn(n),t+=12,5!==i[t++])break;t=nn(i,t);const r=i[t++];let a=(248&r)>>3;31===a&&(a+=1+((7&r)<<3)+((224&i[t])>>5)),s+="."+a}break}case"hvc1":case"hev1":{const t=Qi(i,["hvcC"])[0];if(t&&t.length>12){const e=t[1],i=["","A","B","C"][e>>6],n=31&e,r=zi(t,2),a=(32&e)>>5?"H":"L",o=t[12],l=t.subarray(6,12);s+="."+i+n,s+="."+function(t){let e=0;for(let i=0;i<32;i++)e|=(t>>i&1)<<31-i;return e>>>0}(r).toString(16).toUpperCase(),s+="."+a+o;let h="";for(let t=l.length;t--;){const e=l[t];if(e||h){h="."+e.toString(16).toUpperCase()+h}}s+=h}r=en("hev1"==o?"dvhe":"dvh1",i);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":s=en(s,i)||s;break;case"vp09":{const t=Qi(i,["vpcC"])[0];if(t&&t.length>6){const e=t[4],i=t[5],n=t[6]>>4&15;s+="."+sn(e)+"."+sn(i)+"."+sn(n)}break}case"av01":{const t=Qi(i,["av1C"])[0];if(t&&t.length>2){const e=t[1]>>>5,n=31&t[1],a=t[2]>>>7?"H":"M",o=(64&t[2])>>6,l=(32&t[2])>>5,h=2===e&&o?l?12:10:o?10:8,c=(16&t[2])>>4,u=(8&t[2])>>3,d=(4&t[2])>>2,f=3&t[2],g=1,p=1,m=1,v=0;s+="."+e+"."+sn(n)+a+"."+sn(h)+"."+c+"."+u+d+f+"."+sn(g)+"."+sn(p)+"."+sn(m)+"."+v,r=en("dav1",i)}break}}return{codec:s,encrypted:a,supplemental:r}}function en(t,e){const i=Qi(e,["dvvC"]),n=i.length?i[0]:Qi(e,["dvcC"])[0];if(n){const e=n[2]>>1&127,i=n[2]<<5&32|n[3]>>3&31;return t+"."+sn(e)+"."+sn(i)}}function nn(t,e){const i=e+5;for(;128&t[e++]&&e<i;);return e}function rn(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function sn(t){return(t<10?"0":"")+t}function an(t,e){Qi(t,["moov","trak"]).forEach(t=>{const i=Qi(t,["mdia","minf","stbl","stsd"])[0];if(!i)return;const n=i.subarray(8);let r=Qi(n,["enca"]);const s=r.length>0;s||(r=Qi(n,["encv"])),r.forEach(t=>{Qi(s?t.subarray(28):t.subarray(78),["sinf"]).forEach(t=>{const i=on(t);i&&e(i,s)})})})}function on(t){const e=Qi(t,["schm"])[0];if(e){const i=ji(e.subarray(4,8));if("cbcs"===i||"cenc"===i){const e=Qi(t,["schi","tenc"])[0];if(e)return e}}}function ln(t,e){const i=new Uint8Array(t.length+e.length);return i.set(t),i.set(e,t.length),i}function hn(t,e){const i=[],n=e.samples,r=e.timescale,s=e.id;let a=!1;return Qi(n,["moof"]).map(o=>{const l=o.byteOffset-8;Qi(o,["traf"]).map(o=>{const h=Qi(o,["tfdt"]).map(t=>{const e=t[0];let i=zi(t,4);return 1===e&&(i*=Math.pow(2,32),i+=zi(t,8)),i/r})[0];return void 0!==h&&(t=h),Qi(o,["tfhd"]).map(h=>{const c=zi(h,4),u=16777215&zi(h,0);let d=0;const f=!!(16&u);let g=0;const p=!!(32&u);let m=8;c===s&&(!!(1&u)&&(m+=8),!!(2&u)&&(m+=4),!!(8&u)&&(d=zi(h,m),m+=4),f&&(g=zi(h,m),m+=4),p&&(m+=4),"video"===e.type&&(a=cn(e.codec)),Qi(o,["trun"]).map(s=>{const o=s[0],h=16777215&zi(s,0),c=!!(1&h);let u=0;const f=!!(4&h),p=!!(256&h);let m=0;const v=!!(512&h);let y=0;const A=!!(1024&h),E=!!(2048&h);let T=0;const b=zi(s,4);let S=8;c&&(u=zi(s,S),S+=4),f&&(S+=4);let k=u+l;for(let l=0;l<b;l++){if(p?(m=zi(s,S),S+=4):m=d,v?(y=zi(s,S),S+=4):y=g,A&&(S+=4),E&&(T=0===o?zi(s,S):Xi(s,S),S+=4),e.type===Ni){let e=0;for(;e<y;){const s=zi(n,k);if(k+=4,un(a,n[k])){dn(n.subarray(k,k+s),a?2:1,t+T/r,i)}k+=s,e+=s+4}}t+=m/r}}))})})}),i}function cn(t){if(!t)return!1;const e=t.substring(0,4);return"hvc1"===e||"hev1"===e||"dvh1"===e||"dvhe"===e}function un(t,e){if(t){const t=e>>1&63;return 39===t||40===t}return 6===(31&e)}function dn(t,e,i,n){const r=fn(t);let s=0;s+=e;let a=0,o=0,l=0;for(;s<r.length;){a=0;do{if(s>=r.length)break;l=r[s++],a+=l}while(255===l);o=0;do{if(s>=r.length)break;l=r[s++],o+=l}while(255===l);const t=r.length-s;let e=s;if(o<t)s+=o;else if(o>t){ki.error(`Malformed SEI payload. ${o} is too small, only ${t} bytes left to parse.`);break}if(4===a){if(181===r[e++]){const t=Wi(r,e);if(e+=2,49===t){const t=zi(r,e);if(e+=4,1195456820===t){const t=r[e++];if(3===t){const s=r[e++],o=64&s,l=o?2+3*(31&s):0,h=new Uint8Array(l);if(o){h[0]=s;for(let t=1;t<l;t++)h[t]=r[e++]}n.push({type:t,payloadType:a,pts:i,bytes:h})}}}}}else if(5===a&&o>16){const t=[];for(let i=0;i<16;i++){const n=r[e++].toString(16);t.push(1==n.length?"0"+n:n),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]=r[e++];n.push({payloadType:a,pts:i,uuid:t.join(""),userData:Ii(l),userDataBytes:l})}}}function fn(t){const e=t.byteLength,i=[];let n=1;for(;n<e-2;)0===t[n]&&0===t[n+1]&&3===t[n+2]?(i.push(n+2),n+=2):n++;if(0===i.length)return t;const r=e-i.length,s=new Uint8Array(r);let a=0;for(n=0;n<r;a++,n++)a===i[0]&&(a++,i.shift()),s[n]=t[a];return s}function gn(t,e,i){if(16!==t.byteLength)throw new RangeError("Invalid system id");let n,r,s;n=0,r=new Uint8Array,s=new Uint8Array;const a=new Uint8Array(4);return i.byteLength>0&&new DataView(a.buffer).setUint32(0,i.byteLength,!1),function(t,...e){const i=e.length;let n=8,r=i;for(;r--;)n+=e[r].byteLength;const s=new Uint8Array(n);for(s[0]=n>>24&255,s[1]=n>>16&255,s[2]=n>>8&255,s[3]=255&n,s.set(t,4),r=0,n=8;r<i;r++)s.set(e[r],n),n+=e[r].byteLength;return s}([112,115,115,104],new Uint8Array([0,0,0,0]),t,s,r,a,i)}function pn(t){const e=t.getUint32(0),i=t.byteOffset,n=t.byteLength;if(n<e)return{offset:i,size:n};if(1886614376!==t.getUint32(4))return{offset:i,size:e};const r=t.getUint32(8)>>>24;if(0!==r&&1!==r)return{offset:i,size:e};const s=t.buffer,a=Ri(new Uint8Array(s,i+12,16));let o=null,l=null,h=0;if(0===r)h=28;else{const r=t.getUint32(28);if(!r||n<32+16*r)return{offset:i,size:e};o=[];for(let t=0;t<r;t++)o.push(new Uint8Array(s,i+32+16*t,16));h=32+16*r}if(!h)return{offset:i,size:e};const c=t.getUint32(h);return e-32<c?{offset:i,size:e}:(l=new Uint8Array(s,i+h+4,c),{version:r,systemId:a,kids:o,data:l,offset:i,size:e})}const mn=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),vn={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function yn(t,e){const i=vn[e];return!!i&&!!i[t.slice(0,4)]}function An(t,e,i=!0){return!t.split(",").some(t=>!En(t,e,i))}function En(t,e,i=!0){var n;const r=_i(i);return null!=(n=null==r?void 0:r.isTypeSupported(Tn(t,e)))&&n}function Tn(t,e){return`${e}/mp4;codecs=${t}`}function bn(t){if(t){const e=t.substring(0,4);return vn.video[e]}return 2}function Sn(t){const e=mn();return t.split(",").reduce((t,i)=>{const n=e&&cn(i)?9:vn.video[i];return n?(2*n+t)/(t?3:2):(vn.audio[i]+t)/(t?2:1)},0)}const kn={};const _n=/flac|opus|mp4a\.40\.34/i;function Ln(t,e=!0){return t.replace(_n,t=>function(t,e=!0){if(kn[t])return kn[t];const i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[t];for(let r=0;r<i.length;r++){var n;if(En(i[r],"audio",e))return kn[t]=i[r],i[r];if("mp3"===i[r]&&null!=(n=_i(e))&&n.isTypeSupported("audio/mpeg"))return""}return t}(t.toLowerCase(),e))}function In(t,e){if(t&&(t.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(t))&&(Rn(t,"audio")||Rn(t,"video")))return t;if(e){const i=e.split(",");if(i.length>1){if(t)for(let e=i.length;e--;)if(i[e].substring(0,4)===t.substring(0,4))return i[e];return i[0]}}return e||t}function Rn(t,e){return yn(t,e)&&En(t,e)}function Cn(t){if(t.startsWith("av01.")){const e=t.split("."),i=["0","111","01","01","01","0"];for(let t=e.length;t>4&&t<10;t++)e[t]=i[t-4];return e.join(".")}return t}function Pn(t){const e=_i(t)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Dn(t){return t.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const wn={supported:!1,smooth:!1,powerEfficient:!1},On={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function xn(t,e){return{supported:!1,configurations:e,decodingInfoResults:[wn],error:t}}function Mn(t,e,i,n,r,s){const a=t.videoCodec,o=t.audioCodec?t.audioGroups:null,l=null==s?void 0:s.audioCodec,h=null==s?void 0:s.channels,c=h?parseInt(h):l?1/0:2;let u=null;if(null!=o&&o.length)try{u=1===o.length&&o[0]?e.groups[o[0]].channels:o.reduce((t,i)=>{if(i){const n=e.groups[i];if(!n)throw new Error(`Audio track group ${i} not found`);Object.keys(n.channels).forEach(e=>{t[e]=(t[e]||0)+n.channels[e]})}return t},{2:0})}catch(t){return!0}return void 0!==a&&(a.split(",").some(t=>cn(t))||t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(n,30)||"SDR"!==t.videoRange&&t.videoRange!==i||t.bitrate>Math.max(r,8e6))||!!u&&Je(c)&&Object.keys(u).some(t=>parseInt(t)>c)}function Nn(t,e,i,n={}){const r=t.videoCodec;if(!r&&!t.audioCodec||!i)return Promise.resolve(On);const s=[],a=function(t){var e;const i=null==(e=t.videoCodec)?void 0:e.split(","),n=Bn(t),r=t.width||640,s=t.height||480,a=t.frameRate||30,o=t.videoRange.toLowerCase();return i?i.map(t=>{const e={contentType:Tn(Cn(t),"video"),width:r,height:s,bitrate:n,framerate:a};return"sdr"!==o&&(e.transferFunction=o),e}):[]}(t),o=a.length,l=function(t,e,i){var n;const r=null==(n=t.audioCodec)?void 0:n.split(","),s=Bn(t);if(r&&t.audioGroups)return t.audioGroups.reduce((t,n)=>{var a;const o=n?null==(a=e.groups[n])?void 0:a.tracks:null;return o?o.reduce((t,e)=>{if(e.groupId===n){const n=parseFloat(e.channels||"");r.forEach(e=>{const r={contentType:Tn(e,"audio"),bitrate:i?Fn(e,s):s};n&&(r.channels=""+n),t.push(r)})}return t},t):t},[]);return[]}(t,e,o>0),h=l.length;for(let t=o||1*h||1;t--;){const e={type:"media-source"};if(o&&(e.video=a[t%o]),h){e.audio=l[t%h];const i=e.audio.bitrate;e.video&&i&&(e.video.bitrate-=i)}s.push(e)}if(r){const t=navigator.userAgent;if(r.split(",").some(t=>cn(t))&&mn())return Promise.resolve(xn(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${t})`),s))}return Promise.all(s.map(t=>{const e=function(t){let e="";const{audio:i,video:n}=t;if(n){e+=`${Dn(n.contentType)}_r${n.height}x${n.width}f${Math.ceil(n.framerate)}${n.transferFunction||"sd"}_${Math.ceil(n.bitrate/1e5)}`}if(i){e+=`${n?"_":""}${Dn(i.contentType)}_c${i.channels}`}return e}(t);return n[e]||(n[e]=i.decodingInfo(t))})).then(t=>({supported:!t.some(t=>!t.supported),configurations:s,decodingInfoResults:t})).catch(t=>({supported:!1,configurations:s,decodingInfoResults:[],error:t}))}function Fn(t,e){if(e<=1)return 1;let i=128e3;return"ec-3"===t?i=768e3:"ac-3"===t&&(i=64e4),Math.min(e/2,i)}function Bn(t){return 1e3*Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)/1e3)||1}const Un=["NONE","TYPE-0","TYPE-1",null];const $n=["SDR","PQ","HLG"];var Gn="",Vn="YES",Kn="v2";function Hn(t){const{canSkipUntil:e,canSkipDateRanges:i,age:n}=t;return e&&n<e/2?i?Kn:Vn:Gn}class Yn{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 jn{constructor(t){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[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(","),"supplemental"in t){var e;this.supplemental=t.supplemental;const i=null==(e=t.supplemental)?void 0:e.videoCodec;i&&i!==t.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}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 Wn(this._audioGroups,t)}hasSubtitleGroup(t){return Wn(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 Wn(t,e){return!(!e||!t)&&-1!==t.indexOf(e)}function zn(t,e){let i=!1,n=[];if(t&&(i="SDR"!==t,n=[t]),e){n=e.allowedVideoRanges||$n.slice(0);const t="SDR"!==n.join("")&&!e.videoCodec;i=void 0!==e.preferHDR?e.preferHDR:t&&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||(n=["SDR"])}return{preferHDR:i,allowedVideoRanges:n}}const qn=(t,e)=>JSON.stringify(t,(t=>{const e=new WeakSet;return(i,n)=>{if(t&&(n=t(i,n)),"object"==typeof n&&null!==n){if(e.has(n))return;e.add(n)}return n}})(e));function Xn(t,e){ki.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function Qn(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 n=e.channels||"2";return i.channels[n]=(i.channels[n]||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:{}})}function Zn(t){if(!t)return t;const{lang:e,assocLang:i,characteristics:n,channels:r,audioCodec:s}=t;return{lang:e,assocLang:i,characteristics:n,channels:r,audioCodec:s}}function Jn(t,e,i){if("attrs"in t){const i=e.indexOf(t);if(-1!==i)return i}for(let n=0;n<e.length;n++){if(tr(t,e[n],i))return n}return-1}function tr(t,e,i){const{groupId:n,name:r,lang:s,assocLang:a,default:o}=t,l=t.forced;return(void 0===n||e.groupId===n)&&(void 0===r||e.name===r)&&(void 0===s||function(t,e="--"){if(t.length===e.length)return t===e;return t.startsWith(e)||e.startsWith(t)}(s,e.lang))&&(void 0===s||e.assocLang===a)&&(void 0===o||e.default===o)&&(void 0===l||e.forced===l)&&(!("characteristics"in t)||function(t,e=""){const i=t.split(","),n=e.split(",");return i.length===n.length&&!i.some(t=>-1===n.indexOf(t))}(t.characteristics||"",e.characteristics))&&(void 0===i||i(t,e))}function er(t,e){const{audioCodec:i,channels:n}=t;return!(void 0!==i&&(e.audioCodec||"").substring(0,4)!==i.substring(0,4)||void 0!==n&&n!==(e.channels||"2"))}function ir(t,e,i){for(let n=e;n>-1;n--)if(i(t[n]))return n;for(let n=e+1;n<t.length;n++)if(i(t[n]))return n;return-1}function nr(t,e){var i;return!!t&&t!==(null==(i=e.loadLevelObj)?void 0:i.uri)}const rr=function(t,e){let i=0,n=t.length-1,r=null,s=null;for(;i<=n;){r=(i+n)/2|0,s=t[r];const a=e(s);if(a>0)i=r+1;else{if(!(a<0))return s;n=r-1}}return null};function sr(t,e,i=0,n=0,r=.005){let s=null;if(t){s=e[1+t.sn-e[0].sn]||null;const n=t.endDTS-i;n>0&&n<15e-7&&(i+=15e-7),s&&t.level!==s.level&&s.end<=t.end&&(s=e[2+t.sn-e[0].sn]||null)}else 0===i&&0===e[0].start&&(s=e[0]);if(s&&((!t||t.level===s.level)&&0===ar(i,n,s)||function(t,e,i){if(e&&0===e.start&&e.level<t.level&&(e.endPTS||0)>0){const n=e.tagList.reduce((t,e)=>("INF"===e[0]&&(t+=parseFloat(e[1])),t),i);return t.start<=n}return!1}(s,t,Math.min(r,n))))return s;const a=rr(e,ar.bind(null,i,n));return!a||a===t&&s?s:a}function ar(t=0,e=0,i){if(i.start<=t&&i.start+i.duration>t)return 0;const n=Math.min(e,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-n<=t?1:i.start-n>t&&i.start?-1:0}function or(t,e,i){const n=1e3*Math.min(e,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-n>t}function lr(t,e,i){if(t&&t.startCC<=e&&t.endCC>=e){let n=t.fragments;const{fragmentHint:r}=t;let s;return r&&(n=n.concat(r)),rr(n,t=>t.cc<e?1:t.cc>e?-1:(s=t,t.end<=i?1:t.start>i?-1:0)),s||null}return null}function hr(t){switch(t.details){case ni.FRAG_LOAD_TIMEOUT:case ni.KEY_LOAD_TIMEOUT:case ni.LEVEL_LOAD_TIMEOUT:case ni.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function cr(t){return t.details.startsWith("key")}function ur(t){return cr(t)&&!!t.frag&&!t.frag.decryptdata}function dr(t,e){const i=hr(e);return t.default[(i?"timeout":"error")+"Retry"]}function fr(t,e){const i="linear"===t.backoff?1:Math.pow(2,e);return Math.min(i*t.retryDelayMs,t.maxRetryDelayMs)}function gr(t){return vi(vi({},t),{errorRetry:null,timeoutRetry:null})}function pr(t,e,i,n){if(!t)return!1;const r=null==n?void 0:n.code,s=e<t.maxNumRetry&&(function(t){return mr(t)||!!t&&(t<400||t>499)}(r)||!!i);return t.shouldRetry?t.shouldRetry(t,e,i,n,s):s}function mr(t){return 0===t&&!1===navigator.onLine}var vr=0,yr=2,Ar=3,Er=5,Tr=0,br=1,Sr=2,kr=4;function _r(t){const e={action:vr,flags:Tr};return t&&(e.resolved=!0),e}var Lr="NOT_LOADED",Ir="APPENDING",Rr="PARTIAL",Cr="OK";class Pr{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&&(t.on(ri.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ri.BUFFER_APPENDED,this.onBufferAppended,this),t.on(ri.FRAG_BUFFERED,this.onFragBuffered,this),t.on(ri.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(ri.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ri.BUFFER_APPENDED,this.onBufferAppended,this),t.off(ri.FRAG_BUFFERED,this.onFragBuffered,this),t.off(ri.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=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 n=i[e];if(!n)break;if(n.start<=t&&t<=n.end&&n.loaded)return n}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){return this.getFragAtPos(t,e,!0)}getFragAtPos(t,e,i){const{fragments:n}=this,r=Object.keys(n);for(let s=r.length;s--;){const a=n[r[s]];if((null==a?void 0:a.body.type)===e&&(!i||a.buffered)){const e=a.body;if(e.start<=t&&t<=e.end)return e}}return null}detectEvictedFragments(t,e,i,n,r){this.timeRanges&&(this.timeRanges[t]=e);const s=(null==n?void 0:n.fragment.sn)||-1;Object.keys(this.fragments).forEach(n=>{const a=this.fragments[n];if(!a)return;if(s>=a.body.sn)return;if(!a.buffered&&(!a.loaded||r))return void(a.body.type===i&&this.removeFragment(a.body));const o=a.range[t];o&&(0!==o.time.length?o.time.some(t=>{const i=!this.isTimeBuffered(t.startPTS,t.endPTS,e);return i&&this.removeFragment(a.body),i}):this.removeFragment(a.body))})}detectPartialFragments(t){const e=this.timeRanges;if(!e||"initSegment"===t.frag.sn)return;const i=t.frag,n=wr(i),r=this.fragments[n];if(!r||r.buffered&&i.gap)return;const s=!i.relurl;Object.keys(e).forEach(n=>{const a=i.elementaryStreams[n];if(!a)return;const o=e[n],l=s||!0===a.partial;r.range[n]=this.getBufferedTimes(i,t.part,l,o)}),r.loaded=null,Object.keys(r.range).length?(this.bufferedEnd(r,i),Dr(r)||this.removeParts(i.sn-1,i.type)):this.removeFragment(r.body)}bufferedEnd(t,e){t.buffered=!0;(t.body.endList=e.endList||t.body.endList)&&(this.endListFragments[t.body.type]=t)}removeParts(t,e){const i=this.activePartLists[e];i&&(this.activePartLists[e]=Or(i,e=>e.fragment.sn>=t))}fragBuffered(t,e){const i=wr(t);let n=this.fragments[i];!n&&e&&(n=this.fragments[i]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),n&&(n.loaded=null,this.bufferedEnd(n,t))}getBufferedTimes(t,e,i,n){const r={time:[],partial:i},s=t.start,a=t.end,o=t.minEndPTS||a,l=t.maxStartPTS||s;for(let t=0;t<n.length;t++){const e=n.start(t)-this.bufferPadding,i=n.end(t)+this.bufferPadding;if(l>=e&&o<=i){r.time.push({startPTS:Math.max(s,n.start(t)),endPTS:Math.min(a,n.end(t))});break}if(s<i&&a>e){const e=Math.max(s,n.start(t)),i=Math.min(a,n.end(t));i>e&&(r.partial=!0,r.time.push({startPTS:e,endPTS:i}))}else if(a<=e)break}return r}getPartialFragment(t){let e,i,n,r=null,s=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach(l=>{const h=o[l];h&&Dr(h)&&(i=h.body.start-a,n=h.body.end+a,t>=i&&t<=n&&(e=Math.min(t-i,n-t),s<=e&&(r=h.body,s=e)))}),r}isEndListAppended(t){const e=this.endListFragments[t];return void 0!==e&&(e.buffered||Dr(e))}getState(t){const e=wr(t),i=this.fragments[e];return i?i.buffered?Dr(i)?Rr:Cr:Ir:Lr}isTimeBuffered(t,e,i){let n,r;for(let s=0;s<i.length;s++){if(n=i.start(s)-this.bufferPadding,r=i.end(s)+this.bufferPadding,t>=n&&e<=r)return!0;if(e<=n)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(t,e){if("initSegment"===e.frag.sn||e.frag.bitrateTest)return;const i=e.frag,n=e.part?null:e,r=wr(i);this.fragments[r]={body:i,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:i,part:n,timeRanges:r,type:s}=e;if("initSegment"===i.sn)return;const a=i.type;if(n){let t=this.activePartLists[a];t||(this.activePartLists[a]=t=[]),t.push(n)}this.timeRanges=r;const o=r[s];this.detectEvictedFragments(s,o,a,n)}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=wr(t);return!!this.fragments[e]}hasFragments(t){const{fragments:e}=this,i=Object.keys(e);if(!t)return i.length>0;for(let n=i.length;n--;){const r=e[i[n]];if((null==r?void 0:r.body.type)===t)return!0}return!1}hasParts(t){var e;return!(null==(e=this.activePartLists[t])||!e.length)}removeFragmentsInRange(t,e,i,n,r){n&&!this.hasGaps||Object.keys(this.fragments).forEach(s=>{const a=this.fragments[s];if(!a)return;const o=a.body;o.type!==i||n&&!o.gap||o.start<e&&o.end>t&&(a.buffered||r)&&this.removeFragment(o)})}removeFragment(t){const e=wr(t);t.clearElementaryStreamInfo();const i=this.activePartLists[t.type];if(i){const e=t.sn;this.activePartLists[t.type]=Or(i,t=>t.fragment.sn!==e)}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){var t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const e=null==(t=this.hls)||null==(t=t.latestLevelDetails)?void 0:t.partList;e&&e.forEach(t=>t.clearElementaryStreamInfo())}}function Dr(t){var e,i,n;return t.buffered&&!!(t.body.gap||null!=(e=t.range.video)&&e.partial||null!=(i=t.range.audio)&&i.partial||null!=(n=t.range.audiovideo)&&n.partial)}function wr(t){return`${t.type}_${t.level}_${t.sn}`}function Or(t,e){return t.filter(t=>{const i=e(t);return i||t.clearElementaryStreamInfo(),i})}var xr=0,Mr=1;class Nr{constructor(t,e,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=e,this.aesMode=i}decrypt(t,e){switch(this.aesMode){case xr:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t);case Mr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},e,t);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}class Fr{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,n=i[0],r=i[1],s=i[2],a=i[3],o=this.invSubMix,l=o[0],h=o[1],c=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 v=257*d[i]^16843008*i;n[f]=v<<24|v>>>8,r[f]=v<<16|v>>>16,s[f]=v<<8|v>>>24,a[f]=v,v=16843009*m^65537*p^257*o^16843008*f,l[i]=v<<24|v>>>8,h[i]=v<<16|v>>>16,c[i]=v<<8|v>>>24,u[i]=v,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,n=0;for(;n<e.length&&i;)i=e[n]===this.key[n],n++;if(i)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 s=this.ksRows=4*(r+6+1);let a,o;const l=this.keySchedule=new Uint32Array(s),h=this.invKeySchedule=new Uint32Array(s),c=this.sBox,u=this.rcon,d=this.invSubMix,f=d[0],g=d[1],p=d[2],m=d[3];let v,y;for(a=0;a<s;a++)a<r?v=l[a]=e[a]:(y=v,a%r===0?(y=y<<8|y>>>24,y=c[y>>>24]<<24|c[y>>>16&255]<<16|c[y>>>8&255]<<8|c[255&y],y^=u[a/r|0]<<24):r>6&&a%r===4&&(y=c[y>>>24]<<24|c[y>>>16&255]<<16|c[y>>>8&255]<<8|c[255&y]),l[a]=v=(l[a-r]^y)>>>0);for(o=0;o<s;o++)a=s-o,y=3&o?l[a]:l[a-4],h[o]=o<4||a<=4?y:f[c[y>>>24]]^g[c[y>>>16&255]]^p[c[y>>>8&255]]^m[c[255&y]],h[o]=h[o]>>>0}networkToHostOrderSwap(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24}decrypt(t,e,i){const n=this.keySize+6,r=this.invKeySchedule,s=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],h=a[2],c=a[3],u=this.uint8ArrayToUint32Array_(i);let d=u[0],f=u[1],g=u[2],p=u[3];const m=new Int32Array(t),v=new Int32Array(m.length);let y,A,E,T,b,S,k,_,L,I,R,C,P,D;const w=this.networkToHostOrderSwap;for(;e<m.length;){for(L=w(m[e]),I=w(m[e+1]),R=w(m[e+2]),C=w(m[e+3]),b=L^r[0],S=C^r[1],k=R^r[2],_=I^r[3],P=4,D=1;D<n;D++)y=o[b>>>24]^l[S>>16&255]^h[k>>8&255]^c[255&_]^r[P],A=o[S>>>24]^l[k>>16&255]^h[_>>8&255]^c[255&b]^r[P+1],E=o[k>>>24]^l[_>>16&255]^h[b>>8&255]^c[255&S]^r[P+2],T=o[_>>>24]^l[b>>16&255]^h[S>>8&255]^c[255&k]^r[P+3],b=y,S=A,k=E,_=T,P+=4;y=s[b>>>24]<<24^s[S>>16&255]<<16^s[k>>8&255]<<8^s[255&_]^r[P],A=s[S>>>24]<<24^s[k>>16&255]<<16^s[_>>8&255]<<8^s[255&b]^r[P+1],E=s[k>>>24]<<24^s[_>>16&255]<<16^s[b>>8&255]<<8^s[255&S]^r[P+2],T=s[_>>>24]<<24^s[b>>16&255]<<16^s[S>>8&255]<<8^s[255&k]^r[P+3],v[e]=w(y^d),v[e+1]=w(T^f),v[e+2]=w(E^g),v[e+3]=w(A^p),d=L,f=I,g=R,p=C,e+=4}return v.buffer}}class Br{constructor(t,e,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=t,this.key=e,this.aesMode=i}expandKey(){const t=function(t){switch(t){case xr:return"AES-CBC";case Mr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${t}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:t},!1,["encrypt","decrypt"])}}class Ur{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.enableSoftwareAES=void 0,this.enableSoftwareAES=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?t.slice(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,n){return this.useSoftware?new Promise((r,s)=>{const a=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(a,e,i,n);const o=this.flush();o?r(o.buffer):s(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(t),e,i,n)}softwareDecrypt(t,e,i,n){const{currentIV:r,currentResult:s,remainderData:a}=this;if(n!==xr||16!==e.byteLength)return ki.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(t=ln(a,t),this.remainderData=null);const o=this.getValidChunk(t);if(!o.length)return null;r&&(i=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Fr),l.expandKey(e);const h=s;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=o.slice(-16).buffer,h||null}webCryptoDecrypt(t,e,i,n){if(this.key!==e||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,e,i,n));this.key=e,this.fastAesKey=new Br(this.subtle,e,n)}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 Nr(this.subtle,new Uint8Array(i),n).decrypt(t.buffer,e)}).catch(r=>(ki.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(t,e,i,n)))}onWebCryptoError(t,e,i,n){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,i,n);const r=this.flush();if(r)return r.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(t){let e=t;const i=t.length-t.length%16;return i!==t.length&&(e=t.slice(0,i),this.remainderData=t.slice(i)),e}logOnce(t){this.logEnabled&&(ki.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const $r=Math.pow(2,17);class Gr{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 Hr({type:ii.NETWORK_ERROR,details:ni.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error("Fragment does not have a "+(i?"part list":"url")),networkDetails:null}));this.abort();const n=this.config,r=n.fLoader,s=n.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(Kr(t));t.gap=!1}const l=this.loader=r?new r(n):new s(n),h=Vr(t);t.loader=l;const c=gr(n.fragLoadPolicy.default),u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:$r};t.stats=l.stats;const d={onSuccess:(e,i,n,r)=>{this.resetLoader(t,l);let s=e.data;n.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(s.slice(0,16)),s=s.slice(16)),a({frag:t,part:null,payload:s,networkDetails:r})},onError:(e,n,r,s)=>{this.resetLoader(t,l),o(new Hr({type:ii.NETWORK_ERROR,details:ni.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:vi({url:i,data:void 0},e),error:new Error(`HTTP Error ${e.code} ${e.text}`),networkDetails:r,stats:s}))},onAbort:(e,i,n)=>{this.resetLoader(t,l),o(new Hr({type:ii.NETWORK_ERROR,details:ni.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:n,stats:e}))},onTimeout:(e,i,n)=>{this.resetLoader(t,l),o(new Hr({type:ii.NETWORK_ERROR,details:ni.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:n,stats:e}))}};e&&(d.onProgress=(i,n,r,s)=>e({frag:t,part:null,payload:r,networkDetails:s})),l.load(h,u,d)})}loadPart(t,e,i){this.abort();const n=this.config,r=n.fLoader,s=n.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap)return void o(Kr(t,e));const l=this.loader=r?new r(n):new s(n),h=Vr(t,e);t.loader=l;const c=gr(n.fragLoadPolicy.default),u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:$r};e.stats=l.stats,l.load(h,u,{onSuccess:(n,r,s,o)=>{this.resetLoader(t,l),this.updateStatsFromPart(t,e);const h={frag:t,part:e,payload:n.data,networkDetails:o};i(h),a(h)},onError:(i,n,r,s)=>{this.resetLoader(t,l),o(new Hr({type:ii.NETWORK_ERROR,details:ni.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:vi({url:h.url,data:void 0},i),error:new Error(`HTTP Error ${i.code} ${i.text}`),networkDetails:r,stats:s}))},onAbort:(i,n,r)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,l),o(new Hr({type:ii.NETWORK_ERROR,details:ni.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:r,stats:i}))},onTimeout:(i,n,r)=>{this.resetLoader(t,l),o(new Hr({type:ii.NETWORK_ERROR,details:ni.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:r,stats:i}))}})})}updateStatsFromPart(t,e){const i=t.stats,n=e.stats,r=n.total;if(i.loaded+=n.loaded,r){const n=Math.round(t.duration/e.duration),s=Math.min(Math.round(i.loaded/r),n),a=(n-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=n.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 Vr(t,e=null){const i=e||t,n={frag:t,part:e,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},r=i.byteRangeStartOffset,s=i.byteRangeEndOffset;if(Je(r)&&Je(s)){var a;let e=r,i=s;if("initSegment"===t.sn&&("AES-128"===(o=null==(a=t.decryptdata)?void 0:a.method)||"AES-256"===o)){const t=s-r;t%16&&(i=s+(16-t%16)),0!==r&&(n.resetIV=!0,e=r-16)}n.rangeStart=e,n.rangeEnd=i}var o;return n}function Kr(t,e){const i=new Error(`GAP ${t.gap?"tag":"attribute"} found`),n={type:ii.MEDIA_ERROR,details:ni.FRAG_GAP,fatal:!1,frag:t,error:i,networkDetails:null};return e&&(n.part=e),(e||t).stats.aborted=!0,new Hr(n)}class Hr extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class Yr extends yi{constructor(t,e){super(t,e),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(){}}class jr{constructor(t,e,i,n=0,r=-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=n,this.part=r,this.partial=s}}const Wr={length:0,start:()=>0,end:()=>0};class zr{static isBuffered(t,e){if(t){const i=zr.getBuffered(t);for(let t=i.length;t--;)if(e>=i.start(t)&&e<=i.end(t))return!0}return!1}static bufferedRanges(t){if(t){const e=zr.getBuffered(t);return zr.timeRangesToArray(e)}return[]}static timeRangesToArray(t){const e=[];for(let i=0;i<t.length;i++)e.push({start:t.start(i),end:t.end(i)});return e}static bufferInfo(t,e,i){if(t){const n=zr.bufferedRanges(t);if(n.length)return zr.bufferedInfo(n,e,i)}return{len:0,start:e,end:e,bufferedIndex:-1}}static bufferedInfo(t,e,i){e=Math.max(0,e),t.length>1&&t.sort((t,e)=>t.start-e.start||e.end-t.end);let n=-1,r=[];if(i)for(let s=0;s<t.length;s++){e>=t[s].start&&e<=t[s].end&&(n=s);const a=r.length;if(a){const e=r[a-1].end;t[s].start-e<i?t[s].end>e&&(r[a-1].end=t[s].end):r.push(t[s])}else r.push(t[s])}else r=t;let s,a=0,o=e,l=e;for(let t=0;t<r.length;t++){const h=r[t].start,c=r[t].end;if(-1===n&&e>=h&&e<=c&&(n=t),e+i>=h&&e<c)o=h,l=c,a=l-e;else if(e+i<h){s=h;break}}return{len:a,start:o||0,end:l||0,nextStart:s,buffered:t,bufferedIndex:n}}static getBuffered(t){try{return t.buffered||Wr}catch(t){return ki.log("failed to get media.buffered",t),Wr}}}const qr=/\{\$([a-zA-Z0-9-_]+)\}/g;function Xr(t){return qr.test(t)}function Qr(t,e){if(null!==t.variableList||t.hasVariableRefs){const i=t.variableList;return e.replace(qr,e=>{const n=e.substring(2,e.length-1),r=null==i?void 0:i[n];return void 0===r?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${n}"`)),e):r})}return e}function Zr(t,e,i){let n,r,s=t.variableList;if(s||(t.variableList=s={}),"QUERYPARAM"in e){n=e.QUERYPARAM;try{const t=new self.URL(i).searchParams;if(!t.has(n))throw new Error(`"${n}" does not match any query parameter in URI: "${i}"`);r=t.get(n)}catch(e){t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${e.message}`))}}else n=e.NAME,r=e.VALUE;n in s?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${n}"`)):s[n]=r||""}function Jr(t,e,i){const n=e.IMPORT;if(i&&n in i){let e=t.variableList;e||(t.variableList=e={}),e[n]=i[n]}else t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${n}"`))}const ts=/^(\d+)x(\d+)$/,es=/(.+?)=(".*?"|.*?)(?:,|$)/g;class is{constructor(t,e){"string"==typeof t&&(t=is.parseAttrList(t,e)),pi(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]}enumeratedStringList(t,e){const i=this[t];return(i?i.split(/[ ,]+/):[]).reduce((t,e)=>(t[e.toLowerCase()]=!0,t),e)}bool(t){return"YES"===this[t]}decimalResolution(t){const e=ts.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t,e){let i;const n={};for(es.lastIndex=0;null!==(i=es.exec(t));){const r=i[1].trim();let s=i[2];const a=0===s.indexOf('"')&&s.lastIndexOf('"')===s.length-1;let o=!1;if(a)s=s.slice(1,-1);else switch(r){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(e&&(a||o))s=Qr(e,s);else if(!o&&!a)switch(r){case"CLOSED-CAPTIONS":if("NONE"===s)break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":ki.warn(`${t}: attribute ${r} is missing quotes`)}n[r]=s}return n}}function ns(t){return"ID"!==t&&"CLASS"!==t&&"CUE"!==t&&"START-DATE"!==t&&"DURATION"!==t&&"END-DATE"!==t&&"END-ON-NEXT"!==t}function rs(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t||"SCTE35-CMD"===t}class ss{constructor(t,e,i=0){var n;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==e?void 0:e.tagAnchor)||null,this.tagOrder=null!=(n=null==e?void 0:e.tagOrder)?n:i,e){const i=e.attr;for(const e in i)if(Object.prototype.hasOwnProperty.call(t,e)&&t[e]!==i[e]){ki.warn(`DATERANGE tag attribute: "${e}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=e;break}t=pi(new is({}),i,t)}if(this.attr=t,e?(this._startDate=e._startDate,this._cue=e._cue,this._endDate=e._endDate,this._dateAtEnd=e._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){const t=(null==e?void 0:e.endDate)||new Date(this.attr["END-DATE"]);Je(t.getTime())&&(this._endDate=t)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const t=this._cue;return void 0===t?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):t}get startTime(){const{tagAnchor:t}=this;return null===t||null===t.programDateTime?(ki.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${t}`),NaN):t.start+(this.startDate.getTime()-t.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const t=this._endDate||this._dateAtEnd;if(t)return t;const e=this.duration;return null!==e?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*e):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(Je(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 isInterstitial(){return"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&Je(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}class as{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.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=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}hasKey(t){return this.encryptedFragments.some(e=>{let i=e.decryptdata;return i||(e.setKeyFormat(t.keyFormat),i=e.decryptdata),!!i&&t.matches(i)})}get hasProgramDateTime(){return!!this.fragments.length&&Je(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(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const t=this.partList;if(t){const e=this.lastPartIndex;if(-1!==e){for(let i=t.length;i--;)if(t[i].index>e)return t[i].index;return e}}return 0}get lastPartSn(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const t=this.partEnd-this.fragmentStart;return this.age>Math.max(t,this.totalduration)+this.levelTargetDuration}return!1}}function os(t,e){return t.length===e.length&&!t.some((t,i)=>t!==e[i])}function ls(t,e){return!t&&!e||!(!t||!e)&&os(t,e)}function hs(t){return"AES-128"===t||"AES-256"===t||"AES-256-CTR"===t}function cs(t){switch(t){case"AES-128":case"AES-256":return xr;case"AES-256-CTR":return Mr;default:throw new Error(`invalid full segment method ${t}`)}}function us(t){return Uint8Array.from(atob(t),t=>t.charCodeAt(0))}function ds(t){return Uint8Array.from(unescape(encodeURIComponent(t)),t=>t.charCodeAt(0))}function fs(t){const e=function(t,e,i){const n=t[e];t[e]=t[i],t[i]=n};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}function gs(t){const e=t.split(":");let i=null;if("data"===e[0]&&2===e.length){const t=e[1].split(";"),n=t[t.length-1].split(",");if(2===n.length){const e="base64"===n[0],r=n[1];e?(t.splice(-1,1),i=us(r)):i=function(t){const e=ds(t).subarray(0,16),i=new Uint8Array(16);return i.set(e,16-e.length),i}(r)}}return i}const ps="undefined"!=typeof self?self:void 0;var ms={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},vs="org.w3.clearkey",ys="com.apple.streamingkeydelivery",As="com.microsoft.playready",Es="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function Ts(t){switch(t){case ys:return ms.FAIRPLAY;case As:return ms.PLAYREADY;case Es:return ms.WIDEVINE;case vs:return ms.CLEARKEY}}function bs(t){switch(t){case ms.FAIRPLAY:return ys;case ms.PLAYREADY:return As;case ms.WIDEVINE:return Es;case ms.CLEARKEY:return vs}}function Ss(t){const{drmSystems:e,widevineLicenseUrl:i}=t,n=e?[ms.FAIRPLAY,ms.WIDEVINE,ms.PLAYREADY,ms.CLEARKEY].filter(t=>!!e[t]):[];return!n[ms.WIDEVINE]&&i&&n.push(ms.WIDEVINE),n}const ks=null!=ps&&null!=(_s=ps.navigator)&&_s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var _s;function Ls(t){const e=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),i=String.fromCharCode.apply(null,Array.from(e)),n=i.substring(i.indexOf("<"),i.length),r=(new DOMParser).parseFromString(n,"text/xml").getElementsByTagName("KID")[0];if(r){const t=r.childNodes[0]?r.childNodes[0].nodeValue:r.getAttribute("VALUE");if(t){const e=us(t).subarray(0,16);return fs(e),e}}return null}let Is={};class Rs{static clearKeyUriToKeyIdMap(){Is={}}static setKeyIdForUri(t,e){Is[t]=e}static addKeyIdForUri(t){const e=Object.keys(Is).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,e),Is[t]=i,i}constructor(t,e,i,n=[1],r=null,s){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=n,this.iv=r,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&!hs(t),null!=s&&s.startsWith("0x")&&(this.keyId=new Uint8Array(Ci(s)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&os(t.keyFormatVersions,this.keyFormatVersions)&&ls(t.iv,this.iv)&&ls(t.keyId,this.keyId)}isSupported(){if(this.method){if(hs(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case ys:case Es:case As:case vs:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(t,e){if(!this.encrypted||!this.uri)return null;if(hs(this.method)){let e=this.iv;e||("number"!=typeof t&&(ki.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),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 Rs(this.method,this.uri,"identity",this.keyFormatVersions,e)}if(this.keyId){const t=Is[this.uri];if(t&&!os(this.keyId,t)&&Rs.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const i=gs(this.uri);if(i)switch(this.keyFormat){case Es:if(this.pssh=i,!this.keyId){const t=function(t){const e=[];if(t instanceof ArrayBuffer){const i=t.byteLength;let n=0;for(;n+32<i;){const i=pn(new DataView(t,n));e.push(i),n+=i.size}}return e}(i.buffer);if(t.length){var n;const e=t[0];this.keyId=null!=(n=e.kids)&&n.length?e.kids[0]:null}}this.keyId||(this.keyId=Cs(e));break;case As:{const t=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=gn(t,0,i),this.keyId=Ls(i);break}default:{let t=i.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;t=function(t){const e=null==t?void 0:t[Es];if(e)return e.keyId;return null}(e),t||(t=Cs(e),t||(t=Is[this.uri])),t&&(this.keyId=t,Rs.setKeyIdForUri(this.uri,t))}return this}}function Cs(t){const e=null==t?void 0:t[As];if(e){const t=gs(e.uri);if(t)return Ls(t)}return null}const Ps=/#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,Ds=/#EXT-X-MEDIA:(.*)/g,ws=/^#EXT(?:INF|-X-TARGETDURATION):/m,Os=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),xs=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class Ms{static findGroup(t,e){for(let i=0;i<t.length;i++){const n=t[i];if(n.id===e)return n}}static resolve(t,e){return Oi.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return ws.test(t)}static parseMasterPlaylist(t,e){const i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:Xr(t)},n=[];if(Ps.lastIndex=0,!t.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let r;for(;null!=(r=Ps.exec(t));)if(r[1]){var s;const t=new is(r[1],i),a=Qr(i,r[2]),o={attrs:t,bitrate:t.decimalInteger("BANDWIDTH")||t.decimalInteger("AVERAGE-BANDWIDTH"),name:t.NAME,url:Ms.resolve(a,e)},l=t.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),$s(t.CODECS,o);const h=t["SUPPLEMENTAL-CODECS"];h&&(o.supplemental={},$s(h,o.supplemental)),null!=(s=o.unknownCodecs)&&s.length||n.push(o),i.levels.push(o)}else if(r[3]){const t=r[3],n=r[4];switch(t){case"SESSION-DATA":{const t=new is(n,i),e=t["DATA-ID"];e&&(null===i.sessionData&&(i.sessionData={}),i.sessionData[e]=t);break}case"SESSION-KEY":{const t=Bs(n,e,i);t.encrypted&&t.isSupported()?(null===i.sessionKeys&&(i.sessionKeys=[]),i.sessionKeys.push(t)):ki.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${n}"`);break}case"DEFINE":Zr(i,new is(n,i),e);break;case"CONTENT-STEERING":{const t=new is(n,i);i.contentSteering={uri:Ms.resolve(t["SERVER-URI"],e),pathwayId:t["PATHWAY-ID"]||"."};break}case"START":i.startTimeOffset=Us(n)}}const a=n.length>0&&n.length<i.levels.length;return i.levels=a?n:i.levels,0===i.levels.length&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(t,e,i){let n;const r={},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(Ds.lastIndex=0;null!==(n=Ds.exec(t));){const t=new is(n[1],i),s=t.TYPE;if(s){const i=a[s],n=r[s]||[];r[s]=n;const l=t.LANGUAGE,h=t["ASSOC-LANGUAGE"],c=t.CHANNELS,u=t.CHARACTERISTICS,d=t["INSTREAM-ID"],f={attrs:t,bitrate:0,id:o++,groupId:t["GROUP-ID"]||"",name:t.NAME||l||"",type:s,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:l,url:t.URI?Ms.resolve(t.URI,e):""};if(h&&(f.assocLang=h),c&&(f.channels=c),u&&(f.characteristics=u),d&&(f.instreamId=d),null!=i&&i.length){const t=Ms.findGroup(i,f.groupId)||i[0];Gs(f,t,"audioCodec"),Gs(f,t,"textCodec")}n.push(f)}}return r}static parseLevelPlaylist(t,e,i,n,r,s){var a;const o={url:e},l=new as(e),h=l.fragments,c=[];let u,d,f,g,p=null,m=0,v=0,y=0,A=0,E=0,T=null,b=new $i(n,o),S=-1,k=!1,_=null;if(Os.lastIndex=0,l.m3u8=t,l.hasVariableRefs=Xr(t),"#EXTM3U"!==(null==(a=Os.exec(t))?void 0:a[0]))return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;null!==(u=Os.exec(t));){k&&(k=!1,b=new $i(n,o),b.playlistOffset=y,b.setStart(y),b.sn=m,b.cc=A,E&&(b.bitrate=E),b.level=i,p&&(b.initSegment=p,p.rawProgramDateTime&&(b.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null),_&&(b.setByteRange(_),_=null)));const t=u[1];if(t){b.duration=parseFloat(t);const e=(" "+u[2]).slice(1);b.title=e||null,b.tagList.push(e?["INF",t,e]:["INF",t])}else if(u[3]){if(Je(b.duration)){b.playlistOffset=y,b.setStart(y),f&&Hs(b,f,l),b.sn=m,b.level=i,b.cc=A,h.push(b);const t=(" "+u[3]).slice(1);b.relurl=Qr(l,t),Vs(b,T,c),T=b,y+=b.duration,m++,v=0,k=!0}}else{if(u=u[0].match(xs),!u){ki.warn("No matches on slow regex match for level playlist!");continue}for(d=1;d<u.length&&void 0===u[d];d++);const t=(" "+u[d]).slice(1),r=(" "+u[d+1]).slice(1),a=u[d+2]?(" "+u[d+2]).slice(1):null;switch(t){case"BYTERANGE":T?b.setByteRange(r,T):b.setByteRange(r);break;case"PROGRAM-DATE-TIME":b.rawProgramDateTime=r,b.tagList.push(["PROGRAM-DATE-TIME",r]),-1===S&&(S=h.length);break;case"PLAYLIST-TYPE":l.type&&Ys(l,t,u),l.type=r.toUpperCase();break;case"MEDIA-SEQUENCE":0!==l.startSN?Ys(l,t,u):h.length>0&&js(l,t,u),m=l.startSN=parseInt(r);break;case"SKIP":{l.skippedSegments&&Ys(l,t,u);const e=new is(r,l),i=e.decimalInteger("SKIPPED-SEGMENTS");if(Je(i)){l.skippedSegments+=i;for(let t=i;t--;)h.push(null);m+=i}const n=e.enumeratedString("RECENTLY-REMOVED-DATERANGES");n&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(n.split("\t")));break}case"TARGETDURATION":0!==l.targetduration&&Ys(l,t,u),l.targetduration=Math.max(parseInt(r),1);break;case"VERSION":null!==l.version&&Ys(l,t,u),l.version=parseInt(r);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||Ys(l,t,u),l.live=!1;break;case"#":(r||a)&&b.tagList.push(a?[r,a]:[r]);break;case"DISCONTINUITY":A++,b.tagList.push(["DIS"]);break;case"GAP":b.gap=!0,b.tagList.push([t]);break;case"BITRATE":b.tagList.push([t,r]),E=1e3*parseInt(r),Je(E)?b.bitrate=E:E=0;break;case"DATERANGE":{const t=new is(r,l),e=new ss(t,l.dateRanges[t.ID],l.dateRangeTagCount);l.dateRangeTagCount++,e.isValid||l.skippedSegments?l.dateRanges[e.id]=e:ki.warn(`Ignoring invalid DATERANGE tag: "${r}"`),b.tagList.push(["EXT-X-DATERANGE",r]);break}case"DEFINE":{const t=new is(r,l);"IMPORT"in t?Jr(l,t,s):Zr(l,t,e)}break;case"DISCONTINUITY-SEQUENCE":0!==l.startCC?Ys(l,t,u):h.length>0&&js(l,t,u),l.startCC=A=parseInt(r);break;case"KEY":{const t=Bs(r,e,l);if(t.isSupported()){if("NONE"===t.method){f=void 0;break}f||(f={});const e=f[t.keyFormat];null!=e&&e.matches(t)||(e&&(f=pi({},f)),f[t.keyFormat]=t)}else ki.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${r}"`);break}case"START":l.startTimeOffset=Us(r);break;case"MAP":{const t=new is(r,l);if(b.duration){const e=new $i(n,o);Ks(e,t,i,f),p=e,b.initSegment=p,p.rawProgramDateTime&&!b.rawProgramDateTime&&(b.rawProgramDateTime=p.rawProgramDateTime)}else{const e=b.byteRangeEndOffset;if(e){const t=b.byteRangeStartOffset;_=`${e-t}@${t}`}else _=null;Ks(b,t,i,f),p=b,k=!0}p.cc=A;break}case"SERVER-CONTROL":g&&Ys(l,t,u),g=new is(r),l.canBlockReload=g.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=g.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&g.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=g.optionalFloat("PART-HOLD-BACK",0),l.holdBack=g.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{l.partTarget&&Ys(l,t,u);const e=new is(r);l.partTarget=e.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=l.partList;t||(t=l.partList=[]);const e=v>0?t[t.length-1]:void 0,i=v++,n=new is(r,l),s=new Gi(n,b,o,i,e);t.push(s),b.duration+=s.duration;break}case"PRELOAD-HINT":{const t=new is(r,l);l.preloadHint=t;break}case"RENDITION-REPORT":{const t=new is(r,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(t);break}default:ki.warn(`line parsed but not handled: ${u}`)}}}T&&!T.relurl?(h.pop(),y-=T.duration,l.partList&&(l.fragmentHint=T)):l.partList&&(Vs(b,T,c),b.cc=A,l.fragmentHint=b,f&&Hs(b,f,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const L=h.length,I=h[0],R=h[L-1];if(y+=l.skippedSegments*l.targetduration,y>0&&L&&R){l.averagetargetduration=y/L;const t=R.sn;l.endSN="initSegment"!==t?t:0,l.live||(R.endList=!0),S>0&&(!function(t,e){let i=t[e];for(let n=e;n--;){const e=t[n];if(!e)return;e.programDateTime=i.programDateTime-1e3*e.duration,i=e}}(h,S),I&&c.unshift(I))}return l.fragmentHint&&(y+=l.fragmentHint.duration),l.totalduration=y,c.length&&l.dateRangeTagCount&&I&&Ns(c,l),l.endCC=A,l}}function Ns(t,e){let i=t.length;if(!i){if(!e.hasProgramDateTime)return;{const n=e.fragments[e.fragments.length-1];t.push(n),i++}}const n=t[i-1],r=e.live?1/0:e.totalduration,s=Object.keys(e.dateRanges);for(let o=s.length;o--;){const l=e.dateRanges[s[o]],h=l.startDate.getTime();l.tagAnchor=n.ref;for(let n=i;n--;){var a;if((null==(a=t[n])?void 0:a.sn)<e.startSN)break;const i=Fs(e,h,t,n,r);if(-1!==i){l.tagAnchor=e.fragments[i].ref;break}}}}function Fs(t,e,i,n,r){const s=i[n];if(s){const o=s.programDateTime;if(e>=o||0===n){var a;if(e<=o+1e3*(((null==(a=i[n+1])?void 0:a.start)||r)-s.start)){const r=i[n].sn-t.startSN;if(r<0)return-1;const s=t.fragments;if(s.length>i.length){for(let a=(i[n+1]||s[s.length-1]).sn-t.startSN;a>r;a--){const t=s[a].programDateTime;if(e>=t&&e<t+1e3*s[a].duration)return a}}return r}}}return-1}function Bs(t,e,i){var n,r;const s=new is(t,i),a=null!=(n=s.METHOD)?n:"",o=s.URI,l=s.hexadecimalInteger("IV"),h=s.KEYFORMATVERSIONS,c=null!=(r=s.KEYFORMAT)?r:"identity";o&&s.IV&&!l&&ki.error(`Invalid IV: ${s.IV}`);const u=o?Ms.resolve(o,e):"",d=(h||"1").split("/").map(Number).filter(Number.isFinite);return new Rs(a,u,c,d,l,s.KEYID)}function Us(t){const e=new is(t).decimalFloatingPoint("TIME-OFFSET");return Je(e)?e:null}function $s(t,e){let i=(t||"").split(/[ ,]+/).filter(t=>t);["video","audio","text"].forEach(t=>{const n=i.filter(e=>yn(e,t));n.length&&(e[`${t}Codec`]=n.map(t=>t.split("/")[0]).join(","),i=i.filter(t=>-1===n.indexOf(t)))}),e.unknownCodecs=i}function Gs(t,e,i){const n=e[i];n&&(t[i]=n)}function Vs(t,e,i){t.rawProgramDateTime?i.push(t):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime)}function Ks(t,e,i,n){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=i,t.sn="initSegment",n&&(t.levelkeys=n),t.initSegment=null}function Hs(t,e,i){t.levelkeys=e;const{encryptedFragments:n}=i;n.length&&n[n.length-1].levelkeys===e||!Object.keys(e).some(t=>e[t].isCommonEncryption)||n.push(t)}function Ys(t,e,i){t.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${i[0]})`)}function js(t,e,i){t.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${i[0]})`)}function Ws(t,e){const i=e.startPTS;if(Je(i)){let n,r=0;e.sn>t.sn?(r=i-t.start,n=t):(r=t.start-i,n=e),n.duration!==r&&n.setDuration(r)}else if(e.sn>t.sn){t.cc===e.cc&&t.minEndPTS?e.setStart(t.start+(t.minEndPTS-t.start)):e.setStart(t.start+t.duration)}else e.setStart(Math.max(t.start-e.duration,0))}function zs(t,e,i,n,r,s,a){n-i<=0&&(a.warn("Fragment should have a positive duration",e),n=i+e.duration,s=r+e.duration);let o=i,l=n;const h=e.startPTS,c=e.endPTS;if(Je(h)){const u=Math.abs(h-i);t&&u>t.totalduration?a.warn(`media timestamps and playlist times differ by ${u}s for level ${e.level} ${t.url}`):Je(e.deltaPTS)?e.deltaPTS=Math.max(u,e.deltaPTS):e.deltaPTS=u,o=Math.max(i,h),i=Math.min(i,h),r=void 0!==e.startDTS?Math.min(r,e.startDTS):r,l=Math.min(n,c),n=Math.max(n,c),s=void 0!==e.endDTS?Math.max(s,e.endDTS):s}const u=i-e.start;0!==e.start&&e.setStart(i),e.setDuration(n-e.start),e.startPTS=i,e.maxStartPTS=o,e.startDTS=r,e.endPTS=n,e.minEndPTS=l,e.endDTS=s;const d=e.sn;if(!t||d<t.startSN||d>t.endSN)return 0;let f;const g=d-t.startSN,p=t.fragments;for(p[g]=e,f=g;f>0;f--)Ws(p[f],p[f-1]);for(f=g;f<p.length-1;f++)Ws(p[f],p[f+1]);return t.fragmentHint&&Ws(p[p.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,u}function qs(t,e,i){if(t===e)return;let n=null;const r=t.fragments;for(let t=r.length-1;t>=0;t--){const e=r[t].initSegment;if(e){n=e;break}}let s;t.fragmentHint&&delete t.fragmentHint.endPTS,function(t,e,i){var n;const r=e.skippedSegments,s=Math.max(t.startSN,e.startSN)-e.startSN,a=(t.fragmentHint?1:0)+(r?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,o=e.startSN-t.startSN,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,h=null!=(n=t.fragmentHint)&&n.duration?t.fragments.concat(t.fragmentHint):t.fragments;for(let n=s;n<=a;n++){const s=h[o+n];let a=l[n];if(r&&!a&&s&&(a=e.fragments[n]=s),s&&a){i(s,a,n,l);const r=s.relurl,o=a.relurl;if(r&&ra(r,o))return void(e.playlistParsingError=Xs(`media sequence mismatch ${a.sn}:`,t,e,s,a));if(s.cc!==a.cc)return void(e.playlistParsingError=Xs(`discontinuity sequence mismatch (${s.cc}!=${a.cc})`,t,e,s,a))}}}(t,e,(t,i,r,a)=>{if((!e.startCC||e.skippedSegments)&&i.cc!==t.cc){const n=t.cc-i.cc;for(let t=r;t<a.length;t++)a[t].cc+=n;e.endCC=a[a.length-1].cc}Je(t.startPTS)&&Je(t.endPTS)&&(i.setStart(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.setDuration(t.endPTS-t.startPTS),i.duration&&(s=i),e.PTSKnown=e.alignedSliding=!0),t.hasStreams&&(i.elementaryStreams=t.elementaryStreams),i.loader=t.loader,t.hasStats&&(i.stats=t.stats),t.initSegment&&(i.initSegment=t.initSegment,n=t.initSegment)});const a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(n&&o.forEach(t=>{var e;!t||t.initSegment&&t.initSegment.relurl!==(null==(e=n)?void 0:e.relurl)||(t.initSegment=n)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(t=>!t),e.deltaUpdateFailed){i.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let t=e.skippedSegments;t--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=function(t,e,i){const{dateRanges:n,recentlyRemovedDateranges:r}=e,s=pi({},t);r&&r.forEach(t=>{delete s[t]});const a=Object.keys(s).length;if(!a)return n;return Object.keys(n).forEach(t=>{const e=s[t],r=new ss(n[t].attr,e);r.isValid?(s[t]=r,e||(r.tagOrder+=a)):i.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${qn(n[t].attr)}"`)}),s}(t.dateRanges,e,i));const n=t.fragments.filter(t=>t.rawProgramDateTime);if(t.hasProgramDateTime&&!e.hasProgramDateTime)for(let t=1;t<o.length;t++)null===o[t].programDateTime&&Vs(o[t],o[t-1],n);Ns(n,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var l;const i=ta(t,e.startSN-1);e.startCC=null!=(l=null==i?void 0:i.cc)?l:a[0].cc}!function(t,e,i){if(t&&e){let n=0;for(let r=0,s=t.length;r<s;r++){const s=t[r],a=e[r+n];s&&a&&s.index===a.index&&s.fragment.sn===a.fragment.sn?i(s,a):n--}}}(t.partList,e.partList,(t,e)=>{e.elementaryStreams=t.elementaryStreams,e.stats=t.stats}),s?zs(e,s,s.startPTS,s.endPTS,s.startDTS,s.endDTS,i):Qs(t,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;const h=e.advancedDateTime;if(e.advanced&&h){const t=e.edge;e.driftStart||(e.driftStartTime=h,e.driftStart=t),e.driftEndTime=h,e.driftEnd=t}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime;-1===e.requestScheduled&&(e.requestScheduled=t.requestScheduled)}function Xs(t,e,i,n,r){return new Error(`${t} ${r.url}\nPlaylist starting @${e.startSN}\n${e.m3u8}\n\nPlaylist starting @${i.startSN}\n${i.m3u8}`)}function Qs(t,e,i=!0){const n=e.startSN+e.skippedSegments-t.startSN,r=t.fragments,s=n>=0;let a=0;if(s&&n<r.length)a=r[n].start;else if(s&&e.startSN===t.endSN+1)a=t.fragmentEnd;else if(s&&i)a=t.fragmentStart+n*e.levelTargetDuration;else{if(e.skippedSegments||0!==e.fragmentStart)return;a=t.fragmentStart}Zs(e,a)}function Zs(t,e){if(e){const i=t.fragments;for(let n=t.skippedSegments;n<i.length;n++)i[n].addStart(e);t.fragmentHint&&t.fragmentHint.addStart(e)}}function Js(t,e=1/0){let i=1e3*t.targetduration;if(t.updated){const n=t.fragments,r=4;if(n.length&&i*r>e){const t=1e3*n[n.length-1].duration;t<i&&(i=t)}}else i/=2;return Math.round(i)}function ta(t,e,i){if(!t)return null;let n=t.fragments[e-t.startSN];return n||(n=t.fragmentHint,n&&n.sn===e?n:e<t.startSN&&i&&i.sn===e?i:null)}function ea(t,e,i){return t?ia(t.partList,e,i):null}function ia(t,e,i){if(t)for(let n=t.length;n--;){const r=t[n];if(r.index===i&&r.fragment.sn===e)return r}return null}function na(t){t.forEach((t,e)=>{var i;null==(i=t.details)||i.fragments.forEach(t=>{t.level=e,t.initSegment&&(t.initSegment.level=e)})})}function ra(t,e){return!(t===e||!e)&&sa(t)!==sa(e)}function sa(t){return t.replace(/\?[^?]*$/,"")}function aa(t,e){for(let n=0,r=t.length;n<r;n++){var i;if((null==(i=t[n])?void 0:i.cc)===e)return t[n]}return null}function oa(t,e){const i=t.start+e;t.startPTS=i,t.setStart(i),t.endPTS=i+t.duration}function la(t,e){const i=e.fragments;for(let e=0,n=i.length;e<n;e++)oa(i[e],t);e.fragmentHint&&oa(e.fragmentHint,t),e.alignedSliding=!0}function ha(t,e){if(!function(t,e){return!!(t&&e.startCC<t.endCC&&e.endCC>t.startCC)}(e,t))return;const i=Math.min(e.endCC,t.endCC),n=aa(e.fragments,i),r=aa(t.fragments,i);if(!n||!r)return;ki.log(`Aligning playlist at start of dicontinuity sequence ${i}`);la(n.start-r.start,t)}function ca(t,e){if(!t.hasProgramDateTime||!e.hasProgramDateTime)return;const i=t.fragments,n=e.fragments;if(!i.length||!n.length)return;let r,s;const a=Math.min(e.endCC,t.endCC);e.startCC<a&&t.startCC<a&&(r=aa(n,a),s=aa(i,a)),r&&s||(r=n[Math.floor(n.length/2)],s=aa(i,r.cc)||i[Math.floor(i.length/2)]);const o=r.programDateTime,l=s.programDateTime;if(!o||!l)return;la((l-o)/1e3-(s.start-r.start),t)}function ua(t,e,i){da(t,e,i),t.addEventListener(e,i)}function da(t,e,i){t.removeEventListener(e,i)}const fa=function(t){let e="";const i=t.length;for(let n=0;n<i;n++)e+=`[${t.start(n).toFixed(3)}-${t.end(n).toFixed(3)}]`;return e},ga="STOPPED",pa="IDLE",ma="KEY_LOADING",va="FRAG_LOADING",ya="FRAG_LOADING_WAITING_RETRY",Aa="WAITING_TRACK",Ea="PARSING",Ta="PARSED",ba="ENDED",Sa="ERROR",ka="WAITING_INIT_PTS",_a="WAITING_LEVEL";class La extends Yr{constructor(t,e,i,n,r){super(n,t.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=ga,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:t,fragCurrent:e,media:i,mediaBuffer:n,state:r}=this,s=i?i.currentTime:0,a=zr.bufferInfo(n||i,s,t.maxBufferHole),o=!a.len;if(this.log(`Media seeking to ${Je(s)?s.toFixed(3):s}, state: ${r}, ${o?"out of":"in"} buffer`),this.state===ba)this.resetLoadingState();else if(e){const i=t.maxFragLookUpTolerance,n=e.start-i,r=e.start+e.duration+i;if(o||r<a.start||n>a.end){const t=s>r;(s<n||t)&&(t&&e.loader&&(this.log(`Cancelling fragment load for seek (sn: ${e.sn})`),e.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(i){this.fragmentTracker.removeFragmentsInRange(s,1/0,this.playlistType,!0);if(s>this.lastCurrentTime&&(this.lastCurrentTime=s),!this.loadingParts){const t=Math.max(a.end,s),e=this.shouldLoadParts(this.getLevelDetails(),t);e&&(this.log(`LL-Part loading ON after seeking to ${s.toFixed(2)} with buffer @${t.toFixed(2)}`),this.loadingParts=e)}}this.hls.hasEnoughToStart||(this.log(`Setting ${o?"startPosition":"nextLoadPosition"} to ${s} for seek without enough to start`),this.nextLoadPosition=s,o&&(this.startPosition=s)),o&&this.state===pa&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=t,this.fragmentLoader=new Gr(t.config),this.keyLoader=i,this.fragmentTracker=e,this.config=t.config,this.decrypter=new Ur(t.config)}registerListeners(){const{hls:t}=this;t.on(ri.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(ri.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(ri.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ri.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(ri.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(ri.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(ri.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(ri.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ri.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(ri.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===ga)return;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=ga}get startPositionValue(){const{nextLoadPosition:t,startPosition:e}=this;return-1===e&&t?t:e}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(t,e){if(e.live||!this.media)return!1;const i=t.end||0,n=this.config.timelineOffset||0;if(i<=n)return!1;const r=t.buffered;this.config.maxBufferHole&&r&&r.length>1&&(t=zr.bufferedInfo(r,t.start,0));const s=t.nextStart;if(s&&s>n&&s<e.edge)return!1;if(this.media.currentTime<t.start)return!1;const a=e.partList;if(null!=a&&a.length){const t=a[a.length-1];return zr.isBuffered(this.media,t.start+t.duration/2)}const o=e.fragments[e.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(o)}getLevelDetails(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}get timelineOffset(){const t=this.config.timelineOffset;var e;return t?(null==(e=this.getLevelDetails())?void 0:e.appliedTimelineOffset)||t:0}onMediaAttached(t,e){const i=this.media=this.mediaBuffer=e.media;ua(i,"seeking",this.onMediaSeeking),ua(i,"ended",this.onMediaEnded);const n=this.config;this.levels&&n.autoStartLoad&&this.state===ga&&this.startLoad(n.startPosition)}onMediaDetaching(t,e){const i=!!e.transferMedia,n=this.media;if(null!==n){if(n.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),da(n,"seeking",this.onMediaSeeking),da(n,"ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(t,e){}onManifestLoaded(t,e){this.startTimeOffset=e.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=ga,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.startFragRequested=!0,this._loadFragForPlayback(t,e,i)}_loadFragForPlayback(t,e,i){this._doFragLoad(t,e,i,t=>{const e=t.frag;if(this.fragContextChanged(e))return this.warn(`${e.type} sn: ${e.sn}${t.part?" part: "+t.part.index:""} of ${this.fragInfo(e,!1,t.part)}) was dropped during download.`),void this.fragmentTracker.removeFragment(e);e.stats.chunkCount++,this._handleFragmentLoadProgress(t)}).then(t=>{if(!t)return;const e=this.state,i=t.frag;this.fragContextChanged(i)?(e===va||!this.fragCurrent&&e===Ea)&&(this.fragmentTracker.removeFragment(i),this.state=pa):("payload"in t&&(this.log(`Loaded ${i.type} sn: ${i.sn} of ${this.playlistLabel()} ${i.level}`),this.hls.trigger(ri.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t))}).catch(e=>{this.state!==ga&&this.state!==Sa&&(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)===Ir){const e=t.type,n=this.getFwdBufferInfo(this.mediaBuffer,e),r=Math.max(t.duration,n?n.len:this.config.maxBufferLength),s=this.backtrackFragment;(1===(s?t.sn-s.sn:0)||this.reduceMaxBufferLength(r,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)===Rr&&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)}waitForLive(t){const e=t.details;return(null==e?void 0:e.live)&&"EVENT"!==e.type&&(this.levelLastLoaded!==t||e.expired)}flushMainBuffer(t,e,i=null){if(!(t-e))return;const n={startOffset:t,endOffset:e,type:i};this.hls.trigger(ri.BUFFER_FLUSHING,n)}_loadInitSegment(t,e){this._doFragLoad(t,e).then(t=>{const e=null==t?void 0:t.frag;if(!e||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return t}).then(t=>{const{hls:e}=this,{frag:i,payload:n}=t,r=i.decryptdata;if(n&&n.byteLength>0&&null!=r&&r.key&&r.iv&&hs(r.method)){const s=self.performance.now();return this.decrypter.decrypt(new Uint8Array(n),r.key.buffer,r.iv.buffer,cs(r.method)).catch(t=>{throw e.trigger(ri.ERROR,{type:ii.MEDIA_ERROR,details:ni.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:i}),t}).then(n=>{const r=self.performance.now();return e.trigger(ri.FRAG_DECRYPTED,{frag:i,payload:n,stats:{tstart:s,tdecrypt:r}}),t.payload=n,this.completeInitSegmentLoad(t)})}return this.completeInitSegmentLoad(t)}).catch(e=>{this.state!==ga&&this.state!==Sa&&(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!==ga&&(this.state=pa),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()}unhandledEncryptionError(t,e){var i,n;const r=t.tracks;if(r&&!e.encrypted&&(null!=(i=r.audio)&&i.encrypted||null!=(n=r.video)&&n.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const t=this.media,i=new Error(`Encrypted track with no key in ${this.fragInfo(e)} (media ${t?"attached mediaKeys: "+t.mediaKeys:"detached"})`);return this.warn(i.message),!t||t.mediaKeys?!1:(this.hls.trigger(ri.ERROR,{type:ii.KEY_SYSTEM_ERROR,details:ni.KEY_SYSTEM_NO_KEYS,fatal:!1,error:i,frag:e}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(t){const{fragCurrent:e}=this;return!t||!e||t.sn!==e.sn||t.level!==e.level}fragBufferedComplete(t,e){const i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)} > buffer:${i?fa(zr.getBuffered(i)):"(detached)"})`),Ui(t)){var n;if(t.type!==ui){const e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return void(this.state=pa)}const e=null==(n=this.levels)?void 0:n[t.level];null!=e&&e.fragmentError&&(this.log(`Resetting level fragment error count of ${e.fragmentError} on frag buffered`),e.fragmentError=0)}this.state=pa}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const{frag:i,part:n,partsLoaded:r}=t,s=!r||0===r.length||r.some(t=>!t),a=new jr(i.level,i.sn,i.stats.chunkCount+1,0,n?n.index:-1,!s);e.flush(a)}_handleFragmentLoadProgress(t){}_doFragLoad(t,e,i=null,n){var r;this.fragCurrent=t;const s=e.details;if(!this.levels||!s)throw new Error(`frag load aborted, missing level${s?"":" detail"}s`);let a=null;if(!t.encrypted||null!=(r=t.decryptdata)&&r.key)t.encrypted||(a=this.keyLoader.loadClear(t,s.encryptedFragments,this.startFragRequested),a&&this.log("[eme] blocking frag load until media-keys acquired"));else if(this.log(`Loading key for ${t.sn} of [${s.startSN}-${s.endSN}], ${this.playlistLabel()} ${t.level}`),this.state=ma,this.fragCurrent=t,a=this.keyLoader.load(t).then(t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(ri.KEY_LOADED,t),this.state===ma&&(this.state=pa),t}),this.hls.trigger(ri.KEY_LOADING,{frag:t}),null===this.fragCurrent)return this.log("context changed in KEY_LOADING"),Promise.resolve(null);const o=this.fragPrevious;if(Ui(t)&&(!o||t.sn!==o.sn)){const i=this.shouldLoadParts(e.details,t.end);i!==this.loadingParts&&(this.log(`LL-Part loading ${i?"ON":"OFF"} loading sn ${null==o?void 0:o.sn}->${t.sn}`),this.loadingParts=i)}if(i=Math.max(t.start,i||0),this.loadingParts&&Ui(t)){const r=s.partList;if(r&&n){i>s.fragmentEnd&&s.fragmentHint&&(t=s.fragmentHint);const o=this.getNextPart(r,t,i);if(o>-1){const l=r[o];let h;return t=this.fragCurrent=l.fragment,this.log(`Loading ${t.type} sn: ${t.sn} part: ${l.index} (${o}/${r.length-1}) of ${this.fragInfo(t,!1,l)}) cc: ${t.cc} [${s.startSN}-${s.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=va,h=a?a.then(i=>!i||this.fragContextChanged(i.frag)?null:this.doFragPartsLoad(t,l,e,n)).catch(t=>this.handleFragLoadError(t)):this.doFragPartsLoad(t,l,e,n).catch(t=>this.handleFragLoadError(t)),this.hls.trigger(ri.FRAG_LOADING,{frag:t,part:l,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):h}if(!t.url||this.loadedEndOfParts(r,i))return Promise.resolve(null)}}var l;if(Ui(t)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)} Check buffer at sn: ${t.sn} loaded parts: ${null==(l=s.partList)?void 0:l.filter(t=>t.loaded).map(t=>`[${t.start}-${t.end}]`)}`),this.loadingParts=!1;else if(!t.url)return Promise.resolve(null);this.log(`Loading ${t.type} sn: ${t.sn} of ${this.fragInfo(t,!1)}) cc: ${t.cc} ${"["+s.startSN+"-"+s.endSN+"]"}, target: ${parseFloat(i.toFixed(3))}`),Je(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=va;const h=this.config.progressive&&t.type!==ui;let c;return c=h&&a?a.then(e=>!e||this.fragContextChanged(e.frag)?null:this.fragmentLoader.load(t,n)).catch(t=>this.handleFragLoadError(t)):Promise.all([this.fragmentLoader.load(t,h?n:void 0),a]).then(([t])=>(!h&&n&&n(t),t)).catch(t=>this.handleFragLoadError(t)),this.hls.trigger(ri.FRAG_LOADING,{frag:t,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):c}doFragPartsLoad(t,e,i,n){return new Promise((r,s)=>{var a;const o=[],l=null==(a=i.details)?void 0:a.partList,h=e=>{this.fragmentLoader.loadPart(t,e,n).then(n=>{o[e.index]=n;const s=n.part;this.hls.trigger(ri.FRAG_LOADED,n);const a=ea(i.details,t.sn,e.index+1)||ia(l,t.sn,e.index+1);if(!a)return r({frag:t,part:s,partsLoaded:o});h(a)}).catch(s)};h(e)})}handleFragLoadError(t){if("data"in t){const e=t.data;e.frag&&e.details===ni.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):e.frag&&e.type===ii.KEY_SYSTEM_ERROR?(e.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(e.frag)):this.hls.trigger(ri.ERROR,e)}else this.hls.trigger(ri.ERROR,{type:ii.OTHER_ERROR,details:ni.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==Ea)return void(this.fragCurrent||this.state===ga||this.state===Sa||(this.state=pa));const{frag:i,part:n,level:r}=e,s=self.performance.now();i.stats.parsing.end=s,n&&(n.stats.parsing.end=s);const a=this.getLevelDetails(),o=a&&i.sn>a.endSN||this.shouldLoadParts(a,i.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${i.end.toFixed(2)}`),this.loadingParts=o),this.updateLevelTiming(i,n,r,t.partial)}shouldLoadParts(t,e){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(t.partList){var i;const r=t.partList[0];if(r.fragment.type===ui)return!1;if(e>=r.end+((null==(i=t.fragmentHint)?void 0:i.duration)||0)){var n;if((this.hls.hasEnoughToStart?(null==(n=this.media)?void 0:n.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}}return!1}getCurrentContext(t){const{levels:e,fragCurrent:i}=this,{level:n,sn:r,part:s}=t;if(null==e||!e[n])return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${n}. The current chunk will not be buffered.`),null;const a=e[n],o=a.details,l=s>-1?ea(o,r,s):null,h=l?l.fragment:ta(o,r,i);return h?(i&&i!==h&&(h.stats=i.stats),{frag:h,part:l,level:a}):null}bufferFragmentData(t,e,i,n,r){if(this.state!==Ea)return;const{data1:s,data2:a}=t;let o=s;if(a&&(o=ln(s,a)),!o.length)return;const l=this.initPTS[e.cc],h=l?-l.baseTime/l.timescale:void 0,c={type:t.type,frag:e,part:i,chunkMeta:n,offset:h,parent:e.type,data:o};if(this.hls.trigger(ri.BUFFER_APPENDING,c),t.dropped&&t.independent&&!i){if(r)return;this.flushBufferGap(e)}}flushBufferGap(t){const e=this.media;if(!e)return;if(!zr.isBuffered(e,e.currentTime))return void this.flushMainBuffer(0,t.start);const i=e.currentTime,n=zr.bufferInfo(e,i,0),r=t.duration,s=Math.min(2*this.config.maxFragLookUpTolerance,.25*r),a=Math.max(Math.min(t.start-s,n.end-s),i+s);t.start-a>s&&this.flushMainBuffer(a,t.start)}getFwdBufferInfo(t,e){var i;const n=this.getLoadPosition();if(!Je(n))return null;const r=this.lastCurrentTime>n||null!=(i=this.media)&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,n,e,r)}getFwdBufferInfoAtPos(t,e,i,n){const r=zr.bufferInfo(t,e,n);if(0===r.len&&void 0!==r.nextStart){const s=this.fragmentTracker.getBufferedFrag(e,i);if(s&&(r.nextStart<=s.end||s.gap)){const i=Math.max(Math.min(r.nextStart,s.end)-e,n);return zr.bufferInfo(t,e,i)}}return r}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)}exceedsMaxBuffer(t,e,i){const n=t.nextStart;if(n&&i.start>n){const n=t.buffered;if(n){let r=t.len;const s=t.bufferedIndex;for(let t=n.length-1;t>s;t--)n[t].start<i.start&&(r+=n[t].end-n[t].start);return r>=e}}return!1}reduceMaxBufferLength(t,e){const i=this.config,n=Math.max(Math.min(t-e,i.maxBufferLength),e),r=Math.max(t-3*e,i.maxMaxBufferLength/2,n);return r>=n&&(i.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0)}getAppendedFrag(t,e=hi){const i=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(t,e):null;return i&&"fragment"in i?i.fragment:i}getNextFragment(t,e){const i=e.fragments,n=i.length;if(!n)return null;const{config:r}=this,s=e.fragmentStart,a=r.lowLatencyMode&&!!e.partList;let o=null;if(e.live){const i=r.initialLiveManifestSize;if(n<i)return this.warn(`Not enough fragments to start playback (have: ${n}, need: ${i})`),null;if(!e.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||t<s){var l;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(e);const i=this.config.startPosition,n=this.hls.startPosition,r=this.hls.liveSyncPosition,h=(null==(l=o)?void 0:l.start)||0;let c,u;-1!==n&&n>=s?(c=n,u=n===i?"config":"next load start"):null!==r?(c=r,u="live edge"):(c=t,u="buffer pos"),c<h&&(c=h,u="live frag start"),c<s&&(c=s,u="playlist start"),this.startPosition==c&&this.nextLoadPosition==c||(this.log(`Setting startPosition to ${c.toFixed(3)} ${-1===n?"":`(from ${i}) `}based on ${u}. live edge: ${r} live frag start: ${h.toFixed(3)} playlist start: ${s.toFixed(3)} buffer pos: ${t}`),this.startPosition=this.nextLoadPosition=c)}}else t<=s&&(o=i[0]);if(!o){const i=this.loadingParts?e.partEnd:e.fragmentEnd;o=this.getFragmentAtPosition(t,i,e)}let h=this.filterReplacedPrimary(o,e);if(!h&&o){const t=o.sn-e.startSN;h=this.filterReplacedPrimary(i[t+1]||null,e)}return this.mapToInitFragWhenRequired(h)}isLoopLoading(t,e){if(this.nextLoadPosition<=e)return!1;const i=this.fragmentTracker.getState(t);return i===Cr||i===Rr&&!!t.gap}getNextFragmentLoopLoading(t,e,i,n,r){let s=null;if(t.gap&&(s=this.getNextFragment(this.nextLoadPosition,e),s&&!s.gap&&i.nextStart)){const t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,n,0);if(null!==t&&i.len+t.len>=r){const t=s.sn;return this.loopSn!==t&&(this.log(`buffer full after gaps in "${n}" playlist starting at sn: ${t}`),this.loopSn=t),null}}return this.loopSn=void 0,s}get primaryPrefetch(){if(Ia(this.config)){var t;if(null==(t=this.hls.interstitialsManager)||null==(t=t.playingItem)?void 0:t.event)return!0}return!1}filterReplacedPrimary(t,e){if(!t)return t;if(Ia(this.config)&&t.type!==ui){const i=this.hls.interstitialsManager,n=null==i?void 0:i.bufferingItem;if(n){const i=n.event;if(i){if(i.appendInPlace||Math.abs(t.start-n.start)>1||0===n.start)return null}else{if(t.end<=n.start&&!1===(null==e?void 0:e.live))return null;if(t.start>n.end&&n.nextEvent&&(n.nextEvent.appendInPlace||t.start-n.end>1))return null}}const r=null==i?void 0:i.playerQueue;if(r)for(let e=r.length;e--;){const i=r[e].interstitial;if(i.appendInPlace&&t.start>=i.startTime&&t.end<=i.resumeTime)return null}}return t}mapToInitFragWhenRequired(t){return null==t||!t.initSegment||t.initSegment.data||this.bitrateTest?t:t.initSegment}getNextPart(t,e,i){let n=-1,r=!1,s=!0;for(let a=0,o=t.length;a<o;a++){const o=t[a];if(s=s&&!o.independent,n>-1&&i<o.start)break;const l=o.loaded;l?n=-1:(r||(o.independent||s)&&o.fragment===e)&&(o.fragment!==e&&this.warn(`Need buffer at ${i} but next unloaded part starts at ${o.start}`),n=a),r=l}return n}loadedEndOfParts(t,e){let i;for(let n=t.length;n--;){if(i=t[n],!i.loaded)return!1;if(e>i.start)return!0}return!1}getInitialLiveFragment(t){const e=t.fragments,i=this.fragPrevious;let n=null;if(i){if(t.hasProgramDateTime&&(n=function(t,e,i){if(null===e||!Array.isArray(t)||!t.length||!Je(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;for(let n=0;n<t.length;++n){const r=t[n];if(or(e,i,r))return r}return null}(e,i.endProgramDateTime,this.config.maxFragLookUpTolerance),n&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`)),!n){const r=i.sn+1;if(r>=t.startSN&&r<=t.endSN){const s=e[r-t.startSN];i.cc===s.cc&&(n=s,this.log(`Live playlist, switching playlist, load frag with next SN: ${n.sn}`))}n||(n=lr(t,i.cc,i.end),n&&this.log(`Live playlist, switching playlist, load frag with same CC: ${n.sn}`))}}else{const e=this.hls.liveSyncPosition;null!==e&&(n=this.getFragmentAtPosition(e,this.bitrateTest?t.fragmentEnd:t.edge,t))}return n}getFragmentAtPosition(t,e,i){const{config:n}=this;let{fragPrevious:r}=this,{fragments:s,endSN:a}=i;const{fragmentHint:o}=i,{maxFragLookUpTolerance:l}=n,h=i.partList,c=!!(this.loadingParts&&null!=h&&h.length&&o);let u;if(c&&!this.bitrateTest&&h[h.length-1].fragment.sn===o.sn&&(s=s.concat(o),a=o.sn),t<e){var d;u=sr(r,s,t,t<this.lastCurrentTime||t>e-l||null!=(d=this.media)&&d.paused||!this.startFragRequested?0:l)}else u=s[s.length-1];if(u){const t=u.sn-i.startSN,e=this.fragmentTracker.getState(u);if((e===Cr||e===Rr&&u.gap)&&(r=u),r&&u.sn===r.sn&&(!c||h[0].fragment.sn>u.sn||!i.live)){if(u.level===r.level){const e=s[t+1];u=u.sn<a&&this.fragmentTracker.getState(e)!==Cr?e:null}}}return u}alignPlaylists(t,e,i){const n=t.fragments.length;if(!n)return this.warn("No fragments in live playlist"),0;const r=t.fragmentStart,s=!e,a=t.alignedSliding&&Je(r);if(s||!a&&!r){!function(t,e){t&&(ha(e,t),e.alignedSliding||ca(e,t),e.alignedSliding||e.skippedSegments||Qs(t,e,!1))}(i,t);const r=t.fragmentStart;return this.log(`Live playlist sliding: ${r.toFixed(2)} start-sn: ${e?e.startSN:"na"}->${t.startSN} fragments: ${n}`),r}return r}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;i<e&&(i=-1);const n=this.timelineOffset;if(-1===i){const r=null!==this.startTimeOffset,s=r?this.startTimeOffset:t.startTimeOffset;null!==s&&Je(s)?(i=e+s,s<0&&(i+=t.edge),i=Math.min(Math.max(e,i),e+t.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${s} found in ${r?"multivariant":"media"} playlist`),this.startPosition=i):t.live?(i=this.hls.liveSyncPosition||e,this.log(`Setting startPosition to -1 to start at live edge ${i}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+n}this.nextLoadPosition=i+n}getLoadPosition(){var t;const{media:e}=this;let i=0;return null!=(t=this.hls)&&t.hasEnoughToStart&&e?i=e.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(t,e){this.transmuxer&&t.type===this.playlistType&&Ui(t)&&t.stats.aborted&&(this.log(`Fragment ${t.sn}${e?" part "+e.index:""} of ${this.playlistLabel()} ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){this.fragCurrent&&(this.fragContextChanged(t)||this.state===ya)||(this.state=pa)}onFragmentOrKeyLoadError(t,e){var i;if(e.chunkMeta&&!e.frag){const t=this.getCurrentContext(e.chunkMeta);t&&(e.frag=t.frag)}const n=e.frag;if(!n||n.type!==t||!this.levels)return;var r;if(this.fragContextChanged(n))return void this.warn(`Frag load error must match current frag to retry ${n.url} > ${null==(r=this.fragCurrent)?void 0:r.url}`);const s=e.details===ni.FRAG_GAP;s&&this.fragmentTracker.fragBuffered(n,!0);const a=e.errorAction;if(!a)return void(this.state=Sa);const{action:o,flags:l,retryCount:h=0,retryConfig:c}=a,u=!!c,d=u&&o===Er,f=u&&!a.resolved&&l===br,g=null==(i=this.hls.latestLevelDetails)?void 0:i.live;if(!d&&f&&Ui(n)&&!n.endList&&g&&!ur(e))this.resetFragmentErrors(t),this.treatAsGap(n),a.resolved=!0;else if((d||f)&&h<c.maxNumRetry){var p;const i=mr(null==(p=e.response)?void 0:p.code),r=fr(c,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+r,this.state=ya,a.resolved=!0,i)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(e.reason="offline");this.warn(`Fragment ${n.sn} of ${t} ${n.level} errored with ${e.details}, retrying loading ${h+1}/${c.maxNumRetry} in ${r}ms`)}else if(c){if(this.resetFragmentErrors(t),!(h<c.maxNumRetry))return void this.warn(`${e.details} reached or exceeded max retry (${h})`);s||o===Ar||(a.resolved=!0)}else this.state=o===yr?_a:Sa;this.tickImmediate()}checkRetryDate(){const t=self.performance.now(),e=this.retryDate,i=e===1/0;(!e||t>=e||i&&!mr(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=pa)}reduceLengthAndFlushBuffer(t){if(this.state===Ea||this.state===Ta){const e=t.frag,i=t.parent,n=this.getFwdBufferInfo(this.mediaBuffer,i),r=n&&n.len>.5;r&&this.reduceMaxBufferLength(n.len,(null==e?void 0:e.duration)||10);const s=!r;return s&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${i} buffer`),e&&(this.fragmentTracker.removeFragment(e),this.nextLoadPosition=e.start),this.resetLoadingState(),s}return!1}resetFragmentErrors(t){t===ci&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==ga&&(this.state=pa)}afterBufferFlushed(t,e,i){if(!t)return;const n=zr.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,n,i),this.state===ba&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==ga&&(this.state=pa)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=this.levelLastLoaded,e=t?t.details:null;null!=e&&e.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(e,e.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.log(`Loading context changed while buffering sn ${t.sn} of ${this.playlistLabel()} ${-1===t.level?"<removed>":t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,e,i,n){const r=i.details;if(!r)return void this.warn("level.details undefined");if(!Object.keys(t.elementaryStreams).reduce((e,s)=>{const a=t.elementaryStreams[s];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${t.sn} ${s} duration reliably (${o})`),e||!1;const l=n?0:zs(r,t,a.startPTS,a.endPTS,a.startDTS,a.endDTS,this);return this.hls.trigger(ri.LEVEL_PTS_UPDATED,{details:r,level:i,drift:l,type:s,frag:t,start:a.startPTS,end:a.endPTS}),!0}return e},!1)){var s;const e=null===(null==(s=this.transmuxer)?void 0:s.error);if((0===i.fragmentError||e&&(i.fragmentError<2||t.endList))&&this.treatAsGap(t,i),e){const e=new Error(`Found no media in fragment ${t.sn} of ${this.playlistLabel()} ${t.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(e.message),this.hls.trigger(ri.ERROR,{type:ii.MEDIA_ERROR,details:ni.FRAG_PARSING_ERROR,fatal:!1,error:e,frag:t,reason:`Found no media in msn ${t.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=Ta,this.log(`Parsed ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)})`),this.hls.trigger(ri.FRAG_PARSED,{frag:t,part:e})}playlistLabel(){return this.playlistType===hi?"level":"track"}fragInfo(t,e=!0,i){var n,r;return`${this.playlistLabel()} ${t.level} (${i?"part":"frag"}:[${(null!=(n=e&&!i?t.startPTS:(i||t).start)?n:NaN).toFixed(3)}-${(null!=(r=e&&!i?t.endPTS:(i||t).end)?r:NaN).toFixed(3)}]${i&&"main"===t.type?"INDEPENDENT="+(i.independent?"YES":"NO"):""}`}treatAsGap(t,e){e&&e.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)}resetTransmuxer(){var t;null==(t=this.transmuxer)||t.reset()}recoverWorkerError(t){"demuxerWorker"===t.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`))}get state(){return this._state}}function Ia(t){return!!t.interstitialsController&&!1!==t.enableInterstitialPlayback}class Ra{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 n=0;for(let e=0;e<t.length;e++){const r=t[e];i.set(r,n),n+=r.length}return i}(t,e),this.reset(),i):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}var Ca,Pa={exports:{}};var Da=(Ca||(Ca=1,function(t){var e=Object.prototype.hasOwnProperty,i="~";function n(){}function r(t,e,i){this.fn=t,this.context=e,this.once=i||!1}function s(t,e,n,s,a){if("function"!=typeof n)throw new TypeError("The listener must be a function");var o=new r(n,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 n:delete t._events[e]}function o(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(i=!1)),o.prototype.eventNames=function(){var t,n,r=[];if(0===this._eventsCount)return r;for(n in t=this._events)e.call(t,n)&&r.push(i?n.slice(1):n);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},o.prototype.listeners=function(t){var e=i?i+t:t,n=this._events[e];if(!n)return[];if(n.fn)return[n.fn];for(var r=0,s=n.length,a=new Array(s);r<s;r++)a[r]=n[r].fn;return a},o.prototype.listenerCount=function(t){var e=i?i+t:t,n=this._events[e];return n?n.fn?1:n.length:0},o.prototype.emit=function(t,e,n,r,s,a){var o=i?i+t:t;if(!this._events[o])return!1;var l,h,c=this._events[o],u=arguments.length;if(c.fn){switch(c.once&&this.removeListener(t,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,n),!0;case 4:return c.fn.call(c.context,e,n,r),!0;case 5:return c.fn.call(c.context,e,n,r,s),!0;case 6:return c.fn.call(c.context,e,n,r,s,a),!0}for(h=1,l=new Array(u-1);h<u;h++)l[h-1]=arguments[h];c.fn.apply(c.context,l)}else{var d,f=c.length;for(h=0;h<f;h++)switch(c[h].once&&this.removeListener(t,c[h].fn,void 0,!0),u){case 1:c[h].fn.call(c[h].context);break;case 2:c[h].fn.call(c[h].context,e);break;case 3:c[h].fn.call(c[h].context,e,n);break;case 4:c[h].fn.call(c[h].context,e,n,r);break;default:if(!l)for(d=1,l=new Array(u-1);d<u;d++)l[d-1]=arguments[d];c[h].fn.apply(c[h].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,n,r){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||r&&!o.once||n&&o.context!==n||a(this,s);else{for(var l=0,h=[],c=o.length;l<c;l++)(o[l].fn!==e||r&&!o[l].once||n&&o[l].context!==n)&&h.push(o[l]);h.length?this._events[s]=1===h.length?h[0]:h: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 n,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}(Pa)),Pa.exports),wa=Pi(Da);const Oa="1.6.17",xa={};function Ma(t,e){return 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}function Na(t,e){return 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}function Fa(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}function Ba(t,e){const i=e;let n=0;for(;Na(t,e);){n+=10;n+=Fa(t,e+6),Ma(t,e+10)&&(n+=10),e+=n}if(n>0)return t.subarray(i,i+n)}function Ua(t,e){return 255===t[e]&&240==(246&t[e+1])}function $a(t,e){return 1&t[e+1]?7:9}function Ga(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function Va(t,e){return e+1<t.length&&Ua(t,e)}function Ka(t,e){if(Va(t,e)){const i=$a(t,e);if(e+i>=t.length)return!1;const n=Ga(t,e);if(n<=i)return!1;const r=e+n;return r===t.length||Va(t,r)}return!1}function Ha(t,e,i,n,r){if(!t.samplerate){const s=function(t,e,i,n){const r=e[i+2],s=r>>2&15;if(s>12){const e=new Error(`invalid ADTS sampling index:${s}`);return void t.emit(ri.ERROR,ri.ERROR,{type:ii.MEDIA_ERROR,details:ni.FRAG_PARSING_ERROR,fatal:!0,error:e,reason:e.message})}const a=1+(r>>6&3),o=e[i+3]>>6&3|(1&r)<<2,l="mp4a.40."+a,h=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][s];let c=s;5!==a&&29!==a||(c-=3);const u=[a<<3|(14&c)>>1,(1&c)<<7|o<<3];return ki.log(`manifest codec:${n}, parsed codec:${l}, channels:${o}, rate:${h} (ADTS object type:${a} sampling index:${s})`),{config:u,samplerate:h,channelCount:o,codec:l,parsedCodec:l,manifestCodec:n}}(e,i,n,r);if(!s)return;pi(t,s)}}function Ya(t){return 9216e4/t}function ja(t,e,i,n,r){const s=n+r*Ya(t.samplerate),a=function(t,e){const i=$a(t,e);if(e+i<=t.length){const n=Ga(t,e)-i;if(n>0)return{headerLength:i,frameLength:n}}}(e,i);let o;if(a){const{frameLength:n,headerLength:r}=a,l=r+n,h=Math.max(0,i+l-e.length);h?(o=new Uint8Array(l-r),o.set(e.subarray(i+r,e.length),0)):o=e.subarray(i+r,i+l);const c={unit:o,pts:s};return h||t.samples.push(c),{sample:c,length:l,missing:h}}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}}function Wa(t,e){return Na(t,e)&&Fa(t,e+6)+10<=t.length-e}function za(t,e=0,i=1/0){return function(t,e,i,n){const r=function(t){return t instanceof ArrayBuffer?t:t.buffer}(t);let s=1;"BYTES_PER_ELEMENT"in n&&(s=n.BYTES_PER_ELEMENT);const a=(u=t,u&&u.buffer instanceof ArrayBuffer&&void 0!==u.byteLength&&void 0!==u.byteOffset?t.byteOffset:0),o=(a+t.byteLength)/s,l=(a+e)/s,h=Math.floor(Math.max(0,Math.min(l,o))),c=Math.floor(Math.min(h+Math.max(i,0),o));var u;return new n(r,h,c-h)}(t,e,i,Uint8Array)}function qa(t){const e={key:t.type,description:"",data:"",mimeType:null,pictureType:null};if(t.size<2)return;if(3!==t.data[0])return void console.log("Ignore frame with unrecognized character encoding");const i=t.data.subarray(1).indexOf(0);if(-1===i)return;const n=Ii(za(t.data,1,i)),r=t.data[2+i],s=t.data.subarray(3+i).indexOf(0);if(-1===s)return;const a=Ii(za(t.data,3+i,s));let o;return o="--\x3e"===n?Ii(za(t.data,4+i+s)):function(t){return t instanceof ArrayBuffer?t:0==t.byteOffset&&t.byteLength==t.buffer.byteLength?t.buffer:new Uint8Array(t).buffer}(t.data.subarray(4+i+s)),e.mimeType=n,e.pictureType=r,e.description=a,e.data=o,e}function Xa(t){return"PRIV"===t.type?function(t){if(t.size<2)return;const e=Ii(t.data,!0),i=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:i.buffer}}(t):"W"===t.type[0]?function(t){if("WXXX"===t.type){if(t.size<2)return;let e=1;const i=Ii(t.data.subarray(e),!0);e+=i.length+1;const n=Ii(t.data.subarray(e));return{key:t.type,info:i,data:n}}const e=Ii(t.data);return{key:t.type,info:"",data:e}}(t):"APIC"===t.type?qa(t):function(t){if(t.size<2)return;if("TXXX"===t.type){let e=1;const i=Ii(t.data.subarray(e),!0);e+=i.length+1;const n=Ii(t.data.subarray(e));return{key:t.type,info:i,data:n}}const e=Ii(t.data.subarray(1));return{key:t.type,info:"",data:e}}(t)}function Qa(t){const e=String.fromCharCode(t[0],t[1],t[2],t[3]),i=Fa(t,4);return{type:e,size:i,data:t.subarray(10,10+i)}}function Za(t){let e=0;const i=[];for(;Na(t,e);){const n=Fa(t,e+6);t[e+5]>>6&1&&(e+=10),e+=10;const r=e+n;for(;e+10<r;){const n=Qa(t.subarray(e)),r=Xa(n);r&&i.push(r),e+=n.size+10}Ma(t,e)&&(e+=10)}return i}function Ja(t){return t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info}function to(t){if(8===t.data.byteLength){const e=new Uint8Array(t.data),i=1&e[3];let n=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return n/=45,i&&(n+=47721858.84),Math.round(n)}}function eo(t){const e=Za(t);for(let t=0;t<e.length;t++){const i=e[t];if(Ja(i))return to(i)}}let io=function(t){return t.audioId3="org.id3",t.dateRange="com.apple.quicktime.HLS",t.emsg="https://aomedia.org/emsg/ID3",t.misbklv="urn:misb:KLV:bin:1910.1",t}({});function no(t="",e=9e4){return{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class ro{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,n){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=ln(this.cachedData,t),this.cachedData=null);let i,n=Ba(t,0),r=n?n.length:0;const s=this._audioTrack,a=this._id3Track,o=n?eo(n):void 0,l=t.length;for((null===this.basePTS||0===this.frameIndex&&Je(o))&&(this.basePTS=so(o,e,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),n&&n.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:io.audioId3,duration:Number.POSITIVE_INFINITY});r<l;){if(this.canParse(t,r)){const e=this.appendFrame(s,t,r);e?(this.frameIndex++,this.lastPTS=e.sample.pts,r+=e.length,i=r):r=l}else Wa(t,r)?(n=Ba(t,r),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:io.audioId3,duration:Number.POSITIVE_INFINITY}),r+=n.length,i=r):r++;if(r===l&&i!==l){const e=t.slice(i);this.cachedData?this.cachedData=ln(this.cachedData,e):this.cachedData=e}}return{audioTrack:s,videoTrack:no(),id3Track:a,textTrack:no()}}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:no(),id3Track:this._id3Track,textTrack:no()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const so=(t,e,i)=>{if(Je(t))return 90*t;return 9e4*e+(i?9e4*i.baseTime/i.timescale:0)};let ao=null;const oo=[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],lo=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],ho=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],co=[0,1,1,4];function uo(t,e,i,n,r){if(i+24>e.length)return;const s=fo(e,i);if(s&&i+s.frameLength<=e.length){const a=n+r*(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 fo(t,e){const i=t[e+1]>>3&3,n=t[e+1]>>1&3,r=t[e+2]>>4&15,s=t[e+2]>>2&3;if(1!==i&&0!==r&&15!==r&&3!==s){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*oo[14*(3===i?3-n:3===n?3:4)+r-1],h=lo[3*(3===i?0:2===i?1:2)+s],c=3===o?1:2,u=ho[i][n],d=co[n],f=8*u*d,g=Math.floor(u*l/h+a)*d;if(null===ao){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);ao=t?parseInt(t[1]):0}return!!ao&&ao<=87&&2===n&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:h,channelCount:c,frameLength:g,samplesPerFrame:f}}}function go(t,e){return!(255!==t[e]||224&~t[e+1]||!(6&t[e+1]))}function po(t,e){return e+1<t.length&&go(t,e)}function mo(t,e){if(e+1<t.length&&go(t,e)){const i=4,n=fo(t,e);let r=i;null!=n&&n.frameLength&&(r=n.frameLength);const s=e+r;return s===t.length||po(t,s)}return!1}const vo=(t,e)=>{let i=0,n=5;e+=n;const r=new Uint32Array(1),s=new Uint32Array(1),a=new Uint8Array(1);for(;n>0;){a[0]=t[e];const o=Math.min(n,8),l=8-o;s[0]=4278190080>>>24+l<<l,r[0]=(a[0]&s[0])>>l,i=i?i<<o|r[0]:r[0],e+=1,n-=o}return i};class yo extends ro{constructor(t){super(),this.observer=void 0,this.observer=t}resetInitSegment(t,e,i,n){super.resetInitSegment(t,e,i,n),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:e,duration:n,inputTimeScale:9e4,dropped:0}}canParse(t,e){return e+64<t.length}appendFrame(t,e,i){const n=Ao(t,e,i,this.basePTS,this.frameIndex);if(-1!==n){return{sample:t.samples[t.samples.length-1],length:n,missing:0}}}static probe(t){if(!t)return!1;const e=Ba(t,0);if(!e)return!1;const i=e.length;return 11===t[i]&&119===t[i+1]&&void 0!==eo(e)&&vo(t,i)<16}}function Ao(t,e,i,n,r){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 h=e[i+6]>>5;let c=0;2===h?c+=2:(1&h&&1!==h&&(c+=2),4&h&&(c+=2));const u=(e[i+6]<<8|e[i+7])>>12-c&1,d=[2,1,2,3,3,4,4,5][h]+u,f=e[i+5]>>3,g=7&e[i+5],p=new Uint8Array([s<<6|f<<1|g>>2,(3&g)<<6|h<<3|u<<2|o>>4,o<<4&224]),m=n+r*(1536/a*9e4),v=e.subarray(i,i+l);return t.config=p,t.channelCount=d,t.samplerate=a,t.samples.push({unit:v,pts:m}),l}const Eo=/\/emsg[-/]ID3/i;function To(t,e){return Je(t.presentationTime)?t.presentationTime/t.timeScale:e+t.presentationTimeDelta/t.timeScale}class bo{constructor(t,e,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Ur(e,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,xr)}decryptAacSample(t,e,i){const n=t[e].unit;if(n.length<=16)return;const r=n.subarray(16,n.length-n.length%16),s=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(s).then(r=>{const s=new Uint8Array(r);n.set(s,16),this.decrypter.isSync()||this.decryptAacSamples(t,e+1,i)}).catch(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 n=0;for(let e=32;e<t.length-16;e+=160,n+=16)i.set(t.subarray(e,e+16),n);return i}getAvcDecryptedUnit(t,e){const i=new Uint8Array(e);let n=0;for(let e=32;e<t.length-16;e+=160,n+=16)t.set(i.subarray(n,n+16),e);return t}decryptAvcSample(t,e,i,n,r){const s=fn(r.data),a=this.getAvcEncryptedData(s);this.decryptBuffer(a.buffer).then(a=>{r.data=this.getAvcDecryptedUnit(s,a),this.decrypter.isSync()||this.decryptAvcSamples(t,e,i+1,n)}).catch(n)}decryptAvcSamples(t,e,i,n){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,i=0){if(e>=t.length)return void n();const r=t[e].units;for(;!(i>=r.length);i++){const s=r[i];if(!(s.data.length<=48||1!==s.type&&5!==s.type||(this.decryptAvcSample(t,e,i,n,s),this.decrypter.isSync())))return}}}}class So{constructor(){this.VideoSample=null}createVideoSample(t,e,i){return{key:t,frame:!1,pts:e,dts:i,units:[],length:0}}getLastNalUnit(t){var e;let i,n=this.VideoSample;if(n&&0!==n.units.length||(n=t[t.length-1]),null!=(e=n)&&e.units){const t=n.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,n=i.length;if(!n)return void e.dropped++;{const e=i[n-1];t.pts=e.pts,t.dts=e.dts}}e.samples.push(t)}}parseNALu(t,e,i){const n=e.byteLength;let r=t.naluState||0;const s=r,a=[];let o,l,h,c=0,u=-1,d=0;for(-1===r&&(u=0,d=this.getNALuType(e,0),r=0,c=1);c<n;)if(o=e[c++],r)if(1!==r)if(o)if(1===o){if(l=c-r-1,u>=0){const t={data:e.subarray(u,l),type:d};a.push(t)}else{const i=this.getLastNalUnit(t.samples);i&&(s&&c<=4-s&&i.state&&(i.data=i.data.subarray(0,i.data.byteLength-s)),l>0&&(i.data=ln(i.data,e.subarray(0,l)),i.state=0))}c<n?(h=this.getNALuType(e,c),u=c,d=h,r=0):r=-1}else r=0;else r=3;else r=o?0:2;else r=o?0:1;if(u>=0&&r>=0){const t={data:e.subarray(u,n),type:d,state:r};a.push(t)}if(0===a.length){const i=this.getLastNalUnit(t.samples);i&&(i.data=ln(i.data,e))}return t.naluState=r,a}}class ko{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,n=new Uint8Array(4),r=Math.min(4,e);if(0===r)throw new Error("no bytes available");n.set(t.subarray(i,i+r)),this.word=new DataView(n.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 i=this.word>>>32-e;if(t>32&&ki.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)}}class _o extends So{parsePES(t,e,i,n){const r=this.parseNALu(t,i.data,n);let s,a=this.VideoSample,o=!1;i.data=null,a&&r.length&&!t.audFound&&(this.pushAccessUnit(a,t),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),r.forEach(n=>{var r,l;switch(n.type){case 1:{let e=!1;s=!0;const r=n.data;if(o&&r.length>4){const t=this.readSliceType(r);2!==t&&4!==t&&7!==t&&9!==t||(e=!0)}var h;if(e)null!=(h=a)&&h.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.frame=!0,a.key=e;break}case 5:s=!0,null!=(r=a)&&r.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 6:s=!0,dn(n.data,1,i.pts,e.samples);break;case 7:{var c,u;s=!0,o=!0;const e=n.data,i=this.readSPS(e);if(!t.sps||t.width!==i.width||t.height!==i.height||(null==(c=t.pixelRatio)?void 0:c[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];const n=e.subarray(1,4);let r="avc1.";for(let t=0;t<3;t++){let e=n[t].toString(16);e.length<2&&(e="0"+e),r+=e}t.codec=r}break}case 8:s=!0,t.pps=[n.data];break;case 9:s=!0,t.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,t),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:s=!0;break;default:s=!1}if(a&&s){a.units.push(n)}}),n&&a&&(this.pushAccessUnit(a,t),this.VideoSample=null)}getNALuType(t,e){return 31&t[e]}readSliceType(t){const e=new ko(t);return e.readUByte(),e.readUEG(),e.readUEG()}skipScalingList(t,e){let i,n=8,r=8;for(let s=0;s<t;s++)0!==r&&(i=e.readEG(),r=(n+i+256)%256),n=0===r?n:r}readSPS(t){const e=new ko(t);let i,n,r,s=0,a=0,o=0,l=0;const h=e.readUByte.bind(e),c=e.readBits.bind(e),u=e.readUEG.bind(e),d=e.readBoolean.bind(e),f=e.skipBits.bind(e),g=e.skipEG.bind(e),p=e.skipUEG.bind(e),m=this.skipScalingList.bind(this);h();const v=h();if(c(5),f(3),h(),p(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){const t=u();if(3===t&&f(1),p(),p(),f(1),d())for(n=3!==t?8:12,r=0;r<n;r++)d()&&m(r<6?16:64,e)}p();const y=u();if(0===y)u();else if(1===y)for(f(1),g(),g(),i=u(),r=0;r<i;r++)g();p(),f(1);const A=u(),E=u(),T=c(1);0===T&&f(1),f(1),d()&&(s=u(),a=u(),o=u(),l=u());let b=[1,1];if(d()&&d()){switch(h()){case 1:b=[1,1];break;case 2:b=[12,11];break;case 3:b=[10,11];break;case 4:b=[16,11];break;case 5:b=[40,33];break;case 6:b=[24,11];break;case 7:b=[20,11];break;case 8:b=[32,11];break;case 9:b=[80,33];break;case 10:b=[18,11];break;case 11:b=[15,11];break;case 12:b=[64,33];break;case 13:b=[160,99];break;case 14:b=[4,3];break;case 15:b=[3,2];break;case 16:b=[2,1];break;case 255:b=[h()<<8|h(),h()<<8|h()]}}return{width:Math.ceil(16*(A+1)-2*s-2*a),height:(2-T)*(E+1)*16-(T?2:4)*(o+l),pixelRatio:b}}}class Lo extends So{constructor(...t){super(...t),this.initVPS=null}parsePES(t,e,i,n){const r=this.parseNALu(t,i.data,n);let s,a=this.VideoSample,o=!1;i.data=null,a&&r.length&&!t.audFound&&(this.pushAccessUnit(a,t),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),r.forEach(n=>{var r,l;switch(n.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),a.frame=!0,s=!0;break;case 16:case 17:case 18:case 21:var h;if(s=!0,o)null!=(h=a)&&h.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:s=!0,null!=(r=a)&&r.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 39:s=!0,dn(n.data,2,i.pts,e.samples);break;case 32:s=!0,t.vps||("object"!=typeof t.params&&(t.params={}),t.params=pi(t.params,this.readVPS(n.data)),this.initVPS=n.data),t.vps=[n.data];break;case 33:if(s=!0,o=!0,void 0===t.vps||t.vps[0]===this.initVPS||void 0===t.sps||this.matchSPS(t.sps[0],n.data)||(this.initVPS=t.vps[0],t.sps=t.pps=void 0),!t.sps){const e=this.readSPS(n.data);t.width=e.width,t.height=e.height,t.pixelRatio=e.pixelRatio,t.codec=e.codecString,t.sps=[],"object"!=typeof t.params&&(t.params={});for(const i in e.params)t.params[i]=e.params[i]}this.pushParameterSet(t.sps,n.data,t.vps),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0;break;case 34:if(s=!0,"object"==typeof t.params){if(!t.pps){t.pps=[];const e=this.readPPS(n.data);for(const i in e)t.params[i]=e[i]}this.pushParameterSet(t.pps,n.data,t.vps)}break;case 35:s=!0,t.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,t),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;default:s=!1}if(a&&s){a.units.push(n)}}),n&&a&&(this.pushAccessUnit(a,t),this.VideoSample=null)}pushParameterSet(t,e,i){(i&&i[0]===this.initVPS||!i&&!t.length)&&t.push(e)}getNALuType(t,e){return(126&t[e])>>>1}ebsp2rbsp(t){const e=new Uint8Array(t.byteLength);let i=0;for(let n=0;n<t.byteLength;n++)n>=2&&3===t[n]&&0===t[n-1]&&0===t[n-2]||(e[i]=t[n],i++);return new Uint8Array(e.buffer,0,i)}pushAccessUnit(t,e){super.pushAccessUnit(t,e),this.initVPS&&(this.initVPS=null)}readVPS(t){const e=new ko(t);e.readUByte(),e.readUByte(),e.readBits(4),e.skipBits(2),e.readBits(6);return{numTemporalLayers:e.readBits(3)+1,temporalIdNested:e.readBoolean()}}readSPS(t){const e=new ko(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.readBits(4);const i=e.readBits(3);e.readBoolean();const n=e.readBits(2),r=e.readBoolean(),s=e.readBits(5),a=e.readUByte(),o=e.readUByte(),l=e.readUByte(),h=e.readUByte(),c=e.readUByte(),u=e.readUByte(),d=e.readUByte(),f=e.readUByte(),g=e.readUByte(),p=e.readUByte(),m=e.readUByte(),v=[],y=[];for(let t=0;t<i;t++)v.push(e.readBoolean()),y.push(e.readBoolean());if(i>0)for(let t=i;t<8;t++)e.readBits(2);for(let t=0;t<i;t++)v[t]&&(e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte()),y[t]&&e.readUByte();e.readUEG();const A=e.readUEG();3==A&&e.skipBits(1);const E=e.readUEG(),T=e.readUEG(),b=e.readBoolean();let S=0,k=0,_=0,L=0;b&&(S+=e.readUEG(),k+=e.readUEG(),_+=e.readUEG(),L+=e.readUEG());const I=e.readUEG(),R=e.readUEG(),C=e.readUEG();for(let t=e.readBoolean()?0:i;t<=i;t++)e.skipUEG(),e.skipUEG(),e.skipUEG();e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG();if(e.readBoolean()){if(e.readBoolean())for(let t=0;t<4;t++)for(let i=0;i<(3===t?2:6);i++){if(e.readBoolean()){const i=Math.min(64,1<<4+(t<<1));t>1&&e.readEG();for(let t=0;t<i;t++)e.readEG()}else e.readUEG()}}e.readBoolean(),e.readBoolean();e.readBoolean()&&(e.readUByte(),e.skipUEG(),e.skipUEG(),e.readBoolean());const P=e.readUEG();let D=0;for(let t=0;t<P;t++){let i=!1;if(0!==t&&(i=e.readBoolean()),i){t===P&&e.readUEG(),e.readBoolean(),e.readUEG();let i=0;for(let t=0;t<=D;t++){const t=e.readBoolean();let n=!1;t||(n=e.readBoolean()),(t||n)&&i++}D=i}else{const t=e.readUEG(),i=e.readUEG();D=t+i;for(let i=0;i<t;i++)e.readUEG(),e.readBoolean();for(let t=0;t<i;t++)e.readUEG(),e.readBoolean()}}if(e.readBoolean()){const t=e.readUEG();for(let i=0;i<t;i++){for(let t=0;t<C+4;t++)e.readBits(1);e.readBits(1)}}let w=0,O=1,x=1,M=!0,N=1,F=0;e.readBoolean(),e.readBoolean();let B=!1;if(e.readBoolean()){if(e.readBoolean()){const t=e.readUByte();t>0&&t<16?(O=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][t-1],x=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][t-1]):255===t&&(O=e.readBits(16),x=e.readBits(16))}e.readBoolean()&&e.readBoolean();if(e.readBoolean()){e.readBits(3),e.readBoolean();e.readBoolean()&&(e.readUByte(),e.readUByte(),e.readUByte())}e.readBoolean()&&(e.readUEG(),e.readUEG()),e.readBoolean(),e.readBoolean(),e.readBoolean(),B=e.readBoolean(),B&&(e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG());if(e.readBoolean()){N=e.readBits(32),F=e.readBits(32);e.readBoolean()&&e.readUEG();if(e.readBoolean()){const t=e.readBoolean(),n=e.readBoolean();let r=!1;(t||n)&&(r=e.readBoolean(),r&&(e.readUByte(),e.readBits(5),e.readBoolean(),e.readBits(5)),e.readBits(4),e.readBits(4),r&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let s=0;s<=i;s++){M=e.readBoolean();let i=!1;M||e.readBoolean()?e.readEG():i=e.readBoolean();const s=i?1:e.readUEG()+1;if(t)for(let t=0;t<s;t++)e.readUEG(),e.readUEG(),r&&(e.readUEG(),e.readUEG()),e.skipBits(1);if(n)for(let t=0;t<s;t++)e.readUEG(),e.readUEG(),r&&(e.readUEG(),e.readUEG()),e.skipBits(1)}}}e.readBoolean()&&(e.readBoolean(),e.readBoolean(),e.readBoolean(),w=e.readUEG())}let U=E,$=T;if(b){let t=1,e=1;1===A?t=e=2:2==A&&(t=2),U=E-t*k-t*S,$=T-e*L-e*_}const G=n?["A","B","C"][n]:"",V=a<<24|o<<16|l<<8|h;let K=0;for(let t=0;t<32;t++)K=(K|(V>>t&1)<<31-t)>>>0;let H=K.toString(16);1===s&&"2"===H&&(H="6");return{codecString:`hvc1.${G}${s}.${H}.${r?"H":"L"}${m}.B0`,params:{general_tier_flag:r,general_profile_idc:s,general_profile_space:n,general_profile_compatibility_flags:[a,o,l,h],general_constraint_indicator_flags:[c,u,d,f,g,p],general_level_idc:m,bit_depth:I+8,bit_depth_luma_minus8:I,bit_depth_chroma_minus8:R,min_spatial_segmentation_idc:w,chroma_format_idc:A,frame_rate:{fixed:M,fps:F/N}},width:U,height:$,pixelRatio:[O,x]}}readPPS(t){const e=new ko(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.skipUEG(),e.skipUEG(),e.skipBits(2),e.skipBits(3),e.skipBits(2),e.skipUEG(),e.skipUEG(),e.skipEG(),e.skipBits(2);e.readBoolean()&&e.skipUEG(),e.skipEG(),e.skipEG(),e.skipBits(4);const i=e.readBoolean(),n=e.readBoolean();let r=1;return n&&i?r=0:n?r=3:i&&(r=2),{parallelismType:r}}matchSPS(t,e){return String.fromCharCode.apply(null,t).substr(3)===String.fromCharCode.apply(null,e).substr(3)}}const Io=188;class Ro{constructor(t,e,i,n){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=t,this.config=e,this.typeSupported=i,this.logger=n,this.videoParser=null}static probe(t,e){const i=Ro.syncOffset(t);return i>0&&e.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),-1!==i}static syncOffset(t){const e=t.length;let i=Math.min(940,e-Io)+1,n=0;for(;n<i;){let r=!1,s=-1,a=0;for(let o=n;o<e;o+=Io){if(71!==t[o]||e-o!==Io&&71!==t[o+Io]){if(a)return-1;break}if(a++,-1===s&&(s=o,0!==s&&(i=Math.min(s+18612,t.length-Io)+1)),r||(r=0===Co(t,o)),r&&a>1&&(0===s&&a>2||o+Io>i))return s}n++}return-1}static createTrack(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:Yi[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}}resetInitSegment(t,e,i,n){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Ro.createTrack("video"),this._videoTrack.duration=n,this._audioTrack=Ro.createTrack("audio",n),this._id3Track=Ro.createTrack("id3"),this._txtTrack=Ro.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=i}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,n=!1){let r;i||(this.sampleAes=null);const s=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let h=s.pid,c=s.pesData,u=a.pid,d=o.pid,f=a.pesData,g=o.pesData,p=null,m=this.pmtParsed,v=this._pmtId,y=t.length;if(this.remainderData&&(y=(t=ln(this.remainderData,t)).length,this.remainderData=null),y<Io&&!n)return this.remainderData=t,{audioTrack:a,videoTrack:s,id3Track:o,textTrack:l};const A=Math.max(0,Ro.syncOffset(t));y-=(y-A)%Io,y<t.byteLength&&!n&&(this.remainderData=new Uint8Array(t.buffer,y,t.buffer.byteLength-y));let E=0;for(let e=A;e<y;e+=Io)if(71===t[e]){const n=!!(64&t[e+1]),y=Co(t,e);let E;if((48&t[e+3])>>4>1){if(E=e+5+t[e+4],E===e+Io)continue}else E=e+4;switch(y){case h:n&&(c&&(r=xo(c,this.logger))&&(this.readyVideoParser(s.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(s,l,r,!1)),c={data:[],size:0}),c&&(c.data.push(t.subarray(E,e+Io)),c.size+=e+Io-E);break;case u:if(n){if(f&&(r=xo(f,this.logger)))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+Io)),f.size+=e+Io-E);break;case d:n&&(g&&(r=xo(g,this.logger))&&this.parseID3PES(o,r),g={data:[],size:0}),g&&(g.data.push(t.subarray(E,e+Io)),g.size+=e+Io-E);break;case 0:n&&(E+=t[E]+1),v=this._pmtId=Po(t,E);break;case v:{n&&(E+=t[E]+1);const r=Do(t,E,this.typeSupported,i,this.observer,this.logger);h=r.videoPid,h>0&&(s.pid=h,s.segmentCodec=r.segmentVideoCodec),u=r.audioPid,u>0&&(a.pid=u,a.segmentCodec=r.segmentAudioCodec),d=r.id3Pid,d>0&&(o.pid=d),null===p||m||(this.logger.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=y}}else E++;E>0&&wo(this.observer,new Error(`Found ${E} TS packet/s that do not start with 0x47`),void 0,this.logger),s.pesData=c,a.pesData=f,o.pesData=g;const T={audioTrack:a,videoTrack:s,id3Track:o,textTrack:l};return n&&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:n,textTrack:r}=t,s=i.pesData,a=e.pesData,o=n.pesData;let l;if(s&&(l=xo(s,this.logger))?(this.readyVideoParser(i.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(i,r,l,!0),i.pesData=null)):i.pesData=s,a&&(l=xo(a,this.logger))){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&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),e.pesData=a;o&&(l=xo(o,this.logger))?(this.parseID3PES(n,l),n.pesData=null):n.pesData=o}demuxSampleAes(t,e,i){const n=this.demux(t,i,!0,!this.config.progressive),r=this.sampleAes=new bo(this.observer,this.config,e);return this.decrypt(n,r)}readyVideoParser(t){null===this.videoParser&&("avc"===t?this.videoParser=new _o:"hevc"===t&&(this.videoParser=new Lo))}decrypt(t,e){return new Promise(i=>{const{audioTrack:n,videoTrack:r}=t;n.samples&&"aac"===n.segmentCodec?e.decryptAacSamples(n.samples,0,()=>{r.samples?e.decryptAvcSamples(r.samples,0,0,()=>{i(t)}):i(t)}):r.samples&&e.decryptAvcSamples(r.samples,0,0,()=>{i(t)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(t,e){let i=0;const n=this.aacOverFlow;let r,s,a,o=e.data;if(n){this.aacOverFlow=null;const e=n.missing,r=n.sample.unit.byteLength;if(-1===e)o=ln(n.sample.unit,o);else{const s=r-e;n.sample.unit.set(o.subarray(0,e),s),t.samples.push(n.sample),i=n.missing}}for(r=i,s=o.length;r<s-1&&!Va(o,r);r++);if(r!==i){let t;const e=r<s-1;if(t=e?`AAC PES did not start with ADTS header,offset:${r}`:"No ADTS header found in AAC PES",wo(this.observer,new Error(t),e,this.logger),!e)return}if(Ha(t,this.observer,o,r,this.audioCodec),void 0!==e.pts)a=e.pts;else{if(!n)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const e=Ya(t.samplerate);a=n.sample.pts+e}}let l,h=0;for(;r<s;){if(l=ja(t,o,r,a,h),r+=l.length,l.missing){this.aacOverFlow=l;break}for(h++;r<s-1&&!Va(o,r);r++);}}parseMPEGPES(t,e){const i=e.data,n=i.length;let r=0,s=0;const a=e.pts;if(void 0!==a)for(;s<n;)if(po(i,s)){const e=uo(t,i,s,a,r);if(!e)break;s+=e.length,r++}else s++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(t,e){{const i=e.data,n=e.pts;if(void 0===n)return void this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");const r=i.length;let s,a=0,o=0;for(;o<r&&(s=Ao(t,i,o,n,a++))>0;)o+=s}}parseID3PES(t,e){if(void 0===e.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const i=pi({},e,{type:this._videoTrack?io.emsg:io.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(i)}}function Co(t,e){return((31&t[e+1])<<8)+t[e+2]}function Po(t,e){return(31&t[e+10])<<8|t[e+11]}function Do(t,e,i,n,r,s){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=e+3+((15&t[e+1])<<8|t[e+2])-4;for(e+=12+((15&t[e+10])<<8|t[e+11]);e<o;){const o=Co(t,e),l=(15&t[e+3])<<8|t[e+4];switch(t[e]){case 207:if(!n){Oo("ADTS AAC",s);break}case 15:-1===a.audioPid&&(a.audioPid=o);break;case 21:-1===a.id3Pid&&(a.id3Pid=o);break;case 219:if(!n){Oo("H.264",s);break}case 27:-1===a.videoPid&&(a.videoPid=o);break;case 3:case 4:i.mpeg||i.mp3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="mp3"):s.log("MPEG audio found, not supported in this browser");break;case 193:if(!n){Oo("AC-3",s);break}case 129:i.ac3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="ac3"):s.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===a.audioPid&&l>0){let n=e+5,r=l;for(;r>2;){if(106===t[n])!0!==i.ac3?s.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=o,a.segmentAudioCodec="ac3");const e=t[n+1]+2;n+=e,r-=e}}break;case 194:case 135:return wo(r,new Error("Unsupported EC-3 in M2TS found"),void 0,s),a;case 36:-1===a.videoPid&&(a.videoPid=o,a.segmentVideoCodec="hevc",s.log("HEVC in M2TS found"))}e+=l+5}return a}function wo(t,e,i,n){n.warn(`parsing error: ${e.message}`),t.emit(ri.ERROR,ri.ERROR,{type:ii.MEDIA_ERROR,details:ni.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,error:e,reason:e.message})}function Oo(t,e){e.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function xo(t,e){let i,n,r,s,a,o=0;const l=t.data;if(!t||0===t.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=ln(l[0],l[1]),l.splice(1,1);i=l[0];if(1===(i[0]<<16)+(i[1]<<8)+i[2]){if(n=(i[4]<<8)+i[5],n&&n>t.size-6)return null;const h=i[7];192&h&&(s=536870912*(14&i[9])+4194304*(255&i[10])+16384*(254&i[11])+128*(255&i[12])+(254&i[13])/2,64&h?(a=536870912*(14&i[14])+4194304*(255&i[15])+16384*(254&i[16])+128*(255&i[17])+(254&i[18])/2,s-a>54e5&&(e.warn(`${Math.round((s-a)/9e4)}s delta between PTS and DTS, align them`),s=a)):a=s),r=i[8];let c=r+9;if(t.size<=c)return null;t.size-=c;const u=new Uint8Array(t.size);for(let t=0,e=l.length;t<e;t++){i=l[t];let e=i.byteLength;if(c){if(c>e){c-=e;continue}i=i.subarray(c),e-=c,c=0}u.set(i,o),o+=e}return n&&(n-=r+3),{data:u,pts:s,dts:a,len:n}}return null}class Mo{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 No=Math.pow(2,32)-1;class Fo{static init(){let t;for(t in Fo.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},Fo.types)Fo.types.hasOwnProperty(t)&&(Fo.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]);Fo.HDLR_TYPES={video:e,audio:i};const n=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]);Fo.STTS=Fo.STSC=Fo.STCO=r,Fo.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Fo.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Fo.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Fo.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]);Fo.FTYP=Fo.box(Fo.types.ftyp,s,o,s,a),Fo.DINF=Fo.box(Fo.types.dinf,Fo.box(Fo.types.dref,n))}static box(t,...e){let i=8,n=e.length;const r=n;for(;n--;)i+=e[n].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),n=0,i=8;n<r;n++)s.set(e[n],i),i+=e[n].byteLength;return s}static hdlr(t){return Fo.box(Fo.types.hdlr,Fo.HDLR_TYPES[t])}static mdat(t){return Fo.box(Fo.types.mdat,t)}static mdhd(t,e){e*=t;const i=Math.floor(e/(No+1)),n=Math.floor(e%(No+1));return Fo.box(Fo.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,n>>24,n>>16&255,n>>8&255,255&n,85,196,0,0]))}static mdia(t){return Fo.box(Fo.types.mdia,Fo.mdhd(t.timescale||0,t.duration||0),Fo.hdlr(t.type),Fo.minf(t))}static mfhd(t){return Fo.box(Fo.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?Fo.box(Fo.types.minf,Fo.box(Fo.types.smhd,Fo.SMHD),Fo.DINF,Fo.stbl(t)):Fo.box(Fo.types.minf,Fo.box(Fo.types.vmhd,Fo.VMHD),Fo.DINF,Fo.stbl(t))}static moof(t,e,i){return Fo.box(Fo.types.moof,Fo.mfhd(t),Fo.traf(i,e))}static moov(t){let e=t.length;const i=[];for(;e--;)i[e]=Fo.trak(t[e]);return Fo.box.apply(null,[Fo.types.moov,Fo.mvhd(t[0].timescale||0,t[0].duration||0)].concat(i).concat(Fo.mvex(t)))}static mvex(t){let e=t.length;const i=[];for(;e--;)i[e]=Fo.trex(t[e]);return Fo.box.apply(null,[Fo.types.mvex,...i])}static mvhd(t,e){e*=t;const i=Math.floor(e/(No+1)),n=Math.floor(e%(No+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,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,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 Fo.box(Fo.types.mvhd,r)}static sdtp(t){const e=t.samples||[],i=new Uint8Array(4+e.length);let n,r;for(n=0;n<e.length;n++)r=e[n].flags,i[n+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return Fo.box(Fo.types.sdtp,i)}static stbl(t){return Fo.box(Fo.types.stbl,Fo.stsd(t),Fo.box(Fo.types.stts,Fo.STTS),Fo.box(Fo.types.stsc,Fo.STSC),Fo.box(Fo.types.stsz,Fo.STSZ),Fo.box(Fo.types.stco,Fo.STCO))}static avc1(t){let e,i,n,r=[],s=[];for(e=0;e<t.sps.length;e++)i=t.sps[e],n=i.byteLength,r.push(n>>>8&255),r.push(255&n),r=r.concat(Array.prototype.slice.call(i));for(e=0;e<t.pps.length;e++)i=t.pps[e],n=i.byteLength,s.push(n>>>8&255),s.push(255&n),s=s.concat(Array.prototype.slice.call(i));const a=Fo.box(Fo.types.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|t.sps.length].concat(r).concat([t.pps.length]).concat(s))),o=t.width,l=t.height,h=t.pixelRatio[0],c=t.pixelRatio[1];return Fo.box(Fo.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,Fo.box(Fo.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Fo.box(Fo.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,c>>24,c>>16&255,c>>8&255,255&c])))}static esds(t){const e=t.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...e,6,1,2])}static audioStsd(t){const e=t.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount||0,0,16,0,0,0,0,e>>8&255,255&e,0,0])}static mp4a(t){return Fo.box(Fo.types.mp4a,Fo.audioStsd(t),Fo.box(Fo.types.esds,Fo.esds(t)))}static mp3(t){return Fo.box(Fo.types[".mp3"],Fo.audioStsd(t))}static ac3(t){return Fo.box(Fo.types["ac-3"],Fo.audioStsd(t),Fo.box(Fo.types.dac3,t.config))}static stsd(t){const{segmentCodec:e}=t;if("audio"===t.type){if("aac"===e)return Fo.box(Fo.types.stsd,Fo.STSD,Fo.mp4a(t));if("ac3"===e&&t.config)return Fo.box(Fo.types.stsd,Fo.STSD,Fo.ac3(t));if("mp3"===e&&"mp3"===t.codec)return Fo.box(Fo.types.stsd,Fo.STSD,Fo.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===e)return Fo.box(Fo.types.stsd,Fo.STSD,Fo.avc1(t));if("hevc"===e&&t.vps)return Fo.box(Fo.types.stsd,Fo.STSD,Fo.hvc1(t))}throw new Error(`unsupported ${t.type} segment codec (${e}/${t.codec})`)}static tkhd(t){const e=t.id,i=(t.duration||0)*(t.timescale||0),n=t.width||0,r=t.height||0,s=Math.floor(i/(No+1)),a=Math.floor(i%(No+1));return Fo.box(Fo.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,n>>8&255,255&n,0,0,r>>8&255,255&r,0,0]))}static traf(t,e){const i=Fo.sdtp(t),n=t.id,r=Math.floor(e/(No+1)),s=Math.floor(e%(No+1));return Fo.box(Fo.types.traf,Fo.box(Fo.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n])),Fo.box(Fo.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,s>>24,s>>16&255,s>>8&255,255&s])),Fo.trun(t,i.length+16+20+8+16+8+8),i)}static trak(t){return t.duration=t.duration||4294967295,Fo.box(Fo.types.trak,Fo.tkhd(t),Fo.mdia(t))}static trex(t){const e=t.id;return Fo.box(Fo.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||[],n=i.length,r=12+16*n,s=new Uint8Array(r);let a,o,l,h,c,u;for(e+=8+r,s.set(["video"===t.type?1:0,0,15,1,n>>>24&255,n>>>16&255,n>>>8&255,255&n,e>>>24&255,e>>>16&255,e>>>8&255,255&e],0),a=0;a<n;a++)o=i[a],l=o.duration,h=o.size,c=o.flags,u=o.cts,s.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,h>>>24&255,h>>>16&255,h>>>8&255,255&h,c.isLeading<<2|c.dependsOn,c.isDependedOn<<6|c.hasRedundancy<<4|c.paddingValue<<1|c.isNonSync,61440&c.degradPrio,15&c.degradPrio,u>>>24&255,u>>>16&255,u>>>8&255,255&u],12+16*a);return Fo.box(Fo.types.trun,s)}static initSegment(t){Fo.types||Fo.init();const e=Fo.moov(t);return ln(Fo.FTYP,e)}static hvc1(t){const e=t.params,i=[t.vps,t.sps,t.pps],n=new Uint8Array([1,e.general_profile_space<<6|(e.general_tier_flag?32:0)|e.general_profile_idc,e.general_profile_compatibility_flags[0],e.general_profile_compatibility_flags[1],e.general_profile_compatibility_flags[2],e.general_profile_compatibility_flags[3],e.general_constraint_indicator_flags[0],e.general_constraint_indicator_flags[1],e.general_constraint_indicator_flags[2],e.general_constraint_indicator_flags[3],e.general_constraint_indicator_flags[4],e.general_constraint_indicator_flags[5],e.general_level_idc,240|e.min_spatial_segmentation_idc>>8,255&e.min_spatial_segmentation_idc,252|e.parallelismType,252|e.chroma_format_idc,248|e.bit_depth_luma_minus8,248|e.bit_depth_chroma_minus8,0,parseInt(e.frame_rate.fps),3|e.temporal_id_nested<<2|e.num_temporal_layers<<3|(e.frame_rate.fixed?64:0),i.length]);let r=n.length;for(let t=0;t<i.length;t+=1){r+=3;for(let e=0;e<i[t].length;e+=1)r+=2+i[t][e].length}const s=new Uint8Array(r);s.set(n,0),r=n.length;const a=i.length-1;for(let t=0;t<i.length;t+=1){s.set(new Uint8Array([32+t|(t===a?128:0),0,i[t].length]),r),r+=3;for(let e=0;e<i[t].length;e+=1)s.set(new Uint8Array([i[t][e].length>>8,255&i[t][e].length]),r),r+=2,s.set(i[t][e],r),r+=i[t][e].length}const o=Fo.box(Fo.types.hvcC,s),l=t.width,h=t.height,c=t.pixelRatio[0],u=t.pixelRatio[1];return Fo.box(Fo.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,h>>8&255,255&h,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,Fo.box(Fo.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Fo.box(Fo.types.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,255&c,u>>24,u>>16&255,u>>8&255,255&u])))}}Fo.types=void 0,Fo.HDLR_TYPES=void 0,Fo.STTS=void 0,Fo.STSC=void 0,Fo.STCO=void 0,Fo.STSZ=void 0,Fo.VMHD=void 0,Fo.SMHD=void 0,Fo.STSD=void 0,Fo.FTYP=void 0,Fo.DINF=void 0;function Bo(t,e,i=1,n=!1){const r=t*e*i;return n?Math.round(r):r}function Uo(t,e=!1){return Bo(t,1e3,1/9e4,e)}function $o(t){const{baseTime:e,timescale:i,trackId:n}=t;return`${e/i} (${e}/${i}) trackId: ${n}`}const Go=8589934592;let Vo,Ko=null,Ho=null;function Yo(t,e,i,n){return{duration:e,size:i,cts:n,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1}}}class jo extends yi{constructor(t,e,i,n){if(super("mp4-remuxer",n),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=t,this.config=e,this.typeSupported=i,this.ISGenerated=!1,null===Ko){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ko=t?parseInt(t[1]):0}if(null===Ho){const t=navigator.userAgent.match(/Safari\/(\d+)/i);Ho=t?parseInt(t[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){const e=this._initPTS;e&&t&&t.trackId===e.trackId&&t.baseTime===e.baseTime&&t.timescale===e.timescale||this.log(`Reset initPTS: ${e?$o(e):e} > ${t?$o(t):t}`),this._initPTS=this._initDTS=t}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let e=!1;const i=t[0].pts,n=t.reduce((t,n)=>{let r=n.pts,s=r-t;return s<-4294967296&&(e=!0,r=Wo(r,i),s=r-t),s>0?t:r},i);return e&&this.debug("PTS rollover detected"),n}remux(t,e,i,n,r,s,a,o){let l,h,c,u,d,f,g=r,p=r;const m=t.pid>-1,v=e.pid>-1,y=e.samples.length,A=t.samples.length>0,E=a&&y>0||y>1;if((!m||A)&&(!v||E)||this.ISGenerated||a){if(this.ISGenerated){var T,b,S,k;const t=this.videoTrackConfig;(t&&(e.width!==t.width||e.height!==t.height||(null==(T=e.pixelRatio)?void 0:T[0])!==(null==(b=t.pixelRatio)?void 0:b[0])||(null==(S=e.pixelRatio)?void 0:S[1])!==(null==(k=t.pixelRatio)?void 0:k[1]))||!t&&E||null===this.nextAudioTs&&A)&&this.resetInitSegment()}this.ISGenerated||(c=this.generateIS(t,e,r,s));const i=this.isVideoContiguous;let n,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){this.warn(`Dropped ${a} out of ${y} 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,n=p}else-1===a&&(this.warn(`No keyframe found out of ${y} video samples`),f=!1);if(this.ISGenerated){if(A&&E){const i=this.getVideoStartPts(e.samples),n=(Wo(t.samples[0].pts,i)-i)/e.inputTimeScale;g+=Math.max(0,n),p+=Math.max(0,-n)}if(A){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),c=this.generateIS(t,e,r,s)),h=this.remuxAudio(t,g,this.isAudioContiguous,s,v||E||o===ci?p:void 0),E){const n=h?h.endPTS-h.startPTS:0;e.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),c=this.generateIS(t,e,r,s)),l=this.remuxVideo(e,p,i,n)}}else E&&(l=this.remuxVideo(e,p,i,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=n)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(d=zo(i,r,this._initPTS,this._initDTS)),n.samples.length&&(u=qo(n,r,this._initPTS))),{audio:h,video:l,initSegment:c,independent:f,text:u,id3:d}}computeInitPts(t,e,i,n){const r=Math.round(i*e);let s=Wo(t,r);if(s<r)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-s)/e} ${n}`);s<r;)s+=Go;return s-r}generateIS(t,e,i,n){const r=t.samples,s=e.samples,a=this.typeSupported,o={},l=this._initPTS;let h,c,u,d=!l||n,f="audio/mp4",g=-1;if(d&&(h=c=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):Fo.initSegment([t]),metadata:{channelCount:t.channelCount}},d&&(g=t.id,u=t.inputTimeScale,l&&u===l.timescale?d=!1:h=c=this.computeInitPts(r[0].pts,u,i,"audio"))}if(e.sps&&e.pps&&s.length){if(e.timescale=e.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:Fo.initSegment([e]),metadata:{width:e.width,height:e.height}},d)if(g=e.id,u=e.inputTimeScale,l&&u===l.timescale)d=!1;else{const t=this.getVideoStartPts(s),e=Wo(s[0].dts,t),n=this.computeInitPts(e,u,i,"video"),r=this.computeInitPts(t,u,i,"video");c=Math.min(c,n),h=Math.min(h,r)}this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,d?(l&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${i} ${h/u} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${h/u} (${h}/${u}) trackId: ${g}`),this._initPTS={baseTime:h,timescale:u,trackId:g},this._initDTS={baseTime:c,timescale:u,trackId:g}):h=u=void 0,{tracks:o,initPTS:h,timescale:u,trackId:g}}remuxVideo(t,e,i,n){const r=t.inputTimeScale,s=t.samples,a=[],o=s.length,l=this._initPTS,h=l.baseTime*r/l.timescale;let c,u,d=this.nextVideoTs,f=8,g=this.videoSampleDuration,p=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,v=!1;if(!i||null===d){const t=h+e*r,n=s[0].pts-Wo(s[0].dts,s[0].pts);Ko&&null!==d&&Math.abs(t-n-(d+h))<15e3?i=!0:d=t-n-h}const y=d+h;for(let t=0;t<o;t++){const e=s[t];e.pts=Wo(e.pts,y),e.dts=Wo(e.dts,y),e.dts<s[t>0?t-1:t].dts&&(v=!0)}v&&s.sort(function(t,e){const i=t.dts-e.dts,n=t.pts-e.pts;return i||n}),c=s[0].dts,u=s[s.length-1].dts;const A=u-c,E=A?Math.round(A/(o-1)):g||t.inputTimeScale/30;if(i){const i=c-y,n=i>E,r=i<-1;if((n||r)&&(n?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${Uo(i,!0)} ms (${i}dts) hole between fragments detected at ${e.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${Uo(-i,!0)} ms (${i}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!r||y>=s[0].pts||Ko)){c=y;const t=s[0].pts-i;if(n)s[0].dts=c,s[0].pts=t;else{let e=!0;for(let n=0;n<s.length&&!(s[n].dts>t&&e);n++){const t=s[n].pts;if(s[n].dts-=i,s[n].pts-=i,n<s.length-1){const i=s[n+1].pts;e=i<=s[n].pts==i<=t}}}this.log(`Video: Initial PTS/DTS adjusted: ${Uo(t,!0)}/${Uo(c,!0)}, delta: ${Uo(i,!0)} ms`)}}c=Math.max(0,c);let T=0,b=0,S=c;for(let t=0;t<o;t++){const e=s[t],i=e.units,n=i.length;let r=0;for(let t=0;t<n;t++)r+=i[t].data.length;b+=r,T+=n,e.length=r,e.dts<S?(e.dts=S,S+=E/4|0||1):S=e.dts,p=Math.min(e.pts,p),m=Math.max(e.pts,m)}u=s[o-1].dts;const k=b+4*T+8;let _;try{_=new Uint8Array(k)}catch(t){return void this.observer.emit(ri.ERROR,ri.ERROR,{type:ii.MUX_ERROR,details:ni.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:k,reason:`fail allocating video mdat ${k}`})}const L=new DataView(_.buffer);L.setUint32(0,k),_.set(Fo.types.mdat,4);let I=!1,R=Number.POSITIVE_INFINITY,C=Number.POSITIVE_INFINITY,P=Number.NEGATIVE_INFINITY,D=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],n=e.data,r=e.data.byteLength;L.setUint32(f,r),f+=4,_.set(n,f),f+=r,c+=4+r}if(t<o-1)g=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:E;if(l=t>0?e.pts-s[t-1].pts:E,i.stretchShortVideoTrack&&null!==this.nextAudioTs){const t=Math.floor(i.maxBufferHole*r),s=(n?p+n*r:this.nextAudioTs+h)-e.pts;s>t?(g=s-a,g<0?g=a:I=!0,this.log(`It is approximately ${s/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)):g=a}else g=a}const u=Math.round(e.pts-e.dts);R=Math.min(R,g),P=Math.max(P,g),C=Math.min(C,l),D=Math.max(D,l),a.push(Yo(e.key,g,c,u))}if(a.length)if(Ko){if(Ko<70){const t=a[0].flags;t.dependsOn=2,t.isNonSync=0}}else if(Ho&&D-C<P-R&&E/P<.025&&0===a[0].cts){this.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 n=t+a[e].duration,r=t+a[e].cts;if(e<i-1){const t=n+a[e+1].cts;a[e].duration=t-r}else a[e].duration=e?a[e-1].duration:E;a[e].cts=0,t=n}}g=I||!g?E:g;const w=u+g;this.nextVideoTs=d=w-h,this.videoSampleDuration=g,this.isVideoContiguous=!0;const O={data1:Fo.moof(t.sequenceNumber++,c,pi(t,{samples:a})),data2:_,startPTS:(p-h)/r,endPTS:(m+g-h)/r,startDTS:(c-h)/r,endDTS:d/r,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:t.dropped};return t.samples=[],t.dropped=0,O}getSamplesPerFrame(t){switch(t.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(t,e,i,n,r){const s=t.inputTimeScale,a=s/(t.samplerate?t.samplerate:s),o=this.getSamplesPerFrame(t),l=o*a,h=this._initPTS,c="mp3"===t.segmentCodec&&this.typeSupported.mpeg,u=[],d=void 0!==r;let f=t.samples,g=c?0:8,p=this.nextAudioTs||-1;const m=h.baseTime*s/h.timescale,v=m+e*s;if(this.isAudioContiguous=i=i||f.length&&p>0&&(n&&Math.abs(v-(p+m))<9e3||Math.abs(Wo(f[0].pts,v)-(p+m))<20*l),f.forEach(function(t){t.pts=Wo(t.pts,v)}),!i||p<0){const t=f.length;if(f=f.filter(t=>t.pts>=0),t!==f.length&&this.warn(`Removed ${f.length-t} of ${t} samples (initPTS ${m} / ${s})`),!f.length)return;p=0===r?0:n&&!d?Math.max(0,v-m):f[0].pts-m}if("aac"===t.segmentCodec){const e=this.config.maxAudioFramesDrift;for(let i=0,n=p+m;i<f.length;i++){const r=f[i],a=r.pts,o=a-n,h=Math.abs(1e3*o/s);if(o<=-e*l&&d)0===i&&(this.warn(`Audio frame @ ${(a/s).toFixed(3)}s overlaps marker by ${Math.round(1e3*o/s)} ms.`),this.nextAudioTs=p=a-m,n=a);else if(o>=e*l&&h<1e4&&d){let e=Math.round(o/l);for(n=a-e*l;n<0&&e&&l;)e--,n+=l;0===i&&(this.nextAudioTs=p=n-m),this.warn(`Injecting ${e} audio frames @ ${((n-m)/s).toFixed(3)}s due to ${Math.round(1e3*o/s)} ms gap.`);for(let s=0;s<e;s++){let e=Mo.getSilentFrame(t.parsedCodec||t.manifestCodec||t.codec,t.channelCount);e||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),e=r.unit.subarray()),f.splice(i,0,{unit:e,pts:n}),n+=l,i++}}r.pts=n,n+=l}}let y,A=null,E=null,T=0,b=f.length;for(;b--;)T+=f[b].unit.byteLength;for(let e=0,n=f.length;e<n;e++){const n=f[e],r=n.unit;let s=n.pts;if(null!==E){u[e-1].duration=Math.round((s-E)/a)}else{if(i&&"aac"===t.segmentCodec&&(s=p+m),A=s,!(T>0))return;T+=g;try{y=new Uint8Array(T)}catch(t){return void this.observer.emit(ri.ERROR,ri.ERROR,{type:ii.MUX_ERROR,details:ni.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:T,reason:`fail allocating audio mdat ${T}`})}if(!c){new DataView(y.buffer).setUint32(0,T),y.set(Fo.types.mdat,4)}}y.set(r,g);const l=r.byteLength;g+=l,u.push(Yo(!0,o,l,0)),E=s}const S=u.length;if(!S)return;const k=u[u.length-1];p=E-m,this.nextAudioTs=p+a*k.duration;const _=c?new Uint8Array(0):Fo.moof(t.sequenceNumber++,A/a,pi({},t,{samples:u}));t.samples=[];const L=(A-m)/s,I=this.nextAudioTs/s,R={data1:_,data2:y,startPTS:L,endPTS:I,startDTS:L,endDTS:I,type:"audio",hasAudio:!0,hasVideo:!1,nb:S};return this.isAudioContiguous=!0,R}}function Wo(t,e){let i;if(null===e)return t;for(i=e<t?-8589934592:Go;Math.abs(t-e)>4294967296;)t+=i;return t}function zo(t,e,i,n){const r=t.samples.length;if(!r)return;const s=t.inputTimeScale;for(let a=0;a<r;a++){const r=t.samples[a];r.pts=Wo(r.pts-i.baseTime*s/i.timescale,e*s)/s,r.dts=Wo(r.dts-n.baseTime*s/n.timescale,e*s)/s}const a=t.samples;return t.samples=[],{samples:a}}function qo(t,e,i){const n=t.samples.length;if(!n)return;const r=t.inputTimeScale;for(let s=0;s<n;s++){const n=t.samples[s];n.pts=Wo(n.pts-i.baseTime*r/i.timescale,e*r)/r}t.samples.sort((t,e)=>t.pts-e.pts);const s=t.samples;return t.samples=[],{samples:s}}function Xo(t,e,i=!1){return void 0!==(null==t?void 0:t.start)?(t.start+(i?t.duration:0))/t.timescale:e}function Qo(t,e,i){const n=t.codec;if(n&&n.length>4)return n;if(e===Mi){if("ec-3"===n||"ac-3"===n||"alac"===n)return n;if("fLaC"===n||"Opus"===n){return Ln(n,!1)}return i.warn(`Unhandled audio codec "${n}" in mp4 MAP`),n||"mp4a"}return i.warn(`Unhandled video codec "${n}" in mp4 MAP`),n||"avc1"}try{Vo=self.performance.now.bind(self.performance)}catch(t){Vo=Date.now}const Zo=[{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,n){const r=this.videoTrack=no("video",1),s=this.audioTrack=no("audio",1),a=this.txtTrack=no("text",1);if(this.id3Track=no("id3",1),this.timeOffset=0,null==t||!t.byteLength)return;const o=Ji(t);if(o.video){const{id:t,timescale:e,codec:i,supplemental:n}=o.video;r.id=t,r.timescale=a.timescale=e,r.codec=i,r.supplemental=n}if(o.audio){const{id:t,timescale:e,codec:i}=o.audio;s.id=t,s.timescale=e,s.codec=i}a.id=Yi.text,r.sampleDuration=0,r.duration=s.duration=n}resetContiguity(){this.remainderData=null}static probe(t){return function(t){const e=t.byteLength;for(let i=0;i<e;){const n=zi(t,i);if(n>8&&109===t[i+4]&&111===t[i+5]&&111===t[i+6]&&102===t[i+7])return!0;i=n>1?i+n:e}return!1}(t)}demux(t,e){this.timeOffset=e;let i=t;const n=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=ln(this.remainderData,t));const e=function(t){const e={valid:null,remainder:null},i=Qi(t,["moof"]);if(i.length<2)return e.remainder=t,e;const n=i[i.length-1];return e.valid=t.slice(0,n.byteOffset-8),e.remainder=t.slice(n.byteOffset-8),e}(i);this.remainderData=e.remainder,n.samples=e.valid||new Uint8Array}else n.samples=i;const s=this.extractID3Track(n,e);return r.samples=hn(e,n),{videoTrack:n,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 n=this.extractID3Track(e,this.timeOffset);return i.samples=hn(t,e),{videoTrack:e,audioTrack:no(),id3Track:n,textTrack:no()}}extractID3Track(t,e){const i=this.id3Track;if(t.samples.length){const n=Qi(t.samples,["emsg"]);n&&n.forEach(t=>{const n=function(t){const e=t[0];let i="",n="",r=0,s=0,a=0,o=0,l=0,h=0;if(0===e){for(;"\0"!==ji(t.subarray(h,h+1));)i+=ji(t.subarray(h,h+1)),h+=1;for(i+=ji(t.subarray(h,h+1)),h+=1;"\0"!==ji(t.subarray(h,h+1));)n+=ji(t.subarray(h,h+1)),h+=1;n+=ji(t.subarray(h,h+1)),h+=1,r=zi(t,12),s=zi(t,16),o=zi(t,20),l=zi(t,24),h=28}else if(1===e){h+=4,r=zi(t,h),h+=4;const e=zi(t,h);h+=4;const s=zi(t,h);for(h+=4,a=2**32*e+s,ti(a)||(a=Number.MAX_SAFE_INTEGER,ki.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=zi(t,h),h+=4,l=zi(t,h),h+=4;"\0"!==ji(t.subarray(h,h+1));)i+=ji(t.subarray(h,h+1)),h+=1;for(i+=ji(t.subarray(h,h+1)),h+=1;"\0"!==ji(t.subarray(h,h+1));)n+=ji(t.subarray(h,h+1)),h+=1;n+=ji(t.subarray(h,h+1)),h+=1}return{schemeIdUri:i,value:n,timeScale:r,presentationTime:a,presentationTimeDelta:s,eventDuration:o,id:l,payload:t.subarray(h,t.byteLength)}}(t);if(Eo.test(n.schemeIdUri)){const t=To(n,e);let r=4294967295===n.eventDuration?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;r<=.001&&(r=Number.POSITIVE_INFINITY);const s=n.payload;i.samples.push({data:s,len:s.byteLength,dts:t,pts:t,type:io.emsg,duration:r})}else if(this.config.enableEmsgKLVMetadata&&n.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const t=To(n,e);i.samples.push({data:n.payload,len:n.payload.byteLength,dts:t,pts:t,type:io.misbklv,duration:Number.POSITIVE_INFINITY})}})}return i}demuxSampleAes(t,e,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}},remux:class extends yi{constructor(t,e,i,n){super("passthrough-remuxer",n),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(t){this.lastEndTime=null;const e=this.initPTS;e&&t&&e.baseTime===t.baseTime&&e.timescale===t.timescale||(this.initPTS=t)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(t,e,i,n){this.audioCodec=e,this.videoCodec=i,this.generateInitSegment(t,n),this.emitInitSegment=!0}generateInitSegment(t,e){let{audioCodec:i,videoCodec:n}=this;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const{audio:r,video:s}=this.initData=Ji(t);if(e)!function(t,e){if(!t||!e)return;const i=e.keyId;i&&e.isCommonEncryption&&an(t,(t,e)=>{const n=t.subarray(8,24);n.some(t=>0!==t)||(ki.log(`[eme] Patching keyId in 'enc${e?"a":"v"}>sinf>>tenc' box: ${Ri(n)} -> ${Ri(i)}`),t.set(i,8))})}(t,e);else{const t=r||s;null!=t&&t.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${t.codec}")!`)}r&&(i=Qo(r,Mi,this)),s&&(n=Qo(s,Ni,this));const a={};r&&s?a.audiovideo={container:"video/mp4",codec:i+","+n,supplemental:s.supplemental,encrypted:s.encrypted,initSegment:t,id:"main"}:r?a.audio={container:"audio/mp4",codec:i,encrypted:r.encrypted,initSegment:t,id:"audio"}:s?a.video={container:"video/mp4",codec:n,supplemental:s.supplemental,encrypted:s.encrypted,initSegment:t,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=a}remux(t,e,i,n,r,s){var a,o;let{initPTS:l,lastEndTime:h}=this;const c={audio:void 0,video:void 0,text:n,id3:i,initSegment:void 0};Je(h)||(h=this.lastEndTime=r||0);const u=e.samples;if(!u.length)return c;const d={initPTS:void 0,timescale:void 0,trackId:void 0};let f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(u),f=this.initData),null==(o=f)||!o.length)return this.warn("Failed to generate initSegment."),c;this.emitInitSegment&&(d.tracks=this.initTracks,this.emitInitSegment=!1);const g=function(t,e,i){const n={},r=Qi(t,["moof","traf"]);for(let t=0;t<r.length;t++){const s=r[t],a=Qi(s,["tfhd"])[0],o=zi(a,4),l=e[o];if(!l)continue;n[o]||(n[o]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type});const h=n[o],c=Qi(s,["tfdt"])[0];if(c){const t=c[0];let e=zi(c,4);1===t&&(e===Ki?i.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(e*=Ki+1,e+=zi(c,8))),Je(e)&&(!Je(h.start)||e<h.start)&&(h.start=e)}const u=l.default,d=zi(a,0)|(null==u?void 0:u.flags);let f=(null==u?void 0:u.duration)||0;8&d&&(f=zi(a,2&d?12:8));const g=Qi(s,["trun"]);let p=h.start||0,m=0,v=f;for(let t=0;t<g.length;t++){const e=g[t],i=zi(e,4),n=h.sampleCount;h.sampleCount+=i;const r=1&e[3],s=4&e[3],a=1&e[2],o=2&e[2],l=4&e[2],c=8&e[2];let u=8,d=i;for(r&&(u+=4),s&&i&&(1&e[u+1]||void 0!==h.keyFrameIndex||(h.keyFrameIndex=n),u+=4,a?(v=zi(e,u),u+=4):v=f,o&&(u+=4),c&&(u+=4),p+=v,m+=v,d--);d--;)a?(v=zi(e,u),u+=4):v=f,o&&(u+=4),l&&(1&e[u+1]||void 0===h.keyFrameIndex&&(h.keyFrameIndex=h.sampleCount-(d+1),h.keyFrameStart=p),u+=4),c&&(u+=4),p+=v,m+=v;!m&&f&&(m+=f*i)}h.duration+=m}if(!Object.keys(n).some(t=>n[t].duration)){let e=1/0,i=0;const r=Qi(t,["sidx"]);for(let t=0;t<r.length;t++){const n=Zi(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);i=Math.max(i,t+n.earliestPresentationTime/n.timescale)}}i&&Je(i)&&Object.keys(n).forEach(t=>{n[t].duration||(n[t].duration=i*n[t].timescale-n[t].start)})}return n}(u,f,this),p=f.audio?g[f.audio.id]:null,m=f.video?g[f.video.id]:null,v=Xo(m,1/0),y=Xo(p,1/0),A=Xo(m,0,!0),E=Xo(p,0,!0);let T=r,b=0;const S=p&&(!m||!l&&y<v||l&&l.trackId===f.audio.id),k=S?p:m;if(k){const t=k.timescale,e=k.start-r*t,i=S?f.audio.id:f.video.id;T=k.start/t,b=S?E-y:A-v,!s&&l||!function(t,e,i,n){if(null===t)return!0;const r=Math.max(n,1),s=e-t.baseTime/t.timescale;return Math.abs(s-i)>r}(l,T,r,b)&&t===l.timescale||(l&&this.warn(`Timestamps at playlist time: ${s?"":"~"}${r} ${e/t} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${T-r} (${e}/${t}) trackId: ${i}`),l=null,d.initPTS=e,d.timescale=t,d.trackId=i)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${r}`);l?(d.initPTS=l.baseTime,d.timescale=l.timescale,d.trackId=l.trackId):(d.timescale&&void 0!==d.trackId&&void 0!==d.initPTS||(this.warn("Could not set initPTS"),d.initPTS=T,d.timescale=1,d.trackId=-1),this.initPTS=l={baseTime:d.initPTS,timescale:d.timescale,trackId:d.trackId});const _=T-l.baseTime/l.timescale,L=_+b;b>0?this.lastEndTime=L:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const I=!!f.audio,R=!!f.video;let C="";I&&(C+="audio"),R&&(C+="video");const P={data1:u,startPTS:_,startDTS:_,endPTS:L,endDTS:L,type:C,hasAudio:I,hasVideo:R,nb:1,dropped:0,encrypted:!!f.audio&&f.audio.encrypted||!!f.video&&f.video.encrypted};c.audio=I&&!R?P:void 0,c.video=R?P:void 0;const D=null==m?void 0:m.sampleCount;if(D){const t=m.keyFrameIndex,e=-1!==t;P.nb=D,P.dropped=0===t||this.isVideoContiguous?0:e?t:D,P.independent=e,P.firstKeyFrame=t,e&&m.keyFrameStart&&(P.firstKeyFramePTS=(m.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(c.independent=e),this.isVideoContiguous||(this.isVideoContiguous=e),P.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${t}/${D} dropped: ${P.dropped} start: ${P.firstKeyFramePTS||"NA"}`)}return c.initSegment=d,c.id3=zo(i,r,l,l),n.samples.length&&(c.text=qo(n,r,l)),c}}},{demux:Ro,remux:jo},{demux:class extends ro{constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.observer=t,this.config=e}resetInitSegment(t,e,i,n){super.resetInitSegment(t,e,i,n),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:n,inputTimeScale:9e4,dropped:0}}static probe(t,e){if(!t)return!1;const i=Ba(t,0);let n=(null==i?void 0:i.length)||0;if(mo(t,n))return!1;for(let i=t.length;n<i;n++)if(Ka(t,n))return e.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)&&Ua(t,e)&&Ga(t,e)<=t.length-e}(t,e)}appendFrame(t,e,i){Ha(t,this.observer,e,i,t.manifestCodec);const n=ja(t,e,i,this.basePTS,this.frameIndex);if(n&&0===n.missing)return n}},remux:jo},{demux:class extends ro{resetInitSegment(t,e,i,n){super.resetInitSegment(t,e,i,n),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:n,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=Ba(t,0);let i=(null==e?void 0:e.length)||0;if(e&&11===t[i]&&119===t[i+1]&&void 0!==eo(e)&&vo(t,i)<=16)return!1;for(let e=t.length;i<e;i++)if(mo(t,i))return ki.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return go(t,e)&&4<=t.length-e}(t,e)}appendFrame(t,e,i){if(null!==this.basePTS)return uo(t,e,i,this.basePTS,this.frameIndex)}},remux:jo}];Zo.splice(2,0,{demux:yo,remux:jo});class Jo{constructor(t,e,i,n,r,s){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=t,this.typeSupported=e,this.config=i,this.id=r,this.logger=s}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,i,n){const r=i.transmuxing;r.executeStart=Vo();let s=new Uint8Array(t);const{currentTransmuxState:a,transmuxConfig:o}=this;n&&(this.currentTransmuxState=n);const{contiguous:l,discontinuity:h,trackSwitch:c,accurateTimeOffset:u,timeOffset:d,initSegmentChange:f}=n||a,{audioCodec:g,videoCodec:p,defaultInitPts:m,duration:v,initSegmentData:y}=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&&hs(A.method)){const t=this.getDecrypter(),e=cs(A.method);if(!t.isSync())return this.asyncResult=!0,this.decryptionPromise=t.webCryptoDecrypt(s,A.key.buffer,A.iv.buffer,e).then(t=>{const e=this.push(t,null,i);return this.decryptionPromise=null,e}),this.decryptionPromise;{let n=t.softwareDecrypt(s,A.key.buffer,A.iv.buffer,e);if(i.part>-1){const e=t.flush();n=e?e.buffer:e}if(!n)return r.executeEnd=Vo(),tl(i);s=new Uint8Array(n)}}const E=this.needsProbing(h,c);if(E){const t=this.configureTransmuxer(s);if(t)return this.logger.warn(`[transmuxer] ${t.message}`),this.observer.emit(ri.ERROR,ri.ERROR,{type:ii.MEDIA_ERROR,details:ni.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),r.executeEnd=Vo(),tl(i)}(h||c||f||E)&&this.resetInitSegment(y,g,p,v,e),(h||f||E)&&this.resetInitialTimestamp(m),l||this.resetContiguity();const T=this.transmux(s,A,d,u,i);this.asyncResult=el(T);const b=this.currentTransmuxState;return b.contiguous=!0,b.discontinuity=!1,b.trackSwitch=!1,r.executeEnd=Vo(),T}flush(t){const e=t.transmuxing;e.executeStart=Vo();const{decrypter:i,currentTransmuxState:n,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(t));const s=[],{timeOffset:a}=n;if(i){const e=i.flush();e&&s.push(this.push(e.buffer,null,t))}const{demuxer:o,remuxer:l}=this;if(!o||!l){e.executeEnd=Vo();const i=[tl(t)];return this.asyncResult?Promise.resolve(i):i}const h=o.flush(a);return el(h)?(this.asyncResult=!0,h.then(e=>(this.flushRemux(s,e,t),s))):(this.flushRemux(s,h,t),this.asyncResult?Promise.resolve(s):s)}flushRemux(t,e,i){const{audioTrack:n,videoTrack:r,id3Track:s,textTrack:a}=e,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id===hi?"level":"track"} ${i.level}`);const h=this.remuxer.remux(n,r,s,a,l,o,!0,this.id);t.push({remuxResult:h,chunkMeta:i}),i.transmuxing.executeEnd=Vo()}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,n,r){const{demuxer:s,remuxer:a}=this;s&&a&&(s.resetInitSegment(t,e,i,n),a.resetInitSegment(t,e,i,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,e,i,n,r){let s;return s=e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,i,n,r):this.transmuxUnencrypted(t,i,n,r),s}transmuxUnencrypted(t,e,i,n){const{audioTrack:r,videoTrack:s,id3Track:a,textTrack:o}=this.demuxer.demux(t,e,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,s,a,o,e,i,!1,this.id),chunkMeta:n}}transmuxSampleAes(t,e,i,n,r){return this.demuxer.demuxSampleAes(t,e,i).then(t=>({remuxResult:this.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,i,n,!1,this.id),chunkMeta:r}))}configureTransmuxer(t){const{config:e,observer:i,typeSupported:n}=this;let r;for(let e=0,i=Zo.length;e<i;e++){var s;if(null!=(s=Zo[e].demux)&&s.probe(t,this.logger)){r=Zo[e];break}}if(!r)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=r.remux,h=r.demux;o&&o instanceof l||(this.remuxer=new l(i,e,n,this.logger)),a&&a instanceof h||(this.demuxer=new h(i,e,n,this.logger),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 Ur(this.config)),t}}const tl=t=>({remuxResult:{},chunkMeta:t});function el(t){return"then"in t&&t.then instanceof Function}class il{constructor(t,e,i,n,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=i,this.duration=n,this.defaultInitPts=r||null}}class nl{constructor(t,e,i,n,r,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=n,this.timeOffset=r,this.initSegmentChange=s}}let rl=0;class sl{constructor(t,e,i,n){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=rl++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=t=>{const e=t.data,i=this.hls;if(i&&null!=e&&e.event&&e.instanceNo===this.instanceNo)switch(e.event){case"init":{var n;const t=null==(n=this.workerContext)?void 0:n.objectURL;t&&self.URL.revokeObjectURL(t);break}case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;case"workerLog":i.logger[e.data.logType]&&i.logger[e.data.logType](e.data.message);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.part=this.part,e.data.id=this.id,i.trigger(e.event,e.data)}},this.onWorkerError=t=>{if(!this.hls)return;const e=new Error(`${t.message} (${t.filename}:${t.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(ri.ERROR,{type:ii.OTHER_ERROR,details:ni.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:e})};const r=t.config;this.hls=t,this.id=e,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=i,this.onFlush=n;const s=(t,e)=>{(e=e||{}).frag=this.frag||void 0,t===ri.ERROR&&(e.parent=this.id,e.part=this.part,this.error=e.error),this.hls.trigger(t,e)};this.observer=new wa,this.observer.on(ri.FRAG_DECRYPTED,s),this.observer.on(ri.ERROR,s);const a=Pn(r.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const i=this.hls.logger;if(r.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{r.workerPath?(i.log(`loading Web Worker ${r.workerPath} for "${e}"`),this.workerContext=function(t){const e=xa[t];if(e)return e.clientCount++,e;const i=new self.URL(t,self.location.href).href,n={worker:new self.Worker(i),scriptURL:i,clientCount:1};return xa[t]=n,n}(r.workerPath)):(i.log(`injecting Web Worker for "${e}"`),this.workerContext=function(){const t=xa[Oa];if(t)return t.clientCount++,t;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),i=self.URL.createObjectURL(e),n={worker:new self.Worker(i),objectURL:i,clientCount:1};return xa[Oa]=n,n}());const{worker:t}=this.workerContext;t.addEventListener("message",this.onWorkerMessage),t.addEventListener("error",this.onWorkerError),t.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:e,config:qn(r)})}catch(n){i.warn(`Error setting up "${e}" Web Worker, fallback to inline`,n),this.terminateWorker(),this.error=null,this.transmuxer=new Jo(this.observer,a,r,"",e,t.logger)}return}}this.transmuxer=new Jo(this.observer,a,r,"",e,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=rl++;const e=this.hls.config,i=Pn(e.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:i,id:this.id,config:qn(e)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),function(t){const e=xa[t||Oa];if(e&&1===e.clientCount--){const{worker:i,objectURL:n}=e;delete xa[t||Oa],n&&self.URL.revokeObjectURL(n),i.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(t,e,i,n,r,s,a,o,l,h){var c,u;l.transmuxing.start=self.performance.now();const{instanceNo:d,transmuxer:f}=this,g=s?s.start:r.start,p=r.decryptdata,m=this.frag,v=!(m&&r.cc===m.cc),y=!(m&&l.level===m.level),A=m?l.sn-m.sn:-1,E=this.part?l.part-this.part.index:-1,T=0===A&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),b=!y&&(1===A||0===A&&(1===E||T&&E<=0)),S=self.performance.now();(y||A||0===r.stats.parsing.start)&&(r.stats.parsing.start=S),!s||!E&&b||(s.stats.parsing.start=S);const k=!(m&&(null==(c=r.initSegment)?void 0:c.url)===(null==(u=m.initSegment)?void 0:u.url)),_=new nl(v,b,o,y,g,k);if(!b||v||k){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===hi?"level":"track"}: ${l.level} id: ${l.id}\n discontinuity: ${v}\n trackSwitch: ${y}\n contiguous: ${b}\n accurateTimeOffset: ${o}\n timeOffset: ${g}\n initSegmentChange: ${k}`);const t=new il(i,n,e,a,h);this.configureTransmuxer(t)}if(this.frag=r,this.part=s,this.workerContext)this.workerContext.worker.postMessage({instanceNo:d,cmd:"demux",data:t,decryptdata:p,chunkMeta:l,state:_},t instanceof ArrayBuffer?[t]:[]);else if(f){const e=f.push(t,p,l,_);el(e)?e.then(t=>{this.handleTransmuxComplete(t)}).catch(t=>{this.transmuxerError(t,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(e)}}flush(t){t.transmuxing.start=self.performance.now();const{instanceNo:e,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:e,cmd:"flush",chunkMeta:t});else if(i){const e=i.flush(t);el(e)?e.then(e=>{this.handleFlushResult(e,t)}).catch(e=>{this.transmuxerError(e,t,"transmuxer-interface flush error")}):this.handleFlushResult(e,t)}}transmuxerError(t,e,i){this.hls&&(this.error=t,this.hls.trigger(ri.ERROR,{type:ii.MEDIA_ERROR,details:ni.FRAG_PARSING_ERROR,chunkMeta:e,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:t,err:t,reason:i}))}handleFlushResult(t,e){t.forEach(t=>{this.handleTransmuxComplete(t)}),this.onFlush(e)}configureTransmuxer(t){const{instanceNo:e,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:e,cmd:"configure",config:t}):i&&i.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}class al extends yi{constructor(t,e){super(e,t.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,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.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,e,i){const n=null==e?void 0:e.renditionReports;if(n){let r=-1;for(let i=0;i<n.length;i++){const s=n[i];let a;try{a=new self.URL(s.URI,e.url).href}catch(t){this.warn(`Could not construct new URL for Rendition Report: ${t}`),a=s.URI||""}if(a===t){r=i;break}a===t.substring(0,a.length)&&(r=i)}if(-1!==r){const t=n[r],s=parseInt(t["LAST-MSN"])||e.lastPartSn;let a=parseInt(t["LAST-PART"])||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&&Hn(i);return new Yn(s,a>=0?a:void 0,o)}}}loadPlaylist(t){this.clearTimer()}loadingPlaylist(t,e){this.clearTimer()}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}getUrlWithDirectives(t,e){if(e)try{return e.addDirectives(t)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}return t}playlistLoaded(t,e,i){const{details:n,stats:r}=e,s=self.performance.now(),a=r.loading.first?Math.max(0,s-r.loading.first):0;n.advancedDateTime=Date.now()-a;const o=this.hls.config.timelineOffset;if(o!==n.appliedTimelineOffset){const t=Math.max(o||0,0);n.appliedTimelineOffset=t,n.fragments.forEach(e=>{e.setStart(e.playlistOffset+t)})}if(n.live||null!=i&&i.live){const o="levelInfo"in e?e.levelInfo:e.track;if(n.reloaded(i),i&&n.fragments.length>0){qs(i,n,this);const t=n.playlistParsingError;if(t){this.warn(t);const i=this.hls;if(!i.config.ignorePlaylistParsingErrors){var l;const{networkDetails:s}=e;return void i.trigger(ri.ERROR,{type:ii.NETWORK_ERROR,details:ni.LEVEL_PARSING_ERROR,fatal:!1,url:n.url,error:t,reason:t.message,level:e.level||void 0,parent:null==(l=n.fragments[0])?void 0:l.type,networkDetails:s,stats:r})}n.playlistParsingError=null}}-1===n.requestScheduled&&(n.requestScheduled=r.loading.start);const h=this.hls.mainForwardBufferInfo,c=h?h.end-h.len:0,u=Js(n,1e3*(n.edge-c));if(n.requestScheduled+u<s?n.requestScheduled=s:n.requestScheduled<=s&&(n.requestScheduled+=u),this.log(`live playlist ${t} ${n.advanced?"REFRESHED "+n.lastPartSn+"-"+n.lastPartIndex:n.updated?"UPDATED":"MISSED"}`),!this.canLoad||!n.live)return;let d,f,g;if(n.canBlockReload&&n.endSN&&n.advanced){const t=this.hls.config.lowLatencyMode,r=n.lastPartSn,a=n.endSN,l=n.lastPartIndex,h=r===a;-1!==l?h?(f=a+1,g=t?0:l):(f=r,g=t?l+1:n.maxPartIndex):f=a+1;const c=n.age,u=c+n.ageHeader;let p=Math.min(u-n.partTarget,1.5*n.targetduration);if(p>0){if(u>3*n.targetduration)this.log(`Playlist last advanced ${c.toFixed(2)}s ago. Omitting segment and part directives.`),f=void 0,g=void 0;else if(null!=i&&i.tuneInGoal&&u-n.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${p} with playlist age: ${n.age}`),p=0;else{const t=Math.floor(p/n.targetduration);if(f+=t,void 0!==g){g+=Math.round(p%n.targetduration/n.partTarget)}this.log(`CDN Tune-in age: ${n.ageHeader}s last advanced ${c.toFixed(2)}s goal: ${p} skip sn ${t} to part ${g}`)}n.tuneInGoal=p}if(d=this.getDeliveryDirectives(n,e.deliveryDirectives,f,g),t||!h)return n.requestScheduled=s,void this.loadingPlaylist(o,d)}else(n.canBlockReload||n.canSkipUntil)&&(d=this.getDeliveryDirectives(n,e.deliveryDirectives,f,g));d&&void 0!==f&&n.canBlockReload&&(n.requestScheduled=r.loading.first+Math.max(u-2*a,u/2)),this.scheduleLoading(o,d,n)}else this.clearTimer()}scheduleLoading(t,e,i){const n=i||t.details;if(!n)return void this.loadingPlaylist(t,e);const r=self.performance.now(),s=n.requestScheduled;if(r>=s)return void this.loadingPlaylist(t,e);const a=s-r;this.log(`reload live playlist ${t.name||t.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(t,e),a)}getDeliveryDirectives(t,e,i,n){let r=Hn(t);return null!=e&&e.skip&&t.deltaUpdateFailed&&(i=e.msn,n=e.part,r=Gn),new Yn(i,n,r)}checkRetry(t){const e=t.details,i=hr(t),n=t.errorAction,{action:r,retryCount:s=0,retryConfig:a}=n||{},o=!!n&&!!a&&(r===Er||!n.resolved&&r===yr);if(o){var l;if(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=fr(a,s);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),t),this.warn(`Retrying playlist loading ${s+1}/${a.maxNumRetry} after "${e}" in ${t}ms`)}t.levelRetry=!0,n.resolved=!0}return o}}function ol(t,e){if(t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(!ll(t[i].attrs,e[i].attrs))return!1;return!0}function ll(t,e,i){const n=t["STABLE-RENDITION-ID"];return n&&!i?n===e["STABLE-RENDITION-ID"]:!(i||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>t[i]!==e[i])}function hl(t,e){return e.label.toLowerCase()===t.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(t.lang||"").toLowerCase())}class cl{constructor(t){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=t}destroy(){this.tracks=this.queues=null}append(t,e,i){if(null===this.queues||null===this.tracks)return;const n=this.queues[e];n.push(t),1!==n.length||i||this.executeNext(e)}appendBlocker(t){return new Promise(e=>{const i={label:"async-blocker",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,t)})}prependBlocker(t){return new Promise(e=>{if(this.queues){const i={label:"async-blocker-prepend",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[t].unshift(i)}})}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(t=>{var e;const i=null==(e=t[0])?void 0:e.label;"async-blocker"!==i&&"async-blocker-prepend"!==i||(t[0].execute(),t.splice(0,1))})}unblockAudio(t){if(null===this.queues)return;this.queues.audio[0]===t&&this.shiftAndExecuteNext("audio")}executeNext(t){if(null===this.queues||null===this.tracks)return;const e=this.queues[t];if(e.length){const n=e[0];try{n.execute()}catch(e){var i;if(n.onError(e),null===this.queues||null===this.tracks)return;const r=null==(i=this.tracks[t])?void 0:i.buffer;null!=r&&r.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){null!==this.queues&&(this.queues[t].shift(),this.executeNext(t))}current(t){var e;return(null==(e=this.queues)?void 0:e[t][0])||null}toString(){const{queues:t,tracks:e}=this;return null===t||null===e?"<destroyed>":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(t){var e,i;return null!=(e=this.queues)&&e[t]||null!=(i=this.tracks)&&i[t]?`${t}: (${this.listSbInfo(t)}) ${this.listOps(t)}`:""}listSbInfo(t){var e;const i=null==(e=this.tracks)?void 0:e[t],n=null==i?void 0:i.buffer;return n?`SourceBuffer${n.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(t){var e;return(null==(e=this.queues)?void 0:e[t].map(t=>t.label).join(", "))||""}}const ul=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,dl="HlsJsTrackRemovedError";class fl extends Error{constructor(t){super(t),this.name=dl}}function gl(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach(e=>{t.removeChild(e)})}function pl(t){return"audio"===t?1:0}class ml{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(ri.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(ri.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(ri.MANIFEST_PARSED,this.onManifestParsed,this),t.on(ri.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(ri.BUFFER_CODECS,this.onBufferCodecs,this),t.on(ri.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(ri.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(ri.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(ri.MANIFEST_PARSED,this.onManifestParsed,this),t.off(ri.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(ri.BUFFER_CODECS,this.onBufferCodecs,this),t.off(ri.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&&Je(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,e){this.hls.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}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&&e.logger.log(`Setting autoLevelCapping to ${i}: ${t[i].height}p@${t[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),e.autoLevelCapping=i,e.autoLevelEnabled&&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,ml.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 Math.min(t,this.hls.config.maxDevicePixelRatio)}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;const n=(t,e)=>!e||(t.width!==e.width||t.height!==e.height);let r=t.length-1;const s=Math.max(e,i);for(let e=0;e<t.length;e+=1){const i=t[e];if((i.width>=s||i.height>=s)&&n(i,t[e+1])){r=e;break}}return r}}const vl={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},yl={HLS:"h"};class Al{constructor(t,e){Array.isArray(t)&&(t=t.map(t=>t instanceof Al?t:new Al(t))),this.value=t,this.params=e}}function El(t,e,i,n){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 ${i}`,{cause:n});var r}function Tl(t,e,i){return El("serialize",t,e,i)}class bl{constructor(t){this.description=t}}const Sl="Bare Item";function kl(t){if(!1===ArrayBuffer.isView(t))throw Tl(t,"Byte Sequence");return`:${e=t,btoa(String.fromCharCode(...e))}:`;var e}function _l(t){if(function(t){return t<-999999999999999||999999999999999<t}(t))throw Tl(t,"Integer");return t.toString()}function Ll(t,e){if(t<0)return-Ll(-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=Ll(t,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Tl(t,"Decimal");const i=e.toString();return i.includes(".")?i:`${i}.0`}const Rl=/[\x00-\x1f\x7f]+/;function Cl(t){const e=(i=t).description||i.toString().slice(7,-1);var i;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e))throw Tl(e,"Token");return e}function Pl(t){switch(typeof t){case"number":if(!Je(t))throw Tl(t,Sl);return Number.isInteger(t)?_l(t):Il(t);case"string":return function(t){if(Rl.test(t))throw Tl(t,"String");return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(t);case"symbol":return Cl(t);case"boolean":return function(t){if("boolean"!=typeof t)throw Tl(t,"Boolean");return t?"?1":"?0"}(t);case"object":if(t instanceof Date)return function(t){return`@${_l(t.getTime()/1e3)}`}(t);if(t instanceof Uint8Array)return kl(t);if(t instanceof bl)return Cl(t);default:throw Tl(t,Sl)}}function Dl(t){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(t))throw Tl(t,"Key");return t}function wl(t){return null==t?"":Object.entries(t).map(([t,e])=>!0===e?`;${Dl(t)}`:`;${Dl(t)}=${Pl(e)}`).join("")}function Ol(t){return t instanceof Al?`${Pl(t.value)}${wl(t.params)}`:Pl(t)}function xl(t,e={whitespace:!0}){if("object"!=typeof t||null==t)throw Tl(t,"Dict");const i=t instanceof Map?t.entries():Object.entries(t),n=(null==e?void 0:e.whitespace)?" ":"";return Array.from(i).map(([t,e])=>{e instanceof Al==!1&&(e=new Al(e));let i=Dl(t);var n;return!0===e.value?i+=wl(e.params):(i+="=",Array.isArray(e.value)?i+=`(${(n=e).value.map(Ol).join(" ")})${wl(n.params)}`:i+=Ol(e)),i}).join(`,${n}`)}function Ml(t,e){return xl(t,e)}const Nl="CMCD-Object",Fl="CMCD-Request",Bl="CMCD-Session",Ul="CMCD-Status",$l={br:Nl,ab:Nl,d:Nl,ot:Nl,tb:Nl,tpb:Nl,lb:Nl,tab:Nl,lab:Nl,url:Nl,pb:Fl,bl:Fl,tbl:Fl,dl:Fl,ltc:Fl,mtp:Fl,nor:Fl,nrr:Fl,rc:Fl,sn:Fl,sta:Fl,su:Fl,ttfb:Fl,ttfbb:Fl,ttlb:Fl,cmsdd:Fl,cmsds:Fl,smrt:Fl,df:Fl,cs:Fl,ts:Fl,cid:Bl,pr:Bl,sf:Bl,sid:Bl,st:Bl,v:Bl,msd:Bl,bs:Ul,bsd:Ul,cdn:Ul,rtp:Ul,bg:Ul,pt:Ul,ec:Ul,e:Ul},Gl=Fl;function Vl(t,e){const i={};if(!t)return i;const n=Object.keys(t),r=e?(s=e,Object.keys(s).reduce((t,e)=>{var i;return null===(i=s[e])||void 0===i||i.forEach(i=>t[i]=e),t},{})):{};var s;return n.reduce((e,i)=>{var n;const s=$l[i]||r[i]||Gl;return(null!==(n=e[s])&&void 0!==n?n:e[s]={})[i]=t[i],e},i)}const Kl="event";const Hl=t=>Math.round(t),Yl=(t,e)=>Array.isArray(t)?t.map(t=>Yl(t,e)):t instanceof Al&&"string"==typeof t.value?new Al(Yl(t.value,e),t.params):(e.baseUrl&&(t=function(t,e){const i=new URL(t),n=new URL(e);if(i.origin!==n.origin)return t;const r=i.pathname.split("/").slice(1),s=n.pathname.split("/").slice(1,-1);for(;r[0]===s[0];)r.shift(),s.shift();for(;s.length;)s.shift(),r.unshift("..");return r.join("/")+i.search+i.hash}(t,e.baseUrl)),1===e.version?encodeURIComponent(t):t),jl=t=>100*Hl(t/100),Wl={br:Hl,d:Hl,bl:jl,dl:jl,mtp:jl,nor:(t,e)=>{let i=t;return e.version>=2&&(t instanceof Al&&"string"==typeof t.value?i=new Al([t]):"string"==typeof t&&(i=[t])),Yl(i,e)},rtp:jl,tb:Hl},zl="request",ql="response",Xl=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],Ql=["e"],Zl=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Jl(t){return Zl.test(t)}const th=["d","dl","nor","ot","rtp","su"];const eh=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];const ih=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function nh(t){return ih.includes(t)||Jl(t)}const rh={[ql]:function(t){return Xl.includes(t)||th.includes(t)||eh.includes(t)||Jl(t)},[Kl]:function(t){return Xl.includes(t)||Ql.includes(t)||Jl(t)},[zl]:function(t){return Xl.includes(t)||th.includes(t)||Jl(t)}};function sh(t,e={}){const i={};if(null==t||"object"!=typeof t)return i;const n=e.version||t.v||1,r=e.reportingMode||zl,s=1===n?nh:rh[r];let a=Object.keys(t).filter(s);const o=e.filter;"function"==typeof o&&(a=a.filter(o));const l=r===ql||r===Kl;l&&!a.includes("ts")&&a.push("ts"),n>1&&!a.includes("v")&&a.push("v");const h=pi({},Wl,e.formatters),c={version:n,reportingMode:r,baseUrl:e.baseUrl};return a.sort().forEach(e=>{let r=t[e];const s=h[e];if("function"==typeof s&&(r=s(r,c)),"v"===e){if(1===n)return;r=n}"pr"==e&&1===r||(l&&"ts"===e&&!Je(r)&&(r=Date.now()),function(t){return"number"==typeof t?Je(t):null!=t&&""!==t&&!1!==t}(r)&&(function(t){return["ot","sf","st","e","sta"].includes(t)}(e)&&"string"==typeof r&&(r=new bl(r)),i[e]=r))}),i}function ah(t,e,i){return pi(t,function(t,e={}){const i={};if(!t)return i;const n=Vl(sh(t,e),null==e?void 0:e.customHeaderMap);return Object.entries(n).reduce((t,[e,i])=>{const n=Ml(i,{whitespace:!1});return n&&(t[e]=n),t},i)}(e,i))}function oh(t,e={}){if(!t)return"";const i=function(t,e={}){return t?Ml(sh(t,e),{whitespace:!1}):""}(t,e);return encodeURIComponent(i)}const lh=/CMCD=[^&#]+/;function hh(t,e,i){const n=function(t,e={}){return t?`CMCD=${oh(t,e)}`:""}(e,i);if(!n)return t;if(lh.test(t))return t.replace(lh,n);const r=t.includes("?")?"&":"?";return`${t}${r}${n}`}function ch(t,e,i,n){t&&Object.keys(e).forEach(r=>{const s=t.filter(t=>t.groupId===r).map(t=>{const s=pi({},t);return s.details=void 0,s.attrs=new is(s.attrs),s.url=s.attrs.URI=uh(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),s.groupId=s.attrs["GROUP-ID"]=e[r],s.attrs["PATHWAY-ID"]=n,s});t.push(...s)})}function uh(t,e,i,n){const{HOST:r,PARAMS:s,[i]:a}=n;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),s&&Object.keys(s).sort().forEach(t=>{t&&l.searchParams.set(t,s[t])}),l.href}class dh extends yi{constructor(t){super("eme",t.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=dh.CDMCleanupPromise?[dh.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{const{initDataType:e,initData:i}=t,n=`"${t.type}" event: init data type: "${e}"`;if(this.debug(n),null!==i){if(!this.keyFormatPromise){let t=Object.keys(this.keySystemAccessPromises);t.length||(t=Ss(this.config));const e=t.map(bs).filter(t=>!!t);this.keyFormatPromise=this.getKeyFormatPromise(e)}this.keyFormatPromise.then(r=>{const s=Ts(r);if("sinf"!==e||s!==ms.FAIRPLAY)return void this.log(`Ignoring "${t.type}" event with init data type: "${e}" for selected key-system ${s}`);let a;try{const t=ji(new Uint8Array(i)),e=on(us(JSON.parse(t).sinf));if(!e)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");a=new Uint8Array(e.subarray(8,24))}catch(t){return void this.warn(`${n} Failed to parse sinf: ${t}`)}const o=Ri(a),{keyIdToKeySessionPromise:l,mediaKeySessions:h}=this;let c=l[o];for(let t=0;t<h.length;t++){const n=h[t],r=n.decryptdata;if(!r.keyId)continue;const s=Ri(r.keyId);if(os(a,r.keyId)||-1!==r.uri.replace(/-/g,"").indexOf(o)){if(c=l[s],!c)continue;if(r.pssh)break;delete l[s],r.pssh=new Uint8Array(i),r.keyId=a,c=l[o]=c.then(()=>this.generateRequestWithPreferredKeySession(n,e,i,"encrypted-event-key-match")),c.catch(t=>this.handleError(t));break}}c||this.handleError(new Error(`Key ID ${o} not encountered in playlist. Key-system sessions ${h.length}.`))}).catch(t=>this.handleError(t))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(ri.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(ri.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(ri.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(ri.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(ri.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(ri.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(ri.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(ri.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(ri.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(ri.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(t){const{drmSystems:e,widevineLicenseUrl:i}=this.config,n=null==e?void 0:e[t];return n?n.licenseUrl:t===ms.WIDEVINE&&i?i:void 0}getLicenseServerUrlOrThrow(t){const e=this.getLicenseServerUrl(t);if(void 0===e)throw new Error(`no license server URL configured for key-system "${t}"`);return e}getServerCertificateUrl(t){const{drmSystems:e}=this.config,i=null==e?void 0: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,n=e.map(t=>t.audioCodec).filter(i),r=e.map(t=>t.videoCodec).filter(i);return n.length+r.length===0&&r.push("avc1.42e01e"),new Promise((e,i)=>{const s=t=>{const a=t.shift();this.getMediaKeysPromise(a,n,r).then(t=>e({keySystem:a,mediaKeys:t})).catch(e=>{t.length?s(t):i(e instanceof ph?e:new ph({type:ii.KEY_SYSTEM_ERROR,details:ni.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===ks&&"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){var n;const r=function(t,e,i,n){let r;switch(t){case ms.FAIRPLAY:r=["cenc","sinf"];break;case ms.WIDEVINE:case ms.PLAYREADY:r=["cenc"];break;case ms.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${t}`)}return function(t,e,i,n){return[{initDataTypes:t,persistentState:n.persistentState||"optional",distinctiveIdentifier:n.distinctiveIdentifier||"optional",sessionTypes:n.sessionTypes||[n.sessionType||"temporary"],audioCapabilities:e.map(t=>({contentType:`audio/mp4; codecs=${t}`,robustness:n.audioRobustness||"",encryptionScheme:n.audioEncryptionScheme||null})),videoCapabilities:i.map(t=>({contentType:`video/mp4; codecs=${t}`,robustness:n.videoRobustness||"",encryptionScheme:n.videoEncryptionScheme||null}))}]}(r,e,i,n)}(t,e,i,this.config.drmSystemOptions||{});let s=this.keySystemAccessPromises[t],a=null==(n=s)?void 0:n.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${t}" key-system access with config: ${qn(r)}`),a=this.requestMediaKeySystemAccess(t,r);const e=s=this.keySystemAccessPromises[t]={keySystemAccess:a};return a.catch(e=>{this.log(`Failed to obtain access to key-system "${t}": ${e}`)}),a.then(i=>{this.log(`Access for key-system "${i.keySystem}" obtained`);const n=this.fetchServerCertificate(t);this.log(`Create media-keys for "${t}"`);const r=e.mediaKeys=i.createMediaKeys().then(i=>(this.log(`Media-keys created for "${t}"`),e.hasMediaKeys=!0,n.then(e=>e?this.setMediaKeysServerCertificate(i,t,e):i)));return r.catch(e=>{this.error(`Failed to create media-keys for "${t}"}: ${e}`)}),r})}return a.then(()=>s.mediaKeys)}createMediaKeySessionContext({decryptdata:t,keySystem:e,mediaKeys:i}){this.log(`Creating key-system session "${e}" keyId: ${Ri(t.keyId||[])} keyUri: ${t.uri}`);const n=i.createSession(),r={decryptdata:t,keySystem:e,mediaKeys:i,mediaKeysSession:n,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(t){const e=t.decryptdata;if(e.pssh){const i=this.createMediaKeySessionContext(t),n=fh(e),r="cenc";this.keyIdToKeySessionPromise[n]=this.generateRequestWithPreferredKeySession(i,r,e.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}updateKeySession(t,e){const i=t.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyId ${Ri(t.decryptdata.keyId||[])}\n } (data length: ${e.byteLength})`),i.update(e)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(t=>({keySystem:t,hasMediaKeys:this.keySystemAccessPromises[t].hasMediaKeys})).filter(({hasMediaKeys:t})=>!!t).map(({keySystem:t})=>bs(t)).filter(t=>!!t)}getKeySystemAccess(t){return this.getKeySystemSelectionPromise(t).then(({keySystem:t,mediaKeys:e})=>this.attemptSetMediaKeys(t,e))}selectKeySystem(t){return new Promise((e,i)=>{this.getKeySystemSelectionPromise(t).then(({keySystem:t})=>{const n=bs(t);n?e(n):i(new Error(`Unable to find format for key-system "${t}"`))}).catch(i)})}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){const e=Ss(this.config),i=t.map(Ts).filter(t=>!!t&&-1!==e.indexOf(t));return this.selectKeySystem(i)}getKeyStatus(t){const{mediaKeySessions:e}=this;for(let i=0;i<e.length;i++){const n=gh(t,e[i]);if(n)return n}}loadKey(t){const e=t.keyInfo.decryptdata,i=fh(e),n=this.bannedKeyIds[i];if(n||"internal-error"===this.getKeyStatus(e)){const i=mh(n||"internal-error",e);return this.handleError(i,t.frag),Promise.reject(i)}const r=`(keyId: ${i} format: "${e.keyFormat}" method: ${e.method} uri: ${e.uri})`;this.log(`Starting session for key ${r}`);const s=this.keyIdToKeySessionPromise[i];if(!s){const n=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(),this.createMediaKeySessionContext({keySystem:i,mediaKeys:n,decryptdata:e}))))).then(t=>{const i=e.pssh?e.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(t,"cenc",i,"playlist-key")});return n.catch(e=>this.handleError(e,t.frag)),this.keyIdToKeySessionPromise[i]=n,n}return s.catch(i=>{if(i instanceof ph){const n=vi({},i.data);"internal-error"===this.getKeyStatus(e)&&(n.decryptdata=e);const r=new ph(n,i.message);this.handleError(r,t.frag)}}),s}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t,e){if(this.hls)if(t instanceof ph){e&&(t.data.frag=e);const i=t.data.decryptdata;this.error(`${t.message}${i?` (${Ri(i.keyId||[])})`:""}`),this.hls.trigger(ri.ERROR,t.data)}else this.error(t.message),this.hls.trigger(ri.ERROR,{type:ii.KEY_SYSTEM_ERROR,details:ni.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0})}getKeySystemForKeyPromise(t){const e=fh(t),i=this.keyIdToKeySessionPromise[e];if(!i){const e=Ts(t.keyFormat),i=e?[e]:Ss(this.config);return this.attemptKeySystemAccess(i)}return i}getKeySystemSelectionPromise(t){if(t.length||(t=Ss(this.config)),0===t.length)throw new ph({type:ii.KEY_SYSTEM_ERROR,details:ni.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${qn({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}attemptSetMediaKeys(t,e){if(this.mediaResolved=void 0,this.mediaKeys===e)return Promise.resolve();const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const n=Promise.all(i).then(()=>this.media?this.media.setMediaKeys(e):new Promise((t,i)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return i(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=e,this.media.setMediaKeys(e).then(t).catch(i)}}));return this.mediaKeys=e,this.setMediaKeysQueue.push(n),n.then(()=>{this.log(`Media-keys set for "${t}"`),i.push(n),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(t=>-1===i.indexOf(t))})}generateRequestWithPreferredKeySession(t,e,i,n){var r;const s=null==(r=this.config.drmSystems)||null==(r=r[t.keySystem])?void 0:r.generateRequest;if(s)try{const n=s.call(this.hls,e,i,t);if(!n)throw new Error("Invalid response from configured generateRequest filter");e=n.initDataType,i=n.initData?n.initData:null,t.decryptdata.pssh=i?new Uint8Array(i):null}catch(t){if(this.warn(t.message),this.hls&&this.hls.config.debug)throw t}if(null===i)return this.log(`Skipping key-session request for "${n}" (no initData)`),Promise.resolve(t);const a=fh(t.decryptdata),o=t.decryptdata.uri;this.log(`Generating key-session request for "${n}" keyId: ${a} URI: ${o} (init data type: ${e} length: ${i.byteLength})`);const l=new wa,h=t._onmessage=e=>{const i=t.mediaKeysSession;if(!i)return void l.emit("error",new Error("invalid state"));const{messageType:n,message:r}=e;this.log(`"${n}" message event for session "${i.sessionId}" message size: ${r.byteLength}`),"license-request"===n||"license-renewal"===n?this.renewLicense(t,r).catch(t=>{l.eventNames().length?l.emit("error",t):this.handleError(t)}):"license-release"===n?t.keySystem===ms.FAIRPLAY&&this.updateKeySession(t,ds("acknowledged")).then(()=>this.removeSession(t)).catch(t=>this.handleError(t)):this.warn(`unhandled media key message type "${n}"`)},c=(t,e)=>{let i;e.keyStatus=t,t.startsWith("usable")?l.emit("resolved"):"internal-error"===t||"output-restricted"===t||"output-downscaled"===t?i=mh(t,e.decryptdata):"expired"===t?i=new Error(`key expired (keyId: ${a})`):"released"===t?i=new Error("key released"):"status-pending"===t||this.warn(`unhandled key status change "${t}" (keyId: ${a})`),i&&(l.eventNames().length?l.emit("error",i):this.handleError(i))},u=t._onkeystatuseschange=e=>{if(!t.mediaKeysSession)return void l.emit("error",new Error("invalid state"));const i=this.getKeyStatuses(t);if(!Object.keys(i).some(t=>"status-pending"!==i[t]))return;if("expired"===i[a])return this.log(`Expired key ${qn(i)} in key-session "${t.mediaKeysSession.sessionId}"`),void this.renewKeySession(t);let n=i[a];if(n)c(n,t);else{var r;const e=1e3;t.keyStatusTimeouts||(t.keyStatusTimeouts={}),(r=t.keyStatusTimeouts)[a]||(r[a]=self.setTimeout(()=>{if(!t.mediaKeysSession||!this.mediaKeys)return;const i=this.getKeyStatus(t.decryptdata);if(i&&"status-pending"!==i)return this.log(`No status for keyId ${a} in key-session "${t.mediaKeysSession.sessionId}". Using session key-status ${i} from other session.`),c(i,t);this.log(`key status for ${a} in key-session "${t.mediaKeysSession.sessionId}" timed out after ${e}ms`),n="internal-error",c(n,t)},e)),this.log(`No status for keyId ${a} (${qn(i)}).`)}};ua(t.mediaKeysSession,"message",h),ua(t.mediaKeysSession,"keystatuseschange",u);const d=new Promise((t,e)=>{l.on("error",e),l.on("resolved",t)});return t.mediaKeysSession.generateRequest(e,i).then(()=>{this.log(`Request generated for key-session "${t.mediaKeysSession.sessionId}" keyId: ${a} URI: ${o}`)}).catch(e=>{throw new ph({type:ii.KEY_SYSTEM_ERROR,details:ni.KEY_SYSTEM_NO_SESSION,error:e,decryptdata:t.decryptdata,fatal:!1},`Error generating key-session request: ${e}`)}).then(()=>d).catch(e=>(l.removeAllListeners(),this.removeSession(t).then(()=>{throw e}))).then(()=>(l.removeAllListeners(),t))}getKeyStatuses(t){const e={};return t.mediaKeysSession.keyStatuses.forEach((i,n)=>{if("string"==typeof n&&"object"==typeof i){const t=n;n=i,i=t}const r="buffer"in n?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n);if(t.keySystem===ms.PLAYREADY&&16===r.length){const t=Ri(r);e[t]=i,fs(r)}const s=Ri(r);"internal-error"===i&&(this.bannedKeyIds[s]=i),this.log(`key status change "${i}" for keyStatuses keyId: ${s} key-session "${t.mediaKeysSession.sessionId}"`),e[s]=i}),e}fetchServerCertificate(t){const e=this.config,i=new(0,e.loader)(e),n=this.getServerCertificateUrl(t);return n?(this.log(`Fetching server certificate for "${t}"`),new Promise((r,s)=>{const a={responseType:"arraybuffer",url:n},o=e.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(t,e,i,n)=>{r(t.data)},onError:(e,i,r,o)=>{s(new ph({type:ii.KEY_SYSTEM_ERROR,details:ni.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:vi({url:a.url,data:void 0},e)},`"${t}" certificate request failed (${n}). Status: ${e.code} (${e.text})`))},onTimeout:(e,i,r)=>{s(new ph({type:ii.KEY_SYSTEM_ERROR,details:ni.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:{url:a.url,data:void 0}},`"${t}" certificate request timed out (${n})`))},onAbort:(t,e,i)=>{s(new Error("aborted"))}};i.load(a,l,h)})):Promise.resolve()}setMediaKeysServerCertificate(t,e,i){return new Promise((n,r)=>{t.setServerCertificate(i).then(r=>{this.log(`setServerCertificate ${r?"success":"not supported by CDM"} (${i.byteLength}) on "${e}"`),n(t)}).catch(t=>{r(new ph({type:ii.KEY_SYSTEM_ERROR,details:ni.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(e=>{throw new ph({type:ii.KEY_SYSTEM_ERROR,details:ni.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t.decryptdata,error:e,fatal:!1},e.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 n=(new DOMParser).parseFromString(i,"application/xml"),r=n.querySelectorAll("HttpHeader");if(r.length>0){let e;for(let i=0,n=r.length;i<n;i++){var s,a;e=r[i];const n=null==(s=e.querySelector("name"))?void 0:s.textContent,o=null==(a=e.querySelector("value"))?void 0:a.textContent;n&&o&&t.setRequestHeader(n,o)}}const o=n.querySelector("Challenge"),l=null==o?void 0:o.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return ds(atob(l))}setupLicenseXHR(t,e,i,n){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return r.call(this.hls,t,e,i,n)}).catch(s=>{if(!i.decryptdata)throw s;return t.open("POST",e,!0),r.call(this.hls,t,e,i,n)}).then(i=>{t.readyState||t.open("POST",e,!0);return{xhr:t,licenseChallenge:i||n}}):(t.open("POST",e,!0),Promise.resolve({xhr:t,licenseChallenge:n}))}requestLicense(t,e){const i=this.config.keyLoadPolicy.default;return new Promise((n,r)=>{const s=this.getLicenseServerUrlOrThrow(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 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 i=this.config.licenseResponseCallback;if(i)try{e=i.call(this.hls,a,s,t)}catch(t){this.error(t)}n(e)}else{const o=i.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)r(new ph({type:ii.KEY_SYSTEM_ERROR,details:ni.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t.decryptdata,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(n,r)}}},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==ms.PLAYREADY&&(i=this.unpackPlayReadyKeyMessage(e,i)),e.send(i)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(t,e){if(!this.config.emeEnabled)return;const i=e.media;this.media=i,ua(i,"encrypted",this.onMediaEncrypted),ua(i,"waitingforkey",this.onWaitingForKey);const n=this.mediaResolved;n?n():this.mediaKeys=i.mediaKeys}onMediaDetached(){const t=this.media;t&&(da(t,"encrypted",this.onMediaEncrypted),da(t,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var t;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const e=this.mediaResolved;if(e&&e(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const i=this.media,n=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Rs.clearKeyUriToKeyIdMap();const r=n.length;dh.CDMCleanupPromise=Promise.all(n.map(t=>this.removeSession(t)).concat((null==i||null==(t=i.setMediaKeys(null))?void 0:t.catch(t=>{this.log(`Could not clear media keys: ${t}`),this.hls&&this.hls.trigger(ri.ERROR,{type:ii.OTHER_ERROR,details:ni.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${t}`)})}))||Promise.resolve())).catch(t=>{this.log(`Could not close sessions and clear media keys: ${t}`),this.hls&&this.hls.trigger(ri.ERROR,{type:ii.OTHER_ERROR,details:ni.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${t}`)})}).then(()=>{r&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}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,decryptdata:n}=t;if(e){this.log(`Remove licenses and keys and close session "${e.sessionId}" keyId: ${Ri((null==n?void 0:n.keyId)||[])}`),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);r>-1&&this.mediaKeySessions.splice(r,1);const{keyStatusTimeouts:s}=t;s&&Object.keys(s).forEach(t=>self.clearTimeout(s[t]));const{drmSystemOptions:a}=this.config,o=function(t){var e;return!(!t||"persistent-license"!==t.sessionType&&(null==(e=t.sessionTypes)||!e.some(t=>"persistent-license"===t)))}(a)?new Promise((t,i)=>{self.setTimeout(()=>i(new Error("MediaKeySession.remove() timeout")),8e3),e.remove().then(t).catch(i)}):Promise.resolve();return o.catch(t=>{this.log(`Could not remove session: ${t}`),this.hls&&this.hls.trigger(ri.ERROR,{type:ii.OTHER_ERROR,details:ni.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${t}`)})}).then(()=>e.close()).catch(t=>{this.log(`Could not close session: ${t}`),this.hls&&this.hls.trigger(ri.ERROR,{type:ii.OTHER_ERROR,details:ni.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${t}`)})})}return Promise.resolve()}}function fh(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(null===t.keyId)throw new Error("keyId is null");return Ri(t.keyId)}function gh(t,e){return t.keyId&&e.mediaKeysSession.keyStatuses.has(t.keyId)?e.mediaKeysSession.keyStatuses.get(t.keyId):t.matches(e.decryptdata)?e.keyStatus:void 0}dh.CDMCleanupPromise=void 0;class ph 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}}function mh(t,e){const i="output-restricted"===t,n=i?ni.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:ni.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new ph({type:ii.KEY_SYSTEM_ERROR,details:n,fatal:!1,decryptdata:e},i?"HDCP level output restricted":`key status changed to "${t}"`)}function vh(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 yh(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){ki.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){ki.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${t}`)}}"disabled"===i&&(t.mode=i)}function Ah(t,e){const i=t.mode;if("disabled"===i&&(t.mode="hidden"),t.cues)for(let i=t.cues.length;i--;)e&&t.cues[i].removeEventListener("enter",e),t.removeCue(t.cues[i]);"disabled"===i&&(t.mode=i)}function Eh(t,e,i,n){const r=t.mode;if("disabled"===r&&(t.mode="hidden"),t.cues&&t.cues.length>0){const r=function(t,e,i){const n=[],r=function(t,e){if(e<=t[0].startTime)return 0;const i=t.length-1;if(e>t[i].endTime)return-1;let n,r=0,s=i;for(;r<=s;)if(n=Math.floor((s+r)/2),e<t[n].startTime)s=n-1;else{if(!(e>t[n].startTime&&r<i))return n;r=n+1}return t[r].startTime-e<e-t[s].startTime?r:s}(t,e);if(r>-1)for(let s=r,a=t.length;s<a;s++){const r=t[s];if(r.startTime>=e&&r.endTime<=i)n.push(r);else if(r.startTime>i)return n}return n}(t.cues,e,i);for(let e=0;e<r.length;e++)n&&!n(r[e])||t.removeCue(r[e])}"disabled"===r&&(t.mode=r)}function Th(t){const e=[];for(let i=0;i<t.length;i++){const n=t[i];"subtitles"!==n.kind&&"captions"!==n.kind||!n.label||e.push(t[i])}return e}function bh(t){let e=5381,i=t.length;for(;i;)e=33*e^t.charCodeAt(--i);return(e>>>0).toString()}const Sh=.025;let kh=function(t){return t[t.Point=0]="Point",t[t.Range=1]="Range",t}({});function _h(t,e,i){return`${t.identifier}-${i+1}-${bh(e)}`}class Lh{constructor(t,e){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=e,this.dateRange=t,this.setDateRange(t)}setDateRange(t){this.dateRange=t,this.resumeOffset=t.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=t.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=t.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=t.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var t;this.appendInPlaceStarted=!1,null==(t=this.assetListLoader)||t.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(t){var e;if(t>0&&t>=this.assetList.length)return!0;const i=this.playoutLimit;if(t<=0||isNaN(i))return!1;if(0===i)return!0;return((null==(e=this.assetList[t])?void 0:e.startOffset)||0)>i}findAssetIndex(t){return this.assetList.indexOf(t)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const t=this.dateRange.startTime;if(this.snapOptions.out){const e=this.dateRange.tagAnchor;if(e)return Ih(t,e)}return t}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(0===this.startTime||this.snapOptions.out)return!0;const t=this.dateRange.tagAnchor;if(t){const e=this.dateRange.startTime;return e-Ih(e,t)<.1}return!1}get resumptionOffset(){const t=this.resumeOffset,e=Je(t)?t:this.duration;return this.cumulativeDuration+e}get resumeTime(){const t=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const e=this.resumeAnchor;if(e)return Ih(t,e)}return t}get appendInPlace(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<Sh))}set appendInPlace(t){this.appendInPlaceStarted?this.resetOnResume=!t:this.appendInPlaceDisabled=!t}get timelineStart(){return null!==this._timelineStart?this._timelineStart:this.startTime}set timelineStart(t){this._timelineStart=t}get duration(){const t=this.playoutLimit;let e;return e=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(t)&&t<e&&(e=t),e}set duration(t){this._duration=t}get cue(){return this.dateRange.cue}get timelineOccupancy(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?kh.Range:kh.Point}get supplementsPrimary(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}get contentMayVary(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||null!==this.assetListResponse}toString(){return`["${(t=this).identifier}" ${t.cue.pre?"<pre>":t.cue.post?"<post>":""}${t.timelineStart.toFixed(2)}-${t.resumeTime.toFixed(2)}]`;var t}}function Ih(t,e){return t-e.start<e.duration/2&&!(Math.abs(t-(e.start+e.duration))<Sh)?e.start:e.start+e.duration}function Rh(t,e,i){const n=new self.URL(t,i);return"data:"!==n.protocol&&n.searchParams.set("_HLS_primary_id",e),n}function Ch(t,e){for(;null!=(i=t.assetList[++e])&&i.error;)var i;return e}function Ph(t){const e=t.timelineStart,i=t.duration||0;return`["${t.identifier}" ${e.toFixed(2)}-${(e+i).toFixed(2)}]`}class Dh{constructor(t,e,i,n){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(ri.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new t(e);this.interstitial=i,this.assetItem=n;const s=()=>{this.hasDetails=!0};r.once(ri.LEVEL_LOADED,s),r.once(ri.AUDIO_TRACK_LOADED,s),r.once(ri.SUBTITLE_TRACK_LOADED,s),r.on(ri.MEDIA_ATTACHING,(t,{media:e})=>{this.removeMediaListeners(),this.mediaAttached=e;this.interstitial.playoutLimit&&(e.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(ri.BUFFER_APPENDED,()=>{const t=this.bufferedEnd;this.reachedPlayout(t)&&(this._bufferedEosTime=t,r.trigger(ri.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const t=this.hls;if(t)if(t.url)t.levels.length&&!t.started&&t.startLoad(-1,!0);else{let e=this.assetItem.uri;try{e=Rh(e,t.config.primarySessionId||"").href}catch(t){}t.loadSource(e)}}bufferedInPlaceToEnd(t){var e;if(!this.appendInPlace)return!1;if(null!=(e=this.hls)&&e.bufferedToEnd)return!0;if(!t)return!1;const i=Math.min(this._bufferedEosTime||1/0,this.duration),n=this.timelineOffset,r=zr.bufferInfo(t,n,0);return this.getAssetTime(r.end)>=i-.02}reachedPlayout(t){const e=this.interstitial.playoutLimit;return this.startOffset+t>=e}get destroyed(){var t;return!(null!=(t=this.hls)&&t.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var t;return(null==(t=this.hls)?void 0:t.media)||null}get bufferedEnd(){const t=this.media||this.mediaAttached;if(!t)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const e=zr.bufferInfo(t,t.currentTime,.001);return this.getAssetTime(e.end)}get currentTime(){const t=this.media||this.mediaAttached;return t?this.getAssetTime(t.currentTime):this._currentTime||0}get duration(){const t=this.assetItem.duration;if(!t)return 0;const e=this.interstitial.playoutLimit;if(e){const i=e-this.startOffset;if(i>0&&i<t)return i}return t}get remaining(){const t=this.duration;return t?Math.max(0,t-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var t;return(null==(t=this.hls)?void 0:t.config.timelineOffset)||0}set timelineOffset(t){const e=this.timelineOffset;if(t!==e){const i=t-e;if(Math.abs(i)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=t}}}getAssetTime(t){const e=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,t-e),i)}removeMediaListeners(){const t=this.mediaAttached;t&&(this._currentTime=t.currentTime,this.bufferSnapShot(),t.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){var t;this.mediaAttached&&(null!=(t=this.hls)&&t.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd))}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(t){var e;this.loadSource(),null==(e=this.hls)||e.attachMedia(t)}detachMedia(){var t;this.removeMediaListeners(),this.mediaAttached=null,null==(t=this.hls)||t.detachMedia()}resumeBuffering(){var t;null==(t=this.hls)||t.resumeBuffering()}pauseBuffering(){var t;null==(t=this.hls)||t.pauseBuffering()}transferMedia(){var t;return this.bufferSnapShot(),(null==(t=this.hls)?void 0:t.transferMedia())||null}resetDetails(){const t=this.hls;if(t&&this.hasDetails){t.stopLoad();const e=t=>delete t.details;t.levels.forEach(e),t.allAudioTracks.forEach(e),t.allSubtitleTracks.forEach(e),this.hasDetails=!1}}on(t,e,i){var n;null==(n=this.hls)||n.on(t,e)}once(t,e,i){var n;null==(n=this.hls)||n.once(t,e)}off(t,e,i){var n;null==(n=this.hls)||n.off(t,e)}toString(){var t;return`HlsAssetPlayer: ${Ph(this.assetItem)} ${null==(t=this.hls)?void 0:t.sessionId} ${this.appendInPlace?"append-in-place":""}`}}class wh extends yi{constructor(t,e){super("interstitials-sched",e),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=t}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(t=>t.reset()),this.events=this.items=null}resetErrorsInRange(t,e){return this.events?this.events.reduce((i,n)=>t<=n.startOffset&&e>n.startOffset?(delete n.error,i+1):i,0):0}get duration(){const t=this.items;return t?t[t.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(t){return t&&this.eventMap[t]||null}hasEvent(t){return t in this.eventMap}findItemIndex(t,e){if(t.event)return this.findEventIndex(t.event.identifier);let i=-1;t.nextEvent?i=this.findEventIndex(t.nextEvent.identifier)-1:t.previousEvent&&(i=this.findEventIndex(t.previousEvent.identifier)+1);const n=this.items;if(n)for(n[i]||(void 0===e&&(e=t.start),i=this.findItemIndexAtTime(e));i>=0&&null!=(r=n[i])&&r.event;){var r;i--}return i}findItemIndexAtTime(t,e){const i=this.items;if(i)for(let n=0;n<i.length;n++){let r=i[n];if(e&&"primary"!==e&&(r=r[e]),t===r.start||t>r.start&&t<r.end)return n}return-1}findJumpRestrictedIndex(t,e){const i=this.items;if(i)for(let n=t;n<=e&&i[n];n++){const t=i[n].event;if(null!=t&&t.restrictions.jump&&!t.appendInPlace)return n}return-1}findEventIndex(t){const e=this.items;if(e)for(let n=e.length;n--;){var i;if((null==(i=e[n].event)?void 0:i.identifier)===t)return n}return-1}findAssetIndex(t,e){const i=t.assetList,n=i.length;if(n>1)for(let t=0;t<n;t++){const r=i[t];if(!r.error){const i=r.timelineStart;if(e===i||e>i&&(e<i+(r.duration||0)||t===n-1))return t}}return 0}get assetIdAtEnd(){var t;const e=null==(t=this.items)||null==(t=t[this.length-1])?void 0:t.event;if(e){const t=e.assetList,i=t[t.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(t,e){const i=t.main.details,{dateRanges:n}=i,r=this.events,s=this.parseDateRanges(n,{url:i.url},e),a=Object.keys(n),o=r?r.filter(t=>!a.includes(t.identifier)):[];s.length&&s.sort((t,e)=>{const i=t.cue.pre,n=t.cue.post,r=e.cue.pre,s=e.cue.post;if(i&&!r)return-1;if(r&&!i)return 1;if(n&&!s)return 1;if(s&&!n)return-1;if(!(i||r||n||s)){const i=t.startTime,n=e.startTime;if(i!==n)return i-n}return t.dateRange.tagOrder-e.dateRange.tagOrder}),this.events=s,o.forEach(t=>{this.removeEvent(t)}),this.updateSchedule(t,o)}updateSchedule(t,e=[],i=!1){const n=this.events||[];if(n.length||e.length||this.length<2){const r=this.items,s=this.parseSchedule(n,t);(i||e.length||(null==r?void 0:r.length)!==s.length||s.some((t,e)=>Math.abs(t.playout.start-r[e].playout.start)>.005||Math.abs(t.playout.end-r[e].playout.end)>.005))&&(this.items=s,this.onScheduleUpdate(e,r))}}parseDateRanges(t,e,i){const n=[],r=Object.keys(t);for(let s=0;s<r.length;s++){const a=r[s],o=t[a];if(o.isInterstitial){let t=this.eventMap[a];t?t.setDateRange(o):(t=new Lh(o,e),this.eventMap[a]=t,!1===i&&(t.appendInPlace=i)),n.push(t)}}return n}parseSchedule(t,e){const i=[],n=e.main.details,r=n.live?1/0:n.edge;let s=0;if((t=t.filter(t=>!(t.error||t.cue.once&&t.hasPlayed))).length){this.resolveOffsets(t,e);let n=0,o=0;if(t.forEach((e,a)=>{const l=e.cue.pre,h=e.cue.post,c=t[a-1]||null,u=e.appendInPlace,d=h?r:e.startOffset,f=e.duration,g=e.timelineOccupancy===kh.Range?f:0,p=e.resumptionOffset,m=(null==c?void 0:c.startTime)===d,v=d+e.cumulativeDuration;let y=u?v+f:d+p;if(l||!h&&d<=0){const t=o;o+=g,e.timelineStart=v;const n=s;s+=f,i.push({event:e,start:v,end:y,playout:{start:n,end:s},integrated:{start:t,end:o}})}else{if(!(d<=r))return;{if(!m){const r=d-n;if(r>.033){const l=n,h=o;o+=r;const c=s;s+=r;const u={previousEvent:t[a-1]||null,nextEvent:e,start:l,end:l+r,playout:{start:c,end:s},integrated:{start:h,end:o}};i.push(u)}else r>0&&c&&(c.cumulativeDuration+=r,i[i.length-1].end=d)}h&&(y=v),e.timelineStart=v;const r=o;o+=g;const l=s;s+=f,i.push({event:e,start:v,end:y,playout:{start:l,end:s},integrated:{start:r,end:o}})}}const A=e.resumeTime;n=h||A>r?r:A}),n<r){var a;const t=n,e=o,l=r-n;o+=l;const h=s;s+=l,i.push({previousEvent:(null==(a=i[i.length-1])?void 0:a.event)||null,nextEvent:null,start:n,end:t+l,playout:{start:h,end:s},integrated:{start:e,end:o}})}this.setDurations(r,s,o)}else{const t=0;i.push({previousEvent:null,nextEvent:null,start:t,end:r,playout:{start:t,end:r},integrated:{start:t,end:r}}),this.setDurations(r,r,r)}return i}setDurations(t,e,i){this.durations={primary:t,playout:e,integrated:i}}resolveOffsets(t,e){const i=e.main.details,n=i.live?1/0:i.edge;let r=0,s=-1;t.forEach((a,o)=>{const l=a.cue.pre,h=a.cue.post,c=l?0:h?n:a.startTime;this.updateAssetDurations(a);if(s===c?a.cumulativeDuration=r:(r=0,s=c),!h&&a.snapOptions.in&&(a.resumeAnchor=sr(null,i.fragments,a.startOffset+a.resumptionOffset,0,0)||void 0),a.appendInPlace&&!a.appendInPlaceStarted){this.primaryCanResumeInPlaceAt(a,e)||(a.appendInPlace=!1)}if(!a.appendInPlace&&o+1<t.length){t[o+1].startTime-t[o].resumeTime<.033&&(t[o+1].appendInPlace=!1,t[o+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${a}`))}const u=Je(a.resumeOffset)?a.resumeOffset:a.duration;r+=u})}primaryCanResumeInPlaceAt(t,e){const i=t.resumeTime,n=t.startTime+t.resumptionOffset;if(Math.abs(i-n)>Sh)return this.log(`"${t.identifier}" resumption ${i} not aligned with estimated timeline end ${n}`),!1;return!Object.keys(e).some(n=>{const r=e[n].details,s=r.edge;if(i>=s)return this.log(`"${t.identifier}" resumption ${i} past ${n} playlist end ${s}`),!1;const a=sr(null,r.fragments,i);if(!a)return this.log(`"${t.identifier}" resumption ${i} does not align with any fragments in ${n} playlist (${r.fragStart}-${r.fragmentEnd})`),!0;const o="audio"===n?.175:0;return!(Math.abs(a.start-i)<Sh+o||Math.abs(a.end-i)<Sh+o)&&(this.log(`"${t.identifier}" resumption ${i} not aligned with ${n} fragment bounds (${a.start}-${a.end} sn: ${a.sn} cc: ${a.cc})`),!0)})}updateAssetDurations(t){if(!t.assetListLoaded)return;const e=t.timelineStart;let i=0,n=!1,r=!1;for(let s=0;s<t.assetList.length;s++){const a=t.assetList[s],o=e+i;a.startOffset=i,a.timelineStart=o,n||(n=null===a.duration),r||(r=!!a.error);i+=a.error?0:a.duration||0}t.duration=n&&!r?Math.max(i,t.duration):i}removeEvent(t){t.reset(),delete this.eventMap[t.identifier]}}function Oh(t){return`[${t.event?'"'+t.event.identifier+'"':"primary"}: ${t.start.toFixed(2)}-${t.end.toFixed(2)}]`}class xh{constructor(t){this.hls=void 0,this.hls=t}destroy(){this.hls=null}loadAssetList(t,e){const i=t.assetListUrl;let n;try{n=Rh(i,this.hls.sessionId,t.baseUrl)}catch(e){const n=this.assignAssetListError(t,ni.ASSET_LIST_LOAD_ERROR,e,i);return void this.hls.trigger(ri.ERROR,n)}e&&"data:"!==n.protocol&&n.searchParams.set("_HLS_start_offset",""+e);const r=this.hls.config,s=new(0,r.loader)(r),a={responseType:"json",url:n.href},o=r.interstitialAssetListLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(e,i,n,r)=>{const s=e.data,a=null==s?void 0:s.ASSETS;if(!Array.isArray(a)){const e=this.assignAssetListError(t,ni.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),n.url,i,r);return void this.hls.trigger(ri.ERROR,e)}t.assetListResponse=s,this.hls.trigger(ri.ASSET_LIST_LOADED,{event:t,assetListResponse:s,networkDetails:r})},onError:(e,i,n,r)=>{const s=this.assignAssetListError(t,ni.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${e.code} ${e.text} (${i.url})`),i.url,r,n);this.hls.trigger(ri.ERROR,s)},onTimeout:(e,i,n)=>{const r=this.assignAssetListError(t,ni.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${i.url})`),i.url,e,n);this.hls.trigger(ri.ERROR,r)}};return s.load(a,l,h),this.hls.trigger(ri.ASSET_LIST_LOADING,{event:t}),s}assignAssetListError(t,e,i,n,r,s){return t.error=i,{type:ii.NETWORK_ERROR,details:e,fatal:!1,interstitial:t,url:n,error:i,networkDetails:s,stats:r}}}function Mh(t){var e;null==t||null==(e=t.play())||e.catch(()=>{})}function Nh(t,e){return`[${t}] Advancing timeline position to ${e}`}class Fh{constructor(t){this.buffered=void 0;const e=(e,i,n)=>{if((i>>>=0)>n-1)throw new DOMException(`Failed to execute '${e}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${n})`);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)}}}const Bh={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},Uh=t=>String.fromCharCode(Bh[t]||t),$h=15,Gh=100,Vh={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Kh={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Hh={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Yh={25:2,26:4,29:6,30:8,31:10,27:13,28:15},jh=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Wh{constructor(){this.time=null,this.verboseLevel=0}log(t,e){if(this.verboseLevel>=t){const i="function"==typeof e?e():e;ki.log(`${this.time} [${t}] ${i}`)}}}const zh=function(t){const e=[];for(let i=0;i<t.length;i++)e.push(t[i].toString(16));return e};class qh{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 n=e[i];t.hasOwnProperty(n)&&(this[n]=t[n])}}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 Xh{constructor(){this.uchar=" ",this.penState=new qh}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 Qh{constructor(t){this.chars=[],this.pos=0,this.currPenState=new qh,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Gh;t++)this.chars.push(new Xh);this.logger=t}equals(t){for(let e=0;e<Gh;e++)if(!this.chars[e].equals(t.chars[e]))return!1;return!0}copy(t){for(let e=0;e<Gh;e++)this.chars[e].copy(t.chars[e])}isEmpty(){let t=!0;for(let e=0;e<Gh;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>Gh&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Gh)}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=Uh(t);this.pos>=Gh?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<Gh;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<Gh;i++){const n=this.chars[i].uchar;" "!==n&&(e=!1),t.push(n)}return e?"":t.join("")}setPenStyles(t){this.currPenState.setStyles(t);this.chars[this.pos].setPenState(this.currPenState)}}class Zh{constructor(t){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let e=0;e<$h;e++)this.rows.push(new Qh(t));this.logger=t}reset(){for(let t=0;t<$h;t++)this.rows[t].clear();this.currRow=14}equals(t){let e=!0;for(let i=0;i<$h;i++)if(!this.rows[i].equals(t.rows[i])){e=!1;break}return e}copy(t){for(let e=0;e<$h;e++)this.rows[e].copy(t.rows[e])}isEmpty(){let t=!0;for(let e=0;e<$h;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 = "+qn(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<$h;t++)this.rows[t].clear();const t=this.currRow+1-this.nrRollUpRows,i=this.lastOutputScreen;if(i){const n=i.rows[t].cueStartTime,r=this.logger.time;if(null!==n&&null!==r&&n<r)for(let n=0;n<this.nrRollUpRows;n++)this.rows[e-this.nrRollUpRows+n+1].copy(i.rows[t+n])}}this.currRow=e;const i=this.rows[this.currRow];if(null!==t.indent){const e=t.indent,n=Math.max(e-1,0);i.setCursor(t.indent),t.color=i.chars[n].penState.foreground}const n={foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:!1};this.setPen(n)}setBkgData(t){this.logger.log(2,()=>"bkgData = "+qn(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="",n=-1;for(let i=0;i<$h;i++){const r=this.rows[i].getTextString();r&&(n=i+1,t?e.push("Row "+n+": '"+r+"'"):e.push(r.trim()))}return e.length>0&&(i=t?"["+e.join(" | ")+"]":e.join("\n")),i}getTextAndFormat(){return this.rows}}class Jh{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 Zh(i),this.nonDisplayedMemory=new Zh(i),this.lastOutputScreen=new Zh(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,n=["white","green","blue","cyan","red","yellow","magenta"];e.foreground=n[i]}this.logger.log(2,"MIDROW: "+qn(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 tc{constructor(t,e,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const n=this.logger=new Wh;this.channels=[null,new Jh(t,e,n),new Jh(t+1,i,n)]}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],n=127&e[t+1];let r=!1,s=null;if(0===i&&0===n)continue;this.logger.log(3,()=>"["+zh([e[t],e[t+1]])+"] -> ("+zh([i,n])+")");const a=this.cmdHistory;if(i>=16&&i<=31){if(ic(i,n,a)){ec(null,null,a),this.logger.log(3,()=>"Repeated command ("+zh([i,n])+") is dropped");continue}ec(i,n,this.cmdHistory),r=this.parseCmd(i,n),r||(r=this.parseMidrow(i,n)),r||(r=this.parsePAC(i,n)),r||(r=this.parseBackgroundAttributes(i,n))}else ec(null,null,a);if(!r&&(s=this.parseChars(i,n),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?")}r||s||this.logger.log(2,()=>"Couldn't parse cleaned data "+zh([i,n])+" orig: "+zh([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,n=this.channels[i];return 20===t||21===t||28===t||29===t?32===e?n.ccRCL():33===e?n.ccBS():34===e?n.ccAOF():35===e?n.ccAON():36===e?n.ccDER():37===e?n.ccRU(2):38===e?n.ccRU(3):39===e?n.ccRU(4):40===e?n.ccFON():41===e?n.ccRDC():42===e?n.ccTR():43===e?n.ccRTD():44===e?n.ccEDM():45===e?n.ccCR():46===e?n.ccENM():47===e&&n.ccEOC():n.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 n=this.channels[i];return!!n&&(n.ccMIDROW(e),this.logger.log(3,()=>"MIDROW ("+zh([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 n=t<=23?1:2;i=e>=64&&e<=95?1===n?Vh[t]:Hh[t]:1===n?Kh[t]:Yh[t];const r=this.channels[n];return!!r&&(r.setPAC(this.interpretPAC(i,e)),this.currentChannel=n,!0)}interpretPAC(t,e){let i;const n={color:null,italics:!1,indent:null,underline:!1,row:t};return i=e>95?e-96:e-64,n.underline=!(1&~i),i<=13?n.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(n.italics=!0,n.color="white"):n.indent=4*Math.floor((i-16)/2),n}parseChars(t,e){let i,n=null,r=null;if(t>=25?(i=2,r=t-8):(i=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 '"+Uh(t)+"' in channel "+i),n=[t]}else t>=32&&t<=127&&(n=0===e?[t]:[t,e]);return n&&this.logger.log(3,()=>"Char codes = "+zh(n).join(",")),n}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 n={};16===t||24===t?(i=Math.floor((e-32)/2),n.background=jh[i],e%2==1&&(n.background=n.background+"_semi")):45===e?n.background="transparent":(n.foreground="black",47===e&&(n.underline=!0));const r=t<=23?1:2;return this.channels[r].setBkgData(n),!0}reset(){for(let t=0;t<Object.keys(this.channels).length;t++){const e=this.channels[t];e&&e.reset()}ec(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 ec(t,e,i){i.a=t,i.b=e}function ic(t,e,i){return i.a===t&&i.b===e}var nc=function(){if(null!=ps&&ps.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 n(t){return i(e,t)}function r(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 h="",c=!1,u=e,d=s,f=a,g=null,p="",m=!0,v="auto",y="start",A=50,E="middle",T=50,b="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 c},set:function(t){c=!!t}})),Object.defineProperty(o,"startTime",r({},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",r({},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",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 p},set:function(e){const n=function(e){return i(t,e)}(e);if(!1===n)throw new SyntaxError("An invalid or illegal string was specified.");p=n,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",r({},l,{get:function(){return m},set:function(t){m=!!t,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",r({},l,{get:function(){return v},set:function(t){if("number"!=typeof t&&"auto"!==t)throw new SyntaxError("An invalid number or illegal string was specified.");v=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",r({},l,{get:function(){return y},set:function(t){const e=n(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");y=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",r({},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",r({},l,{get:function(){return E},set:function(t){const e=n(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 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",r({},l,{get:function(){return b},set:function(t){const e=n(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");b=e,this.hasBeenReset=!0}})),o.displayState=void 0}return s.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},s}();class rc{decode(t,e){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function sc(t){function e(t,e,i,n){return 3600*(0|t)+60*(0|e)+(0|i)+parseFloat(n||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 ac{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 n=0;n<i.length;++n)if(e===i[n]){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 oc(t,e,i,n){const r=n?t.split(n):[t];for(const t in r){if("string"!=typeof r[t])continue;const n=r[t].split(i);if(2!==n.length)continue;e(n[0],n[1])}}const lc=new nc(0,0,""),hc="middle"===lc.align?"middle":"center";function cc(t,e,i){const n=t;function r(){const e=sc(t);if(null===e)throw new Error("Malformed timestamp: "+n);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function s(){t=t.replace(/^\s+/,"")}if(s(),e.startTime=r(),s(),"--\x3e"!==t.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+n);t=t.slice(3),s(),e.endTime=r(),s(),function(t,e){const n=new ac;oc(t,function(t,e){let r;switch(t){case"region":for(let r=i.length-1;r>=0;r--)if(i[r].id===e){n.set(t,i[r].region);break}break;case"vertical":n.alt(t,e,["rl","lr"]);break;case"line":r=e.split(","),n.integer(t,r[0]),n.percent(t,r[0])&&n.set("snapToLines",!1),n.alt(t,r[0],["auto"]),2===r.length&&n.alt("lineAlign",r[1],["start",hc,"end"]);break;case"position":r=e.split(","),n.percent(t,r[0]),2===r.length&&n.alt("positionAlign",r[1],["start",hc,"end","line-left","line-right","auto"]);break;case"size":n.percent(t,e);break;case"align":n.alt(t,e,["start",hc,"end","left","right"])}},/:/,/\s/),e.region=n.get("region",null),e.vertical=n.get("vertical","");let r=n.get("line","auto");"auto"===r&&-1===lc.line&&(r=-1),e.line=r,e.lineAlign=n.get("lineAlign","start"),e.snapToLines=n.get("snapToLines",!0),e.size=n.get("size",100),e.align=n.get("align",hc);let s=n.get("position","auto");"auto"===s&&50===lc.position&&(s="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=s}(t,e)}function uc(t){return t.replace(/<br(?: \/)?>/gi,"\n")}class dc{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new rc,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=uc(t);i<t.length&&"\r"!==t[i]&&"\n"!==t[i];)++i;const n=t.slice(0,i);return"\r"===t[i]&&++i,"\n"===t[i]&&++i,e.buffer=t.slice(i),n}function n(t){oc(t,function(t,e){},/:/)}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 n=t.match(/^()?WEBVTT([ \t].*)?$/);if(null==n||!n[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)?n(t):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 nc(0,0,""),e.state="CUE",-1===t.indexOf("--\x3e")){e.cue.id=t;continue}case"CUE":if(!e.cue){e.state="BADCUE";continue}try{cc(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 fc=/\r\n|\n\r|\n|\r/g,gc=function(t,e,i=0){return t.slice(i,i+e.length)===e};function pc(t,e,i){return bh(t.toString())+bh(e.toString())+bh(i)}function mc(t,e,i,n,r,s,a){const o=new dc,l=Ii(new Uint8Array(t)).trim().replace(fc,"\n").split("\n"),h=[],c=e?function(t,e=1){return Bo(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[n];let a=i.ccOffset;const o=(f-c)/9e4;if(null!=s&&s.new&&(void 0!==g?a=i.ccOffset=s.start:function(t,e,i){let n=t[e],r=t[n.prevCC];if(!r||!r.new&&n.new)return t.ccOffset=t.presentationOffset=n.start,void(n.new=!1);for(;null!=(s=r)&&s.new;){var s;t.ccOffset+=n.start-r.start,n.new=!1,n=r,r=t[n.prevCC]}t.presentationOffset=i}(i,n,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=Wo(9e4*(t.startTime+a-g),9e4*r)/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=pc(t.startTime,t.endTime,p)),t.endTime>0&&h.push(t)},o.onparsingerror=function(t){u=t},o.onflush=function(){u?a(u):s(h)},l.forEach(t=>{if(p){if(gc(t,"X-TIMESTAMP-MAP=")){p=!1,t.slice(16).split(",").forEach(t=>{gc(t,"LOCAL:")?d=t.slice(6):gc(t,"MPEGTS:")&&(f=parseInt(t.slice(7)))});try{g=function(t){let e=parseInt(t.slice(-3));const i=parseInt(t.slice(-6,-4)),n=parseInt(t.slice(-9,-7)),r=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!(Je(e)&&Je(i)&&Je(n)&&Je(r)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return e+=1e3*i,e+=6e4*n,e+=36e5*r,e}(d)/1e3}catch(t){u=t}return}""===t&&(p=!1)}o.parse(t+"\n")}),o.flush()}const vc="stpp.ttml.im1t",yc=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Ac=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Ec={left:"start",center:"center",right:"end",start:"start",end:"end"};function Tc(t,e,i,n){const r=Qi(new Uint8Array(t),["mdat"]);if(0===r.length)return void n(new Error("Could not parse IMSC1 mdat"));const s=r.map(t=>Ii(t)),a=function(t,e,i=1,n=!1){return Bo(t,e,1/i,n)}(e.baseTime,1,e.timescale);try{s.forEach(t=>i(function(t,e){const i=(new DOMParser).parseFromString(t,"text/xml"),n=i.getElementsByTagName("tt")[0];if(!n)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},s=Object.keys(r).reduce((t,e)=>(t[e]=n.getAttribute(`ttp:${e}`)||r[e],t),{}),a="preserve"!==n.getAttribute("xml:space"),o=Sc(bc(n,"styling","style")),l=Sc(bc(n,"layout","region")),h=bc(n,"body","[begin]");return[].map.call(h,t=>{const i=kc(t,a);if(!i||!t.hasAttribute("begin"))return null;const n=Ic(t.getAttribute("begin"),s),r=Ic(t.getAttribute("dur"),s);let h=Ic(t.getAttribute("end"),s);if(null===n)throw Lc(t);if(null===h){if(null===r)throw Lc(t);h=n+r}const c=new nc(n-e,h-e,i);c.id=pc(c.startTime,c.endTime,c.text);const u=function(t,e,i){const n="http://www.w3.org/ns/ttml#styling";let r=null;const s=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;a&&i.hasOwnProperty(a)&&(r=i[a]);return s.reduce((i,s)=>{const a=_c(e,n,s)||_c(t,n,s)||_c(r,n,s);return a&&(i[s]=a),i},{})}(l[t.getAttribute("region")],o[t.getAttribute("style")],o),{textAlign:d}=u;if(d){const t=Ec[d];t&&(c.lineAlign=t),c.align=d}return pi(c,u),c}).filter(t=>null!==t)}(t,a)))}catch(t){n(t)}}function bc(t,e,i){const n=t.getElementsByTagName(e)[0];return n?[].slice.call(n.querySelectorAll(i)):[]}function Sc(t){return t.reduce((t,e)=>{const i=e.getAttribute("xml:id");return i&&(t[i]=e),t},{})}function kc(t,e){return[].slice.call(t.childNodes).reduce((t,i,n)=>{var r;return"br"===i.nodeName&&n?t+"\n":null!=(r=i.childNodes)&&r.length?kc(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function _c(t,e,i){return t&&t.hasAttributeNS(e,i)?t.getAttributeNS(e,i):null}function Lc(t){return new Error(`Could not parse ttml timestamp ${t}`)}function Ic(t,e){if(!t)return null;let i=sc(t);return null===i&&(yc.test(t)?i=function(t,e){const i=yc.exec(t),n=(0|i[4])+(0|i[5])/e.subFrameRate;return 3600*(0|i[1])+60*(0|i[2])+(0|i[3])+n/e.frameRate}(t,e):Ac.test(t)&&(i=function(t,e){const i=Ac.exec(t),n=Number(i[1]);switch(i[2]){case"h":return 3600*n;case"m":return 60*n;case"ms":return 1e3*n;case"f":return n/e.frameRate;case"t":return n/e.tickRate}return n}(t,e))),i}class Rc{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}}function Cc(t){return t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles"}function Pc(t,e){return!!t&&t.kind===Cc(e)&&hl(e,t)}function Dc(t,e,i,n){return Math.min(e,n)-Math.max(t,i)}const wc=/\s/,Oc={newCue(t,e,i,n){const r=[];let s,a,o,l,h;const c=self.VTTCue||self.TextTrackCue;for(let d=0;d<n.rows.length;d++)if(s=n.rows[d],o=!0,l=0,h="",!s.isEmpty()){var u;for(let t=0;t<s.chars.length;t++)wc.test(s.chars[t].uchar)&&o?l++:(h+=s.chars[t].uchar,o=!1);s.cueStartTime=e,e===i&&(i+=1e-4),l>=16?l--:l++;const n=uc(h.trim()),f=pc(e,i,n);null!=t&&null!=(u=t.cues)&&u.getCueById(f)||(a=new c(e,i,n),a.id=f,a.line=d+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=>yh(t,e))),r}};const xc=/(\d+)-(\d+)\/(\d+)/;class Mc{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||Nc,this.controller=new self.AbortController,this.stats=new xi}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 n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now();const r=function(t,e){const i={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(pi({},t.headers))};t.rangeEnd&&i.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1));return i}(t,this.controller.signal),s="arraybuffer"===t.responseType,a=s?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=e.loadPolicy;this.context=t,this.config=e,this.callbacks=i,this.request=this.fetchSetup(t,r),self.clearTimeout(this.requestTimeout),e.timeout=o&&Je(o)?o:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,t,this.response))},e.timeout);(el(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(i=>{var r;this.response=this.loader=i;const a=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,t,this.response))},l-(a-n.loading.start)),!i.ok){const{status:t,statusText:e}=i;throw new Fc(e||"fetch, bad network response",t,i)}n.loading.first=a,n.total=function(t){const e=t.get("Content-Range");if(e){const t=function(t){const e=xc.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}(e);if(Je(t))return t}const i=t.get("Content-Length");if(i)return parseInt(i)}(i.headers)||n.total;const o=null==(r=this.callbacks)?void 0:r.onProgress;return o&&Je(e.highWaterMark)?this.loadProgressively(i,n,t,e.highWaterMark,o):s?i.arrayBuffer():"json"===t.responseType?i.json():i.text()}).then(i=>{var r,s;const o=this.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);const l=i[a];l&&(n.loaded=n.total=l);const h={url:o.url,data:i,code:o.status},c=null==(r=this.callbacks)?void 0:r.onProgress;c&&!Je(e.highWaterMark)&&c(n,t,i,o),null==(s=this.callbacks)||s.onSuccess(h,n,t,o)}).catch(e=>{var i;if(self.clearTimeout(this.requestTimeout),n.aborted)return;const r=e&&e.code||0,s=e?e.message:null;null==(i=this.callbacks)||i.onError({code:r,text:s},t,e?e.details:null,n)})}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,n=0,r){const s=new Ra,a=t.body.getReader(),o=()=>a.read().then(a=>{if(a.done)return s.dataLength&&r(e,i,s.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));const l=a.value,h=l.length;return e.loaded+=h,h<n||s.dataLength?(s.push(l),s.dataLength>=n&&r(e,i,s.flush().buffer,t)):r(e,i,l.buffer,t),o()}).catch(()=>Promise.reject());return o()}}function Nc(t,e){return new self.Request(t.url,e)}class Fc extends Error{constructor(t,e,i){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=i}}const Bc=/^age:\s*[\d.]+\s*$/im;class Uc{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 xi,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,n=this.stats;n.loading.first=0,n.loaded=0,n.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(this.loader===i&&!this.stats.aborted)return r(i,e.url)}).catch(t=>{if(this.loader===i&&!this.stats.aborted)return i.open("GET",e.url,!0),r(i,e.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,e,t)}).catch(t=>{var r;null==(r=this.callbacks)||r.onError({code:i.status,text:t.message},e,i,n)}):this.openAndSendXhr(i,e,t)}openAndSendXhr(t,e,i){t.readyState||t.open("GET",e.url,!0);const n=e.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:s}=i.loadPolicy;if(n)for(const e in n)t.setRequestHeader(e,n[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=r&&Je(r)?r: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 n=e.readyState,r=this.config;if(!i.aborted&&n>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.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-(i.loading.first-i.loading.start)))),4===n)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;const n=e.status,l="text"===e.responseType?e.responseText:null;if(n>=200&&n<300){const r=null!=l?l:e.response;if(null!=r){var s,a;i.loading.end=Math.max(self.performance.now(),i.loading.first);const o="arraybuffer"===e.responseType?r.byteLength:r.length;i.loaded=i.total=o,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first);const l=null==(s=this.callbacks)?void 0:s.onProgress;l&&l(i,t,r,e);const h={url:e.responseURL,data:r,code:n};return void(null==(a=this.callbacks)||a.onSuccess(h,i,t,e))}}const h=r.loadPolicy.errorRetry;var o;if(pr(h,i.retry,!1,{url:t.url,data:void 0,code:n}))this.retry(h);else ki.error(`${n} while loading ${t.url}`),null==(o=this.callbacks)||o.onError({code:n,text:e.statusText},t,e,i)}}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry;if(pr(t,this.stats.retry,!0))this.retry(t);else{var e;ki.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=fr(t,i.retry),i.retry++,ki.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&&Bc.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 $c=vi(vi({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:Uc,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class extends yi{constructor(t){super("abr",t.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var e;const{fragCurrent:i,partCurrent:n,hls:r}=this,{autoLevelEnabled:s,media:a}=r;if(!i||!a)return;const o=performance.now(),l=n?n.stats:i.stats,h=n?n.duration:i.duration,c=o-l.loading.start,u=r.minAutoLevel,d=i.level,f=this._nextAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||d<=u)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!s)return;const g=f>-1&&f!==d,p=!!t||g;if(!p&&(a.paused||!a.playbackRate||!a.readyState))return;const m=r.mainForwardBufferInfo;if(!p&&null===m)return;const v=this.bwEstimator.getEstimateTTFB(),y=Math.abs(a.playbackRate);if(c<=Math.max(v,h/(2*y)*1e3))return;const A=m?m.len/y:0,E=l.loading.first?l.loading.first-l.loading.start:-1,T=l.loaded&&E>-1,b=this.getBwEstimate(),S=r.levels,k=S[d],_=Math.max(l.loaded,Math.round(h*(i.bitrate||k.averageBitrate)/8));let L=T?c-E:c;L<1&&T&&(L=Math.min(c,8*l.loaded/b));const I=T?1e3*l.loaded/L:0,R=v/1e3,C=I?(_-l.loaded)/I:8*_/b+R;if(C<=A)return;const P=I?8*I:b,D=!0===(null==(e=(null==t?void 0:t.details)||this.hls.latestLevelDetails)?void 0:e.live),w=this.hls.config.abrBandWidthUpFactor;let O,x=Number.POSITIVE_INFINITY;for(O=d-1;O>u;O--){const t=S[O].maxBitrate,e=!S[O].details||D;if(x=this.getTimeToLoadFrag(R,P,h*t,e),x<Math.min(A,h+R))break}if(x>=C)return;if(x>10*h)return;T?this.bwEstimator.sample(c-Math.min(v,E),l.loaded):this.bwEstimator.sampleTTFB(c);const M=S[O].maxBitrate;this.getBwEstimate()*w>M&&this.resetEstimator(M);const N=this.findBestLevel(M,u,O,0,A,1,1);N>-1&&(O=N),this.warn(`Fragment ${i.sn}${n?" part "+n.index:""} of level ${d} is loading too slowly;\n Fragment duration: ${i.duration.toFixed(3)}\n Time to underbuffer: ${A.toFixed(3)} s\n Estimated load time for current fragment: ${C.toFixed(3)} s\n Estimated load time for down switch fragment: ${x.toFixed(3)} s\n TTFB estimate: ${0|E} ms\n Current BW estimate: ${Je(b)?0|b:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${O} @ ${0|M} bps`),r.nextLoadLevel=r.nextAutoLevel=O,this.clearTimer();const F=()=>{if(this.clearTimer(),this.fragCurrent===i&&this.hls.loadLevel===O&&O>0){const t=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${O>0?"and switching down":""}\n Fragment duration: ${i.duration.toFixed(3)} s\n Time to underbuffer: ${t.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,O>u){let e=this.findBestLevel(this.hls.levels[u].bitrate,u,O,0,t,1,1);-1===e&&(e=u),this.hls.nextLoadLevel=this.hls.nextAutoLevel=e,this.resetEstimator(this.hls.levels[e].bitrate)}}};g||C>2*x?F():this.timer=self.setInterval(F,1e3*x),r.trigger(ri.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:n,stats:l})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){t&&(this.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 fi(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(ri.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ri.FRAG_LOADING,this.onFragLoading,this),t.on(ri.FRAG_LOADED,this.onFragLoaded,this),t.on(ri.FRAG_BUFFERED,this.onFragBuffered,this),t.on(ri.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(ri.LEVEL_LOADED,this.onLevelLoaded,this),t.on(ri.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(ri.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(ri.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(ri.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ri.FRAG_LOADING,this.onFragLoading,this),t.off(ri.FRAG_LOADED,this.onFragLoaded,this),t.off(ri.FRAG_BUFFERED,this.onFragBuffered,this),t.off(ri.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(ri.LEVEL_LOADED,this.onLevelLoaded,this),t.off(ri.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(ri.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(ri.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(t,e){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(t,e){const i=e.frag;if(!this.ignoreFragment(i)){var n;if(!i.bitrateTest)this.fragCurrent=i,this.partCurrent=null!=(n=e.part)?n: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 ni.BUFFER_ADD_CODEC_ERROR:case ni.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case ni.FRAG_LOAD_TIMEOUT:{const t=e.frag,{fragCurrent:i,partCurrent:n}=this;if(t&&i&&t.sn===i.sn&&t.level===i.level){const e=performance.now(),i=n?n.stats:t.stats,r=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(r-Math.min(t,s),i.loaded)}else this.bwEstimator.sampleTTFB(r)}break}}}getTimeToLoadFrag(t,e,i,n){return t+i/e+(n?t+this.lastLevelLoadSec:0)}onLevelLoaded(t,e){const i=this.hls.config,{loading:n}=e.stats,r=n.end-n.first;Je(r)&&(this.lastLevelLoadSec=r/1e3),e.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(e.levelInfo)}onFragLoaded(t,{frag:e,part:i}){const n=i?i.stats:e.stats;if(e.type===hi&&this.bwEstimator.sampleTTFB(n.loading.first-n.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,r=this.hls.levels[e.level],s=(r.loaded?r.loaded.bytes:0)+n.loaded,a=(r.loaded?r.loaded.duration:0)+t;r.loaded={bytes:s,duration:a},r.realBitrate=Math.round(8*s/a)}if(e.bitrateTest){const t={stats:n,frag:e,part:i,id:e.type};this.onFragBuffered(ri.FRAG_BUFFERED,t),e.bitrateTest=!1}else this.lastLoadedFragLevel=e.level}}onFragBuffered(t,e){const{frag:i,part:n}=e,r=null!=n&&n.stats.loaded?n.stats:i.stats;if(r.aborted)return;if(this.ignoreFragment(i))return;const s=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(s,r.loaded),r.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=s/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==hi||"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(),n=this.hls.config.maxStarvationDelay,r=this.findBestLevel(i,e,t,0,n,1,1);if(r>-1)return r;const s=this.hls.firstLevel,a=Math.min(Math.max(s,e),t);return this.warn(`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 n=e&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==t){const e=this.hls.levels;if(e.length>Math.max(t,n)&&e[t].loadError<=e[n].loadError)return t}return this._nextAutoLevel=n,this.nextAutoLevelKey=this.getAutoLevelKey(),n}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;const{maxAutoLevel:n,config:r,minAutoLevel:s}=i,a=e?e.duration:t?t.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let h=r.abrBandWidthFactor,c=r.abrBandWidthUpFactor;if(l){const t=this.findBestLevel(o,s,n,l,0,h,c);if(t>=0)return this.rebufferNotice=-1,t}let u=a?Math.min(a,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const t=this.bitrateTestDelay;if(t){u=(a?Math.min(a,r.maxLoadingDelay):r.maxLoadingDelay)-t,this.info(`bitrate test took ${Math.round(1e3*t)}ms, set first fragment max fetchDuration to ${Math.round(1e3*u)} ms`),h=c=1}}const d=this.findBestLevel(o,s,n,l,u,h,c);if(this.rebufferNotice!==d&&(this.rebufferNotice=d,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${d}`)),d>-1)return d;const f=i.levels[s],g=i.loadLevelObj;return g&&(null==f?void 0:f.bitrate)<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,n=t.mainForwardBufferInfo;return(n?n.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(t,e,i,n,r,s,a){var o;const l=n+r,h=this.lastLoadedFragLevel,c=-1===h?this.hls.firstLevel:h,{fragCurrent:u,partCurrent:d}=this,{levels:f,allAudioTracks:g,loadLevel:p,config:m}=this.hls;if(1===f.length)return 0;const v=f[c],y=!(null==(o=this.hls.latestLevelDetails)||!o.live),A=-1===p||-1===h;let E,T="SDR",b=(null==v?void 0:v.frameRate)||0;const{audioPreference:S,videoPreference:k}=m,_=this.audioTracksByGroup||(this.audioTracksByGroup=Qn(g));let L=-1;if(A){if(-1!==this.firstSelection)return this.firstSelection;const n=this.codecTiers||(this.codecTiers=function(t,e,i,n){return t.slice(i,n+1).reduce((t,i,n)=>{if(!i.codecSet)return t;const r=i.audioGroups;let s=t[i.codecSet];s||(t[i.codecSet]=s={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:n,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!r,fragmentError:0}),s.minBitrate=Math.min(s.minBitrate,i.bitrate);const a=Math.min(i.height,i.width);return s.minHeight=Math.min(s.minHeight,a),s.minFramerate=Math.min(s.minFramerate,i.frameRate),s.minIndex=Math.min(s.minIndex,n),s.maxScore=Math.max(s.maxScore,i.score),s.fragmentError+=i.fragmentError,s.videoRanges[i.videoRange]=(s.videoRanges[i.videoRange]||0)+1,r&&r.forEach(t=>{if(!t)return;const i=e.groups[t];i&&(s.hasDefaultAudio=s.hasDefaultAudio||e.hasDefaultAudio?i.hasDefault:i.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(i.channels).forEach(t=>{s.channels[t]=(s.channels[t]||0)+i.channels[t]}))}),t},{})}(f,_,e,i)),r=function(t,e,i,n,r){const s=Object.keys(t),a=null==n?void 0:n.channels,o=null==n?void 0:n.audioCodec,l=null==r?void 0:r.videoCodec,h=a&&2===parseInt(a);let c=!1,u=!1,d=1/0,f=1/0,g=1/0,p=1/0,m=0,v=[];const{preferHDR:y,allowedVideoRanges:A}=zn(e,r);for(let e=s.length;e--;){const i=t[s[e]];c||(c=i.channels[2]>0),d=Math.min(d,i.minHeight),f=Math.min(f,i.minFramerate),g=Math.min(g,i.minBitrate),A.filter(t=>i.videoRanges[t]>0).length>0&&(u=!0)}d=Je(d)?d:0,f=Je(f)?f:0;const E=Math.max(1080,d),T=Math.max(30,f);g=Je(g)?g:i,i=Math.max(g,i),u||(e=void 0);const b=s.length>1;return{codecSet:s.reduce((e,n)=>{const r=t[n];if(n===e)return e;if(v=u?A.filter(t=>r.videoRanges[t]>0):[],b){if(r.minBitrate>i)return Xn(n,`min bitrate of ${r.minBitrate} > current estimate of ${i}`),e;if(!r.hasDefaultAudio)return Xn(n,"no renditions with default or auto-select sound found"),e;if(o&&n.indexOf(o.substring(0,4))%5!=0)return Xn(n,`audio codec preference "${o}" not found`),e;if(a&&!h){if(!r.channels[a])return Xn(n,`no renditions with ${a} channel sound found (channels options: ${Object.keys(r.channels)})`),e}else if((!o||h)&&c&&0===r.channels[2])return Xn(n,"no renditions with stereo sound found"),e;if(r.minHeight>E)return Xn(n,`min resolution of ${r.minHeight} > maximum of ${E}`),e;if(r.minFramerate>T)return Xn(n,`min framerate of ${r.minFramerate} > maximum of ${T}`),e;if(!v.some(t=>r.videoRanges[t]>0))return Xn(n,`no variants with VIDEO-RANGE of ${qn(v)} found`),e;if(l&&n.indexOf(l.substring(0,4))%5!=0)return Xn(n,`video codec preference "${l}" not found`),e;if(r.maxScore<m)return Xn(n,`max score of ${r.maxScore} < selected max of ${m}`),e}return e&&(Sn(n)>=Sn(e)||r.fragmentError>t[e].fragmentError)?e:(p=r.minIndex,m=r.maxScore,n)},void 0),videoRanges:v,preferHDR:y,minFramerate:f,minBitrate:g,minIndex:p}}(n,T,t,S,k),{codecSet:s,videoRanges:a,minFramerate:o,minBitrate:l,minIndex:h,preferHDR:c}=r;L=h,E=s,T=c?a[a.length-1]:a[0],b=o,t=Math.max(t,l),this.log(`picked start tier ${qn(r)}`)}else E=null==v?void 0:v.codecSet,T=null==v?void 0:v.videoRange;const I=d?d.duration:u?u.duration:0,R=this.bwEstimator.getEstimateTTFB()/1e3,C=[];for(let o=i;o>=e;o--){var P;const e=f[o],u=o>c;if(!e)continue;if(m.useMediaCapabilities&&!e.supportedResult&&!e.supportedPromise){const i=navigator.mediaCapabilities;"function"==typeof(null==i?void 0:i.decodingInfo)&&Mn(e,_,T,b,t,S)?(e.supportedPromise=Nn(e,_,i,this.supportedCache),e.supportedPromise.then(t=>{if(!this.hls)return;e.supportedResult=t;const i=this.hls.levels,n=i.indexOf(e);t.error?this.warn(`MediaCapabilities decodingInfo error: "${t.error}" for level ${n} ${qn(t)}`):t.supported?t.decodingInfoResults.some(t=>!1===t.smooth||!1===t.powerEfficient)&&this.log(`MediaCapabilities decodingInfo for level ${n} not smooth or powerEfficient: ${qn(t)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${n} ${qn(t)}`),n>-1&&i.length>1&&(this.log(`Removing unsupported level ${n}`),this.hls.removeLevel(n),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))}).catch(t=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${t}`)})):e.supportedResult=On}if((E&&e.codecSet!==E||T&&e.videoRange!==T||u&&b>e.frameRate||!u&&b>0&&b<e.frameRate||null!=(P=e.supportedResult)&&null!=(P=P.decodingInfoResults)&&P.some(t=>!1===t.smooth))&&(!A||o!==L)){C.push(o);continue}const g=e.details,v=(d?null==g?void 0:g.partTarget:null==g?void 0:g.averagetargetduration)||I;let k;k=u?a*t:s*t;const D=I&&n>=2*I&&0===r?e.averageBitrate:e.maxBitrate,w=this.getTimeToLoadFrag(R,k,D*v,void 0===g);if(k>=D&&(o===h||0===e.loadError&&0===e.fragmentError)&&(w<=R||!Je(w)||y&&!this.bitrateTestDelay||w<l)){const t=this.forcedAutoLevel;return o===p||-1!==t&&t===p||(C.length&&this.trace(`Skipped level(s) ${C.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${f[C[0]].codecs}" ${f[C[0]].videoRange}; not compatible with "${E}" ${T}`),this.info(`switch candidate:${c}->${o} adjustedbw(${Math.round(k)})-bitrate=${Math.round(k-D)} ttfb:${R.toFixed(1)} avgDuration:${v.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${w.toFixed(1)} firstSelection:${A} codecSet:${e.codecSet} videoRange:${e.videoRange} hls.loadLevel:${p}`)),A&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(t){const e=this.deriveNextAutoLevel(t);this._nextAutoLevel!==e&&(this.nextAutoLevelKey="",this._nextAutoLevel=e)}deriveNextAutoLevel(t){const{maxAutoLevel:e,minAutoLevel:i}=this.hls;return Math.min(Math.max(t,i),e)}},bufferController:class extends yi{constructor(t,e){var i;super("buffer-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=t=>{var e;this.hls&&"open"===(null==(e=this.mediaSource)?void 0:e.readyState)&&this.hls.pauseBuffering()},this._onStartStreaming=t=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=t=>{const{media:e,mediaSource:i}=this;t&&this.log("Media source opened"),e&&i&&(i.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(ri.MEDIA_ATTACHED,{media:e,mediaSource:i}),null!==this.mediaSource&&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&&this.error(`Media element src was set while attaching MediaSource (${e} > ${t})`)},this.hls=t,this.fragmentTracker=e,this.appendSource=(i=_i(t.config.preferManagedMediaSource),"undefined"!=typeof self&&i===self.ManagedMediaSource),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:t}=this;t.on(ri.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(ri.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(ri.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ri.MANIFEST_PARSED,this.onManifestParsed,this),t.on(ri.BUFFER_RESET,this.onBufferReset,this),t.on(ri.BUFFER_APPENDING,this.onBufferAppending,this),t.on(ri.BUFFER_CODECS,this.onBufferCodecs,this),t.on(ri.BUFFER_EOS,this.onBufferEos,this),t.on(ri.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(ri.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(ri.FRAG_PARSED,this.onFragParsed,this),t.on(ri.FRAG_CHANGED,this.onFragChanged,this),t.on(ri.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(ri.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(ri.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(ri.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ri.MANIFEST_PARSED,this.onManifestParsed,this),t.off(ri.BUFFER_RESET,this.onBufferReset,this),t.off(ri.BUFFER_APPENDING,this.onBufferAppending,this),t.off(ri.BUFFER_CODECS,this.onBufferCodecs,this),t.off(ri.BUFFER_EOS,this.onBufferEos,this),t.off(ri.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(ri.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(ri.FRAG_PARSED,this.onFragParsed,this),t.off(ri.FRAG_CHANGED,this.onFragChanged,this),t.off(ri.ERROR,this.onError,this)}transferMedia(){const{media:t,mediaSource:e}=this;if(!t)return null;const i={};if(this.operationQueue){const t=this.isUpdating();t||this.operationQueue.removeBlockers();const e=this.isQueued();(t||e)&&this.warn(`Transfering MediaSource with${e?" operations in queue":""}${t?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const n=this.transferData;return!this.sourceBufferCount&&n&&n.mediaSource===e?pi(i,n.tracks):this.sourceBuffers.forEach(t=>{const[e]=t;e&&(i[e]=pi({},this.tracks[e]),this.removeBuffer(e)),t[0]=t[1]=null}),{media:t,mediaSource:e,tracks:i}}initTracks(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(t,e){var i;let n=2;(e.audio&&!e.video||!e.altAudio)&&(n=1),this.bufferCodecEventsTotal=n,this.log(`${n} bufferCodec event(s) expected.`),null!=(i=this.transferData)&&i.mediaSource&&this.sourceBufferCount&&n&&this.bufferCreated()}onMediaAttaching(t,e){const i=this.media=e.media;this.transferData=this.overrides=void 0;const n=_i(this.appendSource);if(n){const t=!!e.mediaSource;(t||e.overrides)&&(this.transferData=e,this.overrides=e.overrides);const r=this.mediaSource=e.mediaSource||new n;if(this.assignMediaSource(r),t)this._objectUrl=i.src,this.attachTransferred();else{const t=this._objectUrl=self.URL.createObjectURL(r);if(this.appendSource)try{i.removeAttribute("src");const e=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||e&&r instanceof e,gl(i),function(t,e){const i=self.document.createElement("source");i.type="video/mp4",i.src=e,t.appendChild(i)}(i,t),i.load()}catch(e){i.src=t}else i.src=t}i.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(t){var e,i;this.log(`${(null==(e=this.transferData)?void 0:e.mediaSource)===t?"transferred":"created"} media source: ${null==(i=t.constructor)?void 0:i.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))}attachTransferred(){const t=this.media,e=this.transferData;if(!e||!t)return;const i=this.tracks,n=e.tracks,r=n?Object.keys(n):null,s=r?r.length:0,a=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(n&&r&&s){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})\nrequired tracks: ${qn(i,(t,e)=>"initSegment"===t?void 0:e)};\ntransfer tracks: ${qn(n,(t,e)=>"initSegment"===t?void 0:e)}}`),!Li(n,i)){e.mediaSource=null,e.tracks=void 0;const r=t.currentTime,s=this.details,a=Math.max(r,(null==s?void 0:s.fragments[0].start)||0);return a-r>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${r} -> ${a}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(n)}"->"${Object.keys(i)}") start time: ${a} currentTime: ${r}`),this.onMediaDetaching(ri.MEDIA_DETACHING,{}),this.onMediaAttaching(ri.MEDIA_ATTACHING,e),void(t.currentTime=a))}this.transferData=void 0,r.forEach(t=>{const e=t,i=n[e];if(i){const t=i.buffer;if(t){const n=this.fragmentTracker,r=i.id;if(n.hasFragments(r)||n.hasParts(r)){const i=zr.getBuffered(t);n.detectEvictedFragments(e,i,r,null,!0)}const s=pl(e),a=[e,t];this.sourceBuffers[s]=a,t.updating&&this.operationQueue&&this.operationQueue.prependBlocker(e),this.trackSourceBuffer(e,i)}}}),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var t;const e=null==(t=this.mediaSource)?void 0:t.readyState;return"open"===e||"ended"===e}onMediaDetaching(t,e){const i=!!e.transferMedia;this.transferData=this.overrides=void 0;const{media:n,mediaSource:r,_objectUrl:s}=this;if(r){if(this.log("media source "+(i?"transferring":"detaching")),i)this.sourceBuffers.forEach(([t])=>{t&&this.removeBuffer(t)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const t="open"===r.readyState;try{const e=r.sourceBuffers;for(let i=e.length;i--;)t&&e[i].abort(),r.removeSourceBuffer(e[i]);t&&r.endOfStream()}catch(t){this.warn(`onMediaDetaching: ${t.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(r.removeEventListener("startstreaming",this._onStartStreaming),r.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}n&&(n.removeEventListener("emptied",this._onMediaEmptied),i||(s&&self.URL.revokeObjectURL(s),this.mediaSrc===s?(n.removeAttribute("src"),this.appendSource&&gl(n),n.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(ri.MEDIA_DETACHED,e)}onBufferReset(){this.sourceBuffers.forEach(([t])=>{t&&this.resetBuffer(t)}),this.initTracks()}resetBuffer(t){var e;const i=null==(e=this.tracks[t])?void 0:e.buffer;if(this.removeBuffer(t),i)try{var n;null!=(n=this.mediaSource)&&n.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(e){this.warn(`onBufferReset ${t}`,e)}delete this.tracks[t]}removeBuffer(t){this.removeBufferListeners(t),this.sourceBuffers[pl(t)]=[null,null];const e=this.tracks[t];e&&(e.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new cl(this.tracks)}onBufferCodecs(t,e){var i;const n=this.tracks,r=Object.keys(e);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const s="audiovideo"in e&&(n.audio||n.video)||n.audiovideo&&("audio"in e||"video"in e),a=!s&&this.sourceBufferCount&&this.media&&r.some(t=>!n[t]);s||a?this.warn(`Unsupported transition between "${Object.keys(n)}" and "${r}" SourceBuffers`):(r.forEach(t=>{var i,r;const s=e[t],{id:a,codec:o,levelCodec:l,container:h,metadata:c,supplemental:u}=s;let d=n[t];const f=null==(i=this.transferData)||null==(i=i.tracks)?void 0:i[t],g=null!=f&&f.buffer?f:d,p=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),m=null==g?void 0:g.levelCodec;d||(d=n[t]={buffer:void 0,listeners:[],codec:o,supplemental:u,container:h,levelCodec:l,metadata:c,id:a});const v=In(p,m),y=null==v?void 0:v.replace(ul,"$1");let A=In(o,l);const E=null==(r=A)?void 0:r.replace(ul,"$1");A&&v&&y!==E&&("audio"===t.slice(0,5)&&(A=Ln(A,this.appendSource)),this.log(`switching codec ${p} to ${A}`),A!==(d.pendingCodec||d.codec)&&(d.pendingCodec=A),d.container=h,this.appendChangeType(t,h,A))}),(this.tracksReady||this.sourceBufferCount)&&(e.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!e.video&&"main"===(null==(i=e.audio)?void 0:i.id)&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((t,e)=>{const i=this.tracks[e];return t[e]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},t},{})}appendChangeType(t,e,i){const n=`${e};codecs=${i}`,r={label:`change-type=${n}`,execute:()=>{const r=this.tracks[t];if(r){const s=r.buffer;null!=s&&s.changeType&&(this.log(`changing ${t} sourceBuffer type to ${n}`),s.changeType(n),r.codec=i,r.container=e)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn(`Failed to change ${t} SourceBuffer type`,e)}};this.append(r,t,this.isPending(this.tracks[t]))}blockAudio(t){var e;const i=t.start,n=i+.05*t.duration;if(!0===(null==(e=this.fragmentTracker.getAppendedFrag(i,hi))?void 0:e.gap))return;const r={label:"block-audio",execute:()=>{var t;const e=this.tracks.video;(this.lastVideoAppendEnd>n||null!=e&&e.buffer&&zr.isBuffered(e.buffer,n)||!0===(null==(t=this.fragmentTracker.getAppendedFrag(n,hi))?void 0:t.gap))&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn("Error executing block-audio operation",t)}};this.blockedAudioAppend={op:r,frag:t},this.append(r,"audio",!0)}unblockAudio(){const{blockedAudioAppend:t,operationQueue:e}=this;t&&e&&(this.blockedAudioAppend=null,e.unblockAudio(t.op))}onBufferAppending(t,e){const{tracks:i}=this,{data:n,type:r,parent:s,frag:a,part:o,chunkMeta:l,offset:h}=e,c=l.buffering[r],{sn:u,cc:d}=a,f=self.performance.now();c.start=f;const g=a.stats.buffering,p=o?o.stats.buffering:null;0===g.start&&(g.start=f),p&&0===p.start&&(p.start=f);const m=i.audio;let v=!1;"audio"===r&&"audio/mpeg"===(null==m?void 0:m.container)&&(v=!this.lastMpegAudioChunk||1===l.id||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const y=i.video,A=null==y?void 0:y.buffer;if(A&&"initSegment"!==u){const t=o||a,e=this.blockedAudioAppend;if("audio"!==r||"main"===s||this.blockedAudioAppend||y.ending||y.ended){if("video"===r){const i=t.end;if(e){const t=e.frag.start;(i>t||i<this.lastVideoAppendEnd||zr.isBuffered(A,t))&&this.unblockAudio()}this.lastVideoAppendEnd=i}}else{const e=t.start+.05*t.duration,i=A.buffered,n=this.currentOp("video");i.length||n?!n&&!zr.isBuffered(A,e)&&this.lastVideoAppendEnd<e&&this.blockAudio(t):this.blockAudio(t)}}const E=(o||a).start,T={label:`append-${r}`,execute:()=>{var t;c.executeStart=self.performance.now();const e=null==(t=this.tracks[r])?void 0:t.buffer;e&&(v?this.updateTimestampOffset(e,E,.1,r,u,d):void 0!==h&&Je(h)&&this.updateTimestampOffset(e,h,1e-6,r,u,d)),this.appendExecutor(n,r)},onStart:()=>{},onComplete:()=>{const t=self.performance.now();c.executeEnd=c.end=t,0===g.first&&(g.first=t),p&&0===p.first&&(p.first=t);const e={};this.sourceBuffers.forEach(([t,i])=>{t&&(e[t]=zr.getBuffered(i))}),this.appendErrors[r]=0,"audio"===r||"video"===r?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(ri.BUFFER_APPENDED,{type:r,frag:a,part:o,chunkMeta:l,parent:a.type,timeRanges:e})},onError:t=>{var e;const i={type:ii.MEDIA_ERROR,parent:a.type,details:ni.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:a,part:o,chunkMeta:l,error:t,err:t,fatal:!1},n=null==(e=this.media)?void 0:e.error;if(t.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==t.name||"quota"in t)i.details=ni.BUFFER_FULL_ERROR;else if(t.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!n)i.errorAction=_r(!0);else if(t.name===dl&&0===this.sourceBufferCount)i.errorAction=_r(!0);else{const t=++this.appendErrors[r];this.warn(`Failed ${t}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${n||"no media error"})`),(t>=this.hls.config.appendErrorMaxRetry||n)&&(i.fatal=!0)}this.hls.trigger(ri.ERROR,i)}};this.log(`queuing "${r}" append sn: ${u}${o?" p: "+o.index:""} of ${a.type===hi?"level":"track"} ${a.level} cc: ${d}`),this.append(T,r,this.isPending(this.tracks[r]))}getFlushOp(t,e,i){return this.log(`queuing "${t}" remove ${e}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(t,e,i)},onStart:()=>{},onComplete:()=>{this.hls.trigger(ri.BUFFER_FLUSHED,{type:t})},onError:n=>{this.warn(`Failed to remove ${e}-${i} from "${t}" SourceBuffer`,n)}}}onBufferFlushing(t,e){const{type:i,startOffset:n,endOffset:r}=e;i?this.append(this.getFlushOp(i,n,r),i):this.sourceBuffers.forEach(([t])=>{t&&this.append(this.getFlushOp(t,n,r),t)})}onFragParsed(t,e){const{frag:i,part:n}=e,r=[],s=n?n.elementaryStreams:i.elementaryStreams;s[Fi]?r.push("audiovideo"):(s[Mi]&&r.push("audio"),s[Ni]&&r.push("video"));0===r.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,n&&(n.stats.buffering.end=t);const e=n?n.stats:i.stats;this.hls.trigger(ri.FRAG_BUFFERED,{frag:i,part:n,stats:e,id:i.type})},r).catch(t=>{this.warn(`Fragment buffered callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(t,e){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{if(t){const e=this.tracks[t];if(e)return!e.ended||e.ending}return!1})}onBufferEos(t,e){var i;this.sourceBuffers.forEach(([t])=>{if(t){const i=this.tracks[t];e.type&&e.type!==t||(i.ending=!0,i.ended||(i.ended=!0,this.log(`${t} buffer reached EOS`)))}});const n=!1!==(null==(i=this.overrides)?void 0:i.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{var e;return t&&!(null!=(e=this.tracks[t])&&e.ended)})?n?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:t}=this;t&&"open"===t.readyState?(this.log("Calling mediaSource.endOfStream()"),t.endOfStream(),this.hls.trigger(ri.BUFFERED_TO_END,void 0)):t&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${t.readyState}`)})):(this.tracksEnded(),this.hls.trigger(ri.BUFFERED_TO_END,void 0)):"video"===e.type&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([t])=>{if(null!==t){const e=this.tracks[t];e&&(e.ending=!1)}})}onLevelUpdated(t,{details:e}){e.fragments.length&&(this.details=e,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const t=this.getDurationAndRange();t&&this.updateMediaSource(t)})}onError(t,e){if(e.details===ni.BUFFER_APPEND_ERROR&&e.frag){var i;const t=null==(i=e.errorAction)?void 0:i.nextAutoLevel;Je(t)&&t!==e.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:t,details:e,media:i}=this;if(!i||null===e)return;if(!this.sourceBufferCount)return;const n=t.config,r=i.currentTime,s=e.levelTargetDuration,a=e.live&&null!==n.liveBackBufferLength?n.liveBackBufferLength:n.backBufferLength;if(Je(a)&&a>=0){const t=Math.max(a,s),e=Math.floor(r/s)*s-t;this.flushBackBuffer(r,s,e)}const o=n.frontBufferFlushThreshold;if(Je(o)&&o>0){const t=Math.max(n.maxBufferLength,o),e=Math.max(t,s),i=Math.floor(r/s)*s+e;this.flushFrontBuffer(r,s,i)}}flushBackBuffer(t,e,i){this.sourceBuffers.forEach(([t,e])=>{if(e){const r=zr.getBuffered(e);if(r.length>0&&i>r.start(0)){var n;this.hls.trigger(ri.BACK_BUFFER_REACHED,{bufferEnd:i});const e=this.tracks[t];if(null!=(n=this.details)&&n.live)this.hls.trigger(ri.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(null!=e&&e.ended)return void this.log(`Cannot flush ${t} back buffer while SourceBuffer is in ended state`);this.hls.trigger(ri.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:t})}}})}flushFrontBuffer(t,e,i){this.sourceBuffers.forEach(([e,n])=>{if(n){const r=zr.getBuffered(n),s=r.length;if(s<2)return;const a=r.start(s-1),o=r.end(s-1);if(i>a||t>=a&&t<=o)return;this.hls.trigger(ri.BUFFER_FLUSHING,{startOffset:a,endOffset:1/0,type:e})}})}getDurationAndRange(){var t;const{details:e,mediaSource:i}=this;if(!e||!this.media||"open"!==(null==i?void 0:i.readyState))return null;const n=e.edge;if(e.live&&this.hls.config.liveDurationInfinity){if(e.fragments.length&&i.setLiveSeekableRange){const t=Math.max(0,e.fragmentStart);return{duration:1/0,start:t,end:Math.max(t,n)}}return{duration:1/0}}const r=null==(t=this.overrides)?void 0:t.duration;if(r)return Je(r)?{duration:r}:null;const s=this.media.duration;return n>(Je(i.duration)?i.duration:0)&&n>s||!Je(s)?{duration:n}:null}updateMediaSource({duration:t,start:e,end:i}){const n=this.mediaSource;this.media&&n&&"open"===n.readyState&&(n.duration!==t&&(Je(t)&&this.log(`Updating MediaSource duration to ${t.toFixed(3)}`),n.duration=t),void 0!==e&&void 0!==i&&(this.log(`MediaSource duration is set to ${n.duration}. Setting seekable range to ${e}-${i}.`),n.setLiveSeekableRange(e,i)))}get tracksReady(){const t=this.pendingTrackCount;return t>0&&(t>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:t,pendingTrackCount:e,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${e} codec events expected: ${t}) ${qn(i)}`),this.tracksReady){var n;const t=null==(n=this.transferData)?void 0:n.tracks;t&&Object.keys(t).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const t={};this.sourceBuffers.forEach(([e,i])=>{if(e){const n=this.tracks[e];t[e]={buffer:i,container:n.container,codec:n.codec,supplemental:n.supplemental,levelCodec:n.levelCodec,id:n.id,metadata:n.metadata}}}),this.hls.trigger(ri.BUFFER_CREATED,{tracks:t}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(ri.ERROR,{type:ii.MEDIA_ERROR,details:ni.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}createSourceBuffers(){const{tracks:t,sourceBuffers:e,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in t){const s=r,a=t[s];if(this.isPending(a)){const t=this.getTrackCodec(a,s),r=`${a.container};codecs=${t}`;a.codec=t,this.log(`creating sourceBuffer(${r})${this.currentOp(s)?" Queued":""} ${qn(a)}`);try{const t=i.addSourceBuffer(r),n=pl(s),o=[s,t];e[n]=o,a.buffer=t}catch(t){var n;return this.error(`error while trying to add sourceBuffer: ${t.message}`),this.shiftAndExecuteNext(s),null==(n=this.operationQueue)||n.removeBlockers(),delete this.tracks[s],void this.hls.trigger(ri.ERROR,{type:ii.MEDIA_ERROR,details:ni.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:s,mimeType:r,parent:a.id})}this.trackSourceBuffer(s,a)}}this.bufferCreated()}getTrackCodec(t,e){const i=t.supplemental;let n=t.codec;i&&("video"===e||"audiovideo"===e)&&An(i,"video")&&(n=function(t,e){const i=[];if(t){const e=t.split(",");for(let t=0;t<e.length;t++)yn(e[t],"video")||i.push(e[t])}return e&&i.push(e),i.join(",")}(n,i));const r=In(n,t.levelCodec);return r?"audio"===e.slice(0,5)?Ln(r,this.appendSource):r:""}trackSourceBuffer(t,e){const i=e.buffer;if(!i)return;const n=this.getTrackCodec(e,t);this.tracks[t]={buffer:i,codec:n,container:e.container,levelCodec:e.levelCodec,supplemental:e.supplemental,metadata:e.metadata,id:e.id,listeners:[]},this.removeBufferListeners(t),this.addBufferListener(t,"updatestart",this.onSBUpdateStart),this.addBufferListener(t,"updateend",this.onSBUpdateEnd),this.addBufferListener(t,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(t,"bufferedchange",(t,e)=>{const i=e.removedRanges;null!=i&&i.length&&this.hls.trigger(ri.BUFFER_FLUSHED,{type:t})})}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 e=this.currentOp(t);e&&e.onStart()}onSBUpdateEnd(t){var e;if("closed"===(null==(e=this.mediaSource)?void 0:e.readyState))return void this.resetBuffer(t);const i=this.currentOp(t);i&&(i.onComplete(),this.shiftAndExecuteNext(t))}onSBUpdateError(t,e){var i;const n=new Error(`${t} SourceBuffer error. MediaSource readyState: ${null==(i=this.mediaSource)?void 0:i.readyState}`);this.error(`${n}`,e),this.hls.trigger(ri.ERROR,{type:ii.MEDIA_ERROR,details:ni.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:n,fatal:!1});const r=this.currentOp(t);r&&r.onError(n)}updateTimestampOffset(t,e,i,n,r,s){const a=e-t.timestampOffset;Math.abs(a)>=i&&(this.log(`Updating ${n} SourceBuffer timestampOffset to ${e} (sn: ${r} cc: ${s})`),t.timestampOffset=e)}removeExecutor(t,e,i){const{media:n,mediaSource:r}=this,s=this.tracks[t],a=null==s?void 0:s.buffer;if(!n||!r||!a)return this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),void this.shiftAndExecuteNext(t);const o=Je(n.duration)?n.duration:1/0,l=Je(r.duration)?r.duration:1/0,h=Math.max(0,e),c=Math.min(i,o,l);c>h&&(!s.ending||s.ended)?(s.ended=!1,this.log(`Removing [${h},${c}] from the ${t} SourceBuffer`),a.remove(h,c)):this.shiftAndExecuteNext(t)}appendExecutor(t,e){const i=this.tracks[e],n=null==i?void 0:i.buffer;if(!n)throw new fl(`Attempting to append to the ${e} SourceBuffer, but it does not exist`);i.ending=!1,i.ended=!1,n.appendBuffer(t)}blockUntilOpen(t){if(this.isUpdating()||this.isQueued())this.blockBuffers(t).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{t()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([t,e])=>t&&e.updating)}isQueued(){return this.sourceBuffers.some(([t])=>t&&!!this.currentOp(t))}isPending(t){return!!t&&!t.buffer}blockBuffers(t,e=this.sourceBufferTypes){if(!e.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);const{operationQueue:i}=this,n=e.map(t=>this.appendBlocker(t));return e.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(n).then(e=>{i===this.operationQueue&&(t(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(t){t.forEach(t=>{var e;const i=null==(e=this.tracks[t])?void 0:e.buffer;i&&!i.updating&&this.shiftAndExecuteNext(t)})}append(t,e,i){this.operationQueue&&this.operationQueue.append(t,e,i)}appendBlocker(t){if(this.operationQueue)return this.operationQueue.appendBlocker(t)}currentOp(t){return this.operationQueue?this.operationQueue.current(t):null}executeNext(t){t&&this.operationQueue&&this.operationQueue.executeNext(t)}shiftAndExecuteNext(t){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(t)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((t,e)=>t+(this.isPending(this.tracks[e])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((t,[e])=>t+(e?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([t])=>t).filter(t=>!!t)}addBufferListener(t,e,i){const n=this.tracks[t];if(!n)return;const r=n.buffer;if(!r)return;const s=i.bind(this,t);n.listeners.push({event:e,listener:s}),r.addEventListener(e,s)}removeBufferListeners(t){const e=this.tracks[t];if(!e)return;const i=e.buffer;i&&(e.listeners.forEach(t=>{i.removeEventListener(t.event,t.listener)}),e.listeners.length=0)}},capLevelController:ml,errorController:class extends yi{constructor(t){super("error-controller",t.logger),this.hls=void 0,this.playlistError=0,this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(ri.ERROR,this.onError,this),t.on(ri.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ri.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(ri.ERROR,this.onError,this),t.off(ri.ERROR,this.onErrorOut,this),t.off(ri.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ri.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){return(null==t?void 0:t.type)===hi?t.level:this.getVariantIndex()}getVariantIndex(){var t;const e=this.hls,i=e.currentLevel;return null!=(t=e.loadLevelObj)&&t.details||-1===i?e.loadLevel:i}variantHasKey(t,e){if(t){var i;if(null!=(i=t.details)&&i.hasKey(e))return!0;const n=t.audioGroups;if(n){return this.hls.allAudioTracks.filter(t=>n.indexOf(t.groupId)>=0).some(t=>{var i;return null==(i=t.details)?void 0:i.hasKey(e)})}}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(t,e){var i;if(e.fatal)return;const n=this.hls,r=e.context;switch(e.details){case ni.FRAG_LOAD_ERROR:case ni.FRAG_LOAD_TIMEOUT:case ni.KEY_LOAD_ERROR:case ni.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case ni.FRAG_PARSING_ERROR:if(null!=(i=e.frag)&&i.gap)return void(e.errorAction=_r());case ni.FRAG_GAP:case ni.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=yr);case ni.LEVEL_EMPTY_ERROR:case ni.LEVEL_PARSING_ERROR:{var s;const t=e.parent===hi?e.level:n.loadLevel;e.details===ni.LEVEL_EMPTY_ERROR&&null!=(s=e.context)&&null!=(s=s.levelDetails)&&s.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,t):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t))}return;case ni.LEVEL_LOAD_ERROR:case ni.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==r?void 0:r.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,r.level)));case ni.AUDIO_TRACK_LOAD_ERROR:case ni.AUDIO_TRACK_LOAD_TIMEOUT:case ni.SUBTITLE_LOAD_ERROR:case ni.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const t=n.loadLevelObj;if(t&&(r.type===oi&&t.hasAudioGroup(r.groupId)||r.type===li&&t.hasSubtitleGroup(r.groupId)))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,n.loadLevel),e.errorAction.action=yr,void(e.errorAction.flags=br)}return;case ni.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(e.errorAction={action:yr,flags:Sr});case ni.KEY_SYSTEM_SESSION_UPDATE_FAILED:case ni.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case ni.KEY_SYSTEM_NO_SESSION:return void(e.errorAction={action:yr,flags:kr});case ni.BUFFER_ADD_CODEC_ERROR:case ni.REMUX_ALLOC_ERROR:case ni.BUFFER_APPEND_ERROR:var a;if(!e.errorAction)e.errorAction=this.getLevelSwitchAction(e,null!=(a=e.level)?a:n.loadLevel);return;case ni.INTERNAL_EXCEPTION:case ni.BUFFER_APPENDING_ERROR:case ni.BUFFER_FULL_ERROR:case ni.LEVEL_SWITCH_ERROR:case ni.BUFFER_STALLED_ERROR:case ni.BUFFER_SEEK_OVER_HOLE:case ni.BUFFER_NUDGE_ON_STALL:return void(e.errorAction=_r())}e.type===ii.KEY_SYSTEM_ERROR&&(e.levelRetry=!1,e.errorAction=_r())}getPlaylistRetryOrSwitchAction(t,e){const i=dr(this.hls.config.playlistLoadPolicy,t),n=this.playlistError++;if(pr(i,n,hr(t),t.response))return{action:Er,flags:Tr,retryConfig:i,retryCount:n};const r=this.getLevelSwitchAction(t,e);return i&&(r.retryConfig=i,r.retryCount=n),r}getFragRetryOrSwitchAction(t){const e=this.hls,i=this.getVariantLevelIndex(t.frag),n=e.levels[i],{fragLoadPolicy:r,keyLoadPolicy:s}=e.config,a=dr(cr(t)?s:r,t),o=e.levels.reduce((t,e)=>t+e.fragmentError,0);if(n&&(t.details!==ni.FRAG_GAP&&n.fragmentError++,!ur(t))){if(pr(a,o,hr(t),t.response))return{action:Er,flags:Tr,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 n=this.hls.levels[e];if(n){var r,s;const e=t.details;n.loadError++,e===ni.BUFFER_APPEND_ERROR&&n.fragmentError++;let l=-1;const{levels:h,loadLevel:c,minAutoLevel:u,maxAutoLevel:d}=i;i.autoLevelEnabled||i.config.preserveManualLevelOnError||(i.loadLevel=-1);const f=null==(r=t.frag)?void 0:r.type,g=(f===ci&&e===ni.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&(e===ni.BUFFER_ADD_CODEC_ERROR||e===ni.BUFFER_APPEND_ERROR))&&h.some(({audioCodec:t})=>n.audioCodec!==t),p="video"===t.sourceBufferName&&(e===ni.BUFFER_ADD_CODEC_ERROR||e===ni.BUFFER_APPEND_ERROR)&&h.some(({codecSet:t,audioCodec:e})=>n.codecSet!==t&&n.audioCodec===e),{type:m,groupId:v}=null!=(s=t.context)?s:{};for(let i=h.length;i--;){const r=(i+c)%h.length;if(r!==c&&r>=u&&r<=d&&0===h[r].loadError){var a,o;const i=h[r];if(e===ni.FRAG_GAP&&f===hi&&t.frag){const e=h[r].details;if(e){const i=sr(t.frag,e.fragments,t.frag.start);if(null!=i&&i.gap)continue}}else{if(m===oi&&i.hasAudioGroup(v)||m===li&&i.hasSubtitleGroup(v))continue;if(f===ci&&null!=(a=n.audioGroups)&&a.some(t=>i.hasAudioGroup(t))||f===ui&&null!=(o=n.subtitleGroups)&&o.some(t=>i.hasSubtitleGroup(t))||g&&n.audioCodec===i.audioCodec||p&&n.codecSet===i.codecSet||!g&&n.codecSet!==i.codecSet)continue}l=r;break}}if(l>-1&&i.loadLevel!==l)return t.levelRetry=!0,this.playlistError=0,{action:yr,flags:Tr,nextAutoLevel:l}}return{action:yr,flags:br}}onErrorOut(t,e){var i;switch(null==(i=e.errorAction)?void 0:i.action){case vr:break;case yr:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===ni.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:n}=i,r=i.nextAutoLevel;switch(n){case Tr:this.switchLevel(t,r);break;case Sr:{const n=this.getVariantLevelIndex(t.frag),r=e.levels[n],s=null==r?void 0:r.attrs["HDCP-LEVEL"];if(i.hdcpLevel=s,"NONE"===s)this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(s){e.maxHdcpLevel=Un[Un.indexOf(s)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`);break}}case kr:{const e=t.decryptdata;if(e){const n=this.hls.levels,r=n.length;for(let i=r;i--;){var s,a;if(this.variantHasKey(n[i],e))this.log(`Banned key found in level ${i} (${n[i].bitrate}bps) or audio group "${null==(s=n[i].audioGroups)?void 0:s.join(",")}" (${null==(a=t.frag)?void 0:a.type} fragment) ${Ri(e.keyId||[])}`),n[i].fragmentError++,n[i].loadError++,this.log(`Removing level ${i} with key error (${t.error})`),this.hls.removeLevel(i)}const o=t.frag;if(this.hls.levels.length<r)i.resolved=!0;else if(o&&o.type!==hi){const t=o.decryptdata;t&&!e.matches(t)&&(i.resolved=!0)}}break}}i.resolved||this.switchLevel(t,r)}switchLevel(t,e){if(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,t.details===ni.BUFFER_ADD_CODEC_ERROR&&t.mimeType&&"audiovideo"!==t.sourceBufferName)){const e=Dn(t.mimeType),i=this.hls.levels;for(let n=i.length;n--;)i[n][`${t.sourceBufferName}Codec`]===e&&(this.log(`Removing level ${n} for ${t.details} ("${e}" not supported)`),this.hls.removeLevel(n))}}},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(ri.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(ri.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(ri.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(ri.MEDIA_DETACHING,this.onMediaDetaching,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)}}onMediaDetaching(){this.media=null}checkFPS(t,e,i){const n=performance.now();if(e){if(this.lastTime){const t=n-this.lastTime,r=i-this.lastDroppedFrames,s=e-this.lastDecodedFrames,a=1e3*r/t,o=this.hls;if(o.trigger(ri.FPS_DROP,{currentDropped:r,currentDecoded:s,totalDroppedFrames:i}),a>0&&r>o.config.fpsDroppedMonitoringThreshold*s){let t=o.currentLevel;o.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=t)&&(t-=1,o.trigger(ri.FPS_DROP_LEVEL_CAPPING,{level:t,droppedLevel:o.currentLevel}),o.autoLevelCapping=t,this.streamController.nextLevelSwitch())}}this.lastTime=n,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:ks,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:{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}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:Oc,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 La{constructor(t,e,i){super(t,e,i,"subtitle-stream-controller",ui),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(ri.LEVEL_LOADED,this.onLevelLoaded,this),t.on(ri.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(ri.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(ri.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(ri.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(ri.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(ri.LEVEL_LOADED,this.onLevelLoaded,this),t.off(ri.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(ri.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(ri.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(ri.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(ri.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(t,e){this.stopLoad(),this.state=pa,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(t,e){this.tracksBuffered=[],super.onMediaDetaching(t,e)}onLevelLoaded(t,e){this.mainDetails=e.details}onSubtitleFragProcessed(t,e){const{frag:i,success:n}=e;if(this.fragContextChanged(i)||(Ui(i)&&(this.fragPrevious=i),this.state=pa),!n)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let s;const a=i.start;for(let t=0;t<r.length;t++)if(a>=r[t].start&&a<=r[t].end){s=r[t];break}const o=i.start+i.duration;s?s.end=o:(s={start:a,end:o},r.push(s)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick()}onBufferFlushing(t,e){const{startOffset:i,endOffset:n}=e;if(0===i&&n!==Number.POSITIVE_INFINITY){const t=n-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,ui)}}onError(t,e){const i=e.frag;(null==i?void 0:i.type)===ui&&(e.details===ni.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==ga&&(this.state=pa))}onSubtitleTracksUpdated(t,{subtitleTracks:e}){this.levels&&ol(this.levels,e)?this.levels=e.map(t=>new jn(t)):(this.tracksBuffered=[],this.levels=e.map(t=>{const e=new jn(t);return this.tracksBuffered[e.id]=[],e}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,ui),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 n=this.levels[this.currentTrackId];null!=n&&n.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,n&&this.state!==ga&&this.setInterval(500)}onSubtitleTrackLoaded(t,e){var i;const{currentTrackId:n,levels:r}=this,{details:s,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 [${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){if(s.deltaUpdateFailed)return;const t=this.mainDetails;if(!t)return void(this.startFragRequested=!1);const e=t.fragments[0];var h;if(o.details)l=this.alignPlaylists(s,o.details,null==(h=this.levelLastLoaded)?void 0:h.details),0===l&&e&&(l=e.start,Zs(s,l));else s.hasProgramDateTime&&t.hasProgramDateTime?(ca(s,t),l=s.fragmentStart):e&&(l=e.start,Zs(s,l));t&&!this.startFragRequested&&this.setStartPosition(t,l)}if(o.details=s,this.levelLastLoaded=o,a===n&&(this.hls.trigger(ri.SUBTITLE_TRACK_UPDATED,{details:s,id:a,groupId:e.groupId}),this.tick(),s.live&&!this.fragCurrent&&this.media&&this.state===pa)){sr(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,n=e.decryptdata,r=this.hls;if(!this.fragContextChanged(e)&&i&&i.byteLength>0&&null!=n&&n.key&&n.iv&&hs(n.method)){const t=performance.now();this.decrypter.decrypt(new Uint8Array(i),n.key.buffer,n.iv.buffer,cs(n.method)).catch(t=>{throw r.trigger(ri.ERROR,{type:ii.MEDIA_ERROR,details:ni.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t}).then(i=>{const n=performance.now();r.trigger(ri.FRAG_DECRYPTED,{frag:e,payload:i,stats:{tstart:t,tdecrypt:n}})}).catch(t=>{this.warn(`${t.name}: ${t.message}`),this.state=pa})}}doTick(){if(this.media){if(this.state===pa){const{currentTrackId:t,levels:e}=this,i=null==e?void 0:e[t];if(!i||!e.length||!i.details)return;if(this.waitForLive(i))return;const{config:n}=this,r=this.getLoadPosition(),s=zr.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,n.maxBufferHole),{end:a,len:o}=s,l=i.details;if(o>this.hls.maxBufferLength+l.levelTargetDuration)return;const h=l.fragments,c=h.length,u=l.edge;let d=null;const f=this.fragPrevious;if(a<u){const t=n.maxFragLookUpTolerance,e=a>u-t?0:t;d=sr(f,h,Math.max(h[0].start,a),e),!d&&f&&f.start<h[0].start&&(d=h[0])}else d=h[c-1];if(d=this.filterReplacedPrimary(d,i.details),!d)return;const g=h[d.sn-l.startSN-1];if(g&&g.cc===d.cc&&this.fragmentTracker.getState(g)===Lr&&(d=g),this.fragmentTracker.getState(d)===Lr){const t=this.mapToInitFragWhenRequired(d);t&&this.loadFragment(t,i,a)}}}else this.state=pa}loadFragment(t,e,i){Ui(t)?super.loadFragment(t,e,i):this._loadInitSegment(t,e)}get mediaBufferTimeRanges(){return new Fh(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends al{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.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const e=Th(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(ri.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(ri.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(ri.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ri.MANIFEST_PARSED,this.onManifestParsed,this),t.on(ri.LEVEL_LOADING,this.onLevelLoading,this),t.on(ri.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(ri.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(ri.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(ri.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(ri.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(ri.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ri.MANIFEST_PARSED,this.onManifestParsed,this),t.off(ri.LEVEL_LOADING,this.onLevelLoading,this),t.off(ri.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(ri.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(ri.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(t,e){const i=this.media;if(!i)return;const n=!!e.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,n)return;Th(i.textTracks).forEach(t=>{Ah(t)})}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:n,details:r}=e,s=this.tracksInGroup[i];if(!s||s.groupId!==n)return void this.warn(`Subtitle track with id:${i} and group:${n} 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:${n} loaded [${r.startSN}-${r.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,n=this.groupIds;let r=this.currentTrack;if(!i||(null==n?void 0:n.length)!==(null==i?void 0:i.length)||null!=i&&i.some(t=>-1===(null==n?void 0:n.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(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.subtitlePreference;if(!r&&e){this.selectDefaultTrack=!1;const i=Jn(e,t);if(i>-1)r=t[i];else{const t=Jn(e,this.tracks);r=this.tracks[t]}}let n=this.findTrackId(r);-1===n&&r&&(n=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(ri.SUBTITLE_TRACKS_UPDATED,s),-1!==n&&-1===this.trackId&&this.setSubtitleTrack(n)}}findTrackId(t){const e=this.tracksInGroup,i=this.selectDefaultTrack;for(let n=0;n<e.length;n++){const r=e[n];if((!i||r.default)&&(i||t)&&(!t||tr(r,t)))return n}if(t){for(let i=0;i<e.length;i++){const n=e[i];if(ll(t.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<e.length;i++){const n=e[i];if(ll(t.attrs,n.attrs,["LANGUAGE"]))return i}}return-1}findTrackForTextTrack(t){if(t){const e=this.tracksInGroup;for(let i=0;i<e.length;i++){if(hl(e[i],t))return i}}return-1}onError(t,e){!e.fatal&&e.context&&(e.context.type!==li||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){if(-1===t.id)return this.setSubtitleTrack(-1),null;const e=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,e.length){const i=this.currentTrack;if(i&&tr(t,i))return i;const n=Jn(t,this.tracksInGroup);if(n>-1){const t=this.tracksInGroup[n];return this.setSubtitleTrack(n),t}if(i)return null;{const i=Jn(t,e);if(i>-1)return e[i]}}}return null}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const i=t.id,n=t.groupId,r=this.getUrlWithDirectives(t.url,e),s=t.details,a=null==s?void 0:s.age;this.log(`Loading subtitle ${i} "${t.name}" lang:${t.lang} group:${n}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${a&&s.live?" age "+a.toFixed(1)+(s.type&&" "+s.type||""):""} ${r}`),this.hls.trigger(ri.SUBTITLE_TRACK_LOADING,{url:r,id:i,groupId:n,deliveryDirectives:e||null,track:t})}toggleTrackModes(){const{media:t}=this;if(!t)return;const e=Th(t.textTracks),i=this.currentTrack;let n;if(i&&(n=e.filter(t=>hl(i,t))[0],n||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(e).forEach(t=>{"disabled"!==t.mode&&t!==n&&(t.mode="disabled")}),n){const t=this.subtitleDisplay?"showing":"hidden";n.mode!==t&&(n.mode=t)}}setSubtitleTrack(t){const e=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=t);if(t<-1||t>=e.length||!Je(t))return void this.warn(`Invalid subtitle track id: ${t}`);this.selectDefaultTrack=!1;const i=this.currentTrack,n=e[t]||null;if(this.trackId=t,this.currentTrack=n,this.toggleTrackModes(),!n)return void this.hls.trigger(ri.SUBTITLE_TRACK_SWITCH,{id:t});const r=!!n.details&&!n.details.live;if(t===this.trackId&&n===i&&r)return;this.log(`Switching to subtitle-track ${t}`+(n?` "${n.name}" lang:${n.lang} group:${n.groupId}`:""));const{id:s,groupId:a="",name:o,type:l,url:h}=n;this.hls.trigger(ri.SUBTITLE_TRACK_SWITCH,{id:s,groupId:a,name:o,type:l,url:h});const c=this.switchParams(n.url,null==i?void 0:i.details,n.details);this.loadPlaylist(c)}},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(ri.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(ri.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(ri.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ri.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(ri.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(ri.FRAG_LOADING,this.onFragLoading,this),t.on(ri.FRAG_LOADED,this.onFragLoaded,this),t.on(ri.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(ri.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(ri.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(ri.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(ri.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(ri.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(ri.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(ri.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ri.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(ri.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(ri.FRAG_LOADING,this.onFragLoading,this),t.off(ri.FRAG_LOADED,this.onFragLoaded,this),t.off(ri.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(ri.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(ri.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(ri.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(ri.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const t=new Rc(this,"textTrack1"),e=new Rc(this,"textTrack2"),i=new Rc(this,"textTrack3"),n=new Rc(this,"textTrack4");this.cea608Parser1=new tc(1,t,e),this.cea608Parser2=new tc(3,i,n)}addCues(t,e,i,n,r){let s=!1;for(let t=r.length;t--;){const n=r[t],a=Dc(n[0],n[1],e,i);if(a>=0&&(n[0]=Math.min(n[0],e),n[1]=Math.max(n[1],i),s=!0,a/(i-e)>.5))return}if(s||r.push([e,i]),this.config.renderTextTracksNatively){const r=this.captionsTracks[t];this.Cues.newCue(r,e,i,n)}else{const r=this.Cues.newCue(null,e,i,n);this.hls.trigger(ri.CUES_PARSED,{type:"captions",cues:r,track:t})}}onInitPtsFound(t,{frag:e,id:i,initPTS:n,timescale:r,trackId:s}){const{unparsedVttFrags:a}=this;i===hi&&(this.initPTS[e.cc]={baseTime:n,timescale:r,trackId:s}),a.length&&(this.unparsedVttFrags=[],a.forEach(t=>{this.initPTS[t.frag.cc]?this.onFragLoaded(ri.FRAG_LOADED,t):this.hls.trigger(ri.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(t,e){const{media:i}=this;if(i)for(let n=0;n<i.textTracks.length;n++){const r=i.textTracks[n];if(Pc(r,{name:t,lang:e,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))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:i,media:n}=this,{label:r,languageCode:s}=e[t],a=this.getExistingTrack(r,s);if(a)i[t]=a,Ah(i[t]),vh(i[t],n);else{const e=this.createTextTrack("captions",r,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(ri.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(t,e,i){const n=this.media;if(n)return n.addTextTrack(t,e,i)}onMediaAttaching(t,e){this.media=e.media,e.mediaSource||this._cleanTracks()}onMediaDetaching(t,e){const i=!!e.transferMedia;if(this.media=null,i)return;const{captionsTracks:n}=this;Object.keys(n).forEach(t=>{Ah(n[t]),delete n[t]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:t}=this;if(!t)return;const e=t.textTracks;if(e)for(let t=0;t<e.length;t++)Ah(e[t])}onSubtitleTracksUpdated(t,e){const i=e.subtitleTracks||[],n=i.some(t=>t.textCodec===vc);if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if(ol(this.tracks,i))return void(this.tracks=i);if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const t=this.media,e=t?Th(t.textTracks):null;if(this.tracks.forEach((t,i)=>{let n;if(e){let i=null;for(let n=0;n<e.length;n++)if(e[n]&&Pc(e[n],t)){i=e[n],e[n]=null;break}i&&(n=i)}if(n)Ah(n);else{const e=Cc(t);n=this.createTextTrack(e,t.name,t.lang),n&&(n.mode="disabled")}n&&this.textTracks.push(n)}),null!=e&&e.length){const t=e.filter(t=>null!==t).map(t=>t.label);t.length&&this.hls.logger.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(ri.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]}`,n=this.captionsProperties[i];n&&(n.label=t.name,t.lang&&(n.languageCode=t.lang),n.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===hi){var i,n;const{cea608Parser1:t,cea608Parser2:r,lastSn:s}=this,{cc:a,sn:o}=e.frag,l=null!=(i=null==(n=e.part)?void 0:n.index)?i:-1;t&&r&&(o!==s+1||o===s&&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:i,payload:n}=e;if(i.type===ui)if(n.byteLength){const t=i.decryptdata,r="stats"in e;if(null==t||!t.encrypted||r){const t=this.tracks[i.level],r=this.vttCCs;r[i.cc]||(r[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),t&&t.textCodec===vc?this._parseIMSC1(i,n):this._parseVTTs(e)}}else this.hls.trigger(ri.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,e){const i=this.hls;Tc(e,this.initPTS[t.cc],e=>{this._appendCues(e,t.level),i.trigger(ri.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},e=>{i.logger.log(`Failed to parse IMSC1: ${e}`),i.trigger(ri.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:e})})}_parseVTTs(t){var e;const{frag:i,payload:n}=t,{initPTS:r,unparsedVttFrags:s}=this,a=r.length-1;if(!r[i.cc]&&-1===a)return void s.push(t);const o=this.hls;mc(null!=(e=i.initSegment)&&e.data?ln(i.initSegment.data,new Uint8Array(n)).buffer:n,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,t=>{this._appendCues(t,i.level),o.trigger(ri.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},e=>{const r="Missing initPTS for VTT MPEGTS"===e.message;r?s.push(t):this._fallbackToIMSC1(i,n),o.logger.log(`Failed to parse VTT cue: ${e}`),r&&a>i.cc||o.trigger(ri.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:e})})}_fallbackToIMSC1(t,e){const i=this.tracks[t.level];i.textCodec||Tc(e,this.initPTS[t.cc],()=>{i.textCodec=vc,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=>yh(i,t))}else{const n=this.tracks[e];if(!n)return;const r=n.default?"default":"subtitles"+e;i.trigger(ri.CUES_PARSED,{type:"subtitles",cues:t,track:r})}}onFragDecrypted(t,e){const{frag:i}=e;i.type===ui&&this.onFragLoaded(ri.FRAG_LOADED,e)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,e){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:i,samples:n}=e;if(i.type!==hi||"NONE"!==this.closedCaptionsForLevel(i))for(let t=0;t<n.length;t++){const e=n[t].bytes;if(e){this.cea608Parser1||this.initCea608Parsers();const i=this.extractCea608Data(e);this.cea608Parser1.addData(n[t].pts,i[0]),this.cea608Parser2.addData(n[t].pts,i[1])}}}onBufferFlushing(t,{startOffset:e,endOffset:i,endOffsetSubtitles:n,type:r}){const{media:s}=this;if(s&&!(s.currentTime<i)){if(!r||"video"===r){const{captionsTracks:t}=this;Object.keys(t).forEach(n=>Eh(t[n],e,i))}if(this.config.renderTextTracksNatively&&0===e&&void 0!==n){const{textTracks:t}=this;Object.keys(t).forEach(i=>Eh(t[i],e,n))}}}extractCea608Data(t){const e=[[],[]],i=31&t[0];let n=2;for(let r=0;r<i;r++){const i=t[n++],r=127&t[n++],s=127&t[n++];if(0===r&&0===s)continue;if(!!(4&i)){const t=3&i;0!==t&&1!==t||(e[t].push(r),e[t].push(s))}}return e}},audioStreamController:class extends La{constructor(t,e,i){super(t,e,i,"audio-stream-controller",ci),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(ri.LEVEL_LOADED,this.onLevelLoaded,this),t.on(ri.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(ri.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(ri.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(ri.BUFFER_RESET,this.onBufferReset,this),t.on(ri.BUFFER_CREATED,this.onBufferCreated,this),t.on(ri.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(ri.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(ri.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(ri.FRAG_LOADING,this.onFragLoading,this),t.on(ri.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:t}=this;t&&(super.unregisterListeners(),t.off(ri.LEVEL_LOADED,this.onLevelLoaded,this),t.off(ri.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(ri.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(ri.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(ri.BUFFER_RESET,this.onBufferReset,this),t.off(ri.BUFFER_CREATED,this.onBufferCreated,this),t.off(ri.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(ri.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(ri.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(ri.FRAG_LOADING,this.onFragLoading,this),t.off(ri.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(t,{frag:e,id:i,initPTS:n,timescale:r,trackId:s}){if(i===hi){const t=e.cc,i=this.fragCurrent;if(this.initPTS[t]={baseTime:n,timescale:r,trackId:s},this.log(`InitPTS for cc: ${t} found from main: ${n/r} (${n}/${r}) trackId: ${s}`),this.mainAnchor=e,this.state===ka){const i=this.waitingData;(!i&&!this.loadingParts||i&&i.frag.cc!==t)&&this.syncWithAnchor(e,null==i?void 0:i.frag)}else!this.hls.hasEnoughToStart&&i&&i.cc!==t?(i.abortRequests(),this.syncWithAnchor(e,i)):this.state===pa&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(t,e){var i;const n=(null==(i=this.mainFragLoading)?void 0:i.frag)||null;if(e&&(null==n?void 0:n.cc)===e.cc)return;const r=(n||t).cc,s=lr(this.getLevelDetails(),r,this.getLoadPosition());s&&(this.log(`Syncing with main frag at ${s.start} cc ${s.cc}`),this.startFragRequested=!1,this.nextLoadPosition=s.start,this.resetLoadingState(),this.state===pa&&this.doTickIdle())}startLoad(t,e){if(!this.levels)return this.startPosition=t,void(this.state=ga);const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),i>0&&-1===t?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),t=i,this.state=pa):this.state=Aa,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}doTick(){switch(this.state){case pa:this.doTickIdle();break;case Aa:{const{levels:t,trackId:e}=this,i=null==t?void 0:t[e],n=null==i?void 0:i.details;if(n&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(n))break;this.state=ka}break}case ya:this.checkRetryDate();break;case ka:{const t=this.waitingData;if(t){const{frag:e,part:i,cache:n,complete:r}=t,s=this.mainAnchor;if(void 0!==this.initPTS[e.cc]){this.waitingData=null,this.state=va;const t={frag:e,part:i,payload:n.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(t),r&&super._handleFragmentLoadComplete(t)}else s&&s.cc!==t.frag.cc&&this.syncWithAnchor(s,t.frag)}else this.state=pa}}this.onTickEnd()}resetLoadingState(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:t}=this;null!=t&&t.readyState&&(this.lastCurrentTime=t.currentTime)}doTickIdle(){var t;const{hls:e,levels:i,media:n,trackId:r}=this,s=e.config;if(!this.buffering||!n&&!this.primaryPrefetch&&(this.startFragRequested||!s.startFragPrefetch)||null==i||!i[r])return;const a=i[r],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o))return this.state=Aa,void(this.startFragRequested=!1);const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,Mi,ci));const h=this.getFwdBufferInfo(l,ci);if(null===h)return;if(!this.switchingTrack&&this._streamEnded(h,o))return e.trigger(ri.BUFFER_EOS,{type:"audio"}),void(this.state=ba);const c=h.len,u=e.maxBufferLength,d=o.fragments,f=d[0].start,g=this.getLoadPosition(),p=this.flushing?g:h.end;if(this.switchingTrack&&n){const t=g;o.PTSKnown&&t<f&&(h.end>f||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),n.currentTime=f+.05)}if(c>=u&&!this.switchingTrack&&p<d[d.length-1].start)return;let m=this.getNextFragment(p,o);if(m&&this.isLoopLoading(m,p)&&(m=this.getNextFragmentLoopLoading(m,o,h,hi,u)),!m)return void(this.bufferFlushed=!0);if(this.exceedsMaxBuffer(h,u,m))return;let v=(null==(t=this.mainFragLoading)?void 0:t.frag)||null;if(!this.audioOnly&&this.startFragRequested&&v&&Ui(m)&&!m.endList&&(!o.live||!this.loadingParts&&p<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(v)===Cr&&(this.mainFragLoading=v=null),v&&Ui(v))){if(m.start>v.end){const t=this.fragmentTracker.getFragAtPos(p,hi);t&&t.end>v.end&&(v=t,this.mainFragLoading={frag:t,targetBufferTime:null})}if(m.start>v.end)return}this.loadFragment(m,a,p)}onMediaDetaching(t,e){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(t,e)}onAudioTracksUpdated(t,{audioTracks:e}){this.resetTransmuxer(),this.levels=e.map(t=>new jn(t))}onAudioTrackSwitching(t,e){const i=!!e.url;this.trackId=e.id;const{fragCurrent:n}=this;n&&(n.abortRequests(),this.removeUnbufferedFrags(n.start)),this.resetLoadingState(),i?(this.switchingTrack=e,this.flushAudioIfNeeded(e),this.state!==ga&&(this.setInterval(100),this.state=pa,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=e,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(t,e){this.mainDetails=e.details;const i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(ri.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(t,e){var i;const{levels:n}=this,{details:r,id:s,groupId:a,track:o}=e;if(!n)return void this.warn(`Audio tracks reset while loading track ${s} "${o.name}" of "${a}"`);const l=this.mainDetails;if(!l||r.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=e,void(this.state!==ga&&(this.state=Aa));this.cachedTrackLoadedData=null,this.log(`Audio track ${s} "${o.name}" of "${a}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const h=n[s];let c=0;if(r.live||null!=(i=h.details)&&i.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;var u;if(h.details)c=this.alignPlaylists(r,h.details,null==(u=this.levelLastLoaded)?void 0:u.details);r.alignedSliding||(ha(r,l),r.alignedSliding||ca(r,l),c=r.fragmentStart)}h.details=r,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(l,c),this.hls.trigger(ri.AUDIO_TRACK_UPDATED,{details:r,id:s,groupId:e.groupId}),this.state!==Aa||this.waitForCdnTuneIn(r)||(this.state=pa),this.tick()}_handleFragmentLoadProgress(t){var e;const i=t.frag,{part:n,payload:r}=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 h=l.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(i.start);const c=s.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let u=this.transmuxer;u||(u=this.transmuxer=new sl(this.hls,ci,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=n?n.index:-1,s=-1!==e,a=new jr(i.level,i.sn,i.stats.chunkCount,r.byteLength,e,s);u.push(r,f,c,"",i,n,h.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 [${h.startSN} ,${h.endSN}],track ${a}`);const{cache:t}=this.waitingData=this.waitingData||{frag:i,part:n,cache:new Ra,complete:!1};t.push(new Uint8Array(r)),this.state!==ga&&(this.state=ka)}}_handleFragmentLoadComplete(t){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(t,e){this.bufferFlushed=this.flushing=!1;const i=e.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(t,e){!this.audioOnly&&e.frag.type===hi&&Ui(e.frag)&&(this.mainFragLoading=e,this.state===pa&&this.tick())}onFragBuffered(t,e){const{frag:i,part:n}=e;if(i.type===ci)if(this.fragContextChanged(i))this.warn(`Fragment ${i.sn}${n?" p: "+n.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if(Ui(i)){this.fragPrevious=i;const t=this.switchingTrack;t&&(this.bufferedTrack=t,this.switchingTrack=null,this.hls.trigger(ri.AUDIO_TRACK_SWITCHED,vi({},t)))}this.fragBufferedComplete(i,n),this.media&&this.tick()}else this.audioOnly||i.type!==hi||i.elementaryStreams.video||i.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}onError(t,e){var i;if(e.fatal)this.state=Sa;else switch(e.details){case ni.FRAG_GAP:case ni.FRAG_PARSING_ERROR:case ni.FRAG_DECRYPT_ERROR:case ni.FRAG_LOAD_ERROR:case ni.FRAG_LOAD_TIMEOUT:case ni.KEY_LOAD_ERROR:case ni.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(ci,e);break;case ni.AUDIO_TRACK_LOAD_ERROR:case ni.AUDIO_TRACK_LOAD_TIMEOUT:case ni.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==Aa||(null==(i=e.context)?void 0:i.type)!==oi||(this.state=pa);break;case ni.BUFFER_ADD_CODEC_ERROR:case ni.BUFFER_APPEND_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)||this.resetLoadingState();break;case ni.BUFFER_FULL_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case ni.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onBufferFlushing(t,{type:e}){e!==Ni&&(this.flushing=!0)}onBufferFlushed(t,{type:e}){if(e!==Ni){this.flushing=!1,this.bufferFlushed=!0,this.state===ba&&(this.state=pa);const t=this.mediaBuffer||this.media;t&&(this.afterBufferFlushed(t,e,ci),this.tick())}}_handleTransmuxComplete(t){var e;const i="audio",{hls:n}=this,{remuxResult:r,chunkMeta:s}=t,a=this.getCurrentContext(s);if(!a)return void this.resetWhenMissingContext(s);const{frag:o,part:l,level:h}=a,{details:c}=h,{audio:u,text:d,id3:f,initSegment:g}=r;if(!this.fragContextChanged(o)&&c){if(this.state=Ea,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),null!=g&&g.tracks){const t=o.initSegment||o;if(this.unhandledEncryptionError(g,o))return;this._bufferInitSegment(h,g.tracks,t,s),n.trigger(ri.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:i,tracks:g.tracks})}if(u){const{startPTS:t,endPTS:e,startDTS:i,endDTS:n}=u;l&&(l.elementaryStreams[Mi]={startPTS:t,endPTS:e,startDTS:i,endDTS:n}),o.setElementaryStreamInfo(Mi,t,e,i,n),this.bufferFragmentData(u,o,l,s)}if(null!=f&&null!=(e=f.samples)&&e.length){const t=pi({id:i,frag:o,details:c},f);n.trigger(ri.FRAG_PARSING_METADATA,t)}if(d){const t=pi({id:i,frag:o,details:c},d);n.trigger(ri.FRAG_PARSING_USERDATA,t)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(t,e,i,n){if(this.state!==Ea)return;if(e.video&&delete e.video,e.audiovideo&&delete e.audiovideo,!e.audio)return;const r=e.audio;r.id=ci;const s=t.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${s}/${r.codec}]`),s&&1===s.split(",").length&&(r.levelCodec=s),this.hls.trigger(ri.BUFFER_CODECS,e);const a=r.initSegment;if(null!=a&&a.byteLength){const t={type:"audio",frag:i,part:null,chunkMeta:n,parent:i.type,data:a};this.hls.trigger(ri.BUFFER_APPENDING,t)}this.tickImmediate()}loadFragment(t,e,i){const n=this.fragmentTracker.getState(t);var r;if(this.switchingTrack||n===Lr||n===Rr)if(Ui(t))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=ka;const i=this.mainDetails;i&&i.fragmentStart!==e.details.fragmentStart&&ca(e.details,i)}else super.loadFragment(t,e,i);else this._loadInitSegment(t,e);else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){if(this.media&&this.bufferedTrack){const{name:e,lang:i,assocLang:n,characteristics:r,audioCodec:s,channels:a}=this.bufferedTrack;tr({name:e,lang:i,assocLang:n,characteristics:r,audioCodec:s,channels:a},t,er)||(nr(t.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=t)}}completeAudioSwitch(t){const{hls:e}=this;this.flushAudioIfNeeded(t),this.bufferedTrack=t,this.switchingTrack=null,e.trigger(ri.AUDIO_TRACK_SWITCHED,vi({},t))}},audioTrackController:class extends al{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(ri.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ri.MANIFEST_PARSED,this.onManifestParsed,this),t.on(ri.LEVEL_LOADING,this.onLevelLoading,this),t.on(ri.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(ri.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(ri.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(ri.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ri.MANIFEST_PARSED,this.onManifestParsed,this),t.off(ri.LEVEL_LOADING,this.onLevelLoading,this),t.off(ri.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(ri.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(ri.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:n,details:r}=e,s=this.tracksInGroup[i];if(!s||s.groupId!==n)return void this.warn(`Audio track with id:${i} and group:${n} 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:${n} loaded [${r.startSN}-${r.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,n=this.groupIds;let r=this.currentTrack;if(!i||(null==n?void 0:n.length)!==(null==i?void 0:i.length)||null!=i&&i.some(t=>-1===(null==n?void 0:n.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(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.audioPreference;if(!r&&e){const i=Jn(e,t,er);if(i>-1)r=t[i];else{const t=Jn(e,this.tracks);r=this.tracks[t]}}let n=this.findTrackId(r);-1===n&&r&&(n=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(ri.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==n&&-1===o)this.setAudioTrack(n);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(ri.ERROR,{type:ii.MEDIA_ERROR,details:ni.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:e})}}}onError(t,e){!e.fatal&&e.context&&(e.context.type!==oi||e.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||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 n=this.currentTrack;if(n&&tr(t,n,er))return n;const r=Jn(t,this.tracksInGroup,er);if(r>-1){const t=this.tracksInGroup[r];return this.setAudioTrack(r),t}if(n){let n=e.loadLevel;-1===n&&(n=e.firstAutoLevel);const r=function(t,e,i,n,r){const s=e[n],a=e.reduce((t,e,i)=>{const n=e.uri;return(t[n]||(t[n]=[])).push(i),t},{}),o=a[s.uri];o.length>1&&(n=Math.max.apply(Math,o));const l=s.videoRange,h=s.frameRate,c=s.codecSet.substring(0,4),u=ir(e,n,e=>{if(e.videoRange!==l||e.frameRate!==h||e.codecSet.substring(0,4)!==c)return!1;const n=e.audioGroups,s=i.filter(t=>!n||-1!==n.indexOf(t.groupId));return Jn(t,s,r)>-1});return u>-1?u:ir(e,n,e=>{const n=e.audioGroups,s=i.filter(t=>!n||-1!==n.indexOf(t.groupId));return Jn(t,s,r)>-1})}(t,e.levels,i,n,er);if(-1===r)return null;e.nextLoadLevel=r}if(t.channels||t.audioCodec){const e=Jn(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.selectDefaultTrack=!1;const i=this.currentTrack,n=e[t],r=n.details&&!n.details.live;if(t===this.trackId&&n===i&&r)return;if(this.log(`Switching to audio-track ${t} "${n.name}" lang:${n.lang} group:${n.groupId} channels:${n.channels}`),this.trackId=t,this.currentTrack=n,this.hls.trigger(ri.AUDIO_TRACK_SWITCHING,vi({},n)),r)return;const s=this.switchParams(n.url,null==i?void 0:i.details,n.details);this.loadPlaylist(s)}findTrackId(t){const e=this.tracksInGroup;for(let i=0;i<e.length;i++){const n=e[i];if((!this.selectDefaultTrack||n.default)&&(!t||tr(t,n,er)))return i}if(t){const{name:i,lang:n,assocLang:r,characteristics:s,audioCodec:a,channels:o}=t;for(let t=0;t<e.length;t++){if(tr({name:i,lang:n,assocLang:r,characteristics:s,audioCodec:a,channels:o},e[t],er))return t}for(let i=0;i<e.length;i++){const n=e[i];if(ll(t.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<e.length;i++){const n=e[i];if(ll(t.attrs,n.attrs,["LANGUAGE"]))return i}}return-1}loadPlaylist(t){super.loadPlaylist();const e=this.currentTrack;this.shouldLoadPlaylist(e)&&nr(e.url,this.hls)&&this.scheduleLoading(e,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const i=t.id,n=t.groupId,r=this.getUrlWithDirectives(t.url,e),s=t.details,a=null==s?void 0:s.age;this.log(`Loading audio-track ${i} "${t.name}" lang:${t.lang} group:${n}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${a&&s.live?" age "+a.toFixed(1)+(s.type&&" "+s.type||""):""} ${r}`),this.hls.trigger(ri.AUDIO_TRACK_LOADING,{url:r,id:i,groupId:n,deliveryDirectives:e||null,track:t})}},emeController:dh,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:vl.MANIFEST,su:!this.initialized})}catch(t){this.hls.logger.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=t=>{try{const{frag:e,part:i}=t,n=this.hls.levels[e.level],r=this.getObjectType(e),s={d:1e3*(i||e).duration,ot:r};r!==vl.VIDEO&&r!==vl.AUDIO&&r!=vl.MUXED||(s.br=n.bitrate/1e3,s.tb=this.getTopBandwidth(r)/1e3,s.bl=this.getBufferLength(r));const a=i?this.getNextPart(i):this.getNextFrag(e);null!=a&&a.url&&a.url!==e.url&&(s.nor=a.url),this.apply(t,s)}catch(t){this.hls.logger.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||t.sessionId,this.cid=i.contentId,this.useHeaders=!0===i.useHeaders,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const t=this.hls;t.on(ri.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(ri.MEDIA_DETACHED,this.onMediaDetached,this),t.on(ri.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(ri.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(ri.MEDIA_DETACHED,this.onMediaDetached,this),t.off(ri.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(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,n;this.audioBuffer=null==(i=e.tracks.audio)?void 0:i.buffer,this.videoBuffer=null==(n=e.tracks.video)?void 0:n.buffer}createData(){var t;return{v:1,sf:yl.HLS,sid:this.sid,cid:this.cid,pr:null==(t=this.media)?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,e={}){pi(e,this.createData());const i=e.ot===vl.INIT||e.ot===vl.VIDEO||e.ot===vl.MUXED;this.starved&&i&&(e.bs=!0,e.su=!0,this.starved=!1),null==e.su&&(e.su=this.buffering);const{includeKeys:n}=this;n&&(e=Object.keys(e).reduce((t,i)=>(n.includes(i)&&(t[i]=e[i]),t),{}));const r={baseUrl:t.url};this.useHeaders?(t.headers||(t.headers={}),ah(t.headers,e,r)):t.url=hh(t.url,e,r)}getNextFrag(t){var e;const i=null==(e=this.hls.levels[t.level])?void 0:e.details;if(i){const e=t.sn-i.startSN;return i.fragments[e+1]}}getNextPart(t){var e;const{index:i,fragment:n}=t,r=null==(e=this.hls.levels[n.level])||null==(e=e.details)?void 0:e.partList;if(r){const{sn:t}=n;for(let e=r.length-1;e>=0;e--){const n=r[e];if(n.index===i&&n.fragment.sn===t)return r[e+1]}}}getObjectType(t){const{type:e}=t;return"subtitle"===e?vl.TIMED_TEXT:"initSegment"===t.sn?vl.INIT:"audio"===e?vl.AUDIO:"main"===e?this.hls.audioTracks.length?vl.VIDEO:vl.MUXED:void 0}getTopBandwidth(t){let e,i=0;const n=this.hls;if(t===vl.AUDIO)e=n.audioTracks;else{const t=n.maxAutoLevel,i=t>-1?t+1:n.levels.length;e=n.levels.slice(0,i)}return e.forEach(t=>{t.bitrate>i&&(i=t.bitrate)}),i>0?i:NaN}getBufferLength(t){const e=this.media,i=t===vl.AUDIO?this.audioBuffer:this.videoBuffer;if(!i||!e)return NaN;return 1e3*zr.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,n){e(t),this.loader.load(t,i,n)}}}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,n){e(t),this.loader.load(t,i,n)}}}},contentSteeringController:class extends yi{constructor(t){super("content-steering",t.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(ri.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ri.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(ri.MANIFEST_PARSED,this.onManifestParsed,this),t.on(ri.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(ri.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ri.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(ri.MANIFEST_PARSED,this.onManifestParsed,this),t.off(ri.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((t,e)=>(-1===t.indexOf(e.pathwayId)&&t.push(e.pathwayId),t),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(t){this.updatePathwayPriority(t)}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)===yr&&i.flags===br){const t=this.levels;let n=this._pathwayPriority,r=this.pathwayId;if(e.context){const{groupId:i,pathwayId:n,type:s}=e.context;i&&t?r=this.getPathwayForGroupId(i,s,r):n&&(r=n)}r in this.penalizedPathways||(this.penalizedPathways[r]=performance.now()),!n&&t&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),i.resolved=this.pathwayId!==r),e.details!==ni.BUFFER_APPEND_ERROR||e.fatal?i.resolved||this.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${r} levels: ${t?t.length:t} priorities: ${qn(n)} penalized: ${qn(this.penalizedPathways)}`):i.resolved=!0}}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}getLevelsForPathway(t){return null===this.levels?[]:this.levels.filter(e=>t===e.pathwayId)}updatePathwayPriority(t){let e;this._pathwayPriority=t;const i=this.penalizedPathways,n=performance.now();Object.keys(i).forEach(t=>{n-i[t]>3e5&&delete i[t]});for(let n=0;n<t.length;n++){const r=t[n];if(r in i)continue;if(r===this.pathwayId)return;const s=this.hls.nextLoadLevel,a=this.hls.levels[s];if(e=this.getLevelsForPathway(r),e.length>0){this.log(`Setting Pathway to "${r}"`),this.pathwayId=r,na(e),this.hls.trigger(ri.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 n=this.getLevelsForPathway(i).concat(this.levels||[]);for(let i=0;i<n.length;i++)if(e===oi&&n[i].hasAudioGroup(t)||e===li&&n[i].hasSubtitleGroup(t))return n[i].pathwayId;return i}clonePathways(t){const e=this.levels;if(!e)return;const i={},n={};t.forEach(t=>{const{ID:r,"BASE-ID":s,"URI-REPLACEMENT":a}=t;if(e.some(t=>t.pathwayId===r))return;const o=this.getLevelsForPathway(s).map(t=>{const e=new is(t.attrs);e["PATHWAY-ID"]=r;const s=e.AUDIO&&`${e.AUDIO}_clone_${r}`,o=e.SUBTITLES&&`${e.SUBTITLES}_clone_${r}`;s&&(i[e.AUDIO]=s,e.AUDIO=s),o&&(n[e.SUBTITLES]=o,e.SUBTITLES=o);const l=uh(t.uri,e["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),h=new jn({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),ch(this.audioTracks,i,a,r),ch(this.subtitleTracks,n,a,r)})}loadSteeringManifest(t){const e=this.hls.config,i=e.loader;let n;this.loader&&this.loader.destroy(),this.loader=new i(e);try{n=new self.URL(t)}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${t}`)}if("data:"!==n.protocol){const t=0|(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate);n.searchParams.set("_HLS_pathway",this.pathwayId),n.searchParams.set("_HLS_throughput",""+t)}const r={responseType:"json",url:n.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,r)=>{this.log(`Loaded steering manifest: "${n}"`);const s=t.data;if(1!==(null==s?void 0: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,n).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 h={steeringManifest:s,url:n.toString()};this.hls.trigger(ri.STEERING_MANIFEST_LOADED,h),l&&this.updatePathwayPriority(l)},onError:(t,e,i,n)=>{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){const t=this.loader;if("function"==typeof(null==t?void 0:t.getResponseHeader)){const e=t.getResponseHeader("Retry-After");e&&(r=1e3*parseFloat(e))}return void this.log(`Steering manifest ${e.url} rate limited`)}this.scheduleRefresh(this.uri||e.url,r)},onTimeout:(t,e,i)=>{this.log(`Timeout loading steering manifest (${e.url})`),this.scheduleRefresh(this.uri||e.url)}};this.log(`Requesting steering manifest: ${n}`),this.loader.load(r,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)}},interstitialsController:class extends yi{constructor(t,e){super("interstitials",t.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const t=this.currentTime;if(void 0===t||this.playbackDisabled||!this.schedule)return;const e=t-this.timelinePos;if(Math.abs(e)<1/7056e5)return;const i=e<=-.01;-1!==this.timelinePos||this.effectivePlayingItem||this.checkStart(),this.timelinePos=t,this.bufferedPos=t;const n=this.playingItem;if(!n)return void this.checkBuffer();if(i){this.schedule.resetErrorsInRange(t,t-e)&&this.updateSchedule(!0)}if(this.checkBuffer(),i&&t<n.start||t>=n.end){var r;const e=this.findItemIndex(n);let s=this.schedule.findItemIndexAtTime(t);if(-1===s&&(s=e+(i?-1:1),this.log(`seeked ${i?"back ":""}to position not covered by schedule ${t} (resolving from ${e} to ${s})`)),!this.isInterstitial(n)&&null!=(r=this.media)&&r.paused&&(this.shouldPlay=!1),!i&&s>e){const t=this.schedule.findJumpRestrictedIndex(e+1,s);if(t>e)return void this.setSchedulePosition(t)}return void this.setSchedulePosition(s)}const s=this.playingAsset;if(!s){if(this.playingLastItem&&this.isInterstitial(n)){const e=n.event.assetList[0];e&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(t,e))}return}const a=s.timelineStart,o=s.duration||0;var l;(i&&t<a||t>=a+o)&&(null!=(l=n.event)&&l.appendInPlace&&(this.clearAssetPlayers(n.event,n),this.flushFrontBuffer(t)),this.setScheduleToAssetAtTime(t,s))},this.onTimeupdate=()=>{const t=this.currentTime;if(void 0===t||this.playbackDisabled)return;if(-1!==this.timelinePos||this.effectivePlayingItem||this.checkStart(),!(t>this.timelinePos))return;this.timelinePos=t,t>this.bufferedPos&&this.checkBuffer();const e=this.playingItem;if(!e||this.playingLastItem)return;if(t>=e.end){this.timelinePos=e.end;const t=this.findItemIndex(e);this.setSchedulePosition(t+1)}const i=this.playingAsset;if(!i)return;t>=i.timelineStart+(i.duration||0)&&this.setScheduleToAssetAtTime(t,i)},this.onScheduleUpdate=(t,e)=>{const i=this.schedule;if(!i)return;const n=this.playingItem,r=i.events||[],s=i.items||[],a=i.durations,o=t.map(t=>t.identifier),l=!(!r.length&&!o.length);(l||e)&&this.log(`INTERSTITIALS_UPDATED (${r.length}): ${r}\nSchedule: ${s.map(t=>Oh(t))} pos: ${this.timelinePos}`),o.length&&this.log(`Removed events ${o}`);let h=null,c=null;n&&(h=this.updateItem(n,this.timelinePos),this.itemsMatch(n,h)?this.playingItem=h:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const u=this.bufferingItem;if(u&&(c=this.updateItem(u,this.bufferedPos),this.itemsMatch(u,c)?this.bufferingItem=c:u.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(u.event,null))),t.forEach(t=>{t.assetList.forEach(t=>{this.clearAssetPlayer(t.identifier,null)})}),this.playerQueue.forEach(t=>{if(t.interstitial.appendInPlace){const e=t.assetItem.timelineStart,i=t.timelineOffset-e;if(i)try{t.timelineOffset=e}catch(n){Math.abs(i)>Sh&&this.warn(`${n} ("${t.assetId}" ${t.timelineOffset}->${e})`)}}}),l||e){if(this.hls.trigger(ri.INTERSTITIALS_UPDATED,{events:r.slice(0),schedule:s.slice(0),durations:a,removedIds:o}),this.isInterstitial(n)&&o.includes(n.event.identifier))return this.warn(`Interstitial "${n.event.identifier}" removed while playing`),void this.primaryFallback(n.event);n&&this.trimInPlace(h,n),u&&c!==h&&this.trimInPlace(c,u),this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=e,this.assetListLoader=new xh(t),this.schedule=new wh(this.onScheduleUpdate,t.logger),this.registerListeners()}registerListeners(){const t=this.hls;t&&(t.on(ri.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(ri.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(ri.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(ri.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ri.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(ri.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(ri.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on(ri.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(ri.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on(ri.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on(ri.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on(ri.BUFFER_APPENDED,this.onBufferAppended,this),t.on(ri.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(ri.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on(ri.MEDIA_ENDED,this.onMediaEnded,this),t.on(ri.ERROR,this.onError,this),t.on(ri.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off(ri.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(ri.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(ri.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(ri.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ri.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(ri.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(ri.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off(ri.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(ri.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off(ri.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off(ri.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off(ri.BUFFER_CODECS,this.onBufferCodecs,this),t.off(ri.BUFFER_APPENDED,this.onBufferAppended,this),t.off(ri.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(ri.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off(ri.MEDIA_ENDED,this.onMediaEnded,this),t.off(ri.ERROR,this.onError,this),t.off(ri.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var t;null==(t=this.getBufferingPlayer())||t.resumeBuffering()}pauseBuffering(){var t;null==(t=this.getBufferingPlayer())||t.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const t=this.primaryMedia||this.media;t&&this.removeMediaListeners(t)}removeMediaListeners(t){da(t,"play",this.onPlay),da(t,"pause",this.onPause),da(t,"seeking",this.onSeeking),da(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,e){const i=this.media=e.media;ua(i,"seeking",this.onSeeking),ua(i,"timeupdate",this.onTimeupdate),ua(i,"play",this.onPlay),ua(i,"pause",this.onPause)}onMediaAttached(t,e){const i=this.effectivePlayingItem,n=this.detachedData;if(this.detachedData=null,null===i)this.checkStart();else if(!n){this.clearScheduleState();const t=this.findItemIndex(i);this.setSchedulePosition(t)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(t,e){const i=!!e.transferMedia,n=this.media;if(this.media=null,!i&&(n&&this.removeMediaListeners(n),this.detachedData)){const t=this.getBufferingPlayer();t&&(this.log(`Removing schedule state for detachedData and ${t}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,t.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const t=this,e=()=>t.bufferingItem||t.waitingItem,i=e=>e?t.getAssetPlayer(e.identifier):e,n=(e,n,s,a,o)=>{if(e){let l=e[n].start;const h=e.event;if(h){if("playout"===n||h.timelineOccupancy!==kh.Point){const t=i(s);(null==t?void 0:t.interstitial)===h&&(l+=t.assetItem.startOffset+t[o])}}else{l+=("bufferedPos"===a?r():t[a])-e.start}return l}return 0},r=()=>{const e=t.bufferedPos;return e===Number.MAX_VALUE?s("primary"):Math.max(e,0)},s=e=>{var i,n;return null!=(i=t.primaryDetails)&&i.live?t.primaryDetails.edge:(null==(n=t.schedule)?void 0:n.durations[e])||0},a=(e,r)=>{var s,a;const o=t.effectivePlayingItem;if(null!=o&&null!=(s=o.event)&&s.restrictions.skip||!t.schedule)return;t.log(`seek to ${e} "${r}"`);const l=t.effectivePlayingItem,h=t.schedule.findItemIndexAtTime(e,r),c=null==(a=t.schedule.items)?void 0:a[h],u=t.getBufferingPlayer(),d=null==u?void 0:u.interstitial,f=null==d?void 0:d.appendInPlace,g=l&&t.itemsMatch(l,c);if(l&&(f||g)){const s=i(t.playingAsset),a=(null==s?void 0:s.media)||t.primaryMedia;if(a){const i="primary"===r?a.currentTime:n(l,r,t.playingAsset,"timelinePos","currentTime"),o=e-i,h=(f?i:a.currentTime)+o;if(h>=0&&(!s||f||h<=s.duration))return void(a.currentTime=h)}}if(c){let i=e;if("primary"!==r){const t=e-c[r].start;i=c.start+t}const n=!t.isInterstitial(c);if(t.isInterstitial(l)&&!l.event.appendInPlace||!n&&!c.event.appendInPlace){if(l){const s=t.findItemIndex(l);if(h>s){const e=t.schedule.findJumpRestrictedIndex(s+1,h);if(e>s)return void t.setSchedulePosition(e)}let a=0;if(n)t.timelinePos=i,t.checkBuffer();else{const t=c.event.assetList,i=e-(c[r]||c).start;for(let e=t.length;e--;){const n=t[e];if(n.duration&&i>=n.startOffset&&i<n.startOffset+n.duration){a=e;break}}}t.setSchedulePosition(h,a)}}else{const e=t.media||(f?null==u?void 0:u.media:null);e&&(e.currentTime=i)}}},o=()=>{const i=t.effectivePlayingItem;if(t.isInterstitial(i))return i;const n=e();return t.isInterstitial(n)?n:null},l={get bufferedEnd(){const i=e(),r=t.bufferingItem;var s;return r&&r===i&&(n(r,"playout",t.bufferingAsset,"bufferedPos","bufferedEnd")-r.playout.start||(null==(s=t.bufferingAsset)?void 0:s.startOffset))||0},get currentTime(){const e=o(),i=t.effectivePlayingItem;return i&&i===e?n(i,"playout",t.effectivePlayingAsset,"timelinePos","currentTime")-i.playout.start:0},set currentTime(e){const i=o(),n=t.effectivePlayingItem;n&&n===i&&a(e+n.playout.start,"playout")},get duration(){const t=o();return t?t.playout.end-t.playout.start:0},get assetPlayers(){var e;const i=null==(e=o())?void 0:e.event.assetList;return i?i.map(e=>t.getAssetPlayer(e.identifier)):[]},get playingIndex(){var e;const i=null==(e=o())?void 0:e.event;return i&&t.effectivePlayingAsset?i.findAssetIndex(t.effectivePlayingAsset):-1},get scheduleItem(){return o()}};return this.manager={get events(){var e;return(null==(e=t.schedule)||null==(e=e.events)?void 0:e.slice(0))||[]},get schedule(){var e;return(null==(e=t.schedule)||null==(e=e.items)?void 0:e.slice(0))||[]},get interstitialPlayer(){return o()?l:null},get playerQueue(){return t.playerQueue.slice(0)},get bufferingAsset(){return t.bufferingAsset},get bufferingItem(){return e()},get bufferingIndex(){const i=e();return t.findItemIndex(i)},get playingAsset(){return t.effectivePlayingAsset},get playingItem(){return t.effectivePlayingItem},get playingIndex(){const e=t.effectivePlayingItem;return t.findItemIndex(e)},primary:{get bufferedEnd(){return r()},get currentTime(){const e=t.timelinePos;return e>0?e:0},set currentTime(t){a(t,"primary")},get duration(){return s("primary")},get seekableStart(){var e;return(null==(e=t.primaryDetails)?void 0:e.fragmentStart)||0}},integrated:{get bufferedEnd(){return n(e(),"integrated",t.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return n(t.effectivePlayingItem,"integrated",t.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(t){a(t,"integrated")},get duration(){return s("integrated")},get seekableStart(){var e;return((e,i)=>{var n;if(0!==e&&"primary"!==i&&null!=(n=t.schedule)&&n.length){var r;const n=t.schedule.findItemIndexAtTime(e),s=null==(r=t.schedule.items)?void 0:r[n];if(s)return e+(s[i].start-s.start)}return e})((null==(e=t.primaryDetails)?void 0:e.fragmentStart)||0,"integrated")}},skip:()=>{const e=t.effectivePlayingItem,i=null==e?void 0:e.event;if(i&&!i.restrictions.skip){const n=t.findItemIndex(e);if(i.appendInPlace){const t=e.playout.start+e.event.duration;a(t+.001,"playout")}else t.advanceAfterAssetEnded(i,n,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var t;const e=this.playingItem,i=null==(t=this.schedule)?void 0:t.items;return!!(this.playbackStarted&&e&&i)&&this.findItemIndex(e)===i.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var t,e;if(null===this.mediaSelection)return;const i=this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&!i.event.appendInPlace)return;let n=this.media;!n&&null!=(t=this.bufferingItem)&&null!=(t=t.event)&&t.appendInPlace&&(n=this.primaryMedia);const r=null==(e=n)?void 0:e.currentTime;return void 0!==r&&Je(r)?r:void 0}get primaryMedia(){var t;return this.media||(null==(t=this.detachedData)?void 0:t.media)||null}isInterstitial(t){return!(null==t||!t.event)}retreiveMediaSource(t,e){const i=this.getAssetPlayer(t);i&&this.transferMediaFromPlayer(i,e)}transferMediaFromPlayer(t,e){const i=t.interstitial.appendInPlace,n=t.media;if(i&&n===this.primaryMedia){if(this.bufferingAsset=null,(!e||this.isInterstitial(e)&&!e.event.appendInPlace)&&e&&n)return void(this.detachedData={media:n});const i=t.transferMedia();this.log(`transfer MediaSource from ${t} ${qn(i)}`),this.detachedData=i}else e&&n&&(this.shouldPlay||(this.shouldPlay=!n.paused))}transferMediaTo(t,e){var i,n;if(t.media===e)return;let r=null;const s=this.hls,a=t!==s,o=a&&t.interstitial.appendInPlace,l=null==(i=this.detachedData)?void 0:i.mediaSource;let h;if(s.media)o&&(r=s.transferMedia(),this.detachedData=r),h="Primary";else if(l){const t=this.getBufferingPlayer();t?(r=t.transferMedia(),h=`${t}`):h="detached MediaSource"}else h="detached media";if(!r)if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${qn(r)}`);else if(!this.detachedData||s.media===e){const t=this.playerQueue;t.length>1&&t.forEach(t=>{if(a&&t.interstitial.appendInPlace!==o){const e=t.interstitial;this.clearInterstitial(t.interstitial,null),e.appendInPlace=!1,e.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${e}`)}}),this.hls.detachMedia(),this.detachedData={media:e}}const c=r&&"mediaSource"in r&&"closed"!==(null==(n=r.mediaSource)?void 0:n.readyState),u=c&&r?r:e;this.log(`${c?"transfering MediaSource":"attaching media"} to ${a?t:"Primary"} from ${h} (media.currentTime: ${e.currentTime})`);const d=this.schedule;if(u===r&&d){const e=a&&t.assetId===d.assetIdAtEnd;u.overrides={duration:d.duration,endOfStream:!a||e,cueRemoval:!a}}t.attachMedia(u)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const t=this.schedule,e=null==t?void 0:t.events;if(!e||this.playbackDisabled||!this.media)return;-1===this.bufferedPos&&(this.bufferedPos=0);const i=this.timelinePos,n=this.effectivePlayingItem;if(-1===i){const i=this.hls.startPosition;if(this.timelinePos=i,0===e.length)this.setSchedulePosition(0);else if(e[0].cue.pre){this.log(Nh("checkStart (preroll)",i));const n=t.findEventIndex(e[0].identifier);this.setSchedulePosition(n)}else if(i>=0||!this.primaryLive){this.log(Nh("checkStart",i));const e=this.timelinePos=i>0?i:0,n=t.findItemIndexAtTime(e);this.setSchedulePosition(n)}else 0===this.hls.liveSyncPosition?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(n&&!this.playingItem){this.log(Nh("checkStart (playing item)",n.start));const e=t.findItemIndex(n);this.setSchedulePosition(e)}}advanceAssetBuffering(t,e){const i=t.event,n=i.findAssetIndex(e),r=Ch(i,n);if(i.isAssetPastPlayoutLimit(r)){if(this.schedule){var s;const e=null==(s=this.schedule.items)?void 0:s[this.findItemIndex(t)+1];e&&this.bufferedToItem(e)}}else this.bufferedToEvent(t,r)}advanceAfterAssetEnded(t,e,i){const n=Ch(t,i);if(t.isAssetPastPlayoutLimit(n)){if(this.schedule){const i=this.schedule.items;if(i){const n=e+1;if(n>=i.length)return void this.setSchedulePosition(-1);const r=t.resumeTime;this.timelinePos<r&&(this.log(Nh("advanceAfterAssetEnded",r)),this.timelinePos=r,t.appendInPlace&&this.advanceInPlace(r),this.checkBuffer(this.bufferedPos<r)),this.setSchedulePosition(n)}}}else{if(t.appendInPlace){const e=t.assetList[n];e&&this.advanceInPlace(e.timelineStart)}this.setSchedulePosition(e,n)}}setScheduleToAssetAtTime(t,e){const i=this.schedule;if(!i)return;const n=e.parentIdentifier,r=i.getEvent(n);if(r){const e=i.findEventIndex(n),s=i.findAssetIndex(r,t);this.advanceAfterAssetEnded(r,e,s-1)}}setSchedulePosition(t,e){var i;const n=null==(i=this.schedule)?void 0:i.items;if(!n||this.playbackDisabled)return;const r=t>=0?n[t]:null;this.log(`setSchedulePosition ${t}, ${e} (${r?Oh(r):r}) pos: ${this.timelinePos}`);const s=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(s)){const i=s.event,h=this.playingAsset,c=null==h?void 0:h.identifier,u=c?this.getAssetPlayer(c):null;if(u&&c&&(!this.eventItemsMatch(s,r)||void 0!==e&&c!==i.assetList[e].identifier)){var o;const e=i.findAssetIndex(h);if(this.log(`INTERSTITIAL_ASSET_ENDED ${e+1}/${i.assetList.length} ${Ph(h)}`),this.endedAsset=h,this.playingAsset=null,this.hls.trigger(ri.INTERSTITIAL_ASSET_ENDED,{asset:h,assetListIndex:e,event:i,schedule:n.slice(0),scheduleIndex:t,player:u}),s!==this.playingItem)return void(this.itemsMatch(s,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(i,this.findItemIndex(this.playingItem),e));this.retreiveMediaSource(c,r),!u.media||null!=(o=this.detachedData)&&o.mediaSource||u.detachMedia()}if(!this.eventItemsMatch(s,r)&&(this.endedItem=s,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${i} ${Oh(s)}`),i.hasPlayed=!0,this.hls.trigger(ri.INTERSTITIAL_ENDED,{event:i,schedule:n.slice(0),scheduleIndex:t}),i.cue.once)){var l;this.updateSchedule();const t=null==(l=this.schedule)?void 0:l.items;if(r&&t){const i=this.findItemIndex(r);this.advanceSchedule(i,t,e,s,a)}return}}this.advanceSchedule(t,n,e,s,a)}advanceSchedule(t,e,i,n,r){const s=this.schedule;if(!s)return;const a=e[t]||null,o=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(e=>{const i=e.interstitial,n=s.findEventIndex(i.identifier);(n<t||n>t+1)&&this.clearInterstitial(i,a)}),this.isInterstitial(a)){this.timelinePos=Math.min(Math.max(this.timelinePos,a.start),a.end);const r=a.event;if(void 0===i){const e=Ch(r,(i=s.findAssetIndex(r,this.timelinePos))-1);if(r.isAssetPastPlayoutLimit(e)||r.appendInPlace&&this.timelinePos===a.end)return void this.advanceAfterAssetEnded(r,t,i);i=e}const l=this.waitingItem;this.assetsBuffered(a,o)||this.setBufferingItem(a);let h=this.preloadAssets(r,i);if(this.eventItemsMatch(a,l||n)||(this.waitingItem=a,this.log(`INTERSTITIAL_STARTED ${Oh(a)} ${r.appendInPlace?"append in place":""}`),this.hls.trigger(ri.INTERSTITIAL_STARTED,{event:r,schedule:e.slice(0),scheduleIndex:t})),!r.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${r}`);if(r.assetListLoader&&(r.assetListLoader.destroy(),r.assetListLoader=void 0),!o)return void this.log(`Waiting for attachMedia to start Interstitial ${r}`);this.waitingItem=this.endedItem=null,this.playingItem=a;const c=r.assetList[i];if(!c)return void this.advanceAfterAssetEnded(r,t,i||0);if(h||(h=this.getAssetPlayer(c.identifier)),null===h||h.destroyed){const t=r.assetList.length;this.warn(`asset ${i+1}/${t} player destroyed ${r}`),h=this.createAssetPlayer(r,c,i),h.loadSource()}if(!this.eventItemsMatch(a,this.bufferingItem)&&r.appendInPlace&&this.isAssetBuffered(c))return;this.startAssetPlayer(h,i,e,t,o),this.shouldPlay&&Mh(h.media)}else a?(this.resumePrimary(a,t,n),this.shouldPlay&&Mh(this.hls.media)):r&&this.isInterstitial(n)&&(this.endedItem=null,this.playingItem=n,n.event.appendInPlace||this.attachPrimary(s.durations.primary,null))}get playbackDisabled(){return!1===this.hls.config.enableInterstitialPlayback}get primaryDetails(){var t;return null==(t=this.mediaSelection)?void 0:t.main.details}get primaryLive(){var t;return!(null==(t=this.primaryDetails)||!t.live)}resumePrimary(t,e,i){var n,r;if(this.playingItem=t,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(t),this.log(`resuming ${Oh(t)}`),null==(n=this.detachedData)||!n.mediaSource){let i=this.timelinePos;(i<t.start||i>=t.end)&&(i=this.getPrimaryResumption(t,e),this.log(Nh("resumePrimary",i)),this.timelinePos=i),this.attachPrimary(i,t)}if(!i)return;const s=null==(r=this.schedule)?void 0:r.items;s&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Oh(t)}`),this.hls.trigger(ri.INTERSTITIALS_PRIMARY_RESUMED,{schedule:s.slice(0),scheduleIndex:e}),this.checkBuffer())}getPrimaryResumption(t,e){const i=t.start;if(this.primaryLive){const t=this.primaryDetails;if(0===e)return this.hls.startPosition;if(t&&(i<t.fragmentStart||i>t.edge))return this.hls.liveSyncPosition||-1}return i}isAssetBuffered(t){const e=this.getAssetPlayer(t.identifier);if(null!=e&&e.hls)return e.hls.bufferedToEnd;return zr.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=t.timelineStart+(t.duration||0)}attachPrimary(t,e,i){e?this.setBufferingItem(e):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const n=this.primaryMedia;if(!n)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,n),i&&this.startLoadingPrimaryAt(t,i)),i||(this.log(Nh("attachPrimary",t)),this.timelinePos=t,this.startLoadingPrimaryAt(t,i))}startLoadingPrimaryAt(t,e){var i;const n=this.hls;!n.loadingEnabled||!n.media||Math.abs(((null==(i=n.mainForwardBufferInfo)?void 0:i.start)||n.media.currentTime)-t)>.5?n.startLoad(t,e):n.bufferingEnabled||n.resumeBuffering()}onManifestLoading(){var t;this.stopLoad(),null==(t=this.schedule)||t.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(ri.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(ri.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(t,e){if(-1===e.level||!this.schedule)return;const i=this.hls.levels[e.level];if(!i.details)return;const n=vi(vi({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=n,this.schedule.parseInterstitialDateRanges(n,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(t,e){const i=this.hls.audioTracks[e.id],n=this.mediaSelection;if(!n)return void(this.altSelection=vi(vi({},this.altSelection),{},{audio:i}));const r=vi(vi({},n),{},{audio:i});this.mediaSelection=r}onSubtitleTrackUpdated(t,e){const i=this.hls.subtitleTracks[e.id],n=this.mediaSelection;if(!n)return void(this.altSelection=vi(vi({},this.altSelection),{},{subtitles:i}));const r=vi(vi({},n),{},{subtitles:i});this.mediaSelection=r}onAudioTrackSwitching(t,e){const i=Zn(e);this.playerQueue.forEach(({hls:t})=>t&&(t.setAudioOption(e)||t.setAudioOption(i)))}onSubtitleTrackSwitch(t,e){const i=Zn(e);this.playerQueue.forEach(({hls:t})=>t&&(t.setSubtitleOption(e)||-1!==e.id&&t.setSubtitleOption(i)))}onBufferCodecs(t,e){const i=e.tracks;i&&(this.requiredTracks=i)}onBufferAppended(t,e){this.checkBuffer()}onBufferFlushed(t,e){const i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){const t=this.timelinePos;this.bufferedPos=t,this.checkBuffer()}}onBufferedToEnd(t){if(!this.schedule)return;const e=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&e){for(let t=0;t<e.length;t++){const n=e[t];if(n.cue.post){var i;const t=this.schedule.findEventIndex(n.identifier),e=null==(i=this.schedule.items)?void 0:i[t];this.isInterstitial(e)&&this.eventItemsMatch(e,this.bufferingItem)&&this.bufferedToItem(e,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(t){const e=this.playingItem;if(!this.playingLastItem&&e){const t=this.findItemIndex(e);this.setSchedulePosition(t+1)}else this.shouldPlay=!1}updateItem(t,e){var i;const n=null==(i=this.schedule)?void 0:i.items;if(t&&n){return n[this.findItemIndex(t,e)]||null}return null}trimInPlace(t,e){if(this.isInterstitial(t)&&t.event.appendInPlace&&e.end-t.end>.25){t.event.assetList.forEach((e,i)=>{t.event.isAssetPastPlayoutLimit(i)&&this.clearAssetPlayer(e.identifier,null)});const i=t.end+.25,n=zr.bufferInfo(this.primaryMedia,i,0);if(n.end>i||(n.nextStart||0)>i){this.log(`trim buffered interstitial ${Oh(t)} (was ${Oh(e)})`);const n=!0;this.attachPrimary(i,null,n),this.flushFrontBuffer(i)}}}itemsMatch(t,e){return!!e&&(t===e||t.event&&e.event&&this.eventItemsMatch(t,e)||!t.event&&!e.event&&this.findItemIndex(t)===this.findItemIndex(e))}eventItemsMatch(t,e){var i;return!!e&&(t===e||t.event.identifier===(null==(i=e.event)?void 0:i.identifier))}findItemIndex(t,e){return t&&this.schedule?this.schedule.findItemIndex(t,e):-1}updateSchedule(t=!1){var e;const i=this.mediaSelection;i&&(null==(e=this.schedule)||e.updateSchedule(i,[],t))}checkBuffer(t){var e;const i=null==(e=this.schedule)?void 0:e.items;if(!i)return;const n=zr.bufferInfo(this.primaryMedia,this.timelinePos,0);t&&(this.bufferedPos=this.timelinePos),t||(t=n.len<1),this.updateBufferedPos(n.end,i,t)}updateBufferedPos(t,e,i){const n=this.schedule,r=this.bufferingItem;if(this.bufferedPos>t||!n)return;if(1===e.length&&this.itemsMatch(e[0],r))return void(this.bufferedPos=t);const s=this.playingItem,a=this.findItemIndex(s);let o=n.findItemIndexAtTime(t);if(this.bufferedPos<t){var l;const i=this.findItemIndex(r),n=Math.min(i+1,e.length-1),s=e[n];if((-1===o&&r&&t>=r.end||null!=(l=s.event)&&l.appendInPlace&&t+.01>=s.start)&&(o=n),this.isInterstitial(r)){const t=r.event;if(n-a>1&&!1===t.appendInPlace)return;if(0===t.assetList.length&&t.assetListLoader)return}if(this.bufferedPos=t,o>i&&o>a)this.bufferedToItem(s);else{const e=this.primaryDetails;this.primaryLive&&e&&t>e.edge-e.targetduration&&s.start<e.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(s)&&this.preloadAssets(s.event,0)}}else i&&s&&!this.itemsMatch(s,r)&&(o===a?this.bufferedToItem(s):o===a+1&&this.bufferedToItem(e[o]))}assetsBuffered(t,e){return 0!==t.event.assetList.length&&!t.event.assetList.some(t=>{const i=this.getAssetPlayer(t.identifier);return!(null!=i&&i.bufferedInPlaceToEnd(e))})}setBufferingItem(t){const e=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(t,e)&&i){const{items:n,events:r}=i;if(!n||!r)return e;const s=this.isInterstitial(t),a=this.getBufferingPlayer();this.bufferingItem=t,this.bufferedPos=Math.max(t.start,Math.min(t.end,this.timelinePos));const o=a?a.remaining:e?e.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Oh(t)}`+(e?` (${o.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(s){const e=i.findAssetIndex(t.event,this.bufferedPos);t.event.assetList.forEach((t,i)=>{const n=this.getAssetPlayer(t.identifier);n&&(i===e&&n.loadSource(),n.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(t=>t.pauseBuffering());this.hls.trigger(ri.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:n.slice(0),bufferingIndex:this.findItemIndex(t),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==t&&(this.bufferingItem=t);return e}bufferedToItem(t,e=0){const i=this.setBufferingItem(t);if(!this.playbackDisabled)if(this.isInterstitial(t))this.bufferedToEvent(t,e);else if(null!==i){this.bufferingAsset=null;const e=this.detachedData;if(e)if(e.mediaSource){const e=!0;this.attachPrimary(t.start,t,e)}else this.preloadPrimary(t);else this.preloadPrimary(t)}}preloadPrimary(t){const e=this.findItemIndex(t),i=this.getPrimaryResumption(t,e);this.startLoadingPrimaryAt(i)}bufferedToEvent(t,e){const i=t.event,n=0===i.assetList.length&&!i.assetListLoader,r=i.cue.once;if(n||!r){const t=this.preloadAssets(i,e);if(null!=t&&t.interstitial.appendInPlace){const e=this.primaryMedia;e&&this.bufferAssetPlayer(t,e)}}}preloadAssets(t,e){const i=t.assetUrl,n=t.assetList.length,r=0===n&&!t.assetListLoader,s=t.cue.once;if(r){const r=t.timelineStart;if(t.appendInPlace){var a;const e=this.playingItem;this.isInterstitial(e)||(null==e||null==(a=e.nextEvent)?void 0:a.identifier)!==t.identifier||this.flushFrontBuffer(r+.25)}let s,o=0;if(!this.playingItem&&this.primaryLive&&(o=this.hls.startPosition,-1===o&&(o=this.hls.liveSyncPosition||0)),o&&!t.cue.pre&&!t.cue.post){const t=o-r;t>0&&(s=Math.round(1e3*t)/1e3)}if(this.log(`Load interstitial asset ${e+1}/${i?1:n} ${t}${s?` live-start: ${o} start-offset: ${s}`:""}`),i)return this.createAsset(t,0,0,r,t.duration,i);const l=this.assetListLoader.loadAssetList(t,s);l&&(t.assetListLoader=l)}else if(!s&&n){for(let i=e;i<n;i++){const e=t.assetList[i],n=this.getAssetPlayerQueueIndex(e.identifier);-1!==n&&!this.playerQueue[n].destroyed||e.error||this.createAssetPlayer(t,e,i)}const i=t.assetList[e];if(i){const t=this.getAssetPlayer(i.identifier);return t&&t.loadSource(),t}}return null}flushFrontBuffer(t){const e=this.requiredTracks;if(!e)return;this.log(`Removing front buffer starting at ${t}`);Object.keys(e).forEach(e=>{this.hls.trigger(ri.BUFFER_FLUSHING,{startOffset:t,endOffset:1/0,type:e})})}getAssetPlayerQueueIndex(t){const e=this.playerQueue;for(let i=0;i<e.length;i++)if(t===e[i].assetId)return i;return-1}getAssetPlayer(t){const e=this.getAssetPlayerQueueIndex(t);return this.playerQueue[e]||null}getBufferingPlayer(){const{playerQueue:t,primaryMedia:e}=this;if(e)for(let i=0;i<t.length;i++)if(t[i].media===e)return t[i];return null}createAsset(t,e,i,n,r,s){const a={parentIdentifier:t.identifier,identifier:_h(t,s,e),duration:r,startOffset:i,timelineStart:n,uri:s};return this.createAssetPlayer(t,a,e)}createAssetPlayer(t,e,i){const n=this.hls,r=n.userConfig;let s=r.videoPreference;const a=n.loadLevelObj||n.levels[n.currentLevel];(s||a)&&(s=pi({},s),a.videoCodec&&(s.videoCodec=a.videoCodec),a.videoRange&&(s.allowedVideoRanges=[a.videoRange]));const o=n.audioTracks[n.audioTrack],l=n.subtitleTracks[n.subtitleTrack];let h=0;if(this.primaryLive||t.appendInPlace){const t=this.timelinePos-e.timelineStart;if(t>1){const i=e.duration;i&&t<i&&(h=t)}}const c=e.identifier,u=vi(vi({},r),{},{maxMaxBufferLength:Math.min(180,n.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:n.sessionId,assetPlayerId:c,abrEwmaDefaultEstimate:n.bandwidthEstimate,interstitialsController:void 0,startPosition:h,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:s,audioPreference:o||r.audioPreference,subtitlePreference:l||r.subtitlePreference});t.appendInPlace&&(t.appendInPlaceStarted=!0,e.timelineStart&&(u.timelineOffset=e.timelineStart));const d=u.cmcd;null!=d&&d.sessionId&&d.contentId&&(u.cmcd=pi({},d,{contentId:bh(e.uri)})),this.getAssetPlayer(c)&&this.warn(`Duplicate date range identifier ${t} and asset ${c}`);const f=new Dh(this.HlsPlayerClass,u,t,e);this.playerQueue.push(f),t.assetList[i]=e;let g=!0;const p=n=>{if(n.live){var r;const e=new Error(`Interstitials MUST be VOD assets ${t}`),n={fatal:!0,type:ii.OTHER_ERROR,details:ni.INTERSTITIAL_ASSET_ITEM_ERROR,error:e},s=(null==(r=this.schedule)?void 0:r.findEventIndex(t.identifier))||-1;return void this.handleAssetItemError(n,t,s,i,e.message)}const s=n.edge-n.fragmentStart,a=e.duration;(g||null===a||s>a)&&(g=!1,this.log(`Interstitial asset "${c}" duration change ${a} > ${s}`),e.duration=s,this.updateSchedule())};f.on(ri.LEVEL_UPDATED,(t,{details:e})=>p(e)),f.on(ri.LEVEL_PTS_UPDATED,(t,{details:e})=>p(e)),f.on(ri.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const m=(t,e)=>{const i=this.getAssetPlayer(c);if(i&&e.tracks){i.off(ri.BUFFER_CODECS,m),i.tracks=e.tracks;const t=this.primaryMedia;this.bufferingAsset===i.assetItem&&t&&!i.media&&this.bufferAssetPlayer(i,t)}};f.on(ri.BUFFER_CODECS,m);f.on(ri.BUFFERED_TO_END,()=>{var i;const n=this.getAssetPlayer(c);if(this.log(`buffered to end of asset ${n}`),!n||!this.schedule)return;const r=this.schedule.findEventIndex(t.identifier),s=null==(i=this.schedule.items)?void 0:i[r];this.isInterstitial(s)&&this.advanceAssetBuffering(s,e)});const v=e=>()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;this.shouldPlay=!0;const i=this.schedule.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,i,e)};return f.once(ri.MEDIA_ENDED,v(i)),f.once(ri.PLAYOUT_LIMIT_REACHED,v(1/0)),f.on(ri.ERROR,(e,n)=>{if(!this.schedule)return;const r=this.getAssetPlayer(c);if(n.details===ni.BUFFER_STALLED_ERROR)return null!=r&&r.appendInPlace?void this.handleInPlaceStall(t):(this.onTimeupdate(),void this.checkBuffer(!0));this.handleAssetItemError(n,t,this.schedule.findEventIndex(t.identifier),i,`Asset player error ${n.error} ${t}`)}),f.on(ri.DESTROYING,()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;const e=new Error(`Asset player destroyed unexpectedly ${c}`),n={fatal:!0,type:ii.OTHER_ERROR,details:ni.INTERSTITIAL_ASSET_ITEM_ERROR,error:e};this.handleAssetItemError(n,t,this.schedule.findEventIndex(t.identifier),i,e.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Ph(e)}`),this.hls.trigger(ri.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:e,assetListIndex:i,event:t,player:f}),f}clearInterstitial(t,e){this.clearAssetPlayers(t,e),t.reset()}clearAssetPlayers(t,e){t.assetList.forEach(t=>{this.clearAssetPlayer(t.identifier,e)})}resetAssetPlayer(t){const e=this.getAssetPlayerQueueIndex(t);if(-1!==e){this.log(`reset asset player "${t}" after error`);const i=this.playerQueue[e];this.transferMediaFromPlayer(i,null),i.resetDetails()}}clearAssetPlayer(t,e){const i=this.getAssetPlayerQueueIndex(t);if(-1!==i){const t=this.playerQueue[i];this.log(`clear ${t} toSegment: ${e?Oh(e):e}`),this.transferMediaFromPlayer(t,e),this.playerQueue.splice(i,1),t.destroy()}}emptyPlayerQueue(){let t;for(;t=this.playerQueue.pop();)t.destroy();this.playerQueue=[]}startAssetPlayer(t,e,i,n,r){const{interstitial:s,assetItem:a,assetId:o}=t,l=s.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=a,h&&h.identifier===o||(h&&(this.clearAssetPlayer(h.identifier,i[n]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${e+1}/${l} ${Ph(a)}`),this.hls.trigger(ri.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:e,event:s,schedule:i.slice(0),scheduleIndex:n,player:t})),this.bufferAssetPlayer(t,r)}bufferAssetPlayer(t,e){var i,n;if(!this.schedule)return;const{interstitial:r,assetItem:s}=t,a=this.schedule.findEventIndex(r.identifier),o=null==(i=this.schedule.items)?void 0:i[a];if(!o)return;t.loadSource(),this.setBufferingItem(o),this.bufferingAsset=s;const l=this.getBufferingPlayer();if(l===t)return;const h=r.appendInPlace;if(h&&!1===(null==l?void 0:l.interstitial.appendInPlace))return;const c=(null==l?void 0:l.tracks)||(null==(n=this.detachedData)?void 0:n.tracks)||this.requiredTracks;if(h&&s!==this.playingAsset){if(!t.tracks)return void this.log(`Waiting for track info before buffering ${t}`);if(c&&!Li(c,t.tracks)){const e=new Error(`Asset ${Ph(s)} SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(c)}')`),i={fatal:!0,type:ii.OTHER_ERROR,details:ni.INTERSTITIAL_ASSET_ITEM_ERROR,error:e},n=r.findAssetIndex(s);return void this.handleAssetItemError(i,r,a,n,e.message)}}this.transferMediaTo(t,e)}handleInPlaceStall(t){const e=this.schedule,i=this.primaryMedia;if(!e||!i)return;const n=i.currentTime,r=e.findAssetIndex(t,n),s=t.assetList[r];if(s){const a=this.getAssetPlayer(s.identifier);if(a){const o=a.currentTime||n-s.timelineStart,l=a.duration-o;if(this.warn(`Stalled at ${o} of ${o+l} in ${a} ${t} (media.currentTime: ${n})`),o&&(l/i.playbackRate<.5||a.bufferedInPlaceToEnd(i))&&a.hls){const i=e.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,i,r)}}}}advanceInPlace(t){const e=this.primaryMedia;e&&e.currentTime<t&&(e.currentTime=t)}handleAssetItemError(t,e,i,n,r){if(t.details===ni.BUFFER_STALLED_ERROR)return;const s=e.assetList[n]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${s?Ph(s):s} ${t.error}`),!this.schedule)return;const a=(null==s?void 0:s.identifier)||"",o=this.getAssetPlayerQueueIndex(a),l=this.playerQueue[o]||null,h=this.schedule.items,c=pi({},t,{fatal:!1,errorAction:_r(!0),asset:s,assetListIndex:n,event:e,schedule:h,scheduleIndex:i,player:l});if(this.hls.trigger(ri.INTERSTITIAL_ASSET_ERROR,c),!t.fatal)return;const u=this.playingAsset,d=this.bufferingAsset,f=new Error(r);if(s&&(this.clearAssetPlayer(a,null),s.error=f),e.assetList.some(t=>!t.error))for(let t=n;t<e.assetList.length;t++)this.resetAssetPlayer(e.assetList[t].identifier);else e.error=f;this.updateSchedule(!0),e.error?this.primaryFallback(e):u&&u.identifier===a?this.advanceAfterAssetEnded(e,i,n):d&&d.identifier===a&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,d)}primaryFallback(t){const e=t.timelineStart,i=this.effectivePlayingItem;let n=this.timelinePos;if(i){this.log(`Fallback to primary from event "${t.identifier}" start: ${e} pos: ${n} playing: ${Oh(i)} error: ${t.error}`),-1===n&&(n=this.hls.startPosition);const r=this.updateItem(i,n);this.itemsMatch(i,r)&&this.clearInterstitial(t,null),t.appendInPlace&&(this.attachPrimary(e,null),this.flushFrontBuffer(e))}else if(-1===n)return void this.checkStart();if(!this.schedule)return;const r=this.schedule.findItemIndexAtTime(n);this.setSchedulePosition(r)}onAssetListLoaded(t,e){var i,n;const r=e.event,s=r.identifier,a=e.assetListResponse.ASSETS;if(null==(i=this.schedule)||!i.hasEvent(s))return;const o=r.timelineStart,l=r.duration;let h=0;a.forEach((t,e)=>{const i=parseFloat(t.DURATION);this.createAsset(r,e,h,o+h,i,t.URI),h+=i}),r.duration=h,this.log(`Loaded asset-list with duration: ${h} (was: ${l}) ${r}`);const c=this.waitingItem,u=(null==c?void 0:c.event.identifier)===s;this.updateSchedule();const d=null==(n=this.bufferingItem)?void 0:n.event;if(u){var f;const t=this.schedule.findEventIndex(s),e=null==(f=this.schedule.items)?void 0:f[t];if(e){if(!this.playingItem&&this.timelinePos>e.end){if(this.schedule.findItemIndexAtTime(this.timelinePos)!==t)return r.error=new Error(`Interstitial ${a.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),void this.primaryFallback(r)}this.setBufferingItem(e)}this.setSchedulePosition(t)}else if((null==d?void 0:d.identifier)===s){const t=r.assetList[0];if(t){const e=this.getAssetPlayer(t.identifier);if(d.appendInPlace){const t=this.primaryMedia;e&&t&&this.bufferAssetPlayer(e,t)}else e&&e.loadSource()}}}onError(t,e){if(this.schedule)switch(e.details){case ni.ASSET_LIST_PARSING_ERROR:case ni.ASSET_LIST_LOAD_ERROR:case ni.ASSET_LIST_LOAD_TIMEOUT:{const t=e.interstitial;t&&(this.updateSchedule(!0),this.primaryFallback(t));break}case ni.BUFFER_STALLED_ERROR:{const t=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(t)&&t.event.appendInPlace)return void this.handleInPlaceStall(t.event);this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}});function Gc(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(Gc):Object.keys(t).reduce((e,i)=>(e[i]=Gc(t[i]),e),{}):t}function Vc(t,e){const i=t.loader;if(i!==Mc&&i!==Uc)e.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=Mc,t.progressive=!0,t.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class Kc extends Yr{constructor(t,e){super("gap-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var t;null!=(t=this.media)&&t.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var t;this.hls&&(this.ended=(null==(t=this.media)?void 0:t.currentTime)||1,this.hls.trigger(ri.MEDIA_ENDED,{stalled:!1}))},this.hls=t,this.fragmentTracker=e,this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(ri.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(ri.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(ri.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(ri.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(ri.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(ri.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(t,e){this.setInterval(100),this.mediaSource=e.mediaSource;const i=this.media=e.media;ua(i,"playing",this.onMediaPlaying),ua(i,"waiting",this.onMediaWaiting),ua(i,"ended",this.onMediaEnded)}onMediaDetaching(t,e){this.clearInterval();const{media:i}=this;i&&(da(i,"playing",this.onMediaPlaying),da(i,"waiting",this.onMediaWaiting),da(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(t,e){this.buffered=e.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var t;if(null==(t=this.media)||!t.readyState||!this.hasBuffered)return;const e=this.media.currentTime;this.poll(e,this.lastCurrentTime),this.lastCurrentTime=e}poll(t,e){var i,n;const r=null==(i=this.hls)?void 0:i.config;if(!r)return;const s=this.media;if(!s)return;const{seeking:a}=s,o=this.seeking&&!a,l=!this.seeking&&a,h=s.paused&&!a||s.ended||0===s.playbackRate;if(this.seeking=a,t!==e)return e&&(this.ended=0),this.moved=!0,a||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!h&&t>e&&this.nudgeOnVideoHole(t,e)),void(0===this.waiting&&this.stallResolved(t));if(l||o)return void(o&&this.stallResolved(t));if(h)return this.nudgeRetry=0,this.stallResolved(t),void(!this.ended&&s.ended&&this.hls&&(this.ended=t||1,this.hls.trigger(ri.MEDIA_ENDED,{stalled:!1})));if(!zr.getBuffered(s).length)return void(this.nudgeRetry=0);const c=zr.bufferInfo(s,t,0),u=c.nextStart||0,d=this.fragmentTracker;if(a&&d&&this.hls){const e=Hc(this.hls.inFlightFragments,t),i=c.len>2,n=!u||e||u-t>2&&!d.getPartialFragment(t);if(i||n)return;this.moved=!1}const f=null==(n=this.hls)?void 0:n.latestLevelDetails;if(!this.moved&&null!==this.stalled&&d){if(!(c.len>0)&&!u)return;const e=Math.max(u,c.start||0)-t,i=!(null==f||!f.live)?2*f.targetduration:2,n=jc(t,d);if(e>0&&(e<=i||n))return void(s.paused||this._trySkipBufferHole(n))}const g=r.detectStallWithCurrentTimeMs,p=self.performance.now(),m=this.waiting;let v=this.stalled;if(null===v){if(!(m>0&&p-m<g))return void(this.stalled=p);v=this.stalled=m}const y=p-v;if(!a&&(y>=g||m)&&this.hls){var A;if("ended"===(null==(A=this.mediaSource)?void 0:A.readyState)&&(null==f||!f.live)&&Math.abs(t-((null==f?void 0:f.edge)||0))<1){if(this.ended)return;return this.ended=t||1,void this.hls.trigger(ri.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(c),!this.media||!this.hls)return}const E=zr.bufferInfo(s,t,r.maxBufferHole);this._tryFixBufferStall(E,y,t)}stallResolved(t){const e=this.stalled;if(e&&this.hls&&(this.stalled=null,this.stallReported)){const i=self.performance.now()-e;this.log(`playback not stuck anymore @${t}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(ri.STALL_RESOLVED,{})}}nudgeOnVideoHole(t,e){var i;const n=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(i=this.buffered.audio)&&i.length&&n&&n.length>1&&t>n.end(0)){const i=zr.bufferedInfo(zr.timeRangesToArray(this.buffered.audio),t,0);if(i.len>1&&e>=i.start){const i=zr.timeRangesToArray(n),r=zr.bufferedInfo(i,e,0).bufferedIndex;if(r>-1&&r<i.length-1){const e=zr.bufferedInfo(i,t,0).bufferedIndex,n=i[r].end,s=i[r+1].start;if((-1===e||e>r)&&s-n<1&&t-n<2){const i=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${n} -> ${s} buffered index: ${e}`);this.warn(i.message),this.media.currentTime+=1e-6;let r=jc(t,this.fragmentTracker);r&&"fragment"in r?r=r.fragment:r||(r=void 0);const a=zr.bufferInfo(this.media,t,0);this.hls.trigger(ri.ERROR,{type:ii.MEDIA_ERROR,details:ni.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,frag:r,buffer:a.len,bufferInfo:a})}}}}}_tryFixBufferStall(t,e,i){var n,r;const{fragmentTracker:s,media:a}=this,o=null==(n=this.hls)?void 0:n.config;if(!a||!s||!o)return;const l=null==(r=this.hls)?void 0:r.latestLevelDetails,h=jc(i,s);if(h||null!=l&&l.live&&i<l.fragmentStart){if(this._trySkipBufferHole(h)||!this.media)return}const c=t.buffered,u=this.adjacentTraversal(t,i);(c&&c.length>1&&t.len>o.maxBufferHole||t.nextStart&&(t.nextStart-i<o.maxBufferHole||u))&&(e>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}adjacentTraversal(t,e){const i=this.fragmentTracker,n=t.nextStart;if(i&&n){const t=i.getFragAtPos(e,hi),r=i.getFragAtPos(n,hi);if(t&&r)return r.sn-t.sn<2}return!1}_reportStall(t){const{hls:e,media:i,stallReported:n,stalled:r}=this;if(!n&&null!==r&&i&&e){this.stallReported=!0;const n=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${qn(t)})`);this.warn(n.message),e.trigger(ri.ERROR,{type:ii.MEDIA_ERROR,details:ni.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:t.len,bufferInfo:t,stalled:{start:r}})}}_trySkipBufferHole(t){var e;const{fragmentTracker:i,media:n}=this,r=null==(e=this.hls)?void 0:e.config;if(!n||!i||!r)return 0;const s=n.currentTime,a=zr.bufferInfo(n,s,0),o=s<a.start?a.start:a.nextStart;if(o&&this.hls){const e=a.len<=r.maxBufferHole,h=a.len>0&&a.len<1&&n.readyState<3,c=o-s;if(c>0&&(e||h)){if(c>r.maxBufferHole){let e=!1;if(0===s){const t=i.getAppendedFrag(0,hi);t&&o<t.end&&(e=!0)}if(!e&&t){var l;if(null==(l=this.hls.loadLevelObj)||!l.details)return 0;if(Hc(this.hls.inFlightFragments,o))return 0;let e=!1,n=t.end;for(;n<o;){const t=jc(n,i);if(!t){e=!0;break}n+=t.duration}if(e)return 0}}const e=Math.max(o+.05,s+.1);if(this.warn(`skipping hole, adjusting currentTime from ${s} to ${e}`),this.moved=!0,n.currentTime=e,null==t||!t.gap){const i=new Error(`fragment loaded with buffer holes, seeking from ${s} to ${e}`),n={type:ii.MEDIA_ERROR,details:ni.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,buffer:a.len,bufferInfo:a};t&&("fragment"in t?n.part=t:n.frag=t),this.hls.trigger(ri.ERROR,n)}return e}}return 0}_tryNudgeBuffer(t){const{hls:e,media:i,nudgeRetry:n}=this,r=null==e?void 0:e.config;if(!i||!r)return 0;const s=i.currentTime;if(this.nudgeRetry++,n<r.nudgeMaxRetry){const a=s+(n+1)*r.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${s} to ${a}`);this.warn(o.message),i.currentTime=a,e.trigger(ri.ERROR,{type:ii.MEDIA_ERROR,details:ni.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:t.len,bufferInfo:t})}else{const i=new Error(`Playhead still not moving while enough data buffered @${s} after ${r.nudgeMaxRetry} nudges`);this.error(i.message),e.trigger(ri.ERROR,{type:ii.MEDIA_ERROR,details:ni.BUFFER_STALLED_ERROR,error:i,fatal:!0,buffer:t.len,bufferInfo:t})}}}function Hc(t,e){const i=Yc(t.main);if(i&&i.start<=e)return i;const n=Yc(t.audio);return n&&n.start<=e?n:null}function Yc(t){if(!t)return null;switch(t.state){case pa:case ga:case ba:case Sa:return null}return t.frag}function jc(t,e){return e.getAppendedFrag(t,hi)||e.getPartialFragment(t)}function Wc(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function zc(t,e,i,n,r){let s=new t(e,i,"");try{s.value=n,r&&(s.type=r)}catch(a){s=new t(e,i,qn(r?vi({type:r},n):n))}return s}const qc=(()=>{const t=Wc();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class Xc{constructor(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(ri.EVENT_CUE_ENTER,{})},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:t}=this;t&&(t.on(ri.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(ri.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(ri.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(ri.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ri.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(ri.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(ri.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(ri.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(ri.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(ri.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(ri.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(ri.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ri.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(ri.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(ri.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(ri.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(t,e){var i;this.media=e.media,!1===(null==(i=e.overrides)?void 0:i.cueRemoval)&&(this.removeCues=!1)}onMediaAttached(){var t;const e=null==(t=this.hls)?void 0:t.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(t,e){this.media=null;!!e.transferMedia||(this.id3Track&&(this.removeCues&&Ah(this.id3Track,this.onEventCueEnter),this.id3Track=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 vh(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(t,e){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:i,enableID3MetadataCues:n}=this.hls.config;if(!i&&!n)return;const{samples:r}=e;this.id3Track||(this.id3Track=this.createTrack(this.media));const s=Wc();if(s)for(let t=0;t<r.length;t++){const e=r[t].type;if(e===io.emsg&&!i||!n)continue;const a=Za(r[t].data),o=r[t].pts;let l=o+r[t].duration;l>qc&&(l=qc);l-o<=0&&(l=o+.25);for(let t=0;t<a.length;t++){const i=a[t];if(!Ja(i)){this.updateId3CueEnds(o,e);const t=zc(s,o,l,i,e);t&&this.id3Track.addCue(t)}}}}updateId3CueEnds(t,e){var i;const n=null==(i=this.id3Track)?void 0:i.cues;if(n)for(let i=n.length;i--;){const r=n[i];r.type===e&&r.startTime<t&&r.endTime===qc&&(r.endTime=t)}}onBufferFlushing(t,{startOffset:e,endOffset:i,type:n}){const{id3Track:r,hls:s}=this;if(!s)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=s;if(r&&(a||o)){let t;t="audio"===n?t=>t.type===io.audioId3&&o:"video"===n?t=>t.type===io.emsg&&a:t=>t.type===io.audioId3&&o||t.type===io.emsg&&a,Eh(r,e,i,t)}}onLevelUpdated(t,{details:e}){this.updateDateRangeCues(e,!0)}onLevelPtsUpdated(t,e){Math.abs(e.drift)>.01&&this.updateDateRangeCues(e.details)}updateDateRangeCues(t,e){if(!this.hls||!this.media)return;const{assetPlayerId:i,timelineOffset:n,enableDateRangeMetadataCues:r,interstitialsController:s}=this.hls.config;if(!r)return;const a=Wc();if(i&&n&&!s){const{fragmentStart:e,fragmentEnd:n}=t;let r=this.assetCue;r?(r.startTime=e,r.endTime=n):a&&(r=this.assetCue=zc(a,e,n,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),r&&(r.id=i,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(r),r.addEventListener("enter",this.onEventCueEnter)))}if(!t.hasProgramDateTime)return;const{id3Track:o}=this,{dateRanges:l}=t,h=Object.keys(l);let c=this.dateRangeCuesAppended;var u;if(o&&e)if(null!=(u=o.cues)&&u.length){const t=Object.keys(c).filter(t=>!h.includes(t));for(let e=t.length;e--;){var d;const i=t[e],n=null==(d=c[i])?void 0:d.cues;delete c[i],n&&Object.keys(n).forEach(t=>{const e=n[t];if(e){e.removeEventListener("enter",this.onEventCueEnter);try{o.removeCue(e)}catch(t){}}})}}else c=this.dateRangeCuesAppended={};const f=t.fragments[t.fragments.length-1];if(0!==h.length&&Je(null==f?void 0:f.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let t=0;t<h.length;t++){const e=h[t],i=l[e],n=i.startTime,r=c[e],o=(null==r?void 0:r.cues)||{};let u=(null==r?void 0:r.durationKnown)||!1,d=qc;const{duration:f,endDate:g}=i;if(g&&null!==f)d=n+f,u=!0;else if(i.endOnNext&&!u){const t=h.reduce((t,e)=>{if(e!==i.id){const n=l[e];if(n.class===i.class&&n.startDate>i.startDate&&(!t||i.startDate<t.startDate))return n}return t},null);t&&(d=t.startTime,u=!0)}const p=Object.keys(i.attr);for(let t=0;t<p.length;t++){const l=p[t];if(!ns(l))continue;const h=o[l];if(h)!u||null!=r&&r.durationKnown?Math.abs(h.startTime-n)>.01&&(h.startTime=n,h.endTime=d):h.endTime=d;else if(a){let t=i.attr[l];rs(l)&&(t=Ci(t));const r=zc(a,n,d,{key:l,data:t},io.dateRange);r&&(r.id=e,this.id3Track.addCue(r),o[l]=r,s&&("X-ASSET-LIST"!==l&&"X-ASSET-URL"!==l||r.addEventListener("enter",this.onEventCueEnter)))}}c[e]={cues:o,dateRange:i,durationKnown:u}}}}}class Qc{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,e=this.levelDetails;if(!t||!e)return;this.currentTime=t.currentTime;const i=this.computeLatency();if(null===i)return;this._latency=i;const{lowLatencyMode:n,maxLiveSyncPlaybackRate:r}=this.config;if(!n||1===r||!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,r)),i=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20,n=Math.min(e,Math.max(1,i));this.changeMediaPlaybackRate(t,n)}else 1!==t.playbackRate&&0!==t.playbackRate&&this.changeMediaPlaybackRate(t,1)},this.hls=t,this.config=t.config,this.registerListeners()}get levelDetails(){var t;return(null==(t=this.hls)?void 0:t.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:t}=this;if(void 0!==t.liveMaxLatencyDuration)return t.liveMaxLatencyDuration;const e=this.levelDetails;return e?t.liveMaxLatencyDurationCount*e.targetduration:0}get targetLatency(){const t=this.levelDetails;if(null===t||null===this.hls)return null;const{holdBack:e,partHoldBack:i,targetduration:n}=t,{liveSyncDuration:r,liveSyncDurationCount:s,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&i||e;(this._targetLatencyUpdated||o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==r?r:s*n);const h=n;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,h)}set targetLatency(t){this.stallCount=0,this.config.liveSyncDuration=t,this._targetLatencyUpdated=!0}get liveSyncPosition(){const t=this.estimateLiveEdge(),e=this.targetLatency;if(null===t||null===e)return null;const i=this.levelDetails;if(null===i)return null;const n=i.edge,r=t-e-this.edgeStalled,s=n-i.totalduration,a=n-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(s,r),a)}get drift(){const t=this.levelDetails;return null===t?1:t.drift}get edgeStalled(){const t=this.levelDetails;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}=this,e=this.levelDetails;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.hls=null}registerListeners(){const{hls:t}=this;t&&(t.on(ri.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(ri.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(ri.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ri.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(ri.ERROR,this.onError,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(ri.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(ri.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(ri.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ri.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(ri.ERROR,this.onError,this))}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(t,{details:e}){e.advanced&&this.onTimeupdate(),!e.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(t,e){var i;e.details===ni.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(i=this.levelDetails)&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(t,e){var i,n;t.playbackRate!==e&&(null==(i=this.hls)||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(n=this.targetLatency)?void 0:n.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${t.playbackRate} to ${e}`),t.playbackRate=e)}estimateLiveEdge(){const t=this.levelDetails;return null===t?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return null===t?null:t-this.currentTime}}class Zc extends al{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(ri.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ri.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(ri.LEVEL_LOADED,this.onLevelLoaded,this),t.on(ri.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(ri.FRAG_BUFFERED,this.onFragBuffered,this),t.on(ri.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(ri.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ri.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(ri.LEVEL_LOADED,this.onLevelLoaded,this),t.off(ri.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(ri.FRAG_BUFFERED,this.onFragBuffered,this),t.off(ri.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,n=[],r={},s={};let a=!1,o=!1,l=!1;e.levels.forEach(t=>{const e=t.attrs;let{audioCodec:h,videoCodec:c}=t;h&&(t.audioCodec=h=Ln(h,i)||void 0),c&&(c=t.videoCodec=function(t){const e=t.split(",");for(let t=0;t<e.length;t++){const i=e[t].split(".");i.length>2&&"avc1"===i[0]&&(e[t]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`)}return e.join(",")}(c));const{width:u,height:d,unknownCodecs:f}=t,g=(null==f?void 0:f.length)||0;if(a||(a=!(!u||!d)),o||(o=!!c),l||(l=!!h),g||h&&!this.isAudioSupported(h)||c&&!this.isVideoSupported(c))return void this.log(`Some or all CODECS not supported "${e.CODECS}"`);const{CODECS:p,"FRAME-RATE":m,"HDCP-LEVEL":v,"PATHWAY-ID":y,RESOLUTION:A,"VIDEO-RANGE":E}=e,T=`${`${y||"."}-`}${t.bitrate}-${A}-${m}-${p}-${E}-${v}`;if(r[T])if(r[T].uri===t.url||t.attrs["PATHWAY-ID"])r[T].addGroupId("audio",e.AUDIO),r[T].addGroupId("text",e.SUBTITLES);else{const e=s[T]+=1;t.attrs["PATHWAY-ID"]=new Array(e+1).join(".");const i=this.createLevel(t);r[T]=i,n.push(i)}else{const e=this.createLevel(t);r[T]=e,s[T]=1,n.push(e)}}),this.filterAndSortMediaOptions(n,e,a,o,l)}createLevel(t){const e=new jn(t),i=t.supplemental;if(null!=i&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){const t=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(t.message),e.supportedResult=xn(t,[])}return e}isAudioSupported(t){return An(t,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(t){return An(t,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(t,e,i,n,r){var s;let a=[],o=[],l=t;const h=(null==(s=e.stats)?void 0:s.parsing)||{};if((i||n)&&r&&(l=l.filter(({videoCodec:t,videoRange:e,width:i,height:n})=>{return(!!t||!(!i||!n))&&(!!(r=e)&&$n.indexOf(r)>-1);var r})),0===l.length)return Promise.resolve().then(()=>{if(this.hls){let t="no level with compatible codecs found in manifest",i=t;e.levels.length&&(i=`one or more CODECS in variant not supported: ${qn(e.levels.map(t=>t.attrs.CODECS).filter((t,e,i)=>i.indexOf(t)===e))}`,this.warn(i),t+=` (${i})`);const n=new Error(t);this.hls.trigger(ri.ERROR,{type:ii.MEDIA_ERROR,details:ni.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:n,reason:i})}}),void(h.end=performance.now());e.audioTracks&&(a=e.audioTracks.filter(t=>!t.audioCodec||this.isAudioSupported(t.audioCodec)),Jc(a)),e.subtitles&&(o=e.subtitles,Jc(o));const c=l.slice(0);l.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 $n.indexOf(t.videoRange)-$n.indexOf(e.videoRange);if(t.videoCodec!==e.videoCodec){const i=bn(t.videoCodec),n=bn(e.videoCodec);if(i!==n)return n-i}if(t.uri===e.uri&&t.codecSet!==e.codecSet){const i=Sn(t.codecSet),n=Sn(e.codecSet);if(i!==n)return n-i}return t.averageBitrate!==e.averageBitrate?t.averageBitrate-e.averageBitrate:0});let u=c[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==c.length))for(let t=0;t<c.length;t++)if(c[t].pathwayId===l[0].pathwayId){u=c[t];break}this._levels=l;for(let t=0;t<l.length;t++)if(l[t]===u){var d;this._firstLevel=t;const e=u.bitrate,i=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.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>i&&i===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=t)}break}const f=r&&!n,g=this.hls.config,p=!(!g.audioStreamController||!g.audioTrackController),m={levels:l,audioTracks:a,subtitleTracks:o,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:r,video:n,altAudio:p&&!f&&a.some(t=>!!t.url)};h.end=performance.now(),this.hls.trigger(ri.MANIFEST_PARSED,m)}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}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"),n=t<0;if(this.hls.trigger(ri.ERROR,{type:ii.OTHER_ERROR,details:ni.LEVEL_SWITCH_ERROR,level:t,fatal:n,error:i,reason:i.message}),n)return;t=Math.min(t,e.length-1)}const i=this.currentLevelIndex,n=this.currentLevel,r=n?n.attrs["PATHWAY-ID"]:void 0,s=e[t],a=s.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=s,i===t&&n&&r===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}${r?" with Pathway "+r:""}`);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(ri.LEVEL_SWITCHING,o);const l=s.details;if(!l||l.live){const t=this.switchParams(s.uri,null==n?void 0:n.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}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(t){if(this.steering){const e=this.steering.pathways(),i=t.filter(t=>-1!==e.indexOf(t));if(t.length<1)return void this.warn(`pathwayPriority ${t} should contain at least one pathway from list: ${e}`);this.steering.pathwayPriority=i}}onError(t,e){!e.fatal&&e.context&&e.context.type===ai&&e.context.level===this.level&&this.checkRetry(e)}onFragBuffered(t,{frag:e}){if(void 0!==e&&e.type===hi){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:n,details:r}=e,s=e.levelInfo;var a;if(!s)return this.warn(`Invalid level index ${n}`),void(null!=(a=e.deliveryDirectives)&&a.skip&&(r.deltaUpdateFailed=!0));if(s===this.currentLevel||e.withoutMultiVariant){0===s.fragmentError&&(s.loadError=0);let t=s.details;t===e.details&&t.advanced&&(t=void 0),this.playlistLoaded(n,e,t)}else null!=(i=e.deliveryDirectives)&&i.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const i=this.getUrlWithDirectives(t.uri,e),n=this.currentLevelIndex,r=t.attrs["PATHWAY-ID"],s=t.details,a=null==s?void 0:s.age;this.log(`Loading level index ${n}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${r?" Pathway "+r:""}${a&&s.live?" age "+a.toFixed(1)+(s.type&&" "+s.type||""):""} ${i}`),this.hls.trigger(ri.LEVEL_LOADING,{url:i,level:n,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||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;if(1===this._levels.length)return;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));na(i),this._levels=i,this.currentLevelIndex>-1&&null!=(e=this.currentLevel)&&e.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const n=i.length-1;this._firstLevel=Math.min(this._firstLevel,n),this._startLevel&&(this._startLevel=Math.min(this._startLevel,n)),this.hls.trigger(ri.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(ri.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function Jc(t){const e={};t.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}function tu(){return self.SourceBuffer||self.WebKitSourceBuffer}function eu(){if(!_i())return!1;const t=tu();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}class iu extends La{constructor(t,e,i){super(t,e,i,"stream-controller",hi),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const t=this.media,e=t?t.currentTime:null;if(null===e||!Je(e))return;if(this.log(`Media seeked to ${e.toFixed(3)}`),!this.getBufferedFrag(e))return;const i=this.getFwdBufferInfoAtPos(t,e,hi,0);null!==i&&0!==i.len?this.tick():this.warn(`Main forward buffer length at ${e} on "seeked" event ${i?i.len:"empty"})`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(ri.MANIFEST_PARSED,this.onManifestParsed,this),t.on(ri.LEVEL_LOADING,this.onLevelLoading,this),t.on(ri.LEVEL_LOADED,this.onLevelLoaded,this),t.on(ri.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(ri.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(ri.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(ri.BUFFER_CREATED,this.onBufferCreated,this),t.on(ri.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(ri.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(ri.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(ri.MANIFEST_PARSED,this.onManifestParsed,this),t.off(ri.LEVEL_LOADED,this.onLevelLoaded,this),t.off(ri.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(ri.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(ri.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(ri.BUFFER_CREATED,this.onBufferCreated,this),t.off(ri.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(ri.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(ri.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(t,e){if(this.levels){const{lastCurrentTime:i,hls:n}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let t=n.startLevel;-1===t&&(n.config.testBandwidth&&this.levels.length>1?(t=0,this.bitrateTest=!0):t=n.firstAutoLevel),n.nextLoadLevel=t,this.level=n.loadLevel,this._hasEnoughToStart=!!e}i>0&&-1===t&&!e&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),t=i),this.state=pa,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}else this._forceStartLoad=!0,this.state=ga}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case _a:{const{levels:t,level:e}=this,i=null==t?void 0:t[e],n=null==i?void 0:i.details;if(n&&(!n.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(n))break;this.state=pa;break}if(this.hls.nextLoadLevel!==this.level){this.state=pa;break}break}case ya:this.checkRetryDate()}this.state===pa&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var t;super.onTickEnd(),null!=(t=this.media)&&t.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:i,media:n}=this;if(null===e||!n&&!this.primaryPrefetch&&(this.startFragRequested||!t.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const r=this.buffering?t.nextLoadLevel:t.loadLevel;if(null==i||!i[r])return;const s=i[r],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const t={};return 2===this.altAudio&&(t.type="video"),this.hls.trigger(ri.BUFFER_EOS,t),void(this.state=ba)}if(!this.buffering)return;t.loadLevel!==r&&-1===t.manualLevel&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=t.nextLoadLevel=r;const l=s.details;if(!l||this.state===_a||this.waitForLive(s))return this.level=r,this.state=_a,void(this.startFragRequested=!1);const h=a.len,c=this.getMaxBufferLength(s.maxBitrate);if(h>=c)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&&Ui(d)&&this.fragmentTracker.getState(d)!==Cr){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?Mi:Ni,e=(t===Ni?this.videoBuffer:this.mediaBuffer)||this.media;e&&this.afterBufferFlushed(e,t,hi)}d=this.getNextFragmentLoopLoading(d,l,a,hi,c)}d&&(this.exceedsMaxBuffer(a,c,d)||(!d.initSegment||d.initSegment.data||this.bitrateTest||(d=d.initSegment),this.loadFragment(d,s,u)))}loadFragment(t,e,i){const n=this.fragmentTracker.getState(t);n===Lr||n===Rr?Ui(t)?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)):super.loadFragment(t,e,i):this._loadInitSegment(t,e):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,hi)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),0!==this.altAudio){var t;((null==(t=this.getLevelDetails())?void 0:t.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}nextLevelSwitch(){const{levels:t,media:e}=this;if(null!=e&&e.readyState){let i;const n=this.getAppendedFrag(e.currentTime);n&&n.start>1&&this.flushMainBuffer(0,n.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],n=this.fragLastKbps;i=n&&this.fragCurrent?this.fragCurrent.duration*e.maxBitrate/(1e3*n)+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,n=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(n,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 ma:case va:case ya:case Ea:case Ta:this.state=pa}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,2===this.altAudio?"video":null)}onMediaAttached(t,e){super.onMediaAttached(t,e);const i=e.media;ua(i,"playing",this.onMediaPlaying),ua(i,"seeked",this.onMediaSeeked)}onMediaDetaching(t,e){const{media:i}=this;i&&(da(i,"playing",this.onMediaPlaying),da(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(t,e);!!e.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(ri.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(t,e){let i=!1,n=!1;for(let t=0;t<e.levels.length;t++){const r=e.levels[t].audioCodec;r&&(i=i||-1!==r.indexOf("mp4a.40.2"),n=n||-1!==r.indexOf("mp4a.40.5"))}this.audioCodecSwitch=i&&n&&!function(){var t;const e=tu();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!==pa)return;const n=e.levelInfo;(!n.details||n.details.live&&(this.levelLastLoaded!==n||n.details.expired)||this.waitForCdnTuneIn(n.details))&&(this.state=_a)}onLevelLoaded(t,e){var i;const{levels:n,startFragRequested:r}=this,s=e.level,a=e.details,o=a.totalduration;if(!n)return void this.warn(`Levels were reset while loading level ${s}`);this.log(`Level ${s} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=e.levelInfo,h=this.fragCurrent;!h||this.state!==va&&this.state!==ya||h.level!==e.level&&h.loader&&this.abortCurrentFrag();let c=0;if(a.live||null!=(i=l.details)&&i.live){var u;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;c=this.alignPlaylists(a,l.details,null==(u=this.levelLastLoaded)?void 0:u.details)}if(l.details=a,this.levelLastLoaded=l,r||this.setStartPosition(a,c),this.hls.trigger(ri.LEVEL_UPDATED,{details:a,level:s}),this.state===_a){if(this.waitForCdnTuneIn(a))return;this.state=pa}r&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}synchronizeToLiveEdge(t){const{config:e,media:i}=this;if(!i)return;const n=this.hls.liveSyncPosition,r=this.getLoadPosition(),s=t.fragmentStart,a=t.edge,o=r>=s-e.maxFragLookUpTolerance&&r<=a;if(null!==n&&i.duration>n&&(r<n||!o)){const s=void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;if((!o&&i.readyState<4||r<a-s)&&(this._hasEnoughToStart||(this.nextLoadPosition=n),i.readyState))if(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${n.toFixed(3)}`),"buffered"===this.config.liveSyncMode){var l;const t=zr.bufferInfo(i,n,0);if(null==(l=t.buffered)||!l.length)return void(i.currentTime=n);if(t.start<=r)return void(i.currentTime=n);const{nextStart:e}=zr.bufferedInfo(t.buffered,r,0);e&&(i.currentTime=e)}else i.currentTime=n}}_handleFragmentLoadProgress(t){var e;const i=t.frag,{part:n,payload:r}=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];if(!a)return void this.warn(`Level ${i.level} not found on progress`);const 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,h=o.PTSKnown||!o.live,c=null==(e=i.initSegment)?void 0:e.data,u=this._getAudioCodec(a),d=this.transmuxer=this.transmuxer||new sl(this.hls,hi,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=n?n.index:-1,g=-1!==f,p=new jr(i.level,i.sn,i.stats.chunkCount,r.byteLength,f,g),m=this.initPTS[i.cc];d.push(r,c,u,l,i,n,o.totalduration,h,p,m)}onAudioTrackSwitching(t,e){const i=this.hls,n=0!==this.altAudio;if(nr(e.url,i))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;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();if(n)return this.altAudio=0,this.fragmentTracker.removeAllFragments(),i.once(ri.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(ri.AUDIO_TRACK_SWITCHED,e)}),void i.trigger(ri.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});i.trigger(ri.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const i=nr(e.url,this.hls);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?2:0,this.tick()}onBufferCreated(t,e){const i=e.tracks;let n,r,s=!1;for(const t in i){const e=i[t];if("main"===e.id){if(r=t,n=e,"video"===t){const e=i[t];e&&(this.videoBuffer=e.buffer)}}else s=!0}s&&n?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=n.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:i,part:n}=e,r=i.type===hi;if(r){if(this.fragContextChanged(i))return this.warn(`Fragment ${i.sn}${n?" p: "+n.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===Ta&&(this.state=pa));const t=n?n.stats:i.stats;this.fragLastKbps=Math.round(8*t.total/(t.buffering.end-t.loading.first)),Ui(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,n)}const s=this.media;s&&(!this._hasEnoughToStart&&zr.getBuffered(s).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,e){var i;if(e.fatal)this.state=Sa;else switch(e.details){case ni.FRAG_GAP:case ni.FRAG_PARSING_ERROR:case ni.FRAG_DECRYPT_ERROR:case ni.FRAG_LOAD_ERROR:case ni.FRAG_LOAD_TIMEOUT:case ni.KEY_LOAD_ERROR:case ni.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(hi,e);break;case ni.LEVEL_LOAD_ERROR:case ni.LEVEL_LOAD_TIMEOUT:case ni.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==_a||(null==(i=e.context)?void 0:i.type)!==ai||(this.state=pa);break;case ni.BUFFER_ADD_CODEC_ERROR:case ni.BUFFER_APPEND_ERROR:if("main"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&this.resetLoadingState();break;case ni.BUFFER_FULL_ERROR:if("main"!==e.parent)return;if(this.reduceLengthAndFlushBuffer(e)){!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}break;case ni.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onFragLoadEmergencyAborted(){this.state=pa,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==Mi||!this.altAudio){const t=(e===Ni?this.videoBuffer:this.mediaBuffer)||this.media;t&&(this.afterBufferFlushed(t,e,hi),this.tick())}}onLevelsUpdated(t,e){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),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 n=this.timelineOffset;n&&i&&(i+=n);const r=this.getLevelDetails(),s=zr.getBuffered(t),a=s.length?s.start(0):0,o=a-i,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==r?void 0:r.partTarget)||0)))&&(this.log(`adjusting start position by ${o} to match buffer start`),i+=o,this.startPosition=i),e<i&&(this.log(`seek to target start position ${i} from current time ${e} buffer start ${a}`),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(t=>{const{hls:i}=this,n=null==t?void 0:t.frag;if(!n||this.fragContextChanged(n))return;e.fragmentError=0,this.state=pa,this.startFragRequested=!1,this.bitrateTest=!1;const r=n.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),i.trigger(ri.FRAG_LOADED,t),n.bitrateTest=!1}).catch(e=>{this.state!==ga&&this.state!==Sa&&(this.warn(e),this.resetFragmentLoading(t))})}_handleTransmuxComplete(t){const e=this.playlistType,{hls:i}=this,{remuxResult:n,chunkMeta:r}=t,s=this.getCurrentContext(r);if(!s)return void this.resetWhenMissingContext(r);const{frag:a,part:o,level:l}=s,{video:h,text:c,id3:u,initSegment:d}=n,{details:f}=l,g=this.altAudio?void 0:n.audio;if(this.fragContextChanged(a))this.fragmentTracker.removeFragment(a);else{if(this.state=Ea,d){const t=d.tracks;if(t){const n=a.initSegment||a;if(this.unhandledEncryptionError(d,a))return;this._bufferInitSegment(l,t,n,r),i.trigger(ri.FRAG_PARSING_INIT_SEGMENT,{frag:n,id:e,tracks:t})}const n=d.initPTS,s=d.timescale,o=this.initPTS[a.cc];if(Je(n)&&(!o||o.baseTime!==n||o.timescale!==s)){const t=d.trackId;this.initPTS[a.cc]={baseTime:n,timescale:s,trackId:t},i.trigger(ri.INIT_PTS_FOUND,{frag:a,id:e,initPTS:n,timescale:s,trackId:t})}}if(h&&f){g&&"audiovideo"===h.type&&this.logMuxedErr(a);const t=f.fragments[a.sn-1-f.startSN],e=a.sn===f.startSN,i=!t||a.cc>t.cc;if(!1!==n.independent){const{startPTS:t,endPTS:n,startDTS:s,endDTS:l}=h;if(o)o.elementaryStreams[h.type]={startPTS:t,endPTS:n,startDTS:s,endDTS:l};else if(h.firstKeyFrame&&h.independent&&1===r.id&&!i&&(this.couldBacktrack=!0),h.dropped&&h.independent){const r=this.getMainFwdBufferInfo(),s=(r?r.end:this.getLoadPosition())+this.config.maxBufferHole,o=h.firstKeyFramePTS?h.firstKeyFramePTS:t;if(!e&&s<o-this.config.maxBufferHole&&!i)return void this.backtrack(a);i&&(a.gap=!0),a.setElementaryStreamInfo(h.type,a.start,n,a.start,l,!0)}else e&&t-(f.appliedTimelineOffset||0)>2&&(a.gap=!0);a.setElementaryStreamInfo(h.type,t,n,s,l),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(h,a,o,r,e||i)}else{if(!e&&!i)return void this.backtrack(a);a.gap=!0}}if(g){const{startPTS:t,endPTS:e,startDTS:i,endDTS:n}=g;o&&(o.elementaryStreams[Mi]={startPTS:t,endPTS:e,startDTS:i,endDTS:n}),a.setElementaryStreamInfo(Mi,t,e,i,n),this.bufferFragmentData(g,a,o,r)}if(f&&null!=u&&u.samples.length){const t={id:e,frag:a,details:f,samples:u.samples};i.trigger(ri.FRAG_PARSING_METADATA,t)}if(f&&c){const t={id:e,frag:a,details:f,samples:c.samples};i.trigger(ri.FRAG_PARSING_USERDATA,t)}}}logMuxedErr(t){this.warn(`${Ui(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,e,i,n){if(this.state!==Ea)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&(delete e.audio,e.audiovideo&&this.logMuxedErr(i));const{audio:r,video:s,audiovideo:a}=e;if(r){const i=t.audioCodec;let n=In(r.codec,i);"mp4a"===n&&(n="mp4a.40.5");const s=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){n&&(n=-1!==n.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")&&(n="mp4a.40.5")}n&&-1!==n.indexOf("mp4a.40.5")&&-1!==s.indexOf("android")&&"audio/mpeg"!==r.container&&(n="mp4a.40.2",this.log(`Android: force audio codec to ${n}`)),i&&i!==n&&this.log(`Swapping manifest audio codec "${i}" for "${n}"`),r.levelCodec=n,r.id=hi,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${n||""}/${i||""}/${r.codec}]`),delete e.audiovideo}if(s){s.levelCodec=t.videoCodec,s.id=hi;const i=s.codec;if(4===(null==i?void 0:i.length))switch(i){case"hvc1":case"hev1":s.codec="hvc1.1.6.L120.90";break;case"av01":s.codec="av01.0.04M.08";break;case"avc1":s.codec="avc1.42e01e"}this.log(`Init video buffer, container:${s.container}, codecs[level/parsed]=[${t.videoCodec||""}/${i}]${s.codec!==i?" parsed-corrected="+s.codec:""}${s.supplemental?" supplemental="+s.supplemental:""}`),delete e.audiovideo}a&&(this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${t.codecs}/${a.codec}]`),delete e.video,delete e.audio);const o=Object.keys(e);if(o.length){if(this.hls.trigger(ri.BUFFER_CODECS,e),!this.hls)return;o.forEach(t=>{const r=e[t].initSegment;null!=r&&r.byteLength&&this.hls.trigger(ri.BUFFER_APPENDING,{type:t,data:r,frag:i,part:null,chunkMeta:n,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const t=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(t,hi)}get maxBufferLength(){const{levels:t,level:e}=this,i=null==t?void 0:t[e];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}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=pa}checkFragmentChanged(){const t=this.media;let e=null;if(t&&t.readyState>1&&!1===t.seeking){const i=t.currentTime;if(zr.isBuffered(t,i)?e=this.getAppendedFrag(i):zr.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(ri.FRAG_CHANGED,{frag:e}),t&&t.level===i||this.hls.trigger(ri.LEVEL_SWITCHED,{level:i}))}}}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){var t;if(this.fragPlaying)return this.fragPlaying;const e=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;return Je(e)?this.getAppendedFrag(e):null}get currentProgramDateTime(){var t;const e=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;if(Je(e)){const t=this.getLevelDetails(),i=this.currentFrag||(t?sr(null,t.fragments,e):null);if(i){const t=i.programDateTime;if(null!==t){const n=t+1e3*(e-i.start);return new Date(n)}}}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 nu extends yi{constructor(t,e){super("key-loader",e),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=t}abort(t){for(const i in this.keyIdToKeyInfo){const n=this.keyIdToKeyInfo[i].loader;if(n){var e;if(t&&t!==(null==(e=n.context)?void 0:e.frag.type))return;n.abort()}}}detach(){for(const t in this.keyIdToKeyInfo){const e=this.keyIdToKeyInfo[t];(e.mediaKeySessionContext||e.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[t]}}destroy(){this.detach();for(const t in this.keyIdToKeyInfo){const e=this.keyIdToKeyInfo[t].loader;e&&e.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(t,e=ni.KEY_LOAD_ERROR,i,n,r){return new Hr({type:ii.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:r,error:i,networkDetails:n})}loadClear(t,e,i){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(e.length)for(let n=0,r=e.length;n<r;n++){const s=e[n];if(t.cc<=s.cc&&(!Ui(t)||!Ui(s)||t.sn<s.sn)||!i&&n==r-1)return this.emeController.selectKeySystemFormat(s).then(t=>{if(!this.emeController)return;s.setKeyFormat(t);const e=Ts(t);return e?this.emeController.getKeySystemAccess([e]):void 0})}if(this.config.requireKeySystemAccessOnStart){const t=Ss(this.config);if(t.length)return this.emeController.getKeySystemAccess(t)}}return null}load(t){return!t.decryptdata&&t.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(t).then(e=>this.loadInternal(t,e)):this.loadInternal(t)}loadInternal(t,e){var i,n;e&&t.setKeyFormat(e);const r=t.decryptdata;if(!r){const i=new Error(e?`Expected frag.decryptdata to be defined after setting format ${e}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(t,ni.KEY_LOAD_ERROR,i))}const s=r.uri;if(!s)return Promise.reject(this.createKeyLoadError(t,ni.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${s}"`)));const a=ru(r);let o=this.keyIdToKeyInfo[a];if(null!=(i=o)&&i.decryptdata.key)return r.key=o.decryptdata.key,Promise.resolve({frag:t,keyInfo:o});if(this.emeController&&null!=(n=o)&&n.keyLoadPromise){switch(this.emeController.getKeyStatus(o.decryptdata)){case"usable":case"usable-in-future":return o.keyLoadPromise.then(e=>{const{keyInfo:i}=e;return r.key=i.decryptdata.key,{frag:t,keyInfo:i}})}}switch(this.log(`${this.keyIdToKeyInfo[a]?"Rel":"L"}oading${r.keyId?" keyId: "+Ri(r.keyId):""} URI: ${r.uri} from ${t.type} ${t.level}`),o=this.keyIdToKeyInfo[a]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===r.keyFormat?this.loadKeyHTTP(o,t):this.loadKeyEME(o,t);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(o,t);default:return Promise.reject(this.createKeyLoadError(t,ni.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(t,e){const i={frag:e,keyInfo:t};if(this.emeController&&this.config.emeEnabled){var n;if(!t.decryptdata.keyId&&null!=(n=e.initSegment)&&n.data){const i=function(t){const e=[];return an(t,t=>e.push(t.subarray(8,24))),e}(e.initSegment.data);if(i.length){let e=i[0];e.some(t=>0!==t)?(this.log(`Using keyId found in init segment ${Ri(e)}`),Rs.setKeyIdForUri(t.decryptdata.uri,e)):(e=Rs.addKeyIdForUri(t.decryptdata.uri),this.log(`Generating keyId to patch media ${Ri(e)}`)),t.decryptdata.keyId=e}}if(!t.decryptdata.keyId&&!Ui(e))return Promise.resolve(i);const r=this.emeController.loadKey(i);return(t.keyLoadPromise=r.then(e=>(t.mediaKeySessionContext=e,i))).catch(i=>{throw t.keyLoadPromise=null,"data"in i&&(i.data.frag=e),i})}return Promise.resolve(i)}loadKeyHTTP(t,e){const i=this.config,n=new(0,i.loader)(i);return e.keyLoader=t.loader=n,t.keyLoadPromise=new Promise((r,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},h={onSuccess:(t,e,i,n)=>{const{frag:a,keyInfo:o}=i,l=ru(o.decryptdata);if(!a.decryptdata||o!==this.keyIdToKeyInfo[l])return s(this.createKeyLoadError(a,ni.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),n));o.decryptdata.key=a.decryptdata.key=new Uint8Array(t.data),a.keyLoader=null,o.loader=null,r({frag:a,keyInfo:o})},onError:(t,i,n,r)=>{this.resetLoader(i),s(this.createKeyLoadError(e,ni.KEY_LOAD_ERROR,new Error(`HTTP Error ${t.code} loading key ${t.text}`),n,vi({url:a.url,data:void 0},t)))},onTimeout:(t,i,n)=>{this.resetLoader(i),s(this.createKeyLoadError(e,ni.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),n))},onAbort:(t,i,n)=>{this.resetLoader(i),s(this.createKeyLoadError(e,ni.INTERNAL_ABORTED,new Error("key loading aborted"),n))}};n.load(a,l,h)})}resetLoader(t){const{frag:e,keyInfo:i,url:n}=t,r=i.loader;e.keyLoader===r&&(e.keyLoader=null,i.loader=null);const s=ru(i.decryptdata)||n;delete this.keyIdToKeyInfo[s],r&&r.destroy()}}function ru(t){if(t.keyFormat!==ys){const e=t.keyId;if(e)return Ri(e)}return t.uri}function su(t){const{type:e}=t;switch(e){case oi:return ci;case li:return ui;default:return hi}}function au(t,e){let i=t.url;return void 0!==i&&0!==i.indexOf("data:")||(i=e.url),i}class ou{constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=t,this.registerListeners()}startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:t}=this;t.on(ri.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ri.LEVEL_LOADING,this.onLevelLoading,this),t.on(ri.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(ri.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(ri.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(ri.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ri.LEVEL_LOADING,this.onLevelLoading,this),t.off(ri.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(ri.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(ri.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(t){const e=this.hls.config,i=e.pLoader,n=e.loader,r=new(i||n)(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:i}=e;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:si,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(t,e){const{id:i,level:n,pathwayId:r,url:s,deliveryDirectives:a,levelInfo:o}=e;this.load({id:i,level:n,pathwayId:r,responseType:"text",type:ai,url:s,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(t,e){const{id:i,groupId:n,url:r,deliveryDirectives:s,track:a}=e;this.load({id:i,groupId:n,level:null,responseType:"text",type:oi,url:r,deliveryDirectives:s,levelOrTrack:a})}onSubtitleTrackLoading(t,e){const{id:i,groupId:n,url:r,deliveryDirectives:s,track:a}=e;this.load({id:i,groupId:n,level:null,responseType:"text",type:li,url:r,deliveryDirectives:s,levelOrTrack:a})}onLevelsUpdated(t,e){const i=this.loaders[ai];if(i){const t=i.context;t&&!e.levels.some(e=>e===t.levelOrTrack)&&(i.abort(),delete this.loaders[ai])}}load(t){var e;const i=this.hls.config;let n,r=this.getInternalLoader(t);if(r){const e=this.hls.logger,i=r.context;if(i&&i.levelOrTrack===t.levelOrTrack&&(i.url===t.url||i.deliveryDirectives&&!t.deliveryDirectives))return void(i.url===t.url?e.log(`[playlist-loader]: ignore ${t.url} ongoing request`):e.log(`[playlist-loader]: ignore ${t.url} in favor of ${i.url}`));e.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),r.abort()}if(n=t.type===si?i.manifestLoadPolicy.default:pi({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(t),Je(null==(e=t.deliveryDirectives)?void 0:e.part)){let e;if(t.type===ai&&null!==t.level?e=this.hls.levels[t.level].details:t.type===oi&&null!==t.id?e=this.hls.audioTracks[t.id].details:t.type===li&&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);n=pi({},n,{maxTimeToFirstByteMs:Math.min(e,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(e,n.maxTimeToFirstByteMs)})}}}const s=n.errorRetry||n.timeoutRetry||{},a={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:s.maxNumRetry||0,retryDelay:s.retryDelayMs||0,maxRetryDelay:s.maxRetryDelayMs||0},o={onSuccess:(t,e,i,n)=>{const r=this.getInternalLoader(i);this.resetInternalLoader(i.type);const s=t.data;e.parsing.start=performance.now(),Ms.isMediaPlaylist(s)||i.type!==si?this.handleTrackOrLevelPlaylist(t,e,i,n||null,r):this.handleMasterPlaylist(t,e,i,n)},onError:(t,e,i,n)=>{this.handleNetworkError(e,i,!1,t,n)},onTimeout:(t,e,i)=>{this.handleNetworkError(e,i,!0,void 0,t)}};r.load(t,a,o)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:t,startPosition:e},forceStartLoad:i}=this.hls;(t||i)&&(this.hls.logger.log(`${t?"auto":"force"} startLoad with configured startPosition ${e}`),this.hls.startLoad(e))}handleMasterPlaylist(t,e,i,n){const r=this.hls,s=t.data,a=au(t,i),o=Ms.parseMasterPlaylist(s,a);if(o.playlistParsingError)return e.parsing.end=performance.now(),void this.handleManifestParsingError(t,i,o.playlistParsingError,n,e);const{contentSteering:l,levels:h,sessionData:c,sessionKeys:u,startTimeOffset:d,variableList:f}=o;this.variableList=f,h.forEach(t=>{const{unknownCodecs:e}=t;if(e){const{preferManagedMediaSource:i}=this.hls.config;let{audioCodec:n,videoCodec:r}=t;for(let s=e.length;s--;){const a=e[s];An(a,"audio",i)?(t.audioCodec=n=n?`${n},${a}`:a,vn.audio[n.substring(0,4)]=2,e.splice(s,1)):An(a,"video",i)&&(t.videoCodec=r=r?`${r},${a}`:a,vn.video[r.substring(0,4)]=2,e.splice(s,1))}}});const{AUDIO:g=[],SUBTITLES:p,"CLOSED-CAPTIONS":m}=Ms.parseMasterPlaylistMedia(s,a,o);if(g.length){g.some(t=>!t.url)||!h[0].audioCodec||h[0].attrs.AUDIO||(this.hls.logger.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 is({}),bitrate:0,url:""}))}r.trigger(ri.MANIFEST_LOADED,{levels:h,audioTracks:g,subtitles:p,captions:m,contentSteering:l,url:a,stats:e,networkDetails:n,sessionData:c,sessionKeys:u,startTimeOffset:d,variableList:f})}handleTrackOrLevelPlaylist(t,e,i,n,r){const s=this.hls,{id:a,level:o,type:l}=i,h=au(t,i),c=Je(o)?o:Je(a)?a:0,u=su(i),d=Ms.parseLevelPlaylist(t.data,h,c,u,0,this.variableList);if(l===si){const t={attrs:new is({}),bitrate:0,details:d,name:"",url:h};d.requestScheduled=e.loading.start+Js(d,0),s.trigger(ri.MANIFEST_LOADED,{levels:[t],audioTracks:[],url:h,stats:e,networkDetails:n,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),i.levelDetails=d,this.handlePlaylistLoaded(d,t,e,i,n,r)}handleManifestParsingError(t,e,i,n,r){this.hls.trigger(ri.ERROR,{type:ii.NETWORK_ERROR,details:ni.MANIFEST_PARSING_ERROR,fatal:e.type===si,url:t.url,err:i,error:i,reason:i.message,response:t,context:e,networkDetails:n,stats:r})}handleNetworkError(t,e,i=!1,n,r){let s=`A network ${i?"timeout":"error"+(n?" (status "+n.code+")":"")} occurred while loading ${t.type}`;t.type===ai?s+=`: ${t.level} id: ${t.id}`:t.type!==oi&&t.type!==li||(s+=` id: ${t.id} group-id: "${t.groupId}"`);const a=new Error(s);this.hls.logger.warn(`[playlist-loader]: ${s}`);let o=ni.UNKNOWN,l=!1;const h=this.getInternalLoader(t);switch(t.type){case si:o=i?ni.MANIFEST_LOAD_TIMEOUT:ni.MANIFEST_LOAD_ERROR,l=!0;break;case ai:o=i?ni.LEVEL_LOAD_TIMEOUT:ni.LEVEL_LOAD_ERROR,l=!1;break;case oi:o=i?ni.AUDIO_TRACK_LOAD_TIMEOUT:ni.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case li:o=i?ni.SUBTITLE_TRACK_LOAD_TIMEOUT:ni.SUBTITLE_LOAD_ERROR,l=!1}h&&this.resetInternalLoader(t.type);const c={type:ii.NETWORK_ERROR,details:o,fatal:l,url:t.url,loader:h,context:t,error:a,networkDetails:e,stats:r};if(n){const i=(null==e?void 0:e.url)||t.url;c.response=vi({url:i,data:void 0},n)}this.hls.trigger(ri.ERROR,c)}handlePlaylistLoaded(t,e,i,n,r,s){const a=this.hls,{type:o,level:l,levelOrTrack:h,id:c,groupId:u,deliveryDirectives:d}=n,f=au(e,n),g=su(n);let p="number"==typeof n.level&&g===hi?l:void 0;const m=t.playlistParsingError;if(m){if(this.hls.logger.warn(`${m} ${t.url}`),!a.config.ignorePlaylistParsingErrors)return void a.trigger(ri.ERROR,{type:ii.NETWORK_ERROR,details:ni.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:m,reason:m.message,response:e,context:n,level:p,parent:g,networkDetails:r,stats:i});t.playlistParsingError=null}if(!t.fragments.length){const s=t.playlistParsingError=new Error("No Segments found in Playlist");return void a.trigger(ri.ERROR,{type:ii.NETWORK_ERROR,details:ni.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:s,reason:s.message,response:e,context:n,level:p,parent:g,networkDetails:r,stats:i})}switch(t.live&&s&&(s.getCacheAge&&(t.ageHeader=s.getCacheAge()||0),s.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),o){case si:case ai:if(p)if(h){if(h!==a.levels[p]){const t=a.levels.indexOf(h);t>-1&&(p=t)}}else p=0;a.trigger(ri.LEVEL_LOADED,{details:t,levelInfo:h||a.levels[0],level:p||0,id:c||0,stats:i,networkDetails:r,deliveryDirectives:d,withoutMultiVariant:o===si});break;case oi:a.trigger(ri.AUDIO_TRACK_LOADED,{details:t,track:h,id:c||0,groupId:u||"",stats:i,networkDetails:r,deliveryDirectives:d});break;case li:a.trigger(ri.SUBTITLE_TRACK_LOADED,{details:t,track:h,id:c||0,groupId:u||"",stats:i,networkDetails:r,deliveryDirectives:d})}}}class lu{static get version(){return Oa}static isMSESupported(){return eu()}static isSupported(){return function(){if(!eu())return!1;const t=_i();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(Tn(e,"video")))||["mp4a.40.2","fLaC"].some(e=>t.isTypeSupported(Tn(e,"audio"))))}()}static getMediaSource(){return _i()}static get Events(){return ri}static get MetadataSchema(){return io}static get ErrorTypes(){return ii}static get ErrorDetails(){return ni}static get DefaultConfig(){return lu.defaultConfig?lu.defaultConfig:$c}static set DefaultConfig(t){lu.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new wa,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const e=this.logger=function(t,e,i){const n=Ti();if("object"==typeof console&&!0===t||"object"==typeof t){const r=["debug","log","info","warn","error"];r.forEach(e=>{n[e]=bi(e,t,i)});try{n.log(`Debug logs enabled for "${e}" in hls.js version 1.6.17`)}catch(t){return Ti()}r.forEach(e=>{Si[e]=bi(e,t)})}else pi(Si,n);return n}(t.debug||!1,"Hls instance",t.assetPlayerId),i=this.config=function(t,e,i){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 n=Gc(t),r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(t=>{const s=`${"level"===t?"playlist":t}LoadPolicy`,a=void 0===e[s],o=[];r.forEach(i=>{const r=`${t}Loading${i}`,l=e[r];if(void 0!==l&&a){o.push(r);const t=n[s].default;switch(e[s]={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}}}),o.length&&i.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${s}": ${qn(e[s])}`)}),vi(vi({},n),e)}(lu.DefaultConfig,t,e);this.userConfig=t,i.progressive&&Vc(i,e);const{abrController:n,bufferController:r,capLevelController:s,errorController:a,fpsController:o}=i,l=new a(this),h=this.abrController=new n(this),c=new Pr(this),u=i.interstitialsController,d=u?this.interstitialsController=new u(this,lu):null,f=this.bufferController=new r(this,c),g=this.capLevelController=new s(this),p=new o(this),m=new ou(this),v=i.contentSteeringController,y=v?new v(this):null,A=this.levelController=new Zc(this,y),E=new Xc(this),T=new nu(this.config,this.logger),b=this.streamController=new iu(this,c,T),S=this.gapController=new Kc(this,c);g.setStreamController(b),p.setStreamController(b);const k=[m,A,b];d&&k.splice(1,0,d),y&&k.splice(1,0,y),this.networkControllers=k;const _=[h,f,S,g,p,E,c];this.audioTrackController=this.createController(i.audioTrackController,k);const L=i.audioStreamController;L&&k.push(this.audioStreamController=new L(this,c,T)),this.subtitleTrackController=this.createController(i.subtitleTrackController,k);const I=i.subtitleStreamController;I&&k.push(this.subtititleStreamController=new I(this,c,T)),this.createController(i.timelineController,_),T.emeController=this.emeController=this.createController(i.emeController,_),this.cmcdController=this.createController(i.cmcdController,_),this.latencyController=this.createController(Qc,_),this.coreComponents=_,k.push(l);const R=l.onErrorOut;"function"==typeof R&&this.on(ri.ERROR,R,l),this.on(ri.MANIFEST_LOADED,m.onManifestLoaded,m)}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,n){this._emitter.off(t,e,i,n)}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(this.logger.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===ri.ERROR;this.trigger(ri.ERROR,{type:ii.OTHER_ERROR,details:ni.INTERNAL_EXCEPTION,fatal:i,event:t,error:e}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger(ri.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){if(!t||"media"in t&&!t.media){const e=new Error(`attachMedia failed: invalid argument (${t})`);return void this.trigger(ri.ERROR,{type:ii.OTHER_ERROR,details:ni.ATTACH_MEDIA_ERROR,fatal:!0,error:e})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const e="media"in t,i=e?t.media:t,n=e?t:{media:i};this._media=i,this.trigger(ri.MEDIA_ATTACHING,n)}detachMedia(){this.logger.log("detachMedia"),this.trigger(ri.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger(ri.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const e=this.media,i=this._url,n=this._url=Oi.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${n}`),e&&i&&(i!==n||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(e)),this.trigger(ri.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(t=-1,e){this.logger.log(`startLoad(${t+(e?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(t,e),this.started&&this.networkControllers);i++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let t=0;t<this.networkControllers.length&&(this.networkControllers[t].stopLoad(),!this.started&&this.networkControllers);t++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(t=>{t.resumeBuffering&&t.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(t=>{t.pauseBuffering&&t.pauseBuffering()}))}get inFlightFragments(){const t={[hi]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[ci]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[ui]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const t=this._media,e=null==t?void 0:t.currentTime;this.detachMedia(),t&&(this.attachMedia(t),e&&this.startLoad(e))}removeLevel(t){this.levelController.removeLevel(t)}get sessionId(){let t=this._sessionId;return t||(t=this._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)})}}}()),t}get levels(){const t=this.levelController.levels;return t||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){this.logger.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){this.logger.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){this.logger.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){this.logger.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){this.logger.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 abrEwmaDefaultEstimate(){const{bwEstimator:t}=this.abrController;return t?t.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(this.logger.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){(function(t){return Un.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 n=0;n<i;n++)if(t[n].maxBitrate>=e)return n;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:i}=this;let n;if(n=-1===e&&null!=t&&t.length?t.length-1:e,i)for(let e=n;e--;){const n=t[e].attrs["HDCP-LEVEL"];if(n&&n<=i)return e}return n}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()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(t){var e;return(null==(e=this.audioTrackController)?void 0:e.setAudioOption(t))||null}setSubtitleOption(t){var e;return(null==(e=this.subtitleTrackController)?void 0: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}set targetLatency(t){this.latencyController.targetLatency=t}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(t){this.levelController.pathwayPriority=t}get bufferedToEnd(){var t;return!(null==(t=this.bufferController)||!t.bufferedToEnd)}get interstitialsManager(){var t;return(null==(t=this.interstitialsController)?void 0:t.interstitialsManager)||null}getMediaDecodingInfo(t,e=this.allAudioTracks){return Nn(t,Qn(e),navigator.mediaCapabilities)}}function hu(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,n=Array(e);i<e;i++)n[i]=t[i];return n}function cu(t,e,i){return e=gu(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,pu()?Reflect.construct(e,i||[],gu(t).constructor):e.apply(t,i))}function uu(t,e){for(var i=0;i<e.length;i++){var n=e[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,Tu(n.key),n)}}function du(t,e,i){return(e=Tu(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function fu(){return fu="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(t,e,i){var n=function(t,e){for(;!{}.hasOwnProperty.call(t,e)&&null!==(t=gu(t)););return t}(t,e);if(n){var r=Object.getOwnPropertyDescriptor(n,e);return r.get?r.get.call(arguments.length<3?t:i):r.value}},fu.apply(null,arguments)}function gu(t){return gu=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},gu(t)}function pu(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(pu=function(){return!!t})()}function mu(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),i.push.apply(i,n)}return i}function vu(t){for(var e=1;e<arguments.length;e++){var i=null!=arguments[e]?arguments[e]:{};e%2?mu(Object(i),!0).forEach(function(e){du(t,e,i[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):mu(Object(i)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))})}return t}function yu(t,e){return yu=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},yu(t,e)}function Au(t,e,i,n){var r=fu(gu(t.prototype),e,i);return 2&n&&"function"==typeof r?function(t){return r.apply(i,t)}:r}function Eu(t){return function(t){if(Array.isArray(t))return hu(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||function(t,e){if(t){if("string"==typeof t)return hu(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)?hu(t,e):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 Tu(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var n=i.call(t,e);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t,"string");return"symbol"==typeof e?e:e+""}if(lu.defaultConfig=void 0,!lu)throw new Error("@clappr/hlsjs-playback requires hls.js (^1) to be loaded before it");var bu=Z.now,Su=Z.listContainsIgnoreCase;ht.register("PLAYBACK_FRAGMENT_CHANGED"),ht.register("PLAYBACK_FRAGMENT_PARSING_METADATA");var ku=function(t){function e(){var t;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e);for(var i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];return(t=cu(this,e,[].concat(n))).options.hlsPlayback=vu(vu({},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&&yu(t,e)}(e,t),i=e,n=[{key:"name",get:function(){return"hls"}},{key:"supportedVersion",get:function(){return{min:"0.16.2"}}},{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(ht.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===It.LIVE&&"EVENT"!==this._playlistType?this._extrapolatedStartTime:this._playableRegionStartTime}},{key:"_now",get:function(){return bu()}},{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,n=(e.remote+i)/1e3;return Math.max(t-this._extrapolatedWindowDuration,Math.min(n,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(){var t;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=It.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=null!==(t=this.options.hlsRecoverAttempts)&&void 0!==t?t: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=vu({},this.options.playback.hlsjsConfig);this._hls=new lu(t)}},{key:"_attachHLSMedia",value:function(){this._hls&&this._hls.attachMedia(this.el)}},{key:"_listenHLSEvents",value:function(){var t=this;this._hls&&(this._hls.once(lu.Events.MEDIA_ATTACHED,function(){t.options.hlsPlayback.preload&&t._hls.loadSource(t.options.src)}),this._hls.on(lu.Events.MANIFEST_LOADING,function(){t._manifestLoading=!0}),this._hls.on(lu.Events.LEVEL_LOADED,function(e,i){return t._updatePlaybackType(e,i)}),this._hls.on(lu.Events.LEVEL_UPDATED,function(e,i){return t._onLevelUpdated(e,i)}),this._hls.on(lu.Events.LEVEL_SWITCHED,function(e,i){return t._onLevelSwitch(e,i)}),this._hls.on(lu.Events.FRAG_CHANGED,function(e,i){return t._onFragmentChanged(e,i)}),this._hls.on(lu.Events.FRAG_LOADED,function(e,i){return t._onFragmentLoaded(e,i)}),this._hls.on(lu.Events.FRAG_BUFFERED,function(e,i){return t._onFragmentBuffered(e,i)}),this._hls.on(lu.Events.FRAG_PARSING_METADATA,function(e,i){return t._onFragmentParsingMetadata(e,i)}),this._hls.on(lu.Events.ERROR,function(e,i){return t._onHLSJSError(e,i)}),this._hls.on(lu.Events.SUBTITLE_TRACK_LOADED,function(e,i){return t._onSubtitleLoaded(e,i)}),this._hls.on(lu.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,n=e.once?"once":"on";i&&t._hls["".concat(n)](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(ht.Custom.PLAYBACK_FRAGMENT_PARSING_METADATA,{evt:t,data:e})}},{key:"render",value:function(){return this._ready(),Au(e,"render",this,3)([])}},{key:"_ready",value:function(){this._isReadyState||(!this._hls&&this._setup(),this._isReadyState=!0,this.trigger(ht.PLAYBACK_READY,this.name))}},{key:"_recover",value:function(t,e,i){if(this._recoveredDecodingError)if(this._recoveredAudioCodecError){rt.error("hlsjs: failed to recover",{evt:t,data:e}),i.level=St.Levels.FATAL;var n=this.createError(i);this.trigger(ht.PLAYBACK_ERROR,n),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:"getFrameRate",value:function(){if(this._hls&&this._hls.levels&&this._hls.currentLevel>=0){var t=this._hls.levels[this._hls.currentLevel];return t&&t.frameRate?t.frameRate:null}return null}},{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){this.seek(this._duration*(t/100))}},{key:"seek",value:function(t){t<0&&(rt.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===It.VOD?this.settings.left=["playpause","position","duration"]:this.dvrEnabled?this.settings.left=["playpause"]:this.settings.left=["playstop"],this.settings.seekEnabled=this.isSeekEnabled(),this.trigger(ht.PLAYBACK_SETTINGSUPDATE)}},{key:"_onHLSJSError",value:function(t,e){var i,n={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&&(n.description+=", response: ".concat(JSON.stringify(e.response))),e.fatal)if(this._recoverAttemptsRemaining>0)switch(this._recoverAttemptsRemaining-=1,e.type){case lu.ErrorTypes.NETWORK_ERROR:switch(e.details){case lu.ErrorDetails.MANIFEST_LOAD_ERROR:case lu.ErrorDetails.MANIFEST_LOAD_TIMEOUT:case lu.ErrorDetails.MANIFEST_PARSING_ERROR:case lu.ErrorDetails.LEVEL_LOAD_ERROR:case lu.ErrorDetails.LEVEL_LOAD_TIMEOUT:rt.error("hlsjs: unrecoverable network fatal error.",{evt:t,data:e}),i=this.createError(n),this.trigger(ht.PLAYBACK_ERROR,i),this.stop();break;default:rt.warn("hlsjs: trying to recover from network error.",{evt:t,data:e}),n.level=St.Levels.WARN,this._hls.startLoad()}break;case lu.ErrorTypes.MEDIA_ERROR:rt.warn("hlsjs: trying to recover from media error.",{evt:t,data:e}),n.level=St.Levels.WARN,this._recover(t,e,n);break;default:rt.error("hlsjs: could not recover from error.",{evt:t,data:e}),i=this.createError(n),this.trigger(ht.PLAYBACK_ERROR,i),this.stop()}else rt.error("hlsjs: could not recover from error after maximum number of attempts.",{evt:t,data:e}),i=this.createError(n),this.trigger(ht.PLAYBACK_ERROR,i),this.stop();else{if(this.options.playback.triggerFatalErrorOnResourceDenied&&this._keyIsDenied(e))return rt.error("hlsjs: could not load decrypt key.",{evt:t,data:e}),i=this.createError(n),this.trigger(ht.PLAYBACK_ERROR,i),void this.stop();n.level=St.Levels.WARN,rt.warn("hlsjs: non-fatal error occurred",{evt:t,data:e})}}},{key:"_keyIsDenied",value:function(t){return t.type===lu.ErrorTypes.NETWORK_ERROR&&t.details===lu.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(ht.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,n=t.firstFragDateTime===this._lastTimeUpdate.firstFragDateTime,r=e&&i&&n,s=this._now-this._lastTimeUpdateFiredTime<this._timeUpdateThrottleDelay;return r&&s}},{key:"_onDurationChange",value:function(){var t=this.getDuration();Math.abs(this._lastDuration-t)<this._durationChangeMinOffset||(this._lastDuration=t,Au(e,"_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(Eu(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 n={start:t[e].start,current:t[e].end,total:this.getDuration()};this.trigger(ht.PLAYBACK_PROGRESS,n,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),Au(e,"play",this,3)([]),this._startTimeUpdateTimer()}},{key:"pause",value:function(){this._hls&&this.el.pause()}},{key:"stop",value:function(){this._stopTimeUpdateTimer(),this._hls&&Au(e,"stop",this,3)([]),this._destroyHLSInstance()}},{key:"destroy",value:function(){this._stopTimeUpdateTimer(),this._destroyHLSInstance(),Au(e,"destroy",this,3)([])}},{key:"_updatePlaybackType",value:function(t,e){this._playbackType=e.details.live?It.LIVE:It.VOD,this._onLevelUpdated(t,e),this._ccTracksUpdated&&this._playbackType===It.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(ht.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,n=!1,r=e.details.fragments,s=this._playableRegionStartTime,a=this._playableRegionDuration;if(0!==r.length){if(r[0].rawProgramDateTime&&(this._programDateTime=r[0].rawProgramDateTime),this._playableRegionStartTime!==r[0].start&&(i=!0,this._playableRegionStartTime=r[0].start),i)if(this._localStartTimeCorrelation){var o=this._localStartTimeCorrelation,l=this._now-o.local,h=(o.remote+l)/1e3;h<r[0].start?this._localStartTimeCorrelation={local:this._now,remote:1e3*r[0].start}:h>s+this._extrapolatedWindowDuration&&(this._localStartTimeCorrelation={local:this._now,remote:1e3*Math.max(r[0].start,s+this._extrapolatedWindowDuration)})}else this._localStartTimeCorrelation={local:this._now,remote:1e3*(r[0].start+this._extrapolatedWindowDuration/2)};var c=e.details.totalduration;if(this._playbackType===It.LIVE){var u=e.details.targetduration*((this.options.playback.hlsjsConfig||{}).liveSyncDurationCount||lu.DefaultConfig.liveSyncDurationCount);u<=c?(c-=u,this._durationExcludesAfterLiveSyncPoint=!0):this._durationExcludesAfterLiveSyncPoint=!1}c!==this._playableRegionDuration&&(n=!0,this._playableRegionDuration=c);var d=r[0].start+c,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};n&&this._onDurationChange(),i&&this._onProgress()}}},{key:"_onFragmentChanged",value:function(t,e){this._currentFragment=e.frag,this.trigger(ht.Custom.PLAYBACK_FRAGMENT_CHANGED,e)}},{key:"_onFragmentLoaded",value:function(t,e){this.trigger(ht.PLAYBACK_FRAGMENT_LOADED,e)}},{key:"_onFragmentBuffered",value:function(t,e){this.trigger(ht.PLAYBACK_FRAGMENT_BUFFERED,e)}},{key:"_onSubtitleLoaded",value:function(){if(!this._ccIsSetup){this.trigger(ht.PLAYBACK_SUBTITLE_AVAILABLE);var t=this._playbackType===It.LIVE?-1:this.closedCaptionsTrackId;this.closedCaptionsTrackId=t,this._ccIsSetup=!0}}},{key:"_onLevelSwitch",value:function(t,e){this.levels.length||this._fillLevels(),this.trigger(ht.PLAYBACK_LEVEL_SWITCH_END),this.trigger(ht.PLAYBACK_LEVEL_SWITCH,e);var i=this._hls.levels[e.level];i&&(this.highDefinition=i.height>=720||i.bitrate/1e3>=2e3,this.trigger(ht.PLAYBACK_HIGHDEFINITIONUPDATE,this.highDefinition),this.trigger(ht.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()===It.LIVE}},{key:"getPlaybackType",value:function(){return this._playbackType}},{key:"isSeekEnabled",value:function(){return this._playbackType===It.VOD||this.dvrEnabled}}],r=[{key:"HLSJS",get:function(){return lu}}],n&&uu(i.prototype,n),r&&uu(i,r),Object.defineProperty(i,"prototype",{writable:!1}),i;var i,n,r}(jt);return ku.canPlay=function(t,e){var i=t.split("?")[0].match(/.*\.(.*)$/)||[],n=i.length>1&&"m3u8"===i[1].toLowerCase()||Su(e,["application/vnd.apple.mpegurl","application/x-mpegURL"]);return!(!lu.isSupported()||!n)},Ze.Loader.registerPlayback(ku),i(i({},Ze),{},{HLS:ku})});
|
|
1
|
+
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).Clappr=e()}(this,function(){"use strict";function t(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var n=i.call(t,e);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function e(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),i.push.apply(i,n)}return i}function i(i){for(var n=1;n<arguments.length;n++){var r=null!=arguments[n]?arguments[n]:{};n%2?e(Object(r),!0).forEach(function(e){t(i,e,r[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(i,Object.getOwnPropertyDescriptors(r)):e(Object(r)).forEach(function(t){Object.defineProperty(i,t,Object.getOwnPropertyDescriptor(r,t))})}return i}function n(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,n=Array(e);i<e;i++)n[i]=t[i];return n}function r(t,e,i){return e=u(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,f()?Reflect.construct(e,i||[],u(t).constructor):e.apply(t,i))}function s(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function a(t,e){for(var i=0;i<e.length;i++){var n=e[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,E(n.key),n)}}function o(t,e,i){return e&&a(t.prototype,e),i&&a(t,i),Object.defineProperty(t,"prototype",{writable:!1}),t}function l(t,e){var i="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!i){if(Array.isArray(t)||(i=b(t))||e){i&&(t=i);var n=0,r=function(){};return{s:r,n:function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:r}}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 h(t,e,i){return(e=E(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function c(){return c="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(t,e,i){var n=function(t,e){for(;!{}.hasOwnProperty.call(t,e)&&null!==(t=u(t)););return t}(t,e);if(n){var r=Object.getOwnPropertyDescriptor(n,e);return r.get?r.get.call(arguments.length<3?t:i):r.value}},c.apply(null,arguments)}function u(t){return u=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},u(t)}function d(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&&m(t,e)}function f(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(f=function(){return!!t})()}function g(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),i.push.apply(i,n)}return i}function p(t){for(var e=1;e<arguments.length;e++){var i=null!=arguments[e]?arguments[e]:{};e%2?g(Object(i),!0).forEach(function(e){h(t,e,i[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):g(Object(i)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))})}return t}function m(t,e){return m=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},m(t,e)}function v(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 n,r,s,a,o=[],l=!0,h=!1;try{if(s=(i=i.call(t)).next,0===e){if(Object(i)!==i)return;l=!1}else for(;!(l=(n=s.call(i)).done)&&(o.push(n.value),o.length!==e);l=!0);}catch(t){h=!0,r=t}finally{try{if(!l&&null!=i.return&&(a=i.return(),Object(a)!==a))return}finally{if(h)throw r}}return o}}(t,e)||b(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 y(t,e,i,n){var r=c(u(t.prototype),e,i);return"function"==typeof r?function(t){return r.apply(i,t)}:r}function A(t){return function(t){if(Array.isArray(t))return n(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||b(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 E(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var n=i.call(t,e);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t,"string");return"symbol"==typeof e?e:e+""}function T(t){return T="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},T(t)}function b(t,e){if(t){if("string"==typeof t)return n(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)?n(t,e):void 0}}var S,k=function(){var t,e,i,n,r,s,a=[],o=a.concat,l=a.filter,h=a.slice,c=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+(?!\w))[^>]*>/,p=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,m=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)(?![\w:])(?:"[^"]*"|'[^']*'|\/(?!>)|[^>"'\/])*)\/>/gi,v=/^(?:body|html)$/i,y=/([A-Z])/g,A=["val","css","html","text","data","width","height","offset"],E=c.createElement("table"),T=c.createElement("tr"),b={tr:c.createElement("tbody"),tbody:E,thead:E,tfoot:E,td:T,th:T,"*":c.createElement("div")},S=/complete|loaded|interactive/,k=/^[\w-]*$/,_={},L=_.toString,R={},I=c.createElement("div"),C={tabindex:"tabIndex",readonly:"readOnly",for:"htmlFor",class:"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},P=Array.isArray||function(t){return t instanceof Array};function D(t){return null==t?String(t):_[L.call(t)]||"object"}function w(t){return"function"==D(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"==D(t)}function N(t){return M(t)&&!O(t)&&Object.getPrototypeOf(t)==Object.prototype}function F(t){var e=!!t&&"length"in t&&t.length,n=i.type(t);return"function"!=n&&!O(t)&&("array"==n||0===e||"number"==typeof e&&e>0&&e-1 in t)}function B(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 $(t){return t in d?d[t]:d[t]=new RegExp("(^|\\s)"+t+"(\\s|$)")}function U(t,e){return"number"!=typeof e||f[B(t)]?e:e+"px"}function G(t){return"children"in t?h.call(t.children):i.map(t.childNodes,function(t){if(1==t.nodeType)return t})}function V(t,e){var i,n=t?t.length:0;for(i=0;i<n;i++)this[i]=t[i];this.length=n,this.selector=e||""}function K(i,n,r){for(e in n)r&&(N(n[e])||P(n[e]))?(N(n[e])&&!N(i[e])&&(i[e]={}),P(n[e])&&!P(i[e])&&(i[e]=[]),K(i[e],n[e],r)):n[e]!==t&&(i[e]=n[e])}function H(t,e){return null==e?i(t):i(t).filter(e)}function Y(t,e,i,n){return w(e)?e.call(t,i,n):e}function j(t,e,i){null==i?t.removeAttribute(e):t.setAttribute(e,i)}function W(e,i){var n=e.className||"",r=n&&n.baseVal!==t;if(i===t)return r?n.baseVal:n;r?n.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,n=t.childNodes.length;i<n;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 n,r=t.parentNode,s=!r;return s&&(r=I).appendChild(t),n=~R.qsa(r,e).indexOf(t),s&&I.removeChild(t),n},r=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,n,r){var s,a,o,l;return(l=p.exec(e))&&(s=i(c.createElement(l[1]))),s||(e.replace&&(e=e.replace(m,"<$1></$2>")),n===t&&(n=(l=g.exec(e))&&l[1]),Object.prototype.hasOwnProperty.call(b,n)||(n="*"),(o=b[n]).innerHTML=""+e,s=i.each(h.call(o.childNodes),function(){o.removeChild(this)})),N(r)&&(a=i(s),i.each(r,function(t,e){A.indexOf(t)>-1?a[t](e):a.attr(t,e)})),s},R.Z=function(t,e){return new V(t,e)},R.isZ=function(t){return t instanceof R.Z},R.init=function(e,n){var r,s,a;if(!e)return R.Z();if("string"==typeof e)if("<"==(e=e.trim())[0]&&(s=g.exec(e)))r=R.fragment(e,s[1],n),e=null;else{if(n!==t)return i(n).find(e);r=R.qsa(c,e)}else{if(w(e))return i(c).ready(e);if(R.isZ(e))return e;if(P(e))a=e,r=l.call(a,function(t){return null!=t});else if(M(e))r=[e],e=null;else if(s=g.exec(e))r=R.fragment(e.trim(),s[1],n),e=null;else{if(n!==t)return i(n).find(e);r=R.qsa(c,e)}}return R.Z(r,e)},(i=function(t,e){return R.init(t,e)}).extend=function(t){var e,i=h.call(arguments,1);return"boolean"==typeof t&&(e=t,t=i.shift()),i.forEach(function(i){K(t,i,e)}),t},R.qsa=function(t,e){var i,n="#"==e[0],r=!n&&"."==e[0],s=n||r?e.slice(1):e,a=k.test(s);return t.getElementById&&a&&n?(i=t.getElementById(s))?[i]:[]:1!==t.nodeType&&9!==t.nodeType&&11!==t.nodeType?[]:h.call(a&&!n&&t.getElementsByClassName?r?t.getElementsByClassName(s):t.getElementsByTagName(e):t.querySelectorAll(e))},i.contains=c.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=D,i.isFunction=w,i.isWindow=O,i.isArray=P,i.isPlainObject=N,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=r,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 n,r,s,a,o=[];if(F(t))for(r=0;r<t.length;r++)null!=(n=e(t[r],r))&&o.push(n);else for(s in t)null!=(n=e(t[s],s))&&o.push(n);return(a=o).length>0?i.fn.concat.apply([],a):a},i.each=function(t,e){var i,n;if(F(t)){for(i=0;i<t.length;i++)if(!1===e.call(t[i],i,t[i]))return t}else for(n in t)if(!1===e.call(t[n],n,t[n]))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(h.apply(this,arguments))},ready:function(t){return S.test(c.readyState)&&c.body?t(i):c.addEventListener("DOMContentLoaded",function(){t(i)},!1),this},get:function(e){return e===t?h.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 w(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 n=[];if(w(e)&&e.call!==t)this.each(function(t){e.call(this,t)||n.push(this)});else{var r="string"==typeof e?this.filter(e):F(e)&&w(e.item)?h.call(e):i(e);this.forEach(function(t){r.indexOf(t)<0&&n.push(t)})}return i(n)},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 n=[],r="object"==typeof t&&i(t);return this.each(function(i,s){for(;s&&!(r?r.indexOf(s)>=0:R.matches(s,t));)s=s!==e&&!x(s)&&s.parentNode;s&&n.indexOf(s)<0&&n.push(s)}),i(n)},parents:function(t){for(var e=[],n=this;n.length>0;)n=i.map(n,function(t){if((t=t.parentNode)&&!x(t)&&e.indexOf(t)<0)return e.push(t),t});return H(e,t)},parent:function(t){return H(s(this.pluck("parentNode")),t)},children:function(t){return H(this.map(function(){return G(this)}),t)},contents:function(){return this.map(function(){return this.contentDocument||h.call(this.childNodes)})},siblings:function(t){return H(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=c.createElement(t),c.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=w(t);if(this[0]&&!e)var n=i(t).get(0),r=n.parentNode||this.length>1;return this.each(function(s){i(this).wrapAll(e?t.call(this,s):r?n.cloneNode(!0):n)})},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=w(t);return this.each(function(n){var r=i(this),s=r.contents(),a=e?t.call(this,n):t;s.length?s.wrapAll(a):r.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 n=i(this);(e===t?"none"==n.css("display"):e)?n.show():n.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 n=this.innerHTML;i(this).empty().append(Y(this,t,e,n))}):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,n){var r;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,n,t,this.getAttribute(i)))}):0 in this&&1==this[0].nodeType&&null!=(r=this[0].getAttribute(i))?r: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=C[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=C[t]||t,this.each(function(){delete this[t]})},data:function(e,i){var n="data-"+e.replace(y,"-$1").toLowerCase(),r=1 in arguments?this.attr(n,i):this.attr(n);return null!==r?z(r):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 n=i(this),r=Y(this,t,e,n.offset()),s=n.offsetParent().offset(),a={top:r.top-s.top,left:r.left-s.left};"static"==n.css("position")&&(a.position="relative"),n.css(a)});if(!this.length)return null;if(c.documentElement!==this[0]&&!i.contains(c.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,n){if(arguments.length<2){var s=this[0];if("string"==typeof t){if(!s)return;return s.style[r(t)]||getComputedStyle(s,"").getPropertyValue(t)}if(P(t)){if(!s)return;var a={},o=getComputedStyle(s,"");return i.each(t,function(t,e){a[e]=s.style[r(e)]||o.getPropertyValue(e)}),a}}var l="";if("string"==D(t))n||0===n?l=B(t)+":"+U(t,n):this.each(function(){this.style.removeProperty(B(t))});else for(e in t)t[e]||0===t[e]?l+=B(e)+":"+U(e,t[e])+";":this.each(function(){this.style.removeProperty(B(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))},$(t))},addClass:function(t){return t?this.each(function(e){if("className"in this){n=[];var r=W(this);Y(this,t,e,r).split(/\s+/g).forEach(function(t){i(this).hasClass(t)||n.push(t)},this),n.length&&W(this,r+(r?" ":"")+n.join(" "))}}):this},removeClass:function(e){return this.each(function(i){if("className"in this){if(e===t)return W(this,"");n=W(this),Y(this,e,i,n).split(/\s+/g).forEach(function(t){n=n.replace($(t)," ")}),W(this,n.trim())}})},toggleClass:function(e,n){return e?this.each(function(r){var s=i(this);Y(this,e,r,W(this)).split(/\s+/g).forEach(function(e){(n===t?!s.hasClass(e):n)?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(),n=this.offset(),r=v.test(e[0].nodeName)?{top:0,left:0}:e.offset();return n.top-=parseFloat(i(t).css("margin-top"))||0,n.left-=parseFloat(i(t).css("margin-left"))||0,r.top+=parseFloat(i(e[0]).css("border-top-width"))||0,r.left+=parseFloat(i(e[0]).css("border-left-width"))||0,{top:n.top-r.top,left:n.left-r.left}}},offsetParent:function(){return this.map(function(){for(var t=this.offsetParent||c.body;t&&!v.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 n=e.replace(/./,function(t){return t[0].toUpperCase()});i.fn[e]=function(r){var s,a=this[0];return r===t?O(a)?a["inner"+n]:x(a)?a.documentElement["scroll"+n]:(s=this.offset())&&s[e]:this.each(function(t){(a=i(this)).css(e,Y(this,r,t,a[e]()))})}}),["after","prepend","before","append"].forEach(function(e,n){var r=n%2;i.fn[e]=function(){var e,s,a=i.map(arguments,function(n){var r=[];return"array"==(e=D(n))?(n.forEach(function(e){return e.nodeType!==t?r.push(e):i.zepto.isZ(e)?r=r.concat(e.get()):void(r=r.concat(R.fragment(e)))}),r):"object"==e||null==n?n:R.fragment(n)}),o=this.length>1;return a.length<1?this:this.each(function(t,e){s=r?e:e.parentNode,e=0==n?e.nextSibling:1==n?e.firstChild:2==n?e:null;var l=i.contains(c.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[r?e+"To":"insert"+(n?"Before":"After")]=function(t){return i(t)[e](this),this}}),R.Z.prototype=V.prototype=i.fn,R.uniq=s,R.deserializeValue=z,i.zepto=R,i}();window.Zepto=k,void 0===window.$&&(window.$=k),function(t){var e,i,n=+new Date,r=window.document,s=/^(?:text|application)\/javascript/i,a=/^(?:text|application)\/xml/i,o="application/json",l="text/html",h=/^\s*$/,c=r.createElement("a");function u(e,i,n,s){if(e.global)return function(e,i,n){var r=t.Event(i);return t(e).trigger(r,n),!r.isDefaultPrevented()}(i||r,n,s)}function d(t,e){var i=e.context;if(!1===e.beforeSend.call(i,t,e)||!1===u(e,i,"ajaxBeforeSend",[t,e]))return!1;u(e,i,"ajaxSend",[t,e])}function f(t,e,i,n){var r=i.context,s="success";i.success.call(r,t,s,e),n&&n.resolveWith(r,[t,s,e]),u(i,r,"ajaxSuccess",[e,i,t]),p(s,e,i)}function g(t,e,i,n,r){var s=n.context;n.error.call(s,i,e,t),r&&r.rejectWith(s,[i,e,t]),u(n,s,"ajaxError",[i,n,t||e]),p(e,i,n)}function p(e,i,n){var r=n.context;n.complete.call(r,i,e),u(n,r,"ajaxComplete",[i,n]),function(e){e.global&&! --t.active&&u(e,null,"ajaxStop")}(n)}function m(){}function v(t,e){return""==e?t:(t+"&"+e).replace(/[&?]{1,2}/,"?")}function y(e,i,n,r){return t.isFunction(i)&&(r=n,n=i,i=void 0),t.isFunction(n)||(r=n,n=void 0),{url:e,data:i,success:n,dataType:r}}c.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"+n++,h=r.createElement("script"),c=window[l],u=function(e){t(h).triggerHandler("error",e||"abort")},p={abort:u};if(i&&i.promise(p),t(h).on("load error",function(n,r){clearTimeout(a),t(h).off().remove(),"error"!=n.type&&s?f(s[0],p,e,i):g(null,r||"error",p,e,i),window[l]=c,s&&t.isFunction(c)&&c(s[0]),c=s=void 0}),!1===d(p,e))return u("abort"),p;window[l]=function(){s=arguments};var m=e.url.indexOf("?"),v=m>-1?e.url.lastIndexOf("=?"):-1;return h.src=v>m+1?e.url.slice(0,v+1)+l+e.url.slice(v+2):e.url,r.head.appendChild(h),e.timeout>0&&(a=setTimeout(function(){u("timeout")},e.timeout)),p},t.ajaxSettings={type:"GET",beforeSend:m,success:m,error:m,complete:m,context:null,global:!0,xhr:function(){return new window.XMLHttpRequest},accepts:{script:"text/javascript, application/javascript, application/x-javascript",json:o,xml:"application/xml, text/xml",html:l,text:"text/plain"},crossDomain:!1,timeout:0,processData:!0,cache:!0,dataFilter:m},t.ajax=function(n){var p,y,A=t.extend({},n||{}),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++&&u(e,null,"ajaxStart")}(A),A.crossDomain||((p=r.createElement("a")).href=A.url,p.href=p.href,A.crossDomain=c.protocol+"//"+c.host!=p.protocol+"//"+p.host),A.url||(A.url=window.location.toString()),(y=A.url.indexOf("#"))>-1&&(A.url=A.url.slice(0,y)),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,b=/\?.+=\?/.test(A.url);if(b&&(T="jsonp"),!1!==A.cache&&(n&&!0===n.cache||"script"!=T&&"jsonp"!=T)||(A.url=v(A.url,"_="+Date.now())),"jsonp"==T)return b||(A.url=v(A.url,A.jsonp?A.jsonp+"=?":!1===A.jsonp?"":"callback=?")),t.ajaxJSONP(A,E);var S,k=A.accepts[T],_={},L=function(t,e){_[t.toLowerCase()]=[t,e]},R=/^([\w-]+:)\/\//.test(A.url)?RegExp.$1:window.location.protocol,I=A.xhr(),C=I.setRequestHeader;if(E&&E.promise(I),A.crossDomain||L("X-Requested-With","XMLHttpRequest"),L("Accept",k||"*/*"),(k=A.mimeType||k)&&(k.indexOf(",")>-1&&(k=k.split(",",2)[0]),I.overrideMimeType&&I.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(I.setRequestHeader=L,I.onreadystatechange=function(){if(4==I.readyState){I.onreadystatechange=m,clearTimeout(S);var e,i=!1;if(I.status>=200&&I.status<300||304==I.status||0==I.status&&"file:"==R){if(T=T||function(t){return t&&(t=t.split(";",2)[0]),t&&(t==l?"html":t==o?"json":s.test(t)?"script":a.test(t)&&"xml")||"text"}(A.mimeType||I.getResponseHeader("content-type")),"arraybuffer"==I.responseType||"blob"==I.responseType)e=I.response;else{e=I.responseText;try{e=function(t,e,i){if(i.dataFilter==m)return t;var n=i.context;return i.dataFilter.call(n,t,e)}(e,T,A),"script"==T?(0,eval)(e):"xml"==T?e=I.responseXML:"json"==T&&(e=h.test(e)?null:t.parseJSON(e))}catch(t){i=t}if(i)return g(i,"parsererror",I,A,E)}f(e,I,A,E)}else g(I.statusText||null,I.status?"error":"abort",I,A,E)}},!1===d(I,A))return I.abort(),g(null,"abort",I,A,E),I;var P=!("async"in A)||A.async;if(I.open(A.type,A.url,P,A.username,A.password),A.xhrFields)for(i in A.xhrFields)I[i]=A.xhrFields[i];for(i in _)C.apply(I,_[i]);return A.timeout>0&&(S=setTimeout(function(){I.onreadystatechange=m,I.abort(),g(null,"timeout",I,A,E)},A.timeout)),I.send(A.data?A.data:null),I},t.get=function(){return t.ajax(y.apply(null,arguments))},t.post=function(){var e=y.apply(null,arguments);return e.type="POST",t.ajax(e)},t.getJSON=function(){var e=y.apply(null,arguments);return e.dataType="json",t.ajax(e)},t.fn.load=function(e,i,n){if(!this.length)return this;var r,s=this,a=e.split(/\s/),o=y(e,i,n),l=o.success;return a.length>1&&(o.url=a[0],r=a[1]),o.success=function(e){if(r){var i=t("<div>").html(e);i.find("script").remove(),s.html(i.find(r))}else s.html(e);l&&l.apply(s,arguments)},t.ajax(o),this};var A=encodeURIComponent;function E(e,i,n,r){var s,a=t.isArray(i),o=t.isPlainObject(i);t.each(i,function(i,l){s=t.type(l),r&&(i=n?r:r+"["+(o||"object"==s||"array"==s?i:"")+"]"),!r&&a?e.add(l.name,l.value):"array"==s||!n&&"object"==s?E(e,l,n,i):e.add(i,l)})}t.param=function(e,i){var n=[];return n.add=function(e,i){t.isFunction(i)&&(i=i()),null==i&&(i=""),this.push(A(e)+"="+A(i))},E(n,e,i),n.join("&").replace(/%20/g,"+")}}(k),(S=k).Callbacks=function(t){t=S.extend({},t);var e,i,n,r,s,a,o=[],l=!t.once&&[],h=function(u){for(e=t.memory&&u,i=!0,a=r||0,r=0,s=o.length,n=!0;o&&a<s;++a)if(!1===o[a].apply(u[0],u[1])&&t.stopOnFalse){e=!1;break}n=!1,o&&(l?l.length&&h(l.shift()):e?o.length=0:c.disable())},c={add:function(){if(o){var i=o.length,a=function(e){S.each(e,function(e,i){"function"==typeof i?t.unique&&c.has(i)||o.push(i):i&&i.length&&"string"!=typeof i&&a(i)})};a(arguments),n?s=o.length:e&&(r=i,h(e))}return this},remove:function(){return o&&S.each(arguments,function(t,e){for(var i;(i=S.inArray(e,o,i))>-1;)o.splice(i,1),n&&(i<=s&&--s,i<=a&&--a)}),this},has:function(t){return!(!o||!(t?S.inArray(t,o)>-1:o.length))},empty:function(){return s=o.length=0,this},disable:function(){return o=l=e=void 0,this},disabled:function(){return!o},lock:function(){return l=void 0,e||c.disable(),this},locked:function(){return!l},fireWith:function(t,e){return!o||i&&!l||(e=[t,(e=e||[]).slice?e.slice():e],n?l.push(e):h(e)),this},fire:function(){return c.fireWith(this,arguments)},fired:function(){return!!i}};return c},function(t){var e=Array.prototype.slice;function i(e){var n=[["resolve","done",t.Callbacks({once:1,memory:1}),"resolved"],["reject","fail",t.Callbacks({once:1,memory:1}),"rejected"],["notify","progress",t.Callbacks({memory:1})]],r="pending",s={state:function(){return r},always:function(){return a.done(arguments).fail(arguments),this},then:function(){var e=arguments;return i(function(i){t.each(n,function(n,r){var o=t.isFunction(e[n])&&e[n];a[r[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 n=this===s?i.promise():this,a=o?[e]:arguments;i[r[0]+"With"](n,a)}})}),e=null}).promise()},promise:function(e){return null!=e?t.extend(e,s):s}},a={};return t.each(n,function(t,e){var i=e[2],o=e[3];s[e[1]]=i.add,o&&i.add(function(){r=o},n[1^t][2].disable,n[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(n){var r,s,a,o=e.call(arguments),l=o.length,h=0,c=1!==l||n&&t.isFunction(n.promise)?l:0,u=1===c?n:i(),d=function(t,i,n){return function(s){i[t]=this,n[t]=arguments.length>1?e.call(arguments):s,n===r?u.notifyWith(i,n):--c||u.resolveWith(i,n)}};if(l>1)for(r=new Array(l),s=new Array(l),a=new Array(l);h<l;++h)o[h]&&t.isFunction(o[h].promise)?o[h].promise().done(d(h,a,o)).fail(u.reject).progress(d(h,s,r)):--c;return c||u.resolveWith(a,o),u.promise()},t.Deferred=i}(k),function(t){var e,i=1,n=Array.prototype.slice,r=t.isFunction,s=function(t){return"string"==typeof t},a=Object.create(null),o={},l="onfocusin"in window,h={focus:"focusin",blur:"focusout"},c={mouseenter:"mouseover",mouseleave:"mouseout"};function u(t){var e=t._zid;return"number"!=typeof e&&(t._zid=e=i++),e}function d(t,e,i,n){if((e=f(e)).ns)var r=(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||r.test(t.ns))&&(!i||u(t.fn)===u(i))&&(!n||t.sel==n)})}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 h||!!e}function p(t){return c[t]||l&&h[t]||t}function m(i,n,r,s,o,l,h){var d=u(i),m=a[d]||(a[d]=[]);n.split(/\s/).forEach(function(n){if("ready"==n)return t(document).ready(r);var a=f(n);a.fn=r,a.sel=o,a.e in c&&(r=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||r;a.proxy=function(t){if(!(t=b(t)).isImmediatePropagationStopped()){t.data=s;var n=u.apply(i,t._args==e?[t]:[t].concat(t._args));return!1===n&&(t.preventDefault(),t.stopPropagation()),n}},a.i=m.length,m.push(a),"addEventListener"in i&&i.addEventListener(p(a.e),a.proxy,g(a,h))})}function v(t,e,i,n,r){var s=u(t);(e||"").split(/\s/).forEach(function(e){d(t,e,i,n).forEach(function(e){delete a[s][e.i],"removeEventListener"in t&&t.removeEventListener(p(e.e),e.proxy,g(e,r))})})}o.click=o.mousedown=o.mouseup=o.mousemove="MouseEvents",t.event={add:m,remove:v},t.proxy=function(e,i){var a=2 in arguments&&n.call(arguments,2);if(r(e)){var o=function(){return e.apply(i,a?a.concat(n.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,n){return this.on(t,e,i,n,1)};var y=function(){return!0},A=function(){return!1},E=/^([A-Z]|returnValue$|layer[XY]$|webkitMovement[XY]$)/,T={preventDefault:"isDefaultPrevented",stopImmediatePropagation:"isImmediatePropagationStopped",stopPropagation:"isPropagationStopped"};function b(i,n){return!n&&i.isDefaultPrevented||(n||(n=i),t.each(T,function(t,e){var r=n[t];i[t]=function(){return this[e]=y,r&&r.apply(n,arguments)},i[e]=A}),(n.defaultPrevented!==e?n.defaultPrevented:"returnValue"in n?!1===n.returnValue:n.getPreventDefault&&n.getPreventDefault())&&(i.isDefaultPrevented=y)),i}function S(t){var i,n={originalEvent:t};for(i in t)E.test(i)||t[i]===e||(n[i]=t[i]);return b(n,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,h){var c,u,d=this;return i&&!s(i)?(t.each(i,function(t,e){d.on(t,a,o,e,h)}),d):(s(a)||r(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,r){h&&(c=function(t){return v(r,t.type,l),l.apply(this,arguments)}),a&&(u=function(e){var i,s=t(e.target).closest(a,r).get(0);if(s&&s!==r)return i=t.extend(S(e),{currentTarget:s,liveFired:r}),(c||l).apply(s,[i].concat(n.call(arguments,1)))}),m(r,i,l,o,a,u||c)}))},t.fn.off=function(i,n,a){var o=this;return i&&!s(i)?(t.each(i,function(t,e){o.off(t,n,e)}),o):(s(n)||r(a)||!1===a||(a=n,n=e),!1===a&&(a=A),o.each(function(){v(this,i,a,n)}))},t.fn.trigger=function(e,i){return(e=s(e)||t.isPlainObject(e)?t.Event(e):b(e))._args=i,this.each(function(){e.type in h&&"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 n,r;return this.each(function(a,o){(n=S(s(e)?t.Event(e):e))._args=i,n.target=o,t.each(d(o,e.type||e),function(t,e){if(r=e.proxy(n),n.isImmediatePropagationStopped())return!1})}),r},"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]||(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"),n=!0;if(e)for(var r in e)"bubbles"==r?n=!!e[r]:i[r]=e[r];return i.initEvent(t,n,!0),b(i)}}(k),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,n=e.matches;function r(e){return!(!(e=t(e)).width()&&!e.height())&&"none"!==e.css("display")}var s=t.expr[":"]={visible:function(){if(r(this))return this},hidden:function(){if(!r(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,n){if(t(this).text().indexOf(n)>-1)return this},has:function(t,i,n){if(e.qsa(this,n).length)return this}},a=new RegExp("(.*):(\\w+)(?:\\(([^)]+)\\))?$\\s*"),o=/^\s*>/,l="Zepto"+ +new Date;function h(t,e){t=t.replace(/=#\]/g,'="#"]');var i,n,r=a.exec(t);if(r&&r[2]in s&&(i=s[r[2]],n=r[3],t=r[1],n)){var o=Number(n);n=isNaN(o)?n.replace(/^["']|["']$/g,""):o}return e(t,i,n)}e.qsa=function(n,r){return h(r,function(s,a,h){try{var c;!s&&a?s="*":o.test(s)&&(c=t(n).addClass(l),s="."+l+" "+s);var u=i(n,s)}catch(t){throw console.error("error performing selector: %o",r),t}finally{c&&c.removeClass(l)}return a?e.uniq(t.map(u,function(t,e){return a.call(t,e,u,h)})):u})},e.matches=function(t,e){return h(e,function(e,i,r){return(!e||n(t,e))&&(!i||i.call(t,null,r)===t)})}}(k),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 n=arguments[1],r=0;r<i;){var s=e[r];if(t.call(n,s,r,e))return s;r++}}}),Object.entries||(Object.entries=function(t){for(var e=Object.keys(t),i=e.length,n=new Array(i);i--;)n[i]=[e[i],t[e[i]]];return n}),Object.values||(Object.values=function(t){for(var e=Object.keys(t),i=e.length,n=new Array(i);i--;)n[i]=t[e[i]];return n}),"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),n=1;n<arguments.length;n++){var r=arguments[n];if(null!=r)for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(i[s]=r[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 n=arguments[1],r=0;r<i;){var s=e[r];if(t.call(n,s,r,e))return r;r++}return-1},configurable:!0,writable:!0});var _,L={mp4:"data:video/mp4;base64,AAAAHGZ0eXBpc29tAAACAGlzb21pc28ybXA0MQAAAAhmcmVlAAAC721kYXQhEAUgpBv/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA3pwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcCEQBSCkG//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADengAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcAAAAsJtb292AAAAbG12aGQAAAAAAAAAAAAAAAAAAAPoAAAALwABAAABAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAB7HRyYWsAAABcdGtoZAAAAAMAAAAAAAAAAAAAAAIAAAAAAAAALwAAAAAAAAAAAAAAAQEAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAACRlZHRzAAAAHGVsc3QAAAAAAAAAAQAAAC8AAAAAAAEAAAAAAWRtZGlhAAAAIG1kaGQAAAAAAAAAAAAAAAAAAKxEAAAIAFXEAAAAAAAtaGRscgAAAAAAAAAAc291bgAAAAAAAAAAAAAAAFNvdW5kSGFuZGxlcgAAAAEPbWluZgAAABBzbWhkAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAADTc3RibAAAAGdzdHNkAAAAAAAAAAEAAABXbXA0YQAAAAAAAAABAAAAAAAAAAAAAgAQAAAAAKxEAAAAAAAzZXNkcwAAAAADgICAIgACAASAgIAUQBUAAAAAAfQAAAHz+QWAgIACEhAGgICAAQIAAAAYc3R0cwAAAAAAAAABAAAAAgAABAAAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAIAAAABAAAAHHN0c3oAAAAAAAAAAAAAAAIAAAFzAAABdAAAABRzdGNvAAAAAAAAAAEAAAAsAAAAYnVkdGEAAABabWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAbWRpcmFwcGwAAAAAAAAAAAAAAAAtaWxzdAAAACWpdG9vAAAAHWRhdGEAAAABAAAAAExhdmY1Ni40MC4xMDE="},R=[{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.]*)"}],I=[{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"}],C={},P=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]))},D=function(t,e,i){var n="["===e.substr(0,1)?new RegExp(e,"g"):e,r=t.split(n,2);"."!==e&&(t=t.replace(new RegExp(e,"g"),".")),i.fullVersion=t,r&&r[0]&&(i.majorVersion=parseInt(r[0])),r&&r[1]&&(i.minorVersion=parseInt(r[1]))},w=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);C.isEdge=/Edg|EdgiOS|EdgA/i.test(navigator.userAgent),C.isChrome=/Chrome|CriOS/i.test(navigator.userAgent)&&!C.isEdge,C.isSafari=/Safari/i.test(navigator.userAgent)&&!C.isChrome&&!C.isEdge,C.isFirefox=/Firefox/i.test(navigator.userAgent),C.isLegacyIE=!!window.ActiveXObject,C.isIE=C.isLegacyIE||/trident.*rv:1\d/i.test(navigator.userAgent),C.isIE11=/trident.*rv:11/i.test(navigator.userAgent),C.isChromecast=C.isChrome&&/CrKey/i.test(navigator.userAgent),C.isMobile=/Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone|IEMobile|Mobile Safari|Opera Mini/i.test(navigator.userAgent),C.isiOS=/iPad|iPhone|iPod/i.test(navigator.userAgent),C.isAndroid=/Android/i.test(navigator.userAgent),C.isWindowsPhone=/Windows Phone/i.test(navigator.userAgent),C.isWin8App=/MSAppHost/i.test(navigator.userAgent),C.isWiiU=/WiiU/i.test(navigator.userAgent),C.isPS4=/PlayStation 4/i.test(navigator.userAgent),C.hasLocalstorage=function(){try{return localStorage.setItem("clappr","clappr"),localStorage.removeItem("clappr"),!0}catch(t){return!1}}(),C.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)}}(),C.name=w.name,C.version=w.version,C.userAgent=navigator.userAgent,C.data=function(){var t,e={},i=C.userAgent.toLowerCase(),n=l(R);try{for(n.s();!(t=n.n()).done;){var r=t.value,s=new RegExp(r.identifier.toLowerCase()).exec(i);if(null!=s&&s[1]){if(e.name=r.name,e.group=r.group,r.versionIdentifier){var a=new RegExp(r.versionIdentifier.toLowerCase()).exec(i);null!=a&&a[1]&&P(a[1],e)}else P(s[1],e);break}}}catch(t){n.e(t)}finally{n.f()}return e}(),C.os=function(){var t,e={},i=C.userAgent.toLowerCase(),n=l(I);try{for(n.s();!(t=n.n()).done;){var r=t.value,s=new RegExp(r.identifier.toLowerCase()).exec(i);if(null!=s){if(e.name=r.name,e.group=r.group,r.version)D(r.version,r.versionSeparator?r.versionSeparator:".",e);else if(s[1])D(s[1],r.versionSeparator?r.versionSeparator:".",e);else if(r.versionIdentifier){var a=new RegExp(r.versionIdentifier.toLowerCase()).exec(i);null!=a&&a[1]&&D(a[1],r.versionSeparator?r.versionSeparator:".",e)}break}}}catch(t){n.e(t)}finally{n.f()}return e}(),C.isWindows=/^Windows$/i.test(C.os.group),C.isMacOS=/^Mac OS$/i.test(C.os.group),C.isLinux=/^Linux$/i.test(C.os.group),C.viewport=((_={}).width=k(window).width(),_.height=k(window).height(),_),C.device=function(t){var e=/\((iP(?:hone|ad|od))?(?:[^;]*; ){0,2}([^)]+(?=\)))/.exec(t);return e&&(e[1]||e[2])||""}(C.userAgent),void 0!==window.orientation&&function(){switch(window.orientation){case-90:case 90:C.viewport.orientation="landscape";break;default:C.viewport.orientation="portrait"}}();var O={},x=[],M=(window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||function(t){window.setTimeout(t,1e3/60)}).bind(window),N=(window.cancelAnimationFrame||window.mozCancelAnimationFrame||window.webkitCancelAnimationFrame||window.clearTimeout).bind(window);function F(t,e){if(e)for(var i in e){var n=Object.getOwnPropertyDescriptor(e,i);n?Object.defineProperty(t,i,n):t[i]=e[i]}return t}function B(t,e){var i=function(t){function i(){var t;s(this,i);for(var n=arguments.length,a=new Array(n),o=0;o<n;o++)a[o]=arguments[o];return t=r(this,i,[].concat(a)),e.initialize&&e.initialize.apply(t,a),t}return d(i,t),o(i)}(t);return F(i.prototype,e),i}var $={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)}},U=function(){return o(function t(){s(this,t)},null,[{key:"_defaultConfig",value:function(){return{volume:{value:100,parse:parseInt}}}},{key:"_defaultValueFor",value:function(t){try{return this._defaultConfig()[t].parse(this._defaultConfig()[t].value)}catch(t){return}}},{key:"_createKeyspace",value:function(t){return"clappr.".concat(document.domain,".").concat(t)}},{key:"restore",value:function(t){return C.hasLocalstorage&&localStorage[this._createKeyspace(t)]?this._defaultConfig()[t].parse(localStorage[this._createKeyspace(t)]):this._defaultValueFor(t)}},{key:"persist",value:function(t,e){if(C.hasLocalstorage)try{return localStorage[this._createKeyspace(t)]=e,!0}catch(t){return!1}}}])}(),G=function(){return o(function t(){s(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,n=/([^&=]+)=?([^&]*)/g,r=function(t){return decodeURIComponent(t.replace(i," "))},s={};e=n.exec(t);)s[r(e[1]).toLowerCase()]=r(e[2]);return s}}])}();function V(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"t",e=0,i=G.params[t]||G.hashParams[t]||"",n=i.match(/[0-9]+[hms]+/g)||[];if(n.length>0){var r={h:3600,m:60,s:1};n.forEach(function(t){if(t){var i=t[t.length-1],n=parseInt(t.slice(0,t.length-1),10);e+=n*r[i]}})}else i&&(e=parseInt(i,10));return e}function K(t){return O[t]||(O[t]=0),t+ ++O[t]}function H(t){return t-parseFloat(t)+1>=0}function Y(){var t=document.getElementsByTagName("script");return t.length?t[t.length-1].src:""}function j(){return window.navigator&&window.navigator.language}function W(t,e){var i=(e=Object.assign({inline:!1,muted:!1,timeout:250,type:"video",source:L.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 n=i.play(),r=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(r),t(e,i)};void 0!==n?n.then(function(){return s(!0)}).catch(function(t){return s(!1,t)}):s(!0)}var z=function(){return o(function t(){s(this,t)},null,[{key:"configure",value:function(t){this.options=k.extend(!0,this.options,t)}},{key:"create",value:function(t){return this.options.recycleVideo&&"video"===t&&x.length>0?x.shift():document.createElement(t)}},{key:"garbage",value:function(t){this.options.recycleVideo&&"VIDEO"===t.tagName.toUpperCase()&&(k(t).children().remove(),Object.values(t.attributes).forEach(function(e){return t.removeAttribute(e.name)}),x.push(t))}}])}();z.options={recycleVideo:!1};var q=function(){return o(function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:500;s(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],n=(new Date).getTime(),r=n-this.lastTime;r<this.delay&&r>0&&(e(),i&&t.preventDefault()),this.lastTime=n}}])}(),X={Config:U,Fullscreen:$,QueryString:G,DomRecycler:z,assign:F,extend:B,formatTime:function(t,e){if(!isFinite(t))return"--:--";t*=1e3;var i=(t=parseInt(t/1e3))%60,n=(t=parseInt(t/60))%60,r=(t=parseInt(t/60))%24,s=parseInt(t/24),a="";return s&&s>0&&(a+=s+":",r<1&&(a+="00:")),(r&&r>0||e)&&(a+=("0"+r).slice(-2)+":"),a+=("0"+n).slice(-2)+":",(a+=("0"+i).slice(-2)).trim()},seekStringToSeconds:V,uniqueId:K,currentScriptUrl:Y,isNumber:H,requestAnimationFrame:M,cancelAnimationFrame:N,getBrowserLanguage:j,now:function(){return window.performance&&window.performance.now?performance.now():Date.now()},removeArrayItem:function(t,e){var i=t.indexOf(e);i>=0&&t.splice(i,1)},listContainsIgnoreCase:function(t,e){return void 0!==t&&void 0!==e&&void 0!==e.find(function(e){return t.toLowerCase()===e.toLowerCase()})},canAutoPlayMedia:W,Media:L,DoubleEventHandler:q},Q="font-weight: bold; font-size: 13px;",Z="color: #ff8000;"+Q,J="color: #ff0000;"+Q,tt=["color: #0000ff;"+Q,"color: #006600;"+Q,Z,J,J],et=["debug","info","warn","error","disabled"],it=function(){return o(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;s(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 "+et[this.level],Z)}},{key:"log",value:function(t,e,i){if(!(e<this.level||this.EXCLUDE_LIST.indexOf(i[0])>=0)){i||(i=t,t=null);var n=tt[e],r="";t&&(r="["+t+"]"),window.console&&window.console.log&&window.console.log.apply(console,["%c["+et[e]+"]"+r,n].concat(i))}}}])}();it.LEVEL_DEBUG=0,it.LEVEL_INFO=1,it.LEVEL_WARN=2,it.LEVEL_ERROR=3,it.getInstance=function(){return void 0===this._instance&&(this._instance=new this),this._instance},it.setLevel=function(t){this.getInstance().level=t},it.debug=function(){this.getInstance().debug.apply(this.getInstance(),arguments)},it.info=function(){this.getInstance().info.apply(this.getInstance(),arguments)},it.warn=function(){this.getInstance().warn.apply(this.getInstance(),arguments)},it.error=function(){this.getInstance().error.apply(this.getInstance(),arguments)};var nt=Array.prototype.slice,rt=/\s+/,st=function(t,e,i,n){if(!i)return!0;if("object"===T(i)){for(var r in i)t[e].apply(t,[r,i[r]].concat(n));return!1}if(rt.test(i)){for(var s=i.split(rt),a=0,o=s.length;a<o;a++)t[e].apply(t,[s[a]].concat(n));return!1}return!0},at=function(t,e,i,n){var r,s=-1,a=t.length,o=e[0],l=e[1],h=e[2];!function c(){try{switch(e.length){case 0:for(;++s<a;)(r=t[s]).callback.call(r.ctx);return;case 1:for(;++s<a;)(r=t[s]).callback.call(r.ctx,o);return;case 2:for(;++s<a;)(r=t[s]).callback.call(r.ctx,o,l);return;case 3:for(;++s<a;)(r=t[s]).callback.call(r.ctx,o,l,h);return;default:for(;++s<a;)(r=t[s]).callback.apply(r.ctx,e);return}}catch(t){it.error.apply(it,[i,"error on event",n,"trigger","-",t]),c()}}()},ot=function(){function t(){s(this,t)}return o(t,[{key:"on",value:function(t,e,i){return st(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 n=this;if(!st(this,"once",t,[e,i])||!e)return this;var r=function(){n.off(t,r),e.apply(this,arguments)};return r._callback=e,this.on(t,r,i)}},{key:"off",value:function(t,e,i){var n,r,s,a,o,l,h;if(!this._events||!st(this,"off",t,[e,i]))return this;if(!t&&!e&&!i)return this._events=void 0,this;var c=t?[t]:Object.keys(this._events);for(a=0,o=c.length;a<o;a++)if(t=c[a],s=this._events[t]){if(this._events[t]=n=[],e||i)for(l=0,h=s.length;l<h;l++)r=s[l],(e&&e!==r.callback&&e!==r.callback._callback||i&&i!==r.context)&&n.push(r);n.length||delete this._events[t]}return this}},{key:"trigger",value:function(t){var e=this.name||this.constructor.name;if(it.debug.apply(it,[e].concat(Array.prototype.slice.call(arguments))),!this._events)return this;var i=nt.call(arguments,1);if(!st(this,"trigger",t,i))return this;var n=this._events[t],r=this._events.all;return n&&at(n,i,e,t),r&&at(r,arguments,e,t),this}},{key:"stopListening",value:function(t,e,i){var n=this._listeningTo;if(!n)return this;var r=!e&&!i;for(var s in i||"object"!==T(e)||(i=this),t&&((n={})[t._listenId]=t),n)(t=n[s]).off(e,i,this),(r||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[0].toUpperCase()+t.slice(1)}).join(""):it.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]})}}])}();ot.prototype.listenTo=function(t,e,i){return(this._listeningTo||(this._listeningTo={}))[t._listenId||(t._listenId=K("l"))]=t,i||"object"!==T(e)||(i=this),t.on(e,i,this),this},ot.prototype.listenToOnce=function(t,e,i){return(this._listeningTo||(this._listeningTo={}))[t._listenId||(t._listenId=K("l"))]=t,i||"object"!==T(e)||(i=this),t.once(e,i,this),this},ot.PLAYER_READY="ready",ot.PLAYER_RESIZE="resize",ot.PLAYER_FULLSCREEN="fullscreen",ot.PLAYER_PLAY="play",ot.PLAYER_PAUSE="pause",ot.PLAYER_STOP="stop",ot.PLAYER_ENDED="ended",ot.PLAYER_SEEK="seek",ot.PLAYER_ERROR="playererror",ot.ERROR="error",ot.PLAYER_TIMEUPDATE="timeupdate",ot.PLAYER_VOLUMEUPDATE="volumeupdate",ot.PLAYER_SUBTITLE_AVAILABLE="subtitleavailable",ot.PLAYBACK_PIP_ENTER="playback:picture-in-picture:enter",ot.PLAYBACK_PIP_EXIT="playback:picture-in-picture:exit",ot.PLAYBACK_PROGRESS="playback:progress",ot.PLAYBACK_TIMEUPDATE="playback:timeupdate",ot.PLAYBACK_READY="playback:ready",ot.PLAYBACK_BUFFERING="playback:buffering",ot.PLAYBACK_BUFFERFULL="playback:bufferfull",ot.PLAYBACK_SETTINGSUPDATE="playback:settingsupdate",ot.PLAYBACK_LOADEDMETADATA="playback:loadedmetadata",ot.PLAYBACK_HIGHDEFINITIONUPDATE="playback:highdefinitionupdate",ot.PLAYBACK_BITRATE="playback:bitrate",ot.PLAYBACK_LEVELS_AVAILABLE="playback:levels:available",ot.PLAYBACK_LEVEL_SWITCH_START="playback:levels:switch:start",ot.PLAYBACK_LEVEL_SWITCH_END="playback:levels:switch:end",ot.PLAYBACK_PLAYBACKSTATE="playback:playbackstate",ot.PLAYBACK_DVR="playback:dvr",ot.PLAYBACK_MEDIACONTROL_DISABLE="playback:mediacontrol:disable",ot.PLAYBACK_MEDIACONTROL_ENABLE="playback:mediacontrol:enable",ot.PLAYBACK_ENDED="playback:ended",ot.PLAYBACK_PLAY_INTENT="playback:play:intent",ot.PLAYBACK_PLAY="playback:play",ot.PLAYBACK_PAUSE="playback:pause",ot.PLAYBACK_SEEK="playback:seek",ot.PLAYBACK_SEEKED="playback:seeked",ot.PLAYBACK_STOP="playback:stop",ot.PLAYBACK_ERROR="playback:error",ot.PLAYBACK_STATS_ADD="playback:stats:add",ot.PLAYBACK_FRAGMENT_LOADED="playback:fragment:loaded",ot.PLAYBACK_FRAGMENT_BUFFERED="playback:fragment:buffered",ot.PLAYBACK_LEVEL_SWITCH="playback:level:switch",ot.PLAYBACK_SUBTITLE_AVAILABLE="playback:subtitle:available",ot.PLAYBACK_SUBTITLE_CHANGED="playback:subtitle:changed",ot.PLAYBACK_AUDIO_AVAILABLE="playback:audio:available",ot.PLAYBACK_AUDIO_CHANGED="playback:audio:changed",ot.PLAYBACK_RESIZE="playback:resize",ot.CORE_CONTAINERS_CREATED="core:containers:created",ot.CORE_ACTIVE_CONTAINER_CHANGED="core:active:container:changed",ot.CORE_OPTIONS_WILL_CHANGE="core:options:will:change",ot.CORE_OPTIONS_CHANGE="core:options:change",ot.CORE_READY="core:ready",ot.CORE_FULLSCREEN="core:fullscreen",ot.CORE_RESIZE="core:resize",ot.CORE_SCREEN_ORIENTATION_CHANGED="core:screen:orientation:changed",ot.CORE_MOUSE_MOVE="core:mousemove",ot.CORE_MOUSE_LEAVE="core:mouseleave",ot.CONTAINER_PLAYBACKSTATE="container:playbackstate",ot.CONTAINER_PLAYBACKDVRSTATECHANGED="container:dvr",ot.CONTAINER_BITRATE="container:bitrate",ot.CONTAINER_STATS_REPORT="container:stats:report",ot.CONTAINER_DESTROYED="container:destroyed",ot.CONTAINER_READY="container:ready",ot.CONTAINER_RESIZE="container:resize",ot.CONTAINER_ERROR="container:error",ot.CONTAINER_LOADEDMETADATA="container:loadedmetadata",ot.CONTAINER_SUBTITLE_AVAILABLE="container:subtitle:available",ot.CONTAINER_SUBTITLE_CHANGED="container:subtitle:changed",ot.CONTAINER_AUDIO_AVAILABLE="container:audio:available",ot.CONTAINER_AUDIO_CHANGED="container:audio:changed",ot.CONTAINER_TIMEUPDATE="container:timeupdate",ot.CONTAINER_PROGRESS="container:progress",ot.CONTAINER_PLAY="container:play",ot.CONTAINER_STOP="container:stop",ot.CONTAINER_PAUSE="container:pause",ot.CONTAINER_ENDED="container:ended",ot.CONTAINER_CLICK="container:click",ot.CONTAINER_DBLCLICK="container:dblclick",ot.CONTAINER_CONTEXTMENU="container:contextmenu",ot.CONTAINER_MOUSE_ENTER="container:mouseenter",ot.CONTAINER_MOUSE_LEAVE="container:mouseleave",ot.CONTAINER_MOUSE_UP="container:mouseup",ot.CONTAINER_MOUSE_DOWN="container:mousedown",ot.CONTAINER_PIP_ENTER="container:picture-in-picture:enter",ot.CONTAINER_PIP_EXIT="container:picture-in-picture:exit",ot.CONTAINER_SEEK="container:seek",ot.CONTAINER_SEEKED="container:seeked",ot.CONTAINER_VOLUME="container:volume",ot.CONTAINER_FULLSCREEN="container:fullscreen",ot.CONTAINER_STATE_BUFFERING="container:state:buffering",ot.CONTAINER_STATE_BUFFERFULL="container:state:bufferfull",ot.CONTAINER_SETTINGSUPDATE="container:settingsupdate",ot.CONTAINER_HIGHDEFINITIONUPDATE="container:highdefinitionupdate",ot.CONTAINER_MEDIACONTROL_SHOW="container:mediacontrol:show",ot.CONTAINER_MEDIACONTROL_HIDE="container:mediacontrol:hide",ot.CONTAINER_MEDIACONTROL_DISABLE="container:mediacontrol:disable",ot.CONTAINER_MEDIACONTROL_ENABLE="container:mediacontrol:enable",ot.CONTAINER_STATS_ADD="container:stats:add",ot.CONTAINER_OPTIONS_WILL_CHANGE="container:options:will:change",ot.CONTAINER_OPTIONS_CHANGE="container:options:change",ot.MEDIACONTROL_RENDERED="mediacontrol:rendered",ot.MEDIACONTROL_FULLSCREEN="mediacontrol:fullscreen",ot.MEDIACONTROL_SHOW="mediacontrol:show",ot.MEDIACONTROL_HIDE="mediacontrol:hide",ot.MEDIACONTROL_MOUSEMOVE_SEEKBAR="mediacontrol:mousemove:seekbar",ot.MEDIACONTROL_MOUSELEAVE_SEEKBAR="mediacontrol:mouseleave:seekbar",ot.MEDIACONTROL_PLAYING="mediacontrol:playing",ot.MEDIACONTROL_NOTPLAYING="mediacontrol:notplaying",ot.MEDIACONTROL_CONTAINERCHANGED="mediacontrol:containerchanged",ot.MEDIACONTROL_OPTIONS_CHANGE="mediacontrol:options:change";var lt=function(t){function e(){var t,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return s(this,e),(t=r(this,e,[i]))._options=i,t.uniqueId=K("o"),t}return d(e,t),o(e,[{key:"options",get:function(){return this._options}}])}(ot),ht={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g},ct=/(.)^/,ut={"'":"'","\\":"\\","\r":"r","\n":"n","\t":"t","\u2028":"u2028","\u2029":"u2029"},dt=/\\|'|\r|\n|\t|\u2028|\u2029/g,ft={"&":"&","<":"<",">":">",'"':""","'":"'"},gt=new RegExp("[&<>\"']","g"),pt=function(t){return null===t?"":(""+t).replace(gt,function(t){return ft[t]})},mt=0,vt=function(t,e){var i,n=new RegExp([(ht.escape||ct).source,(ht.interpolate||ct).source,(ht.evaluate||ct).source].join("|")+"|$","g"),r=0,s="__p+='";t.replace(n,function(e,i,n,a,o){return s+=t.slice(r,o).replace(dt,function(t){return"\\"+ut[t]}),i&&(s+="'+\n((__t=("+i+"))==null?'':escapeExpr(__t))+\n'"),n&&(s+="'+\n((__t=("+n+"))==null?'':__t)+\n'"),a&&(s+="';\n"+a+"\n__p+='"),r=o+e.length,e}),s+="';\n",ht.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["+mt+++"]";try{i=new Function(ht.variable||"obj","escapeExpr",s)}catch(t){throw t.source=s,t}if(e)return i(e,pt);var a=function(t){return i.call(this,t,pt)};return a.source="function("+(ht.variable||"obj")+"){\n"+s+"}",a};vt.settings=ht;var yt={getStyleFor:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{baseUrl:""};return k('<style class="clappr-style"></style>').html(vt(t.toString())(e))}},At=/^(\S+)\s*(.*)$/,Et=function(t){function e(t){var i;return s(this,e),(i=r(this,e,[t])).cid=K("c"),i._ensureElement(),i.delegateEvents(),i}return d(e,t),o(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=k.zepto.isZ(t)?t:k(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 n=e.match(At),r=n[1],s=n[2];r+=".delegateEvents"+this.cid,""===s?this.$el.on(r,i.bind(this)):this.$el.on(r,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=k.extend(!0,{},this.attributes);this.id&&(t.id=this.id),this.className&&(t.class=this.className);var e=k(z.create(this.tagName)).attr(t);this.setElement(e,!1)}}},{key:"onResize",value:function(){return this}},{key:"resize",value:function(t){var e=H(t.width)?"".concat(t.width,"px"):"".concat(t.width),i=H(t.height)?"".concat(t.height,"px"):"".concat(t.height);return this.el.style.width=e,this.el.style.height=i,this.onResize(t),this}}])}(lt),Tt=function(t){function e(){var t,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;return s(this,e),(t=r(this,e,[i])).core=n,t}return d(e,t),o(e,[{key:"name",get:function(){return"error"}},{key:"createError",value:function(t){this.core?this.core.trigger(ot.ERROR,t):it.warn(this.name,"Core is not set. Error: ",t)}}],[{key:"Levels",get:function(){return{FATAL:"FATAL",WARN:"WARN",INFO:"INFO"}}}])}(lt),bt={createError:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{useCodePrefix:!0},i=this.constructor&&this.constructor.type||"",n=this.name||i,r=this.i18n||this.core&&this.core.i18n||this.container&&this.container.i18n,s="".concat(n,":").concat(t&&t.code||"unknown"),a={description:"",level:Tt.Levels.FATAL,origin:n,scope:i,raw:{}},o=Object.assign({},a,t,{code:e.useCodePrefix?s:t.code});if(r&&o.level===Tt.Levels.FATAL&&!o.UI){var l={title:r.t("default_error_title"),message:r.t("default_error_message")};o.UI=l}return this.playerError?this.playerError.createError(o):it.warn(n,"PlayerError is not defined. Error: ",o),o}},St=function(t){function e(t){var i;return s(this,e),(i=r(this,e,[t.options])).core=t,i.enabled=!0,i.bindEvents(),i.render(),i}return d(e,t),o(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}}])}(Et);Object.assign(St.prototype,bt),St.extend=function(t){return B(St,t)},St.type="core";var kt=function(t){function e(t,i,n){var a;return s(this,e),(a=r(this,e,[t]))._i18n=i,a.currentTime=0,a.volume=100,a.playback=t.playback,a.playerError=n,a.settings=k.extend(!0,{},a.playback.settings),a.isReady=!1,a.mediaControlDisabled=!1,a.plugins=[a.playback],a.dblTapHandler=new q(500),a.clickTimer=null,a.clickDelay=200,a.actionsMetadata={},a.bindEvents(),a}return d(e,t),o(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,ot.PLAYBACK_PROGRESS,this.onProgress),this.listenTo(this.playback,ot.PLAYBACK_TIMEUPDATE,this.timeUpdated),this.listenTo(this.playback,ot.PLAYBACK_READY,this.ready),this.listenTo(this.playback,ot.PLAYBACK_BUFFERING,this.onBuffering),this.listenTo(this.playback,ot.PLAYBACK_BUFFERFULL,this.bufferfull),this.listenTo(this.playback,ot.PLAYBACK_SETTINGSUPDATE,this.settingsUpdate),this.listenTo(this.playback,ot.PLAYBACK_LOADEDMETADATA,this.loadedMetadata),this.listenTo(this.playback,ot.PLAYBACK_HIGHDEFINITIONUPDATE,this.highDefinitionUpdate),this.listenTo(this.playback,ot.PLAYBACK_BITRATE,this.updateBitrate),this.listenTo(this.playback,ot.PLAYBACK_PLAYBACKSTATE,this.playbackStateChanged),this.listenTo(this.playback,ot.PLAYBACK_DVR,this.playbackDvrStateChanged),this.listenTo(this.playback,ot.PLAYBACK_MEDIACONTROL_DISABLE,this.disableMediaControl),this.listenTo(this.playback,ot.PLAYBACK_MEDIACONTROL_ENABLE,this.enableMediaControl),this.listenTo(this.playback,ot.PLAYBACK_SEEK,this.onSeek),this.listenTo(this.playback,ot.PLAYBACK_SEEKED,this.onSeeked),this.listenTo(this.playback,ot.PLAYBACK_ENDED,this.onEnded),this.listenTo(this.playback,ot.PLAYBACK_PLAY,this.playing),this.listenTo(this.playback,ot.PLAYBACK_PAUSE,this.paused),this.listenTo(this.playback,ot.PLAYBACK_STOP,this.stopped),this.listenTo(this.playback,ot.PLAYBACK_ERROR,this.error),this.listenTo(this.playback,ot.PLAYBACK_SUBTITLE_AVAILABLE,this.subtitleAvailable),this.listenTo(this.playback,ot.PLAYBACK_SUBTITLE_CHANGED,this.subtitleChanged),this.listenTo(this.playback,ot.PLAYBACK_AUDIO_AVAILABLE,this.audioAvailable),this.listenTo(this.playback,ot.PLAYBACK_AUDIO_CHANGED,this.audioChanged),this.listenTo(this.playback,ot.PLAYBACK_PIP_ENTER,this.onEnterPiP),this.listenTo(this.playback,ot.PLAYBACK_PIP_EXIT,this.onExitPiP)}},{key:"subtitleAvailable",value:function(){this.trigger(ot.CONTAINER_SUBTITLE_AVAILABLE)}},{key:"subtitleChanged",value:function(t){this.trigger(ot.CONTAINER_SUBTITLE_CHANGED,t)}},{key:"audioAvailable",value:function(t){this.trigger(ot.CONTAINER_AUDIO_AVAILABLE,t)}},{key:"audioChanged",value:function(t){this.trigger(ot.CONTAINER_AUDIO_CHANGED,t)}},{key:"playbackStateChanged",value:function(t){this.trigger(ot.CONTAINER_PLAYBACKSTATE,t)}},{key:"playbackDvrStateChanged",value:function(t){this.settings=this.playback.settings,this.dvrInUse=t,this.trigger(ot.CONTAINER_PLAYBACKDVRSTATECHANGED,t)}},{key:"updateBitrate",value:function(t){this.trigger(ot.CONTAINER_BITRATE,t)}},{key:"statsReport",value:function(t){this.trigger(ot.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(ot.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(ot.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(ot.CONTAINER_ERROR,t,this.name)}},{key:"loadedMetadata",value:function(t){this.trigger(ot.CONTAINER_LOADEDMETADATA,t)}},{key:"timeUpdated",value:function(t){this.currentTime=t.current,this.trigger(ot.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,[ot.CONTAINER_PROGRESS].concat(e,[this.name]))}},{key:"playing",value:function(){this.trigger(ot.CONTAINER_PLAY,this.name,this.actionsMetadata.playEvent||{}),this.actionsMetadata.playEvent={}}},{key:"paused",value:function(){this.trigger(ot.CONTAINER_PAUSE,this.name,this.actionsMetadata.pauseEvent||{}),this.actionsMetadata.pauseEvent={}}},{key:"stopped",value:function(){this.trigger(ot.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(ot.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(ot.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(ot.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(ot.CONTAINER_DBLCLICK,e,e.name)})}},{key:"onContextMenu",value:function(t){this.options.chromeless&&!this.options.allowUserInteraction||this.trigger(ot.CONTAINER_CONTEXTMENU,t,this.name)}},{key:"seek",value:function(t){this.playback.seek(t)}},{key:"onSeek",value:function(t){this.trigger(ot.CONTAINER_SEEK,t,this.name)}},{key:"onSeeked",value:function(){this.trigger(ot.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(ot.CONTAINER_VOLUME,this.volume,this.name),this.playback.volume(this.volume)}},{key:"fullscreen",value:function(){this.trigger(ot.CONTAINER_FULLSCREEN,this.name)}},{key:"onBuffering",value:function(){this.trigger(ot.CONTAINER_STATE_BUFFERING,this.name)}},{key:"bufferfull",value:function(){this.trigger(ot.CONTAINER_STATE_BUFFERFULL,this.name)}},{key:"onEnterPiP",value:function(){this.trigger(ot.CONTAINER_PIP_ENTER,this.name)}},{key:"onExitPiP",value:function(){this.trigger(ot.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(ot.CONTAINER_MOUSE_ENTER)}},{key:"mouseLeave",value:function(){this.options.chromeless&&!this.options.allowUserInteraction||this.trigger(ot.CONTAINER_MOUSE_LEAVE)}},{key:"mouseUp",value:function(){this.options.chromeless&&!this.options.allowUserInteraction||this.trigger(ot.CONTAINER_MOUSE_UP)}},{key:"mouseDown",value:function(){this.options.chromeless&&!this.options.allowUserInteraction||this.trigger(ot.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(ot.CONTAINER_SETTINGSUPDATE)}},{key:"highDefinitionUpdate",value:function(t){this.trigger(ot.CONTAINER_HIGHDEFINITIONUPDATE,t)}},{key:"isHighDefinitionInUse",value:function(){return this.playback.isHighDefinitionInUse()}},{key:"disableMediaControl",value:function(){this.mediaControlDisabled||(this.mediaControlDisabled=!0,this.trigger(ot.CONTAINER_MEDIACONTROL_DISABLE))}},{key:"enableMediaControl",value:function(){this.mediaControlDisabled&&(this.mediaControlDisabled=!1,this.trigger(ot.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(ot.CONTAINER_RESIZE,t))}},{key:"onResize",value:function(t){return this.playback.resize(t),this}},{key:"configure",value:function(t,e){this.trigger(ot.CONTAINER_OPTIONS_WILL_CHANGE,e),this._options=k.extend(!0,this._options,t),this.updateStyle(),this.playback.configure(this.options),this.trigger(ot.CONTAINER_OPTIONS_CHANGE)}},{key:"render",value:function(){var t=yt.getStyleFor(".container[data-container] {\n position: absolute;\n background-color: black;\n height: 100%;\n width: 100%;\n max-width: 100%;\n}\n.container[data-container] .chromeless {\n cursor: default;\n}\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}}])}(Et);Object.assign(kt.prototype,bt);var _t=function(t){function e(t,i,n){var a;return s(this,e),(a=r(this,e,[t])).settings={},a._i18n=i,a.playerError=n,a._consented=!1,a}return d(e,t),o(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:"getFrameRate",value:function(){return null}},{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=k.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(ot.PLAYBACK_RESIZE,t),this}}])}(Et);Object.assign(_t.prototype,bt),_t.extend=function(t){return B(_t,t)},_t.canPlay=function(t,e){return!1},_t.VOD="vod",_t.AOD="aod",_t.LIVE="live",_t.NO_OP="no_op",_t.type="playback";var Lt=function(t){function e(t,i,n,a){var o;return s(this,e),(o=r(this,e,[t]))._i18n=n,o.loader=i,o.playerError=a,o}return d(e,t),o(e,[{key:"options",get:function(){return this._options},set:function(t){this._options=t}},{key:"createContainers",value:function(){var t=this;return k.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,i=this.options.mimeType;"object"===T(t)?(e=t.source.toString(),t.mimeType&&(i=t.mimeType)):e=t.toString(),e.match(/^\/\//)&&(e=window.location.protocol+e);var n=p(p({},this.options),{},{src:e,mimeType:i}),r=this.findPlaybackPlugin(e,i),s=r?new r(n,this._i18n,this.playerError):new _t;n=p(p({},n),{},{playback:s});var a=new kt(n,this._i18n,this.playerError),o=k.Deferred();return o.promise(a),this.addContainerPlugins(a),this.listenToOnce(a,ot.CONTAINER_READY,function(){return o.resolve(a)}),a}},{key:"addContainerPlugins",value:function(t){this.loader.containerPlugins.forEach(function(e){t.addPlugin(new e(t))})}}])}(lt);var Rt=function(t){function e(t){var i;return s(this,e),(i=r(this,e,[t])).playerError=new Tt(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)},k(document).bind("fullscreenchange",i._boundFullscreenHandler),k(document).bind("MSFullscreenChange",i._boundFullscreenHandler),k(document).bind("mozfullscreenchange",i._boundFullscreenHandler),C.isMobile&&k(window).bind("resize",i._boundHandleWindowResize),i}return d(e,t),o(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 St(this)),this._dummyMediaControl}},{key:"activeContainer",get:function(){return this._activeContainer},set:function(t){this._activeContainer=t,this.trigger(ot.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;z.configure({recycleVideo:t})}},{key:"createContainers",value:function(t){this.defer=k.Deferred(),this.defer.promise(this),this.containerFactory=new Lt(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(){C.isiOS||(this.$el.addClass("fullscreen"),this.$el.removeAttr("style"),this.previousSize={width:this.options.width,height:this.options.height},this.currentSize={width:k(window).width(),height:k(window).height()})}},{key:"setPlayerSize",value:function(){this.$el.removeClass("fullscreen"),this.currentSize=this.previousSize,this.previousSize={width:k(window).width(),height:k(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(){var e,i,n=null!==(e=t.el.clientWidth)&&void 0!==e?e:t.options.width,r=null!==(i=t.el.clientHeight)&&void 0!==i?i:t.options.height;t.triggerResize({width:n,height:r})},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(ot.CORE_RESIZE,t))}},{key:"disableResizeObserver",value:function(){this.resizeObserverInterval&&clearInterval(this.resizeObserverInterval),this.resizeObserverInterval=null}},{key:"resolveOnContainersReady",value:function(t){var e=this;k.when.apply(k,t).done(function(){e.defer.resolve(e),e.ready=!0,e.trigger(ot.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=k.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(),k(document).unbind("fullscreenchange",this._boundFullscreenHandler),k(document).unbind("MSFullscreenChange",this._boundFullscreenHandler),k(document).unbind("mozfullscreenchange",this._boundFullscreenHandler),C.isMobile&&k(window).unbind("resize",this._boundHandleWindowResize),this.stopListening(),this.undelegateEvents()}},{key:"handleFullscreenChange",value:function(){this.trigger(ot.CORE_FULLSCREEN,this.isFullscreen()),this.updateSize()}},{key:"handleWindowResize",value:function(t){var e,i,n=window.innerWidth>window.innerHeight?"landscape":"portrait";if(this._screenOrientation!==n){this._screenOrientation=n;var r=null!==(e=this.el.clientWidth)&&void 0!==e?e:this.options.width,s=null!==(i=this.el.clientHeight)&&void 0!==i?i:this.options.height;this.triggerResize({width:r,height:s}),this.trigger(ot.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,ot.CONTAINER_DESTROYED,this.removeContainer),this.containers.push(t)}},{key:"setupContainers",value:function(t){return t.forEach(this.setupContainer.bind(this)),this.trigger(ot.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=$.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=C.isiOS?this.activePlaybackEl:document;$.cancelFullscreen(e),!C.isiOS&&this.$el.removeClass("fullscreen nocursor")}else{var i=C.isiOS?this.activePlaybackEl:this.el;if(!i)return;var n=function(){!C.isiOS&&t.$el.addClass("fullscreen")};if(C.isSafari||C.isiOS)$.requestFullscreen(i),n();else{var r=$.requestFullscreen(i),s=null!=r&&"function"==typeof r.then?r:Promise.resolve();n(),s.then(function(){},function(e){setTimeout(function(){if(!t.isFullscreen()){if(t.$el.removeClass("fullscreen"),function(t){if(!t)return!1;var e=t.message||String(t);return/disallowed by permissions policy|permissions policy|fullscreen is not allowed/i.test(e)}(e))return;throw new ReferenceError(e.message||String(e))}},600)})}}}},{key:"onMouseMove",value:function(t){this.trigger(ot.CORE_MOUSE_MOVE,t)}},{key:"onMouseLeave",value:function(t){this.trigger(ot.CORE_MOUSE_LEAVE,t)}},{key:"configure",value:function(t){var e=this,i=k.extend(!0,{},this._options);this.trigger(ot.CORE_OPTIONS_WILL_CHANGE,i),this._options=k.extend(!0,this._options,t),this.configureDomRecycler();var n=t.source||t.sources;n&&this.load(n,t.mimeType||this.options.mimeType),this.trigger(ot.CORE_OPTIONS_CHANGE,t),this.containers.forEach(function(t){return t.configure(e.options,i)})}},{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=yt.getStyleFor('[data-player] {\n -webkit-touch-callout: none;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n -o-user-select: none;\n user-select: none;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n -webkit-transform: translate3d(0, 0, 0);\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 -webkit-box-sizing: border-box;\n box-sizing: border-box;\n}\n[data-player]:focus {\n outline: 0;\n}\n[data-player] * {\n -webkit-box-sizing: inherit;\n box-sizing: inherit;\n}\n[data-player] > * {\n float: none;\n max-width: none;\n}\n[data-player] > div {\n display: block;\n}\n[data-player].fullscreen {\n width: 100% !important;\n height: 100% !important;\n top: 0;\n left: 0;\n}\n[data-player].nocursor {\n cursor: none;\n}\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=yt.getStyleFor('[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}\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}}])}(Et);Object.assign(Rt.prototype,bt);var It,Ct,Pt=function(t){function e(t){var i;return s(this,e),(i=r(this,e,[t.options])).player=t,i}return d(e,t),o(e,[{key:"loader",get:function(){return this.player.loader}},{key:"create",value:function(){return this.options.loader=this.loader,this.core=new Rt(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)}}])}(lt),Dt=/(\d+)(?:\.(\d+))?(?:\.(\d+))?/,wt=function(){function t(e,i,n){s(this,t),this.major=parseInt(e||0,10),this.minor=parseInt(i||0,10),this.patch=parseInt(n||0,10)}return o(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=v((arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").match(Dt)||[],4),i=e[1],n=e[2],r=e[3];return void 0===i?null:new t(i,n,r)}}])}(),Ot=function(t,e){return t&&e?Object.entries(t).filter(function(t){return v(t,2)[1].type===e}).reduce(function(t,e){var i=v(e,2),n=i[0],r=i[1];return t[n]=r,t},{}):{}},xt=(It={plugins:{},playbacks:[]},Ct="0.16.3",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;s(this,t),this.playerId=i,this.playbackPlugins=A(It.playbacks);var n=t.registeredPlugins,r=n.core,a=n.container;this.containerPlugins=Object.values(a),this.corePlugins=Object.values(r),Array.isArray(e)||this.validateExternalPluginsType(e),this.addExternalPlugins(e)}return o(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)),n=[];for(var r in i)n.unshift(i[r]);return n}},{key:"addExternalPlugins",value:function(e){var i="boolean"!=typeof e.loadExternalPluginsFirst||e.loadExternalPluginsFirst,n="boolean"!=typeof e.loadExternalPlaybacksFirst||e.loadExternalPlaybacksFirst;if((e=this.groupPluginsByType(e)).playback){var r=e.playback.filter(function(e){return t.checkVersionSupport(e),!0});this.playbackPlugins=n?this.removeDups(r.concat(this.playbackPlugins)):this.removeDups(this.playbackPlugins.concat(r),!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 A(It.playbacks)}},{key:"registeredPlugins",get:function(){var t=It.plugins;return{core:Ot(t,"core"),container:Ot(t,"container")}}},{key:"checkVersionSupport",value:function(t){var e=t.prototype,i=e.supportedVersion,n=e.name;if(!i||!i.min)return it.warn("Loader","missing version information for ".concat(n)),!1;var r=i.max?wt.parse(i.max):wt.parse(i.min).inc("minor"),s=wt.parse(i.min);return!!wt.parse(Ct).satisfies(s,r)||(it.warn("Loader","unsupported plugin ".concat(n,": Clappr version ").concat(Ct," does not match required range [").concat(s,",").concat(r,")")),!1)}},{key:"registerPlugin",value:function(e){if(!e||!e.prototype.name)return it.warn("Loader","missing information to register plugin: ".concat(e)),!1;t.checkVersionSupport(e);var i=It.plugins;if(!i)return!1;var n=i[e.prototype.name];return n&&it.warn("Loader","overriding plugin entry: ".concat(e.prototype.name," - ").concat(n)),i[e.prototype.name]=e,!0}},{key:"registerPlayback",value:function(e){if(!e||!e.prototype.name)return!1;t.checkVersionSupport(e);var i=It.playbacks,n=i.findIndex(function(t){return t.prototype.name===e.prototype.name});if(n>=0){var r=i[n];i.splice(n,1),it.warn("Loader","overriding playback entry: ".concat(r.name," - ").concat(r))}return It.playbacks=[e].concat(A(i)),!0}},{key:"unregisterPlugin",value:function(t){if(!t)return!1;var e=It.plugins;return!!e[t]&&(delete e[t],!0)}},{key:"unregisterPlayback",value:function(t){if(!t)return!1;var e=It.playbacks,i=e.findIndex(function(e){return e.prototype.name===t});return!(i<0||(e.splice(i,1),It.playbacks=e,0))}},{key:"clearPlugins",value:function(){It.plugins={}}},{key:"clearPlaybacks",value:function(){It.playbacks=[]}}])}()),Mt=Y().replace(/\/[^/]+$/,""),Nt=function(t){function e(t){var i;s(this,e),i=r(this,e,[t]);var n={playerId:K(""),persistConfig:!0,width:640,height:360,baseUrl:Mt,allowUserInteraction:C.isMobile,includeResetStyle:!0,playback:{recycleVideo:!0}};i._options=k.extend(!0,n,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 Pt(i);var a=i._getParentElement(i.options);return a&&i.attachTo(a),i}return d(e,t),o(e,[{key:"loader",get:function(){return this._loader||(this._loader=new xt(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:ot.PLAYER_READY,onResize:ot.PLAYER_RESIZE,onPlay:ot.PLAYER_PLAY,onPause:ot.PLAYER_PAUSE,onStop:ot.PLAYER_STOP,onEnded:ot.PLAYER_ENDED,onSeek:ot.PLAYER_SEEK,onError:ot.PLAYER_ERROR,onTimeUpdate:ot.PLAYER_TIMEUPDATE,onVolumeUpdate:ot.PLAYER_VOLUMEUPDATE,onSubtitleAvailable:ot.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,ot.CORE_READY,this._onReady),this.listenTo(this.core,ot.CORE_ACTIVE_CONTAINER_CHANGED,this._containerChanged),this.listenTo(this.core,ot.CORE_FULLSCREEN,this._onFullscreenChange),this.listenTo(this.core,ot.CORE_RESIZE,this._onResize),this}},{key:"_addContainerEventListeners",value:function(){var t=this.core.activeContainer;return t&&(this.listenTo(t,ot.CONTAINER_PLAY,this._onPlay),this.listenTo(t,ot.CONTAINER_PAUSE,this._onPause),this.listenTo(t,ot.CONTAINER_STOP,this._onStop),this.listenTo(t,ot.CONTAINER_ENDED,this._onEnded),this.listenTo(t,ot.CONTAINER_SEEK,this._onSeek),this.listenTo(t,ot.CONTAINER_ERROR,this._onError),this.listenTo(t,ot.CONTAINER_TIMEUPDATE,this._onTimeUpdate),this.listenTo(t,ot.CONTAINER_VOLUME,this._onVolumeUpdate),this.listenTo(t,ot.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 n=t.eventsMapping[e];n&&t.off(n,i[e])}),Object.keys(e).forEach(function(i){var n=t.eventsMapping[i];if(n){var r=e[i];(r="function"==typeof r&&r)&&t.on(n,r)}}),this}},{key:"_unregisterOptionEventListeners",value:function(){var t=this;return this.options.events?(Object.keys(this.options.events).forEach(function(e){var i=t.eventsMapping[e],n=t.options.events[e];i&&n&&t.off(i,n)}),this):this}},{key:"_containerChanged",value:function(){this.stopListening(),this._addEventListeners()}},{key:"_onReady",value:function(){this._ready=!0,this._addContainerEventListeners(),this.trigger(ot.PLAYER_READY)}},{key:"_onFullscreenChange",value:function(t){this.trigger(ot.PLAYER_FULLSCREEN,t)}},{key:"_onVolumeUpdate",value:function(t){this.trigger(ot.PLAYER_VOLUMEUPDATE,t)}},{key:"_onSubtitleAvailable",value:function(){this.trigger(ot.PLAYER_SUBTITLE_AVAILABLE)}},{key:"_onResize",value:function(t){this.trigger(ot.PLAYER_RESIZE,t)}},{key:"_onPlay",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.trigger(ot.PLAYER_PLAY,e)}},{key:"_onPause",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.trigger(ot.PLAYER_PAUSE,e)}},{key:"_onStop",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.trigger(ot.PLAYER_STOP,this.getCurrentTime(),t)}},{key:"_onEnded",value:function(){this.trigger(ot.PLAYER_ENDED)}},{key:"_onSeek",value:function(t){this.trigger(ot.PLAYER_SEEK,t)}},{key:"_onTimeUpdate",value:function(t){this.trigger(ot.PLAYER_TIMEUPDATE,t)}},{key:"_onError",value:function(t){this.trigger(ot.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._unregisterOptionEventListeners(),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:"setVolume",value:function(t){return this.core.activeContainer.setVolume(t),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()}}])}(lt);Object.assign(Nt.prototype,bt);var Ft=function(t){function e(t){var i;return s(this,e),(i=r(this,e,[t.options])).container=t,i.enabled=!0,i.bindEvents(),i}return d(e,t),o(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()}}])}(lt);Object.assign(Ft.prototype,bt),Ft.extend=function(t){return B(Ft,t)},Ft.type="container";var Bt=function(t){function e(t){var i;return s(this,e),(i=r(this,e,[t.options])).core=t,i.enabled=!0,i.bindEvents(),i}return d(e,t),o(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()}}])}(lt);Object.assign(Bt.prototype,bt),Bt.extend=function(t){return B(Bt,t)},Bt.type="core";var $t=function(t){function e(t){var i;return s(this,e),(i=r(this,e,[t.options])).container=t,i.enabled=!0,i.bindEvents(),i}return d(e,t),o(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(){}}])}(Et);Object.assign($t.prototype,bt),$t.extend=function(t){return B($t,t)},$t.type="container";var Ut={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"]};Ut.ogv=Ut.ogg,Ut["3gp"]=Ut["3gpp"];var Gt={wav:["audio/wav"],mp3:["audio/mp3",'audio/mpeg;codecs="mp3"'],aac:['audio/mp4;codecs="mp4a.40.5"'],oga:["audio/ogg"]},Vt=Object.keys(Gt).reduce(function(t,e){return[].concat(A(t),A(Gt[e]))},[]),Kt={code:"unknown",message:"unknown"},Ht=function(t){function e(){var t;s(this,e);for(var i=arguments.length,n=new Array(i),a=0;a<i;a++)n[a]=arguments[a];(t=r(this,e,[].concat(n)))._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 o,l=t.options.playback,h=l.preload||(C.isSafari?"auto":t.options.preload);return t.options.poster&&("string"==typeof t.options.poster?o=t.options.poster:"string"==typeof t.options.poster.url&&(o=t.options.poster.url)),k.extend(!0,t.el,{muted:t.options.mute,defaultMuted:t.options.mute,loop:t.options.loop,poster:o,preload:h||"metadata",crossOrigin:l.crossOrigin,"x-webkit-playsinline":l.playInline}),(l.controls||t.options.useVideoTagDefaultControls)&&t.$el.attr("controls",""),l.playInline&&t.$el.attr({playsinline:"playsinline"}),l.crossOrigin&&t.$el.attr({crossorigin:l.crossOrigin}),t.settings={default:["seekbar"]},t.settings.left=["playpause","position","duration"],t.settings.right=["fullscreen","volume","hd-indicator"],l.externalTracks&&t._setupExternalTracks(l.externalTracks),t.options.autoPlay&&t.attemptAutoPlay(),t}return d(e,t),o(e,[{key:"name",get:function(){return"html5_video"}},{key:"supportedVersion",get:function(){return{min:"0.16.3"}}},{key:"tagName",get:function(){return this.isAudioOnly?"audio":"video"}},{key:"isAudioOnly",get:function(){var t=this.options.src,i=e._mimeTypesForUrl(t,Gt,this.options.mimeType);return this.options.playback&&this.options.playback.audioOnly||this.options.audioOnly||Vt.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()===_t.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){y(e,"configure",this)([t]),this.el.loop=!!t.loop}},{key:"attemptAutoPlay",value:function(){var t=this;this.canAutoPlay(function(e,i){i&&it.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};C.isMobile&&z.options.recycleVideo&&(e.element=this.el),W(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(ot.PLAYBACK_LOADEDMETADATA,{duration:t.target.duration,data:t}),this._updateSettings();var e=void 0===this._options.autoSeekFromUrl||this._options.autoSeekFromUrl;this.getPlaybackType()!==_t.LIVE&&e&&this._checkInitialSeek()}},{key:"_onDurationChange",value:function(){this._updateSettings(),this._onTimeUpdate(),this._onProgress()}},{key:"_updateSettings",value:function(){this.getPlaybackType()===_t.VOD||this.getPlaybackType()===_t.AOD?this.settings.left=["playpause","position","duration"]:this.settings.left=["playstop"],this.settings.seekEnabled=this.isSeekEnabled(),this.trigger(ot.PLAYBACK_SETTINGSUPDATE)}},{key:"isSeekEnabled",value:function(){return isFinite(this.getDuration())}},{key:"getPlaybackType",value:function(){var t="audio"===this.tagName?_t.AOD:_t.VOD;return[0,void 0,1/0].indexOf(this.el.duration)>=0?_t.LIVE:t}},{key:"isHighDefinitionInUse",value:function(){return!1}},{key:"consent",value:function(t){var i=this;if(this.isPlaying()||this.el._consented)y(e,"consent",this)([t]);else{var n=function(){i.el.removeEventListener("loadedmetadata",n,!1),i.el.removeEventListener("error",n,!1),i.el._consented=!0,y(e,"consent",i)([t])};this.el.addEventListener("loadedmetadata",n,!1),this.el.addEventListener("error",n,!1),this.el.load()}}},{key:"play",value:function(){var t=this;this.trigger(ot.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 it.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(ot.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(ot.PLAYBACK_PLAY)}},{key:"_onPause",value:function(){this.dvrEnabled&&this._updateDvr(!0),this._stopPlayheadMovingChecks(),this._handleBufferingEvents(),this.trigger(ot.PLAYBACK_PAUSE)}},{key:"_onSeeking",value:function(){var t=this.getCurrentTime();this.dvrEnabled&&this._updateDvr(t<this.getDuration()-3),this.trigger(ot.PLAYBACK_SEEK,t),this._handleBufferingEvents()}},{key:"_onSeeked",value:function(){this._handleBufferingEvents(),this.trigger(ot.PLAYBACK_SEEKED)}},{key:"_onEnded",value:function(){this._handleBufferingEvents(),this.trigger(ot.PLAYBACK_ENDED,this.name)}},{key:"_onEnterPiP",value:function(){this.trigger(ot.PLAYBACK_PIP_ENTER,this.name)}},{key:"_onExitPiP",value:function(){this.trigger(ot.PLAYBACK_PIP_EXIT,this.name)}},{key:"enterPiP",value:function(){var t=this;this.el.requestPictureInPicture().then(function(){it.info(t.name,"enter PIP success")}).catch(function(e){it.warn(t.name,"enter PIP failed",e)})}},{key:"exitPiP",value:function(){var t=this;document.exitPictureInPicture().then(function(){it.info(t.name,"exit PIP success")}).catch(function(e){it.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,n=t&&e;this._playheadMovingCheckEnabled&&(n=n||t&&i),this._isBuffering!==n&&(this._isBuffering=n,n?this.trigger(ot.PLAYBACK_BUFFERING,this.name):this.trigger(ot.PLAYBACK_BUFFERFULL,this.name))}},{key:"_onError",value:function(){var t=this.el.error||Kt,e=t.code,i=t.message,n=e===Kt.code,r=this.createError({code:e,description:i,raw:this.el.error,level:n?Tt.Levels.WARN:Tt.Levels.FATAL});n?it.warn(this.name,"HTML5 unknown error: ",r):this.trigger(ot.PLAYBACK_ERROR,r)}},{key:"destroy",value:function(){this._destroyed=!0,this._stopPlayheadMovingChecks(),this.handleTextTrackChange&&this.el.textTracks.removeEventListener("change",this.handleTextTrackChange),this.$el.off("contextmenu"),y(e,"destroy",this)([]),this.el.removeAttribute("src"),this.el.load(),this._src=null,z.garbage(this.el)}},{key:"_updateDvr",value:function(t){this.trigger(ot.PLAYBACK_DVR,t),this.trigger(ot.PLAYBACK_STATS_ADD,{dvr:t})}},{key:"seek",value:function(t){t<0&&(it.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=V();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(ot.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(A(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 n={start:t[e].start,current:t[e].end,total:this.el.duration};this.trigger(ot.PLAYBACK_PROGRESS,n,t)}}},{key:"_typeFor",value:function(t){var i=e._mimeTypesForUrl(t,Ut,this.options.mimeType);return 0===i.length&&(i=e._mimeTypesForUrl(t,Gt,this.options.mimeType)),(i[0]||"").split(";")[0]}},{key:"_ready",value:function(){this._isReadyState||(this._isReadyState=!0,this.trigger(ot.PLAYBACK_READY,this.name))}},{key:"_checkForClosedCaptions",value:function(){if(this.isHTML5Video&&!this._ccIsSetup){if(this.hasClosedCaptionsTracks){this.trigger(ot.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(ot.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(H(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){t.track.mode="hidden"}),e&&(e.track.mode="showing"),this._ccTrackId=t,this.trigger(ot.PLAYBACK_SUBTITLE_CHANGED,{id:t})}}},{key:"template",get:function(){return vt('<% 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=yt.getStyleFor("[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}}])}(_t);Ht._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],n=e||i&&t[i.toLowerCase()]||[];return n.constructor===Array?n:[n]},Ht._canPlay=function(t,e,i,n){var r=Ht._mimeTypesForUrl(i,e,n),s=document.createElement(t);return!!r.filter(function(t){return!!s.canPlayType(t).replace(/no/,"")})[0]},Ht.canPlay=function(t,e){return Ht._canPlay("audio",Gt,t,e)||Ht._canPlay("video",Ut,t,e)};var Yt=function(t){function e(){return s(this,e),r(this,e,arguments)}return d(e,t),o(e,[{key:"name",get:function(){return"html5_audio"}},{key:"supportedVersion",get:function(){return{min:"0.16.3"}}},{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(ot.PLAYBACK_SETTINGSUPDATE)}},{key:"getPlaybackType",value:function(){return _t.AOD}}])}(Ht);Yt.canPlay=function(t,e){return Ht._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 jt=function(t){function e(t){var i;return s(this,e),(i=r(this,e,[t])).el.src=t.src,i}return d(e,t),o(e,[{key:"name",get:function(){return"html_img"}},{key:"supportedVersion",get:function(){return{min:"0.16.3"}}},{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 _t.NO_OP}},{key:"render",value:function(){var t=yt.getStyleFor("[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(ot.PLAYBACK_READY,this.name),this}},{key:"_onLoad",value:function(){this.trigger(ot.PLAYBACK_ENDED,this.name)}},{key:"_onError",value:function(t){var e="error"===t.type?"load error":"loading aborted";this.trigger(ot.PLAYBACK_ERROR,{message:e},this.name)}}])}(_t);jt.canPlay=function(t){return/\.(png|jpg|jpeg|gif|bmp|tiff|pgm|pnm|webp)(|\?.*)$/i.test(t)};var Wt=function(t){function e(){var t;s(this,e);for(var i=arguments.length,n=new Array(i),a=0;a<i;a++)n[a]=arguments[a];return(t=r(this,e,[].concat(n)))._noiseFrameNum=-1,t}return d(e,t),o(e,[{key:"name",get:function(){return"no_op"}},{key:"supportedVersion",get:function(){return{min:"0.16.3"}}},{key:"template",get:function(){return vt("<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=yt.getStyleFor("[data-no-op] {\n position: absolute;\n height: 100%;\n width: 100%;\n text-align: center;\n}\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 -webkit-transform: translateY(-50%);\n transform: translateY(-50%);\n max-height: 100%;\n overflow: auto;\n}\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(ot.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(r){t=new Uint32Array(this.context.canvas.width*this.context.canvas.height*4);for(var i=e.data,n=0;n<i.length;n++)t[n]=i[n]}for(var r=t.length,s=6*Math.random()+4,a=0,o=0,l=0;l<r;){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=M(function(){return t._loop()}))}},{key:"destroy",value:function(){this._animationHandle&&(N(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()}}])}(_t);Wt.canPlay=function(t){return!0};var zt=function(t){function e(t){var i;return s(this,e),(i=r(this,e,[t]))._initializeMessages(),i}return d(e,t),o(e,[{key:"name",get:function(){return"strings"}},{key:"supportedVersion",get:function(){return{min:"0.16.3"}}},{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||j()}},{key:"_initializeMessages",value:function(){this._messages=k.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}}])}(Bt),qt=function(t){function e(){return s(this,e),r(this,e,arguments)}return d(e,t),o(e,[{key:"name",get:function(){return"sources"}},{key:"supportedVersion",get:function(){return{min:"0.16.3"}}},{key:"bindEvents",value:function(){this.listenTo(this.core,ot.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()})}}])}(Bt);xt.registerPlugin(zt),xt.registerPlugin(qt),xt.registerPlayback(Wt),xt.registerPlayback(jt),xt.registerPlayback(Yt),xt.registerPlayback(Ht);var Xt={Player:Nt,Events:ot,Browser:C,ContainerPlugin:Ft,UIContainerPlugin:$t,CorePlugin:Bt,UICorePlugin:St,Playback:_t,Container:kt,Core:Rt,PlayerError:Tt,Loader:xt,BaseObject:lt,UIObject:Et,Utils:X,HTML5Audio:Yt,HTML5Video:Ht,HTMLImg:jt,Log:it,Styler:yt,version:"0.16.3",template:vt,$:k};function Qt(t,e,i){return e=ee(e),re(t,ne()?Reflect.construct(e,i||[],ee(t).constructor):e.apply(t,i))}function Zt(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function Jt(t,e,i){return e&&function(t,e){for(var i=0;i<e.length;i++){var n=e[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,oe(n.key),n)}}(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t}function te(){return te="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(t,e,i){var n=function(t,e){for(;!{}.hasOwnProperty.call(t,e)&&null!==(t=ee(t)););return t}(t,e);if(n){var r=Object.getOwnPropertyDescriptor(n,e);return r.get?r.get.call(arguments.length<3?t:i):r.value}},te.apply(null,arguments)}function ee(t){return ee=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},ee(t)}function ie(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&&se(t,e)}function ne(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(ne=function(){return!!t})()}function re(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)}function se(t,e){return se=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},se(t,e)}function ae(t,e,i,n){var r=te(ee(t.prototype),e,i);return"function"==typeof r?function(t){return r.apply(i,t)}:r}function oe(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var n=i.call(t,e);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t,"string");return"symbol"==typeof e?e:e+""}function le(t){return le="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},le(t)}var he=function(t){function e(){return Zt(this,e),Qt(this,e,arguments)}return ie(e,t),Jt(e,[{key:"name",get:function(){return"click_to_pause"}},{key:"supportedVersion",get:function(){return{min:"0.16.3"}}},{key:"config",get:function(){return this.container.options.clickToPauseConfig||{}}},{key:"bindEvents",value:function(){this.listenTo(this.container,ot.CONTAINER_CLICK,this.click),this.listenTo(this.container,ot.CONTAINER_SETTINGSUPDATE,this.settingsUpdate)}},{key:"click",value:function(){var t=this.config.onClickPayload;(this.container.getPlaybackType()!==_t.LIVE||this.container.isDvrEnabled())&&(this.container.isPlaying()?this.container.pause(t):this.container.play(t))}},{key:"settingsUpdate",value:function(){var t=this.container.getPlaybackType()!==_t.LIVE||this.container.isDvrEnabled();if(t!==this.pointerEnabled){var e=t?"addClass":"removeClass";this.container.$el[e]("pointer-enabled"),this.pointerEnabled=t}}}])}(Ft),ce=function(t){function e(t){var i;Zt(this,e),i=Qt(this,e,[t]);var n=t.options.closedCaptionsConfig;return i._title=n&&n.title?n.title:null,i._ariaLabel=n&&n.ariaLabel?n.ariaLabel:"cc-button",i._labelCb=n&&n.labelCallback&&"function"==typeof n.labelCallback?n.labelCallback:function(t){return t.name},i}return ie(e,t),Jt(e,[{key:"name",get:function(){return"closed_captions"}},{key:"supportedVersion",get:function(){return{min:"0.16.3"}}},{key:"template",get:function(){return vt('<button type="button" class="cc-button media-control-button media-control-icon" data-cc-button aria-label="<%= ariaLabel %>"></button>\n<ul>\n <% if (title) { %>\n <li data-title><%= title %></li>\n <% }; %>\n <li><a href="#" data-cc-select="-1"><%= disabledLabel %></a></li>\n <% for (var i = 0; i < tracks.length; i++) { %>\n <li><a href="#" data-cc-select="<%= tracks[i].id %>"><%= tracks[i].label %></a></li>\n <% }; %>\n</ul>\n')}},{key:"events",get:function(){return{"click [data-cc-button]":"toggleContextMenu","click [data-cc-select]":"onTrackSelect"}}},{key:"attributes",get:function(){return{class:"cc-controls","data-cc-controls":""}}},{key:"bindEvents",value:function(){this.listenTo(this.core,ot.CORE_ACTIVE_CONTAINER_CHANGED,this.containerChanged),this.listenTo(this.core.mediaControl,ot.MEDIACONTROL_RENDERED,this.render),this.listenTo(this.core.mediaControl,ot.MEDIACONTROL_HIDE,this.hideContextMenu),this.bindContainerEvents()}},{key:"bindContainerEvents",value:function(){this.container=this.core.activeContainer,this.container&&(this.listenTo(this.container,ot.CONTAINER_SUBTITLE_AVAILABLE,this.onSubtitleAvailable),this.listenTo(this.container,ot.CONTAINER_SUBTITLE_CHANGED,this.onSubtitleChanged),this.listenTo(this.container,ot.CONTAINER_STOP,this.onContainerStop))}},{key:"onContainerStop",value:function(){this.ccAvailable(!1)}},{key:"containerChanged",value:function(){this.ccAvailable(!1),this.stopListening(),this.bindEvents()}},{key:"onSubtitleAvailable",value:function(){this.renderCcButton(),this.ccAvailable(!0)}},{key:"onSubtitleChanged",value:function(t){this.setCurrentContextMenuElement(t.id)}},{key:"onTrackSelect",value:function(t){var e=parseInt(t.target.dataset.ccSelect,10);return this.container.closedCaptionsTrackId=e,this.hideContextMenu(),t.stopPropagation(),!1}},{key:"ccAvailable",value:function(t){var e=t?"addClass":"removeClass";this.$el[e]("available")}},{key:"toggleContextMenu",value:function(){this.$el.find("ul").toggle()}},{key:"hideContextMenu",value:function(){this.$el.find("ul").hide()}},{key:"contextMenuElement",value:function(t){return this.$el.find("ul a"+(isNaN(t)?"":'[data-cc-select="'+t+'"]')).parent()}},{key:"setCurrentContextMenuElement",value:function(t){if(this._trackId!==t){this.contextMenuElement().removeClass("current"),this.contextMenuElement(t).addClass("current");var e=t>-1?"addClass":"removeClass";this.$ccButton[e]("enabled"),this._trackId=t}}},{key:"renderCcButton",value:function(){for(var t=this.container?this.container.closedCaptionsTracks:[],e=0;e<t.length;e++)t[e].label=this._labelCb(t[e]);var i=yt.getStyleFor(".cc-controls[data-cc-controls] {\n float: right;\n position: relative;\n display: none;\n}\n.cc-controls[data-cc-controls].available {\n display: block;\n}\n.cc-controls[data-cc-controls] .cc-button {\n padding: 6px !important;\n}\n.cc-controls[data-cc-controls] .cc-button.enabled {\n display: block;\n opacity: 1;\n}\n.cc-controls[data-cc-controls] .cc-button.enabled:hover {\n opacity: 1;\n text-shadow: none;\n}\n.cc-controls[data-cc-controls] > ul {\n list-style-type: none;\n position: absolute;\n bottom: 25px;\n border: 1px solid black;\n display: none;\n background-color: #e6e6e6;\n}\n.cc-controls[data-cc-controls] li {\n font-size: 10px;\n}\n.cc-controls[data-cc-controls] li[data-title] {\n background-color: #c3c2c2;\n padding: 5px;\n}\n.cc-controls[data-cc-controls] li a {\n color: #444;\n padding: 2px 10px;\n display: block;\n text-decoration: none;\n}\n.cc-controls[data-cc-controls] li a:hover {\n background-color: #555;\n color: white;\n}\n.cc-controls[data-cc-controls] li a:hover a {\n color: white;\n text-decoration: none;\n}\n.cc-controls[data-cc-controls] li.current a {\n color: #f00;\n}",{baseUrl:this.options.baseUrl});this.$el.html(this.template({ariaLabel:this._ariaLabel,disabledLabel:this.core.i18n.t("disabled"),title:this._title,tracks:t})),this.$ccButton=this.$el.find("button.cc-button[data-cc-button]"),this.$ccButton.append('<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"\n\t viewBox="0 0 49 41.8" style="enable-background:new 0 0 49 41.8;" xml:space="preserve">\n<path d="M47.1,0H3.2C1.6,0,0,1.2,0,2.8v31.5C0,35.9,1.6,37,3.2,37h11.9l3.2,1.9l4.7,2.7c0.9,0.5,2-0.1,2-1.1V37h22.1\n\tc1.6,0,1.9-1.1,1.9-2.7V2.8C49,1.2,48.7,0,47.1,0z M7.2,18.6c0-4.8,3.5-9.3,9.9-9.3c4.8,0,7.1,2.7,7.1,2.7l-2.5,4\n\tc0,0-1.7-1.7-4.2-1.7c-2.8,0-4.3,2.1-4.3,4.3c0,2.1,1.5,4.4,4.5,4.4c2.5,0,4.9-2.1,4.9-2.1l2.2,4.2c0,0-2.7,2.9-7.6,2.9\n\tC10.8,27.9,7.2,23.5,7.2,18.6z M36.9,27.9c-6.4,0-9.9-4.4-9.9-9.3c0-4.8,3.5-9.3,9.9-9.3C41.7,9.3,44,12,44,12l-2.5,4\n\tc0,0-1.7-1.7-4.2-1.7c-2.8,0-4.3,2.1-4.3,4.3c0,2.1,1.5,4.4,4.5,4.4c2.5,0,4.9-2.1,4.9-2.1l2.2,4.2C44.5,25,41.9,27.9,36.9,27.9z"/>\n</svg>'),this.$el.append(i[0])}},{key:"render",value:function(){this.renderCcButton();var t=this.core.mediaControl.$el.find("button[data-fullscreen]");return t[0]?this.$el.insertAfter(t):this.core.mediaControl.$el.find(".media-control-right-panel[data-media-control]").prepend(this.$el),this}}])}(St),ue=function(t){function e(t){var i;return Zt(this,e),(i=Qt(this,e,[t])).settingsUpdate(),i}return ie(e,t),Jt(e,[{key:"template",get:function(){return vt('<div class="live-info"><%= live %></div>\n<button type="button" class="live-button" aria-label="<%= backToLive %>"><%= backToLive %></button>\n')}},{key:"name",get:function(){return"dvr_controls"}},{key:"supportedVersion",get:function(){return{min:"0.16.3"}}},{key:"events",get:function(){return{"click .live-button":"click"}}},{key:"attributes",get:function(){return{class:"dvr-controls","data-dvr-controls":""}}},{key:"bindEvents",value:function(){this.bindCoreEvents(),this.bindContainerEvents()}},{key:"bindCoreEvents",value:function(){var t=this;this.core.mediaControl.settings?(this.listenTo(this.core.mediaControl,ot.MEDIACONTROL_CONTAINERCHANGED,this.containerChanged),this.listenTo(this.core.mediaControl,ot.MEDIACONTROL_RENDERED,this.settingsUpdate),this.listenTo(this.core,ot.CORE_OPTIONS_CHANGE,this.render)):setTimeout(function(){return t.bindCoreEvents()},100)}},{key:"bindContainerEvents",value:function(){this.core.activeContainer&&(this.listenToOnce(this.core.activeContainer,ot.CONTAINER_TIMEUPDATE,this.render),this.listenTo(this.core.activeContainer,ot.CONTAINER_PLAYBACKDVRSTATECHANGED,this.dvrChanged))}},{key:"containerChanged",value:function(){this.stopListening(),this.bindEvents()}},{key:"dvrChanged",value:function(t){this.core.getPlaybackType()===_t.LIVE&&(this.settingsUpdate(),this.core.mediaControl.$el.addClass("live"),t?(this.core.mediaControl.$el.addClass("dvr"),this.core.mediaControl.$el.find(".media-control-indicator[data-position], .media-control-indicator[data-duration]").hide()):this.core.mediaControl.$el.removeClass("dvr"))}},{key:"click",value:function(){var t=this.core.mediaControl,e=t.container;e.isPlaying()||e.play(),t.$el.hasClass("dvr")&&e.seek(e.getDuration())}},{key:"settingsUpdate",value:function(){var t=this;this.stopListening(),this.core.mediaControl.$el.removeClass("live"),this.shouldRender()&&(this.render(),this.$el.click(function(){return t.click()})),this.bindEvents()}},{key:"shouldRender",value:function(){return(void 0===this.core.options.useDvrControls||!!this.core.options.useDvrControls)&&this.core.getPlaybackType()===_t.LIVE}},{key:"render",value:function(){var t=yt.getStyleFor('.dvr-controls[data-dvr-controls] {\n display: inline-block;\n float: left;\n color: #fff;\n line-height: 32px;\n font-size: 10px;\n font-weight: bold;\n margin-left: 6px;\n}\n.dvr-controls[data-dvr-controls] .live-info {\n cursor: default;\n font-family: "Roboto", "Open Sans", Arial, sans-serif;\n text-transform: uppercase;\n}\n.dvr-controls[data-dvr-controls] .live-info:before {\n content: "";\n display: inline-block;\n position: relative;\n width: 7px;\n height: 7px;\n border-radius: 3.5px;\n margin-right: 3.5px;\n background-color: #ff0101;\n}\n.dvr-controls[data-dvr-controls] .live-info.disabled {\n opacity: 0.3;\n}\n.dvr-controls[data-dvr-controls] .live-info.disabled:before {\n background-color: #fff;\n}\n.dvr-controls[data-dvr-controls] .live-button {\n cursor: pointer;\n outline: none;\n display: none;\n border: 0;\n color: #fff;\n background-color: transparent;\n height: 32px;\n padding: 0;\n opacity: 0.7;\n font-family: "Roboto", "Open Sans", Arial, sans-serif;\n text-transform: uppercase;\n -webkit-transition: all 0.1s ease;\n transition: all 0.1s ease;\n}\n.dvr-controls[data-dvr-controls] .live-button:before {\n content: "";\n display: inline-block;\n position: relative;\n width: 7px;\n height: 7px;\n border-radius: 3.5px;\n margin-right: 3.5px;\n background-color: #fff;\n}\n.dvr-controls[data-dvr-controls] .live-button:hover {\n opacity: 1;\n text-shadow: rgba(255, 255, 255, 0.75) 0 0 5px;\n}\n\n.dvr .dvr-controls[data-dvr-controls] .live-info {\n display: none;\n}\n.dvr .dvr-controls[data-dvr-controls] .live-button {\n display: block;\n}\n.dvr.media-control.live[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar] {\n background-color: #005aff;\n}\n\n.media-control.live[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar] {\n background-color: #ff0101;\n}',{baseUrl:this.options.baseUrl});return this.$el.html(this.template({live:this.core.i18n.t("live"),backToLive:this.core.i18n.t("back_to_live")})),this.$el.append(t[0]),this.shouldRender()&&(this.core.mediaControl.$el.addClass("live"),this.core.mediaControl.$(".media-control-left-panel[data-media-control]").append(this.$el)),this}}])}(St),de=function(t){function e(){return Zt(this,e),Qt(this,e,arguments)}return ie(e,t),Jt(e,[{key:"name",get:function(){return"end_video"}},{key:"supportedVersion",get:function(){return{min:"0.16.3"}}},{key:"bindEvents",value:function(){this.listenTo(this.core,ot.CORE_ACTIVE_CONTAINER_CHANGED,this.containerChanged);var t=this.core.activeContainer;t&&(this.listenTo(t,ot.CONTAINER_ENDED,this.ended),this.listenTo(t,ot.CONTAINER_STOP,this.ended))}},{key:"containerChanged",value:function(){this.stopListening(),this.bindEvents()}},{key:"ended",value:function(){(void 0===this.core.options.exitFullscreenOnEnd||this.core.options.exitFullscreenOnEnd)&&this.core.isFullscreen()&&this.core.toggleFullscreen()}}])}(Bt),fe=function(t){function e(t){var i;return Zt(this,e),(i=Qt(this,e,[t])).options.disableErrorScreen?re(i,i.disable()):i}return ie(e,t),Jt(e,[{key:"name",get:function(){return"error_screen"}},{key:"supportedVersion",get:function(){return{min:"0.16.3"}}},{key:"template",get:function(){return vt('<div class="player-error-screen__content" data-error-screen>\n <% if (icon) { %>\n <div class="player-error-screen__icon" data-error-screen><%= icon %></div>\n <% } %>\n <div class="player-error-screen__title" data-error-screen><%= title %></div>\n <div class="player-error-screen__message" data-error-screen><%= message %></div>\n <div class="player-error-screen__code" data-error-screen>Error code: <%= code %></div>\n <div class="player-error-screen__reload" data-error-screen><%= reloadIcon %></div>\n</div>\n')}},{key:"container",get:function(){return this.core.getCurrentContainer()}},{key:"attributes",get:function(){return{class:"player-error-screen","data-error-screen":""}}},{key:"bindEvents",value:function(){this.listenTo(this.core,ot.ERROR,this.onError),this.listenTo(this.core,ot.CORE_ACTIVE_CONTAINER_CHANGED,this.onContainerChanged)}},{key:"bindReload",value:function(){this.reloadButton=this.$el.find(".player-error-screen__reload"),this.reloadButton&&this.reloadButton.on("click",this.reload.bind(this))}},{key:"reload",value:function(){var t=this;this.listenToOnce(this.core,ot.CORE_READY,function(){return t.container.play()}),this.core.load(this.options.sources,this.options.mimeType),this.unbindReload()}},{key:"unbindReload",value:function(){this.reloadButton&&this.reloadButton.off("click")}},{key:"onContainerChanged",value:function(){this.err=null,this.unbindReload(),this.hide()}},{key:"onError",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};t.level===Tt.Levels.FATAL&&(this.err=t,this.container.disableMediaControl(),this.container.stop(),this.show())}},{key:"show",value:function(){this.render(),this.$el.show()}},{key:"hide",value:function(){this.$el.hide()}},{key:"render",value:function(){if(this.err){var t=yt.getStyleFor("[data-player] .player-error-screen {\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n color: #CCCACA;\n position: absolute;\n top: 0;\n height: 100%;\n width: 100%;\n background-color: rgba(0, 0, 0, 0.7);\n z-index: 2000;\n display: -webkit-box;\n display: -ms-flexbox;\n display: flex;\n -webkit-box-orient: vertical;\n -webkit-box-direction: normal;\n -ms-flex-direction: column;\n flex-direction: column;\n -webkit-box-pack: center;\n -ms-flex-pack: center;\n justify-content: center;\n}\n[data-player] .player-error-screen__content[data-error-screen] {\n font-size: 14px;\n color: #CCCACA;\n margin-top: 45px;\n}\n[data-player] .player-error-screen__title[data-error-screen] {\n font-weight: bold;\n line-height: 30px;\n font-size: 18px;\n}\n[data-player] .player-error-screen__message[data-error-screen] {\n width: 90%;\n margin: 0 auto;\n}\n[data-player] .player-error-screen__code[data-error-screen] {\n font-size: 13px;\n margin-top: 15px;\n}\n[data-player] .player-error-screen__reload {\n cursor: pointer;\n width: 30px;\n margin: 15px auto 0 !important;\n}",{baseUrl:this.options.baseUrl});return this.$el.html(this.template({title:this.err.UI.title,message:this.err.UI.message,code:this.err.code,icon:this.err.UI.icon||"",reloadIcon:'<svg fill="#FFFFFF" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg">\n <path d="M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"/>\n <path d="M0 0h24v24H0z" fill="none"/>\n</svg>'})),this.$el.append(t[0]),this.core.$el.append(this.el),this.bindReload(),this}}}])}(St),ge='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">\n <path fill="#010101" d="M1.425.35L14.575 8l-13.15 7.65V.35z"/>\n</svg>',pe='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">\n <path fill-rule="evenodd" clip-rule="evenodd" fill="#010101" d="M1.712 14.76H6.43V1.24H1.71v13.52zm7.86-13.52v13.52h4.716V1.24H9.573z"/>\n</svg>',me=k('link[rel="shortcut icon"]'),ve=function(t){function e(t){var i;return Zt(this,e),(i=Qt(this,e,[t]))._container=null,i.configure(),i}return ie(e,t),Jt(e,[{key:"name",get:function(){return"favicon"}},{key:"supportedVersion",get:function(){return{min:"0.16.3"}}},{key:"oldIcon",get:function(){return me}},{key:"configure",value:function(){this.core.options.changeFavicon?this.enabled||(this.stopListening(this.core,ot.CORE_OPTIONS_CHANGE),this.enable()):this.enabled&&(this.disable(),this.listenTo(this.core,ot.CORE_OPTIONS_CHANGE,this.configure))}},{key:"bindEvents",value:function(){this.listenTo(this.core,ot.CORE_OPTIONS_CHANGE,this.configure),this.listenTo(this.core,ot.CORE_ACTIVE_CONTAINER_CHANGED,this.containerChanged),this.core.activeContainer&&this.containerChanged()}},{key:"containerChanged",value:function(){this._container&&this.stopListening(this._container),this._container=this.core.activeContainer,this.listenTo(this._container,ot.CONTAINER_PLAY,this.setPlayIcon),this.listenTo(this._container,ot.CONTAINER_PAUSE,this.setPauseIcon),this.listenTo(this._container,ot.CONTAINER_STOP,this.resetIcon),this.listenTo(this._container,ot.CONTAINER_ENDED,this.resetIcon),this.listenTo(this._container,ot.CONTAINER_ERROR,this.resetIcon),this.resetIcon()}},{key:"disable",value:function(){ae(e,"disable",this)([]),this.resetIcon()}},{key:"destroy",value:function(){ae(e,"destroy",this)([]),this.resetIcon()}},{key:"createIcon",value:function(t){var e=k("<canvas/>");e[0].width=16,e[0].height=16;var i=e[0].getContext("2d");i.fillStyle="#000";var n=k(t).find("path").attr("d"),r=new Path2D(n);i.fill(r);var s=k('<link rel="shortcut icon" type="image/png"/>');return s.attr("href",e[0].toDataURL("image/png")),s}},{key:"setPlayIcon",value:function(){this.playIcon||(this.playIcon=this.createIcon(ge)),this.changeIcon(this.playIcon)}},{key:"setPauseIcon",value:function(){this.pauseIcon||(this.pauseIcon=this.createIcon(pe)),this.changeIcon(this.pauseIcon)}},{key:"resetIcon",value:function(){k('link[rel="shortcut icon"]').remove(),k("head").append(this.oldIcon)}},{key:"changeIcon",value:function(t){t&&(k('link[rel="shortcut icon"]').remove(),k("head").append(t))}}])}(Bt),ye=function(t){function e(t){var i;return Zt(this,e),(i=Qt(this,e,[t])).container.options.gaAccount&&(i.account=i.container.options.gaAccount,i.trackerName=i.container.options.gaTrackerName?i.container.options.gaTrackerName+".":"Clappr.",i.domainName=i.container.options.gaDomainName,i.currentHDState=void 0,i.embedScript()),i}return ie(e,t),Jt(e,[{key:"name",get:function(){return"google_analytics"}},{key:"supportedVersion",get:function(){return{min:"0.16.3"}}},{key:"embedScript",value:function(){var t=this;if(window._gat)this.addEventListeners();else{var e=document.createElement("script");e.setAttribute("type","text/javascript"),e.setAttribute("async","async"),e.setAttribute("src","//www.google-analytics.com/ga.js"),e.onload=function(){return t.addEventListeners()},document.body.appendChild(e)}}},{key:"addEventListeners",value:function(){var t=this;this.container&&(this.listenTo(this.container,ot.CONTAINER_READY,this.onReady),this.listenTo(this.container,ot.CONTAINER_PLAY,this.onPlay),this.listenTo(this.container,ot.CONTAINER_STOP,this.onStop),this.listenTo(this.container,ot.CONTAINER_PAUSE,this.onPause),this.listenTo(this.container,ot.CONTAINER_ENDED,this.onEnded),this.listenTo(this.container,ot.CONTAINER_STATE_BUFFERING,this.onBuffering),this.listenTo(this.container,ot.CONTAINER_STATE_BUFFERFULL,this.onBufferFull),this.listenTo(this.container,ot.CONTAINER_ERROR,this.onError),this.listenTo(this.container,ot.CONTAINER_PLAYBACKSTATE,this.onPlaybackChanged),this.listenTo(this.container,ot.CONTAINER_VOLUME,function(e){return t.onVolumeChanged(e)}),this.listenTo(this.container,ot.CONTAINER_SEEK,function(e){return t.onSeek(e)}),this.listenTo(this.container,ot.CONTAINER_FULL_SCREEN,this.onFullscreen),this.listenTo(this.container,ot.CONTAINER_HIGHDEFINITIONUPDATE,this.onHD),this.listenTo(this.container,ot.CONTAINER_PLAYBACKDVRSTATECHANGED,this.onDVR)),_gaq.push([this.trackerName+"_setAccount",this.account]),this.domainName&&_gaq.push([this.trackerName+"_setDomainName",this.domainName])}},{key:"onReady",value:function(){this.push(["Video","Playback",this.container.playback.name])}},{key:"onPlay",value:function(){this.push(["Video","Play",this.container.playback.src])}},{key:"onStop",value:function(){this.push(["Video","Stop",this.container.playback.src])}},{key:"onEnded",value:function(){this.push(["Video","Ended",this.container.playback.src])}},{key:"onBuffering",value:function(){this.push(["Video","Buffering",this.container.playback.src])}},{key:"onBufferFull",value:function(){this.push(["Video","Bufferfull",this.container.playback.src])}},{key:"onError",value:function(){this.push(["Video","Error",this.container.playback.src])}},{key:"onHD",value:function(t){var e=t?"ON":"OFF";e!==this.currentHDState&&(this.currentHDState=e,this.push(["Video","HD - "+e,this.container.playback.src]))}},{key:"onPlaybackChanged",value:function(t){null!==t.type&&this.push(["Video","Playback Type - "+t.type,this.container.playback.src])}},{key:"onDVR",value:function(t){var e=t?"ON":"OFF";this.push(["Interaction","DVR - "+e,this.container.playback.src])}},{key:"onPause",value:function(){this.push(["Video","Pause",this.container.playback.src])}},{key:"onSeek",value:function(){this.push(["Video","Seek",this.container.playback.src])}},{key:"onVolumeChanged",value:function(){this.push(["Interaction","Volume",this.container.playback.src])}},{key:"onFullscreen",value:function(){this.push(["Interaction","Fullscreen",this.container.playback.src])}},{key:"push",value:function(t){var e=[this.trackerName+"_trackEvent"].concat(t);_gaq.push(e)}}])}(Ft),Ae=function(t){this.element=t||window.document,this.initialize()};Ae.KEY_NAMES_BY_CODE={8:"backspace",9:"tab",13:"enter",16:"shift",17:"ctrl",18:"alt",20:"caps_lock",27:"esc",32:"space",37:"left",38:"up",39:"right",40:"down",48:"0",49:"1",50:"2",51:"3",52:"4",53:"5",54:"6",55:"7",56:"8",57:"9",65:"a",66:"b",67:"c",68:"d",69:"e",70:"f",71:"g",72:"h",73:"i",74:"j",75:"k",76:"l",77:"m",78:"n",79:"o",80:"p",81:"q",82:"r",83:"s",84:"t",85:"u",86:"v",87:"w",88:"x",89:"y",90:"z",112:"f1",113:"f2",114:"f3",115:"f4",116:"f5",117:"f6",118:"f7",119:"f8",120:"f9",121:"f10",122:"f11",123:"f12"},Ae.KEY_CODES_BY_NAME={},function(){for(var t in Ae.KEY_NAMES_BY_CODE)Object.prototype.hasOwnProperty.call(Ae.KEY_NAMES_BY_CODE,t)&&(Ae.KEY_CODES_BY_NAME[Ae.KEY_NAMES_BY_CODE[t]]=+t)}(),Ae.MODIFIERS=["shift","ctrl","alt"],Ae.registerEvent=document.addEventListener?function(t,e,i){t.addEventListener(e,i,!1)}:document.attachEvent?function(t,e,i){t.attachEvent("on"+e,i)}:void 0,Ae.unregisterEvent=document.removeEventListener?function(t,e,i){t.removeEventListener(e,i,!1)}:document.detachEvent?function(t,e,i){t.detachEvent("on"+e,i)}:void 0,Ae.stringContains=function(t,e){return-1!==t.indexOf(e)},Ae.neatString=function(t){return t.replace(/^\s+|\s+$/g,"").replace(/\s+/g," ")},Ae.capitalize=function(t){return t.toLowerCase().replace(/^./,function(t){return t.toUpperCase()})},Ae.isString=function(t){return Ae.stringContains(Object.prototype.toString.call(t),"String")},Ae.arrayIncludes=Array.prototype.indexOf?function(t,e){return-1!==t.indexOf(e)}:function(t,e){for(var i=0;i<t.length;i++)if(t[i]===e)return!0;return!1},Ae.extractModifiers=function(t){var e,i;for(e=[],i=0;i<Ae.MODIFIERS.length;i++)Ae.stringContains(t,Ae.MODIFIERS[i])&&e.push(Ae.MODIFIERS[i]);return e},Ae.extractKey=function(t){var e,i;for(e=Ae.neatString(t).split(" "),i=0;i<e.length;i++)if(!Ae.arrayIncludes(Ae.MODIFIERS,e[i]))return e[i]},Ae.modifiersAndKey=function(t){var e,i;return Ae.stringContains(t,"any")?Ae.neatString(t).split(" ").slice(0,2).join(" "):(e=Ae.extractModifiers(t),(i=Ae.extractKey(t))&&!Ae.arrayIncludes(Ae.MODIFIERS,i)&&e.push(i),e.join(" "))},Ae.keyName=function(t){return Ae.KEY_NAMES_BY_CODE[t+""]},Ae.keyCode=function(t){return+Ae.KEY_CODES_BY_NAME[t]},Ae.prototype.initialize=function(){var t,e=this;for(this.lastKeyCode=-1,this.lastModifiers={},t=0;t<Ae.MODIFIERS.length;t++)this.lastModifiers[Ae.MODIFIERS[t]]=!1;this.keysDown={any:[]},this.keysUp={any:[]},this.downHandler=this.handler("down"),this.upHandler=this.handler("up"),Ae.registerEvent(this.element,"keydown",this.downHandler),Ae.registerEvent(this.element,"keyup",this.upHandler);var i="object"===le(window.onbeforeunload)?"beforeunload":"unload";Ae.registerEvent(window,i,function t(){Ae.unregisterEvent(e.element,"keydown",e.downHandler),Ae.unregisterEvent(e.element,"keyup",e.upHandler),Ae.unregisterEvent(window,i,t)})},Ae.prototype.handler=function(t){var e=this;return function(i){var n,r,s;for(i=i||window.event,e.lastKeyCode=i.keyCode,n=0;n<Ae.MODIFIERS.length;n++)e.lastModifiers[Ae.MODIFIERS[n]]=i[Ae.MODIFIERS[n]+"Key"];for(Ae.arrayIncludes(Ae.MODIFIERS,Ae.keyName(e.lastKeyCode))&&(e.lastModifiers[Ae.keyName(e.lastKeyCode)]=!0),r=e["keys"+Ae.capitalize(t)],n=0;n<r.any.length;n++)!1===r.any[n](i)&&i.preventDefault&&i.preventDefault();if(r[s=e.lastModifiersAndKey()])for(n=0;n<r[s].length;n++)!1===r[s][n](i)&&i.preventDefault&&i.preventDefault()}},Ae.prototype.registerKeys=function(t,e,i){var n,r,s=this["keys"+Ae.capitalize(t)];for(Ae.isString(e)&&(e=[e]),n=0;n<e.length;n++)r=e[n],s[r=Ae.modifiersAndKey(r+"")]?s[r].push(i):s[r]=[i];return this},Ae.prototype.unregisterKeys=function(t,e,i){var n,r,s,a=this["keys"+Ae.capitalize(t)];for(Ae.isString(e)&&(e=[e]),n=0;n<e.length;n++)if(s=e[n],s=Ae.modifiersAndKey(s+""),null===i)delete a[s];else if(a[s])for(r=0;r<a[s].length;r++)if(String(a[s][r])===String(i)){a[s].splice(r,1);break}return this},Ae.prototype.off=function(t){return this.unregisterKeys("down",t,null)},Ae.prototype.delegate=function(t,e,i){return null!==i||void 0!==i?this.registerKeys(t,e,i):this.unregisterKeys(t,e,i)},Ae.prototype.down=function(t,e){return this.delegate("down",t,e)},Ae.prototype.up=function(t,e){return this.delegate("up",t,e)},Ae.prototype.lastKey=function(t){return t?this.lastModifiers[t]:Ae.keyName(this.lastKeyCode)},Ae.prototype.lastModifiersAndKey=function(){var t,e;for(t=[],e=0;e<Ae.MODIFIERS.length;e++)this.lastKey(Ae.MODIFIERS[e])&&t.push(Ae.MODIFIERS[e]);return Ae.arrayIncludes(t,this.lastKey())||t.push(this.lastKey()),t.join(" ")};var Ee={Kibo:Ae},Te='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">\n <path fill-rule="evenodd" clip-rule="evenodd" fill="#010101" d="M1.712 1.24h12.6v13.52h-12.6z"/>\n</svg>',be='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">\n <path fill-rule="evenodd" clip-rule="evenodd" fill="#010101" d="M11.5 11h-.002v1.502L7.798 10H4.5V6h3.297l3.7-2.502V4.5h.003V11zM11 4.49L7.953 6.5H5v3h2.953L11 11.51V4.49z"/>\n</svg>',Se='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">\n <path fill="#010101" d="M7.156 8L4 11.156V8.5H3V13h4.5v-1H4.844L8 8.844 7.156 8zM8.5 3v1h2.657L8 7.157 8.846 8 12 4.844V7.5h1V3H8.5z"/>\n</svg>',ke=X.Config,_e=X.Fullscreen,Le=X.formatTime,Re=X.extend,Ie=X.removeArrayItem,Ce=function(t){function e(t){var i;return Zt(this,e),(i=Qt(this,e,[t])).persistConfig=i.options.persistConfig,i._previousVolumeState=null,i.currentPositionValue=null,i.currentDurationValue=null,i.keepVisible=!1,i.fullScreenOnVideoTagSupported=null,i.setInitialVolume(),i.settings={left:["play","stop","pause"],right:["volume"],default:["position","seekbar","duration"]},i.kibo=new Ae(i.options.focusElement),i.bindKeyEvents(),i.container?k.isEmptyObject(i.container.settings)||(i.settings=k.extend({},i.container.settings)):i.settings={},i.userDisabled=!1,(i.container&&i.container.mediaControlDisabled||i.options.chromeless)&&i.disable(),i.stopDragHandler=function(t){return i.stopDrag(t)},i.updateDragHandler=function(t){return i.updateDrag(t)},k(document).bind("mouseup",i.stopDragHandler),k(document).bind("mousemove",i.updateDragHandler),i}return ie(e,t),Jt(e,[{key:"name",get:function(){return"media_control"}},{key:"supportedVersion",get:function(){return{min:"0.16.3"}}},{key:"disabled",get:function(){var t=this.container&&this.container.getPlaybackType()===_t.NO_OP;return this.userDisabled||t}},{key:"container",get:function(){return this.core&&this.core.activeContainer}},{key:"playback",get:function(){return this.core&&this.core.activePlayback}},{key:"attributes",get:function(){return{class:"media-control","data-media-control":""}}},{key:"events",get:function(){return{"click [data-play]":"play","click [data-pause]":"pause","click [data-playpause]":"togglePlayPause","click [data-stop]":"stop","click [data-playstop]":"togglePlayStop","click [data-fullscreen]":"toggleFullscreen","click .bar-container[data-seekbar]":"seek","click .bar-container[data-volume]":"onVolumeClick","click .drawer-icon[data-volume]":"toggleMute","mouseenter .drawer-container[data-volume]":"showVolumeBar","mouseleave .drawer-container[data-volume]":"hideVolumeBar","mousedown .bar-container[data-volume]":"startVolumeDrag","mousemove .bar-container[data-volume]":"mousemoveOnVolumeBar","mousedown .bar-scrubber[data-seekbar]":"startSeekDrag","mousemove .bar-container[data-seekbar]":"mousemoveOnSeekBar","mouseleave .bar-container[data-seekbar]":"mouseleaveOnSeekBar","mouseenter .media-control-layer[data-controls]":"setUserKeepVisible","mouseleave .media-control-layer[data-controls]":"resetUserKeepVisible"}}},{key:"template",get:function(){return vt('<div class="media-control-background" data-background></div>\n<div class="media-control-layer" data-controls>\n <% var renderBar = function(name) { %>\n <div class="bar-container" data-<%= name %>>\n <div class="bar-background" data-<%= name %>>\n <div class="bar-fill-1" data-<%= name %>></div>\n <div class="bar-fill-2" data-<%= name %>></div>\n <div class="bar-hover" data-<%= name %>></div>\n </div>\n <div class="bar-scrubber" data-<%= name %>>\n <div class="bar-scrubber-icon" data-<%= name %>></div>\n </div>\n </div>\n <% }; %>\n <% var renderSegmentedBar = function(name, segments) {\n segments = segments || 10; %>\n <div class="bar-container" data-<%= name %>>\n <% for (var i = 0; i < segments; i++) { %>\n <div class="segmented-bar-element" data-<%= name %>></div>\n <% } %>\n </div>\n <% }; %>\n <% var renderDrawer = function(name, renderContent) { %>\n <div class="drawer-container" data-<%= name %>>\n <div class="drawer-icon-container" data-<%= name %>>\n <div class="drawer-icon media-control-icon" data-<%= name %>></div>\n <span class="drawer-text" data-<%= name %>></span>\n </div>\n <% renderContent(name); %>\n </div>\n <% }; %>\n <% var renderIndicator = function(name) { %>\n <div class="media-control-indicator" data-<%= name %>></div>\n <% }; %>\n <% var renderButton = function(name) { %>\n <button type="button" class="media-control-button media-control-icon" data-<%= name %> aria-label="<%= name %>"></button>\n <% }; %>\n <% var templates = {\n bar: renderBar,\n segmentedBar: renderSegmentedBar,\n };\n var render = function(settingsList) {\n settingsList.forEach(function(setting) {\n if(setting === "seekbar") {\n renderBar(setting);\n } else if (setting === "volume") {\n renderDrawer(setting, settings.volumeBarTemplate ? templates[settings.volumeBarTemplate] : function(name) { return renderSegmentedBar(name); });\n } else if (setting === "duration" || setting === "position") {\n renderIndicator(setting);\n } else {\n renderButton(setting);\n }\n });\n }; %>\n <% if (settings.default && settings.default.length) { %>\n <div class="media-control-center-panel" data-media-control>\n <% render(settings.default); %>\n </div>\n <% } %>\n <% if (settings.left && settings.left.length) { %>\n <div class="media-control-left-panel" data-media-control>\n <% render(settings.left); %>\n </div>\n <% } %>\n <% if (settings.right && settings.right.length) { %>\n <div class="media-control-right-panel" data-media-control>\n <% render(settings.right); %>\n </div>\n <% } %>\n</div>\n')}},{key:"volume",get:function(){return this.container&&this.container.isReady?this.container.volume:this.intendedVolume}},{key:"muted",get:function(){return 0===this.volume}},{key:"getExternalInterface",value:function(){var t=this;return{setVolume:this.setVolume,getVolume:function(){return t.volume}}}},{key:"bindEvents",value:function(){var t=this;this.stopListening(),this.listenTo(this.core,ot.CORE_ACTIVE_CONTAINER_CHANGED,this.onActiveContainerChanged),this.listenTo(this.core,ot.CORE_MOUSE_MOVE,this.show),this.listenTo(this.core,ot.CORE_MOUSE_LEAVE,function(){return t.hide(t.options.hideMediaControlDelay)}),this.listenTo(this.core,ot.CORE_FULLSCREEN,this.show),this.listenTo(this.core,ot.CORE_OPTIONS_CHANGE,this.configure),this.listenTo(this.core,ot.CORE_RESIZE,this.playerResize),this.bindContainerEvents()}},{key:"bindContainerEvents",value:function(){this.container&&(this.listenTo(this.container,ot.CONTAINER_PLAY,this.changeTogglePlay),this.listenTo(this.container,ot.CONTAINER_PAUSE,this.changeTogglePlay),this.listenTo(this.container,ot.CONTAINER_STOP,this.changeTogglePlay),this.listenTo(this.container,ot.CONTAINER_DBLCLICK,this.toggleFullscreen),this.listenTo(this.container,ot.CONTAINER_TIMEUPDATE,this.onTimeUpdate),this.listenTo(this.container,ot.CONTAINER_PROGRESS,this.updateProgressBar),this.listenTo(this.container,ot.CONTAINER_SETTINGSUPDATE,this.settingsUpdate),this.listenTo(this.container,ot.CONTAINER_PLAYBACKDVRSTATECHANGED,this.settingsUpdate),this.listenTo(this.container,ot.CONTAINER_HIGHDEFINITIONUPDATE,this.highDefinitionUpdate),this.listenTo(this.container,ot.CONTAINER_MEDIACONTROL_DISABLE,this.disable),this.listenTo(this.container,ot.CONTAINER_MEDIACONTROL_ENABLE,this.enable),this.listenTo(this.container,ot.CONTAINER_ENDED,this.ended),this.listenTo(this.container,ot.CONTAINER_VOLUME,this.onVolumeChanged),this.listenTo(this.container,ot.CONTAINER_OPTIONS_CHANGE,this.setInitialVolume),"video"===this.container.playback.el.nodeName.toLowerCase()&&this.listenToOnce(this.container,ot.CONTAINER_LOADEDMETADATA,this.onLoadedMetadataOnVideoTag))}},{key:"disable",value:function(){this.userDisabled=!0,this.hide(),this.unbindKeyEvents(),this.$el.hide()}},{key:"enable",value:function(){this.options.chromeless||(this.userDisabled=!1,this.bindKeyEvents(),this.show())}},{key:"play",value:function(){this.container&&this.container.play()}},{key:"pause",value:function(){this.container&&this.container.pause()}},{key:"stop",value:function(){this.container&&this.container.stop()}},{key:"setInitialVolume",value:function(){this._previousVolumeState=null;var t=this.persistConfig?ke.restore("volume"):100,e=this.container&&this.container.options||this.options;this.setVolume(e.mute?0:t,!0)}},{key:"onVolumeChanged",value:function(){this.updateVolumeUI()}},{key:"onLoadedMetadataOnVideoTag",value:function(){var t=this.playback&&this.playback.el;!_e.fullscreenEnabled()&&t.webkitSupportsFullscreen&&(this.fullScreenOnVideoTagSupported=!0,this.settingsUpdate())}},{key:"updateVolumeUI",value:function(){if(this.rendered){this.$volumeBarContainer.find(".bar-fill-2").css({});var t=this.$volumeBarContainer.width(),e=this.$volumeBarBackground.width(),i=(t-e)/2,n=e*this.volume/100+i;this.$volumeBarFill.css({width:"".concat(this.volume,"%")}),this.$volumeBarScrubber.css({left:n}),this.$volumeBarContainer.find(".segmented-bar-element").removeClass("fill");var r=Math.ceil(this.volume/10);this.$volumeBarContainer.find(".segmented-bar-element").slice(0,r).addClass("fill"),this.$volumeIcon.html(""),this.$volumeIcon.removeClass("muted"),this.muted?(this.$volumeIcon.append('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">\n <path fill-rule="evenodd" clip-rule="evenodd" fill="#010101" d="M9.75 11.51L6.7 9.5H3.75v-3H6.7L9.75 4.49v.664l.497.498V3.498L6.547 6H3.248v4h3.296l3.7 2.502v-2.154l-.497.5v.662zm3-5.165L12.404 6l-1.655 1.653L9.093 6l-.346.345L10.402 8 8.747 9.654l.346.347 1.655-1.653L12.403 10l.348-.346L11.097 8l1.655-1.655z"/>\n</svg>'),this.$volumeIcon.addClass("muted")):this.$volumeIcon.append(be),this.applyButtonStyle(this.$volumeIcon)}}},{key:"changeTogglePlay",value:function(){this.$playPauseToggle.html(""),this.$playStopToggle.html(""),this.container&&this.container.isPlaying()?(this.$playPauseToggle.append(pe),this.$playStopToggle.append(Te),this.trigger(ot.MEDIACONTROL_PLAYING)):(this.$playPauseToggle.append(ge),this.$playStopToggle.append(ge),this.trigger(ot.MEDIACONTROL_NOTPLAYING),C.isMobile&&this.show()),this.applyButtonStyle(this.$playPauseToggle),this.applyButtonStyle(this.$playStopToggle)}},{key:"mousemoveOnSeekBar",value:function(t){if(this.settings.seekEnabled){var e=t.pageX-this.$seekBarContainer.offset().left-this.$seekBarHover.width()/2;this.$seekBarHover.css({left:e})}this.trigger(ot.MEDIACONTROL_MOUSEMOVE_SEEKBAR,t)}},{key:"mouseleaveOnSeekBar",value:function(t){this.trigger(ot.MEDIACONTROL_MOUSELEAVE_SEEKBAR,t)}},{key:"onVolumeClick",value:function(t){this.setVolume(this.getVolumeFromUIEvent(t))}},{key:"mousemoveOnVolumeBar",value:function(t){this.draggingVolumeBar&&this.setVolume(this.getVolumeFromUIEvent(t))}},{key:"playerResize",value:function(t){this.$fullscreenToggle.html("");var e=this.core.isFullscreen()?'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">\n <path fill="#010101" d="M13.5 3.344l-.844-.844L9.5 5.656V3h-1v4.5H13v-1h-2.656L13.5 3.344zM3 9.5h2.656L2.5 12.656l.844.844L6.5 10.344V13h1V8.5H3v1z"/>\n</svg>':Se;this.$fullscreenToggle.append(e),this.applyButtonStyle(this.$fullscreenToggle),0!==this.$el.find(".media-control").length&&this.$el.removeClass("w320"),(t.width<=320||this.options.hideVolumeBar)&&this.$el.addClass("w320")}},{key:"togglePlayPause",value:function(){return this.container.isPlaying()?this.container.pause():this.container.play(),!1}},{key:"togglePlayStop",value:function(){this.container.isPlaying()?this.container.stop():this.container.play()}},{key:"startSeekDrag",value:function(t){this.settings.seekEnabled&&(this.draggingSeekBar=!0,this.$el.addClass("dragging"),this.$seekBarLoaded.addClass("media-control-notransition"),this.$seekBarPosition.addClass("media-control-notransition"),this.$seekBarScrubber.addClass("media-control-notransition"),t&&t.preventDefault())}},{key:"startVolumeDrag",value:function(t){this.draggingVolumeBar=!0,this.$el.addClass("dragging"),t&&t.preventDefault()}},{key:"stopDrag",value:function(t){this.draggingSeekBar&&this.seek(t),this.$el.removeClass("dragging"),this.$seekBarLoaded.removeClass("media-control-notransition"),this.$seekBarPosition.removeClass("media-control-notransition"),this.$seekBarScrubber.removeClass("media-control-notransition dragging"),this.draggingSeekBar=!1,this.draggingVolumeBar=!1}},{key:"updateDrag",value:function(t){if(this.draggingSeekBar){t.preventDefault();var e=(t.pageX-this.$seekBarContainer.offset().left)/this.$seekBarContainer.width()*100;e=Math.min(100,Math.max(e,0)),this.setSeekPercentage(e)}else this.draggingVolumeBar&&(t.preventDefault(),this.setVolume(this.getVolumeFromUIEvent(t)))}},{key:"getVolumeFromUIEvent",value:function(t){return(t.pageX-this.$volumeBarContainer.offset().left)/this.$volumeBarContainer.width()*100}},{key:"toggleMute",value:function(){if(this.muted){var t=this._previousVolumeState;this._previousVolumeState=null;var e=null!=t&&t>0?t:100;this.setVolume(e)}else{var i=this.volume;this._previousVolumeState=i>0?i:null,this.setVolume(0)}}},{key:"setVolume",value:function(t){var e=this,i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];t=Math.min(100,Math.max(t,0)),this.intendedVolume=t,this.persistConfig&&!i&&ke.persist("volume",t);var n=function(){e.container&&e.container.isReady?e.container.setVolume(t):e.listenToOnce(e.container,ot.CONTAINER_READY,function(){e.container.setVolume(t)})};this.container?n():this.listenToOnce(this,ot.MEDIACONTROL_CONTAINERCHANGED,function(){return n()})}},{key:"toggleFullscreen",value:function(){this.trigger(ot.MEDIACONTROL_FULLSCREEN,this.name),this.container.fullscreen(),this.core.toggleFullscreen(),this.resetUserKeepVisible()}},{key:"onActiveContainerChanged",value:function(){this.fullScreenOnVideoTagSupported=null,this.bindEvents(),this.setInitialVolume(),this.changeTogglePlay(),this.bindContainerEvents(),this.settingsUpdate(),this.container&&this.container.trigger(ot.CONTAINER_PLAYBACKDVRSTATECHANGED,this.container.isDvrInUse()),this.container&&this.container.mediaControlDisabled&&this.disable(),this.trigger(ot.MEDIACONTROL_CONTAINERCHANGED)}},{key:"showVolumeBar",value:function(){this.hideVolumeId&&clearTimeout(this.hideVolumeId),this.$volumeBarContainer.removeClass("volume-bar-hide")}},{key:"hideVolumeBar",value:function(){var t=this,e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:400;this.$volumeBarContainer&&(this.draggingVolumeBar?this.hideVolumeId=setTimeout(function(){return t.hideVolumeBar()},e):(this.hideVolumeId&&clearTimeout(this.hideVolumeId),this.hideVolumeId=setTimeout(function(){return t.$volumeBarContainer.addClass("volume-bar-hide")},e)))}},{key:"ended",value:function(){this.changeTogglePlay()}},{key:"updateProgressBar",value:function(t){var e=t.start/t.total*100,i=t.current/t.total*100;this.$seekBarLoaded.css({left:"".concat(e,"%"),width:"".concat(i-e,"%")})}},{key:"onTimeUpdate",value:function(t){if(!this.draggingSeekBar){var e=t.current<0?t.total:t.current;this.currentPositionValue=e,this.currentDurationValue=t.total,this.renderSeekBar()}}},{key:"renderSeekBar",value:function(){if(null!==this.currentPositionValue&&null!==this.currentDurationValue){this.currentSeekBarPercentage=100,this.container&&(this.container.getPlaybackType()!==_t.LIVE||this.container.isDvrInUse())&&(this.currentSeekBarPercentage=this.currentPositionValue/this.currentDurationValue*100),this.setSeekPercentage(this.currentSeekBarPercentage);var t=Le(this.currentPositionValue),e=Le(this.currentDurationValue);t!==this.displayedPosition&&(this.$position.text(t),this.displayedPosition=t),e!==this.displayedDuration&&(this.$duration.text(e),this.displayedDuration=e)}}},{key:"seek",value:function(t){if(this.settings.seekEnabled){var e=(t.pageX-this.$seekBarContainer.offset().left)/this.$seekBarContainer.width()*100;return e=Math.min(100,Math.max(e,0)),this.container&&this.container.seekPercentage(e),this.setSeekPercentage(e),!1}}},{key:"setKeepVisible",value:function(){this.keepVisible=!0}},{key:"resetKeepVisible",value:function(){this.keepVisible=!1}},{key:"setUserKeepVisible",value:function(){this.userKeepVisible=!0}},{key:"resetUserKeepVisible",value:function(){this.userKeepVisible=!1}},{key:"isVisible",value:function(){return!this.$el.hasClass("media-control-hide")}},{key:"show",value:function(t){var e=this;if(!this.disabled){var i=t&&t.clientX!==this.lastMouseX&&t.clientY!==this.lastMouseY;(!t||i||navigator.userAgent.match(/firefox/i))&&(clearTimeout(this.hideId),this.$el.show(),this.trigger(ot.MEDIACONTROL_SHOW,this.name),this.container&&this.container.trigger(ot.CONTAINER_MEDIACONTROL_SHOW,this.name),this.$el.removeClass("media-control-hide"),this.hideId=setTimeout(function(){return e.hide()},2e3),t&&(this.lastMouseX=t.clientX,this.lastMouseY=t.clientY));this.updateCursorStyle(!0)}}},{key:"hide",value:function(){var t=this,e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;if(this.isVisible()){var i=e||2e3;if(clearTimeout(this.hideId),this.disabled||!1!==this.options.hideMediaControl){var n=this.userKeepVisible||this.keepVisible,r=this.draggingSeekBar||this.draggingVolumeBar;if(!this.disabled&&(e||n||r))this.hideId=setTimeout(function(){return t.hide()},i);else{this.trigger(ot.MEDIACONTROL_HIDE,this.name),this.container&&this.container.trigger(ot.CONTAINER_MEDIACONTROL_HIDE,this.name),this.$el.addClass("media-control-hide"),this.hideVolumeBar(0);this.updateCursorStyle(!1)}}}}},{key:"updateCursorStyle",value:function(t){t?this.core.$el.removeClass("nocursor"):this.core.isFullscreen()&&this.core.$el.addClass("nocursor")}},{key:"settingsUpdate",value:function(){var t=this.getSettings();!t||this.fullScreenOnVideoTagSupported||_e.fullscreenEnabled()||(t.default&&Ie(t.default,"fullscreen"),t.left&&Ie(t.left,"fullscreen"),t.right&&Ie(t.right,"fullscreen")),JSON.stringify(this.settings)!==JSON.stringify(t)&&(this.settings=t,this.render())}},{key:"getSettings",value:function(){return k.extend(!0,{},this.container&&this.container.settings)}},{key:"highDefinitionUpdate",value:function(t){this.isHD=t;var e=t?"addClass":"removeClass";this.$hdIndicator[e]("enabled")}},{key:"createCachedElements",value:function(){var t=this.$el.find(".media-control-layer");this.$duration=t.find(".media-control-indicator[data-duration]"),this.$fullscreenToggle=t.find("button.media-control-button[data-fullscreen]"),this.$playPauseToggle=t.find("button.media-control-button[data-playpause]"),this.$playStopToggle=t.find("button.media-control-button[data-playstop]"),this.$position=t.find(".media-control-indicator[data-position]"),this.$seekBarContainer=t.find(".bar-container[data-seekbar]"),this.$seekBarHover=t.find(".bar-hover[data-seekbar]"),this.$seekBarLoaded=t.find(".bar-fill-1[data-seekbar]"),this.$seekBarPosition=t.find(".bar-fill-2[data-seekbar]"),this.$seekBarScrubber=t.find(".bar-scrubber[data-seekbar]"),this.$volumeBarContainer=t.find(".bar-container[data-volume]"),this.$volumeContainer=t.find(".drawer-container[data-volume]"),this.$volumeIcon=t.find(".drawer-icon[data-volume]"),this.$volumeBarBackground=this.$el.find(".bar-background[data-volume]"),this.$volumeBarFill=this.$el.find(".bar-fill-1[data-volume]"),this.$volumeBarScrubber=this.$el.find(".bar-scrubber[data-volume]"),this.$hdIndicator=this.$el.find("button.media-control-button[data-hd-indicator]"),this.resetIndicators(),this.initializeIcons()}},{key:"resetIndicators",value:function(){this.displayedPosition=this.$position.text(),this.displayedDuration=this.$duration.text()}},{key:"initializeIcons",value:function(){var t=this.$el.find(".media-control-layer");t.find("button.media-control-button[data-play]").append(ge),t.find("button.media-control-button[data-pause]").append(pe),t.find("button.media-control-button[data-stop]").append(Te),this.$playPauseToggle.append(ge),this.$playStopToggle.append(ge),this.$volumeIcon.append(be),this.$fullscreenToggle.append(Se),this.$hdIndicator.append('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">\n <path fill="#010101" d="M5.375 7.062H2.637V4.26H.502v7.488h2.135V8.9h2.738v2.848h2.133V4.26H5.375v2.802zm5.97-2.81h-2.84v7.496h2.798c2.65 0 4.195-1.607 4.195-3.77v-.022c0-2.162-1.523-3.704-4.154-3.704zm2.06 3.758c0 1.21-.81 1.896-2.03 1.896h-.83V6.093h.83c1.22 0 2.03.696 2.03 1.896v.02z"/>\n</svg>')}},{key:"setSeekPercentage",value:function(t){t=Math.max(Math.min(t,100),0),this.displayedSeekBarPercentage!==t&&(this.displayedSeekBarPercentage=t,this.$seekBarPosition.removeClass("media-control-notransition"),this.$seekBarScrubber.removeClass("media-control-notransition"),this.$seekBarPosition.css({width:"".concat(t,"%")}),this.$seekBarScrubber.css({left:"".concat(t,"%")}))}},{key:"seekRelative",value:function(t){if(this.settings.seekEnabled){var e=this.container.getCurrentTime(),i=this.container.getDuration(),n=Math.min(Math.max(e+t,0),i);n=Math.min(100*n/i,100),this.container.seekPercentage(n)}}},{key:"bindKeyAndShow",value:function(t,e){var i=this;this.kibo.down(t,function(){return i.show(),e()})}},{key:"bindKeyEvents",value:function(){var t=this;if(!C.isMobile&&!this.options.disableKeyboardShortcuts){this.unbindKeyEvents(),this.kibo=new Ae(this.options.focusElement||this.options.parentElement),this.bindKeyAndShow("space",function(){return t.togglePlayPause()}),this.bindKeyAndShow("left",function(){return t.seekRelative(-5)}),this.bindKeyAndShow("right",function(){return t.seekRelative(5)}),this.bindKeyAndShow("shift left",function(){return t.seekRelative(-10)}),this.bindKeyAndShow("shift right",function(){return t.seekRelative(10)}),this.bindKeyAndShow("shift ctrl left",function(){return t.seekRelative(-15)}),this.bindKeyAndShow("shift ctrl right",function(){return t.seekRelative(15)});["1","2","3","4","5","6","7","8","9","0"].forEach(function(e){t.bindKeyAndShow(e,function(){t.settings.seekEnabled&&t.container&&t.container.seekPercentage(10*e)})})}}},{key:"unbindKeyEvents",value:function(){this.kibo&&(this.kibo.off("space"),this.kibo.off("left"),this.kibo.off("right"),this.kibo.off("shift left"),this.kibo.off("shift right"),this.kibo.off("shift ctrl left"),this.kibo.off("shift ctrl right"),this.kibo.off(["1","2","3","4","5","6","7","8","9","0"]))}},{key:"parseColors",value:function(){if(this.options.mediacontrol){this.buttonsColor=this.options.mediacontrol.buttons;var t=this.options.mediacontrol.seekbar;this.$el.find(".bar-fill-2[data-seekbar]").css("background-color",t),this.$el.find(".media-control-icon svg path").css("fill",this.buttonsColor),this.$el.find(".segmented-bar-element[data-volume]").css("boxShadow","inset 2px 0 0 "+this.buttonsColor)}}},{key:"applyButtonStyle",value:function(t){this.buttonsColor&&t&&k(t).find("svg path").css("fill",this.buttonsColor)}},{key:"destroy",value:function(){k(document).unbind("mouseup",this.stopDragHandler),k(document).unbind("mousemove",this.updateDragHandler),this.unbindKeyEvents(),this.stopListening(),ae(e,"destroy",this)([])}},{key:"configure",value:function(t){this.options.chromeless||t.source||t.sources?this.disable():this.enable(),this.trigger(ot.MEDIACONTROL_OPTIONS_CHANGE)}},{key:"render",value:function(){var t=this,e=this.options.hideMediaControlDelay||2e3;this.settings&&this.$el.html(this.template({settings:this.settings}));var i=yt.getStyleFor('.media-control-notransition {\n -webkit-transition: none !important;\n transition: none !important;\n}\n\n.media-control[data-media-control] {\n position: absolute;\n width: 100%;\n height: 100%;\n z-index: 9999;\n pointer-events: none;\n}\n.media-control[data-media-control].dragging {\n pointer-events: auto;\n cursor: -webkit-grabbing !important;\n cursor: grabbing !important;\n cursor: url("closed-hand.cur"), move;\n}\n.media-control[data-media-control].dragging * {\n cursor: -webkit-grabbing !important;\n cursor: grabbing !important;\n cursor: url("closed-hand.cur"), move;\n}\n.media-control[data-media-control] .media-control-background[data-background] {\n position: absolute;\n height: 40%;\n width: 100%;\n bottom: 0;\n background: -webkit-gradient(linear, left top, left bottom, from(transparent), to(rgba(0, 0, 0, 0.9)));\n background: linear-gradient(transparent, rgba(0, 0, 0, 0.9));\n will-change: transform, opacity;\n -webkit-transition: opacity 0.6s ease-out;\n transition: opacity 0.6s ease-out;\n}\n.media-control[data-media-control] .media-control-icon {\n line-height: 0;\n letter-spacing: 0;\n speak: none;\n color: #fff;\n opacity: 0.5;\n vertical-align: middle;\n text-align: left;\n -webkit-transition: all 0.1s ease;\n transition: all 0.1s ease;\n}\n.media-control[data-media-control] .media-control-icon:hover {\n color: white;\n opacity: 0.75;\n text-shadow: rgba(255, 255, 255, 0.8) 0 0 5px;\n}\n.media-control[data-media-control].media-control-hide .media-control-background[data-background] {\n opacity: 0;\n}\n.media-control[data-media-control].media-control-hide .media-control-layer[data-controls] {\n -webkit-transform: translateY(50px);\n transform: translateY(50px);\n}\n.media-control[data-media-control].media-control-hide .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar] {\n opacity: 0;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] {\n position: absolute;\n -webkit-transform: translateY(-7px);\n transform: translateY(-7px);\n bottom: 0;\n width: 100%;\n height: 32px;\n font-size: 0;\n vertical-align: middle;\n pointer-events: auto;\n -webkit-transition: bottom 0.4s ease-out;\n transition: bottom 0.4s ease-out;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .media-control-left-panel[data-media-control] {\n position: absolute;\n top: 0;\n left: 4px;\n height: 100%;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .media-control-center-panel[data-media-control] {\n height: 100%;\n text-align: center;\n line-height: 32px;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .media-control-right-panel[data-media-control] {\n position: absolute;\n top: 0;\n right: 4px;\n height: 100%;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button {\n background-color: transparent;\n border: 0;\n margin: 0 6px;\n padding: 0;\n cursor: pointer;\n display: inline-block;\n width: 32px;\n height: 100%;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button svg {\n width: 100%;\n height: 22px;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button svg path {\n fill: white;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button:focus {\n outline: none;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-play] {\n float: left;\n height: 100%;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-pause] {\n float: left;\n height: 100%;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-stop] {\n float: left;\n height: 100%;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-fullscreen] {\n float: right;\n background-color: transparent;\n border: 0;\n height: 100%;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator] {\n background-color: transparent;\n border: 0;\n cursor: default;\n display: none;\n float: right;\n height: 100%;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator].enabled {\n display: block;\n opacity: 1;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator].enabled:hover {\n opacity: 1;\n text-shadow: none;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause] {\n float: left;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop] {\n float: left;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-position], .media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration] {\n display: inline-block;\n font-size: 10px;\n color: white;\n cursor: default;\n line-height: 32px;\n position: relative;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-position] {\n margin: 0 6px 0 7px;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration]:before {\n content: "|";\n margin-right: 7px;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration] {\n color: rgba(255, 255, 255, 0.5);\n margin-right: 6px;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] {\n position: absolute;\n top: -20px;\n left: 0;\n display: inline-block;\n vertical-align: middle;\n width: 100%;\n height: 25px;\n cursor: pointer;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] {\n width: 100%;\n height: 1px;\n position: relative;\n top: 12px;\n background-color: #666666;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-1[data-seekbar] {\n position: absolute;\n top: 0;\n left: 0;\n width: 0;\n height: 100%;\n background-color: #c2c2c2;\n -webkit-transition: all 0.1s ease-out;\n transition: all 0.1s ease-out;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar] {\n position: absolute;\n top: 0;\n left: 0;\n width: 0;\n height: 100%;\n background-color: #005aff;\n -webkit-transition: all 0.1s ease-out;\n transition: all 0.1s ease-out;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-hover[data-seekbar] {\n opacity: 0;\n position: absolute;\n top: -3px;\n width: 5px;\n height: 7px;\n background-color: rgba(255, 255, 255, 0.5);\n -webkit-transition: opacity 0.1s ease;\n transition: opacity 0.1s ease;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar]:hover .bar-background[data-seekbar] .bar-hover[data-seekbar] {\n opacity: 1;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar].seek-disabled {\n cursor: default;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar].seek-disabled:hover .bar-background[data-seekbar] .bar-hover[data-seekbar] {\n opacity: 0;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar] {\n position: absolute;\n -webkit-transform: translateX(-50%);\n transform: translateX(-50%);\n top: 2px;\n left: 0;\n width: 20px;\n height: 20px;\n opacity: 1;\n -webkit-transition: all 0.1s ease-out;\n transition: all 0.1s ease-out;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar] .bar-scrubber-icon[data-seekbar] {\n position: absolute;\n left: 6px;\n top: 6px;\n width: 8px;\n height: 8px;\n border-radius: 10px;\n -webkit-box-shadow: 0 0 0 6px rgba(255, 255, 255, 0.2);\n box-shadow: 0 0 0 6px rgba(255, 255, 255, 0.2);\n background-color: white;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] {\n float: right;\n display: inline-block;\n height: 32px;\n cursor: pointer;\n margin: 0 6px;\n -webkit-box-sizing: border-box;\n box-sizing: border-box;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] {\n float: left;\n bottom: 0;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume] {\n background-color: transparent;\n border: 0;\n -webkit-box-sizing: content-box;\n box-sizing: content-box;\n width: 32px;\n height: 32px;\n opacity: 0.5;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume]:hover {\n opacity: 0.75;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume] svg {\n height: 24px;\n position: relative;\n top: 3px;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume] svg path {\n fill: white;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume].muted svg {\n margin-left: 2px;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] {\n float: left;\n position: relative;\n overflow: hidden;\n top: 6px;\n width: 42px;\n height: 18px;\n padding: 3px 0;\n -webkit-transition: width 0.2s ease-out;\n transition: width 0.2s ease-out;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-background[data-volume] {\n height: 1px;\n position: relative;\n top: 7px;\n margin: 0 3px;\n background-color: #666666;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-background[data-volume] .bar-fill-1[data-volume] {\n position: absolute;\n top: 0;\n left: 0;\n width: 0;\n height: 100%;\n background-color: #c2c2c2;\n -webkit-transition: all 0.1s ease-out;\n transition: all 0.1s ease-out;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-background[data-volume] .bar-fill-2[data-volume] {\n position: absolute;\n top: 0;\n left: 0;\n width: 0;\n height: 100%;\n background-color: #005aff;\n -webkit-transition: all 0.1s ease-out;\n transition: all 0.1s ease-out;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-background[data-volume] .bar-hover[data-volume] {\n opacity: 0;\n position: absolute;\n top: -3px;\n width: 5px;\n height: 7px;\n background-color: rgba(255, 255, 255, 0.5);\n -webkit-transition: opacity 0.1s ease;\n transition: opacity 0.1s ease;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-scrubber[data-volume] {\n position: absolute;\n -webkit-transform: translateX(-50%);\n transform: translateX(-50%);\n top: 0px;\n left: 0;\n width: 20px;\n height: 20px;\n opacity: 1;\n -webkit-transition: all 0.1s ease-out;\n transition: all 0.1s ease-out;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-scrubber[data-volume] .bar-scrubber-icon[data-volume] {\n position: absolute;\n left: 6px;\n top: 6px;\n width: 8px;\n height: 8px;\n border-radius: 10px;\n -webkit-box-shadow: 0 0 0 6px rgba(255, 255, 255, 0.2);\n box-shadow: 0 0 0 6px rgba(255, 255, 255, 0.2);\n background-color: white;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .segmented-bar-element[data-volume] {\n float: left;\n width: 4px;\n padding-left: 2px;\n height: 12px;\n opacity: 0.5;\n -webkit-box-shadow: inset 2px 0 0 white;\n box-shadow: inset 2px 0 0 white;\n -webkit-transition: -webkit-transform 0.2s ease-out;\n transition: -webkit-transform 0.2s ease-out;\n transition: transform 0.2s ease-out;\n transition: transform 0.2s ease-out, -webkit-transform 0.2s ease-out;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .segmented-bar-element[data-volume].fill {\n -webkit-box-shadow: inset 2px 0 0 #fff;\n box-shadow: inset 2px 0 0 #fff;\n opacity: 1;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .segmented-bar-element[data-volume]:nth-of-type(1) {\n padding-left: 0;\n}\n.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .segmented-bar-element[data-volume]:hover {\n -webkit-transform: scaleY(1.5);\n transform: scaleY(1.5);\n}\n.media-control[data-media-control].w320 .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume].volume-bar-hide {\n width: 0;\n height: 12px;\n top: 9px;\n padding: 0;\n}',{baseUrl:this.options.baseUrl});this.$el.append(i[0]),this.createCachedElements(),this.$playPauseToggle.addClass("paused"),this.$playStopToggle.addClass("stopped"),this.changeTogglePlay(),this.container&&(this.hideId=setTimeout(function(){return t.hide()},e),this.disabled&&this.hide()),C.isSafari&&C.isMobile&&(C.version<10?this.$volumeContainer.css("display","none"):this.$volumeBarContainer.css("display","none")),this.$seekBarPosition.addClass("media-control-notransition"),this.$seekBarScrubber.addClass("media-control-notransition");var n=0;return this.displayedSeekBarPercentage&&(n=this.displayedSeekBarPercentage),this.displayedSeekBarPercentage=null,this.setSeekPercentage(n),setTimeout(function(){!t.settings.seekEnabled&&t.$seekBarContainer.addClass("seek-disabled"),!C.isMobile&&!t.options.disableKeyboardShortcuts&&t.bindKeyEvents(),t.playerResize({width:t.options.width,height:t.options.height}),t.hideVolumeBar(0)},0),this.parseColors(),this.highDefinitionUpdate(this.isHD),this.core.$el.append(this.el),this.rendered=!0,this.updateVolumeUI(),this.trigger(ot.MEDIACONTROL_RENDERED),this}}])}(St);Ce.extend=function(t){return Re(Ce,t)};for(var Pe=function(t){function e(t){var i;return Zt(this,e),(i=Qt(this,e,[t])).hasStartedPlaying=!1,i.playRequested=!1,i.render(),setTimeout(function(){return i.update()},0),i}return ie(e,t),Jt(e,[{key:"name",get:function(){return"poster"}},{key:"supportedVersion",get:function(){return{min:"0.16.3"}}},{key:"template",get:function(){return vt('<div class="play-wrapper" data-poster></div>\n')}},{key:"shouldRender",get:function(){var t=!(!this.options.poster||!this.options.poster.showForNoOp);return"html_img"!==this.container.playback.name&&(this.container.playback.getPlaybackType()!==_t.NO_OP||t)}},{key:"attributes",get:function(){return{class:"player-poster","data-poster":""}}},{key:"events",get:function(){return{click:"clicked"}}},{key:"showOnVideoEnd",get:function(){return!this.options.poster||this.options.poster.showOnVideoEnd||void 0===this.options.poster.showOnVideoEnd}},{key:"bindEvents",value:function(){this.listenTo(this.container,ot.CONTAINER_STOP,this.onStop),this.listenTo(this.container,ot.CONTAINER_PLAY,this.onPlay),this.listenTo(this.container,ot.CONTAINER_STATE_BUFFERING,this.update),this.listenTo(this.container,ot.CONTAINER_STATE_BUFFERFULL,this.update),this.listenTo(this.container,ot.CONTAINER_OPTIONS_CHANGE,this.render),this.listenTo(this.container,ot.CONTAINER_ERROR,this.onError),this.showOnVideoEnd&&this.listenTo(this.container,ot.CONTAINER_ENDED,this.onStop)}},{key:"onError",value:function(t){this.hasFatalError=t.level===Tt.Levels.FATAL,this.hasFatalError&&(this.hasStartedPlaying=!1,this.playRequested=!1,this.showPlayButton())}},{key:"onPlay",value:function(){this.hasStartedPlaying=!0,this.update()}},{key:"onStop",value:function(){this.hasStartedPlaying=!1,this.playRequested=!1,this.update()}},{key:"updatePlayButton",value:function(t){!t||this.options.chromeless&&!this.options.allowUserInteraction?this.hidePlayButton():this.showPlayButton()}},{key:"showPlayButton",value:function(){this.hasFatalError&&!this.options.disableErrorScreen||(this.$playButton.show(),this.$el.addClass("clickable"))}},{key:"hidePlayButton",value:function(){this.$playButton.hide(),this.$el.removeClass("clickable")}},{key:"clicked",value:function(){if(!this.hasStartedPlaying)return this.options.chromeless&&!this.options.allowUserInteraction||(this.playRequested=!0,this.update(),this.container.playback&&(this.container.playback._consented=!0),this.container.play()),!1}},{key:"shouldHideOnPlay",value:function(){return!this.container.playback.isAudioOnly}},{key:"update",value:function(){if(this.shouldRender){var t=!this.playRequested&&!this.hasStartedPlaying&&!this.container.buffering;this.updatePlayButton(t),this.updatePoster()}}},{key:"updatePoster",value:function(){this.hasStartedPlaying?this.hidePoster():this.showPoster()}},{key:"showPoster",value:function(){this.container.disableMediaControl(),this.$el.show()}},{key:"hidePoster",value:function(){this.container.enableMediaControl(),this.shouldHideOnPlay()&&this.$el.hide()}},{key:"render",value:function(){if(this.shouldRender){var t=yt.getStyleFor(".player-poster[data-poster] {\n display: -webkit-box;\n display: -ms-flexbox;\n display: flex;\n -webkit-box-pack: center;\n -ms-flex-pack: center;\n justify-content: center;\n -webkit-box-align: center;\n -ms-flex-align: center;\n align-items: center;\n position: absolute;\n height: 100%;\n width: 100%;\n z-index: 998;\n top: 0;\n left: 0;\n background-color: transparent;\n background-size: cover;\n background-repeat: no-repeat;\n background-position: 50% 50%;\n}\n.player-poster[data-poster].clickable {\n cursor: pointer;\n}\n.player-poster[data-poster]:hover .play-wrapper[data-poster] {\n opacity: 1;\n}\n.player-poster[data-poster] .play-wrapper[data-poster] {\n width: 100%;\n height: 25%;\n margin: 0 auto;\n opacity: 0.75;\n -webkit-transition: opacity 0.1s ease;\n transition: opacity 0.1s ease;\n}\n.player-poster[data-poster] .play-wrapper[data-poster] svg {\n height: 100%;\n}\n.player-poster[data-poster] .play-wrapper[data-poster] svg path {\n fill: #fff;\n}",{baseUrl:this.options.baseUrl});if(this.$el.html(this.template()),this.$el.append(t[0]),this.options.poster&&void 0===this.options.poster.custom){var e=this.options.poster.url||this.options.poster;this.$el.css({"background-image":"url("+e+")"}),this.removeVideoElementPoster()}else this.options.poster&&(this.$el.css({background:this.options.poster.custom}),this.removeVideoElementPoster());this.container.$el.append(this.el),this.$playWrapper=this.$el.find(".play-wrapper"),this.$playWrapper.append(ge),this.$playButton=this.$playWrapper.find("svg"),this.$playButton.addClass("poster-icon"),this.$playButton.attr("data-poster","");var i=this.options.mediacontrol&&this.options.mediacontrol.buttons;return i&&this.$el.find("svg path").css("fill",i),this.options.mediacontrol&&this.options.mediacontrol.buttons&&(i=this.options.mediacontrol.buttons,this.$playButton.css("color",i)),this.update(),this}}},{key:"removeVideoElementPoster",value:function(){this.container.playback&&this.container.playback.$el&&this.container.playback.$el[0]&&this.container.playback.$el[0].removeAttribute&&this.container.playback.$el[0].removeAttribute("poster")}}])}($t),De=X.formatTime,we=function(t){function e(t){var i;return Zt(this,e),(i=Qt(this,e,[t])).hoveringOverSeekBar=!1,i.hoverPosition=null,i.duration=null,i.firstFragDateTime=null,i.actualLiveTime=!!i.mediaControl.options.actualLiveTime,i.actualLiveTime&&(i.mediaControl.options.actualLiveServerTime?i.actualLiveServerTimeDiff=(new Date).getTime()-new Date(i.mediaControl.options.actualLiveServerTime).getTime():i.actualLiveServerTimeDiff=0),i}return ie(e,t),Jt(e,[{key:"name",get:function(){return"seek_time"}},{key:"supportedVersion",get:function(){return{min:"0.16.3"}}},{key:"template",get:function(){return vt("<span data-seek-time></span>\n<span data-duration></span>\n")}},{key:"attributes",get:function(){return{class:"seek-time","data-seek-time":""}}},{key:"mediaControl",get:function(){return this.core.mediaControl}},{key:"mediaControlContainer",get:function(){return this.mediaControl.container}},{key:"isLiveStreamWithDvr",get:function(){return this.mediaControlContainer&&this.mediaControlContainer.getPlaybackType()===_t.LIVE&&this.mediaControlContainer.isDvrEnabled()}},{key:"durationShown",get:function(){return this.isLiveStreamWithDvr&&!this.actualLiveTime}},{key:"useActualLiveTime",get:function(){return this.actualLiveTime&&this.isLiveStreamWithDvr}},{key:"bindEvents",value:function(){this.listenTo(this.mediaControl,ot.MEDIACONTROL_RENDERED,this.render),this.listenTo(this.mediaControl,ot.MEDIACONTROL_MOUSEMOVE_SEEKBAR,this.showTime),this.listenTo(this.mediaControl,ot.MEDIACONTROL_MOUSELEAVE_SEEKBAR,this.hideTime),this.listenTo(this.mediaControl,ot.MEDIACONTROL_CONTAINERCHANGED,this.onContainerChanged),this.mediaControlContainer&&(this.listenTo(this.mediaControlContainer,ot.CONTAINER_PLAYBACKDVRSTATECHANGED,this.update),this.listenTo(this.mediaControlContainer,ot.CONTAINER_TIMEUPDATE,this.updateDuration))}},{key:"onContainerChanged",value:function(){this.stopListening(),this.bindEvents()}},{key:"updateDuration",value:function(t){this.duration=t.total,this.firstFragDateTime=t.firstFragDateTime,this.update()}},{key:"showTime",value:function(t){this.hoveringOverSeekBar=!0,this.calculateHoverPosition(t),this.update()}},{key:"hideTime",value:function(){this.hoveringOverSeekBar=!1,this.update()}},{key:"calculateHoverPosition",value:function(t){var e=t.pageX-this.mediaControl.$seekBarContainer.offset().left;this.hoverPosition=Math.min(1,Math.max(e/this.mediaControl.$seekBarContainer.width(),0))}},{key:"getSeekTime",value:function(){var t,e,i,n;return this.useActualLiveTime?(this.firstFragDateTime?(n=new Date(this.firstFragDateTime),(i=new Date(this.firstFragDateTime)).setHours(0,0,0,0),e=(n.getTime()-i.getTime())/1e3+this.duration):(i=new Date((new Date).getTime()-this.actualLiveServerTimeDiff),e=((n=new Date(i))-i.setHours(0,0,0,0))/1e3),(t=e-this.duration+this.hoverPosition*this.duration)<0&&(t+=86400)):t=this.hoverPosition*this.duration,{seekTime:t,secondsSinceMidnight:e}}},{key:"update",value:function(){if(this.rendered)if(this.shouldBeVisible()){var t=this.getSeekTime(),e=De(t.seekTime,this.useActualLiveTime);if(e!==this.displayedSeekTime&&(this.$seekTimeEl.text(e),this.displayedSeekTime=e),this.durationShown){this.$durationEl.show();var i=De(this.actualLiveTime?t.secondsSinceMidnight:this.duration,this.actualLiveTime);i!==this.displayedDuration&&(this.$durationEl.text(i),this.displayedDuration=i)}else this.$durationEl.hide();this.$el.show();var n=this.mediaControl.$seekBarContainer.width(),r=this.$el.width(),s=this.hoverPosition*n;s-=r/2,s=Math.max(0,Math.min(s,n-r)),this.$el.css("left",s)}else this.$el.hide(),this.$el.css("left","-100%")}},{key:"shouldBeVisible",value:function(){return this.mediaControlContainer&&this.mediaControlContainer.settings.seekEnabled&&this.hoveringOverSeekBar&&null!==this.hoverPosition&&null!==this.duration}},{key:"render",value:function(){var t=yt.getStyleFor('.seek-time[data-seek-time] {\n position: absolute;\n white-space: nowrap;\n height: 20px;\n line-height: 20px;\n font-size: 0;\n left: -100%;\n bottom: 55px;\n background-color: rgba(2, 2, 2, 0.5);\n z-index: 9999;\n -webkit-transition: opacity 0.1s ease;\n transition: opacity 0.1s ease;\n}\n.seek-time[data-seek-time].hidden[data-seek-time] {\n opacity: 0;\n}\n.seek-time[data-seek-time] [data-seek-time] {\n display: inline-block;\n color: white;\n font-size: 10px;\n padding-left: 7px;\n padding-right: 7px;\n vertical-align: top;\n}\n.seek-time[data-seek-time] [data-duration] {\n display: inline-block;\n color: rgba(255, 255, 255, 0.5);\n font-size: 10px;\n padding-right: 7px;\n vertical-align: top;\n}\n.seek-time[data-seek-time] [data-duration]:before {\n content: "|";\n margin-right: 7px;\n}',{baseUrl:this.options.baseUrl});this.rendered=!0,this.displayedDuration=null,this.displayedSeekTime=null,this.$el.html(this.template()),this.$el.append(t[0]),this.$el.hide(),this.mediaControl.$el.append(this.el),this.$seekTimeEl=this.$el.find("[data-seek-time]"),this.$durationEl=this.$el.find("[data-duration]"),this.$durationEl.hide(),this.update()}}])}(St),Oe={ClickToPause:he,ClosedCaptions:ce,DVRControls:ue,EndVideo:de,ErrorScreen:fe,Favicon:ve,GoogleAnalytics:ye,MediaControl:Ce,Poster:Pe,SeekTime:we,SpinnerThreeBounce:function(t){function e(t){var i;return Zt(this,e),(i=Qt(this,e,[t])).template=vt("<div data-bounce1></div><div data-bounce2></div><div data-bounce3></div>\n"),i.showTimeout=null,i.listenTo(i.container,ot.CONTAINER_STATE_BUFFERING,i.onBuffering),i.listenTo(i.container,ot.CONTAINER_STATE_BUFFERFULL,i.onBufferFull),i.listenTo(i.container,ot.CONTAINER_STOP,i.onStop),i.listenTo(i.container,ot.CONTAINER_ENDED,i.onStop),i.listenTo(i.container,ot.CONTAINER_ERROR,i.onStop),i.render(),i}return ie(e,t),Jt(e,[{key:"name",get:function(){return"spinner"}},{key:"supportedVersion",get:function(){return{min:"0.16.3"}}},{key:"attributes",get:function(){return{"data-spinner":"",class:"spinner-three-bounce"}}},{key:"onBuffering",value:function(){this.show()}},{key:"onBufferFull",value:function(){this.hide()}},{key:"onStop",value:function(){this.hide()}},{key:"show",value:function(){var t=this;null===this.showTimeout&&(this.showTimeout=setTimeout(function(){return t.$el.show()},300))}},{key:"hide",value:function(){null!==this.showTimeout&&(clearTimeout(this.showTimeout),this.showTimeout=null),this.$el.hide()}},{key:"render",value:function(){var t=yt.getStyleFor(".spinner-three-bounce[data-spinner] {\n position: absolute;\n margin: 0 auto;\n width: 70px;\n text-align: center;\n z-index: 999;\n left: 0;\n right: 0;\n margin-left: auto;\n margin-right: auto;\n /* center vertically */\n top: 50%;\n -webkit-transform: translateY(-50%);\n transform: translateY(-50%);\n}\n.spinner-three-bounce[data-spinner] > div {\n width: 18px;\n height: 18px;\n background-color: #FFFFFF;\n border-radius: 100%;\n display: inline-block;\n -webkit-animation: bouncedelay 1.4s infinite ease-in-out;\n animation: bouncedelay 1.4s infinite ease-in-out;\n /* Prevent first frame from flickering when animation starts */\n -webkit-animation-fill-mode: both;\n animation-fill-mode: both;\n}\n.spinner-three-bounce[data-spinner] [data-bounce1] {\n -webkit-animation-delay: -0.32s;\n animation-delay: -0.32s;\n}\n.spinner-three-bounce[data-spinner] [data-bounce2] {\n -webkit-animation-delay: -0.16s;\n animation-delay: -0.16s;\n}\n\n@-webkit-keyframes bouncedelay {\n 0%, 80%, 100% {\n -webkit-transform: scale(0);\n transform: scale(0);\n }\n 40% {\n -webkit-transform: scale(1);\n transform: scale(1);\n }\n}\n\n@keyframes bouncedelay {\n 0%, 80%, 100% {\n -webkit-transform: scale(0);\n transform: scale(0);\n }\n 40% {\n -webkit-transform: scale(1);\n transform: scale(1);\n }\n}",{baseUrl:this.options.baseUrl});return this.$el.html(this.template()),this.$el.append(t[0]),this.container.$el.append(this.$el),this.$el.hide(),this.container.buffering&&this.onBuffering(),this}}])}($t),Stats:function(t){function e(t){var i;return Zt(this,e),(i=Qt(this,e,[t])).setInitialAttrs(),i.reportInterval=i.options.reportInterval||5e3,i.state="IDLE",i}return ie(e,t),Jt(e,[{key:"name",get:function(){return"stats"}},{key:"supportedVersion",get:function(){return{min:"0.16.3"}}},{key:"bindEvents",value:function(){this.listenTo(this.container.playback,ot.PLAYBACK_PLAY,this.onPlay),this.listenTo(this.container,ot.CONTAINER_STOP,this.onStop),this.listenTo(this.container,ot.CONTAINER_ENDED,this.onStop),this.listenTo(this.container,ot.CONTAINER_DESTROYED,this.onStop),this.listenTo(this.container,ot.CONTAINER_STATE_BUFFERING,this.onBuffering),this.listenTo(this.container,ot.CONTAINER_STATE_BUFFERFULL,this.onBufferFull),this.listenTo(this.container,ot.CONTAINER_STATS_ADD,this.onStatsAdd),this.listenTo(this.container,ot.CONTAINER_BITRATE,this.onStatsAdd),this.listenTo(this.container.playback,ot.PLAYBACK_STATS_ADD,this.onStatsAdd)}},{key:"setInitialAttrs",value:function(){this.firstPlay=!0,this.startupTime=0,this.rebufferingTime=0,this.watchingTime=0,this.rebuffers=0,this.externalMetrics={}}},{key:"onPlay",value:function(){this.state="PLAYING",this.watchingTimeInit=Date.now(),this.intervalId||(this.intervalId=setInterval(this.report.bind(this),this.reportInterval))}},{key:"onStop",value:function(){clearInterval(this.intervalId),this.report(),this.intervalId=void 0,this.state="STOPPED"}},{key:"onBuffering",value:function(){this.firstPlay?this.startupTimeInit=Date.now():this.rebufferingTimeInit=Date.now(),this.state="BUFFERING",this.rebuffers++}},{key:"onBufferFull",value:function(){this.firstPlay&&this.startupTimeInit?(this.firstPlay=!1,this.startupTime=Date.now()-this.startupTimeInit,this.watchingTimeInit=Date.now()):this.rebufferingTimeInit&&(this.rebufferingTime+=this.getRebufferingTime()),this.rebufferingTimeInit=void 0,this.state="PLAYING"}},{key:"getRebufferingTime",value:function(){return Date.now()-this.rebufferingTimeInit}},{key:"getWatchingTime",value:function(){return Date.now()-this.watchingTimeInit-this.rebufferingTime}},{key:"isRebuffering",value:function(){return!!this.rebufferingTimeInit}},{key:"onStatsAdd",value:function(t){k.extend(this.externalMetrics,t)}},{key:"getStats",value:function(){var t={startupTime:this.startupTime,rebuffers:this.rebuffers,rebufferingTime:this.isRebuffering()?this.rebufferingTime+this.getRebufferingTime():this.rebufferingTime,watchingTime:this.isRebuffering()?this.getWatchingTime()-this.getRebufferingTime():this.getWatchingTime()};return k.extend(t,this.externalMetrics),t}},{key:"report",value:function(){this.container.statsReport(this.getStats())}}])}(Ft),WaterMark:function(t){function e(t){var i;return Zt(this,e),(i=Qt(this,e,[t])).configure(),i}return ie(e,t),Jt(e,[{key:"name",get:function(){return"watermark"}},{key:"supportedVersion",get:function(){return{min:"0.16.3"}}},{key:"template",get:function(){return vt('<div class="clappr-watermark" data-watermark data-watermark-<%=position %>>\n<% if(typeof imageLink !== \'undefined\') { %>\n<a target="_blank" href="<%= imageLink %>">\n<% } %>\n<img src="<%= imageUrl %>">\n<% if(typeof imageLink !== \'undefined\') { %>\n</a>\n<% } %>\n</div>\n')}},{key:"bindEvents",value:function(){this.listenTo(this.container,ot.CONTAINER_PLAY,this.onPlay),this.listenTo(this.container,ot.CONTAINER_STOP,this.onStop),this.listenTo(this.container,ot.CONTAINER_OPTIONS_CHANGE,this.configure)}},{key:"configure",value:function(){this.position=this.options.position||"bottom-right",this.options.watermark?(this.imageUrl=this.options.watermark,this.imageLink=this.options.watermarkLink,this.render()):this.$el.remove()}},{key:"onPlay",value:function(){this.hidden||this.$el.show()}},{key:"onStop",value:function(){this.$el.hide()}},{key:"render",value:function(){this.$el.hide();var t=yt.getStyleFor(".clappr-watermark[data-watermark] {\n position: absolute;\n min-width: 70px;\n max-width: 200px;\n width: 12%;\n text-align: center;\n z-index: 10;\n}\n\n.clappr-watermark[data-watermark] a {\n outline: none;\n cursor: pointer;\n}\n\n.clappr-watermark[data-watermark] img {\n max-width: 100%;\n}\n\n.clappr-watermark[data-watermark-bottom-left] {\n bottom: 10px;\n left: 10px;\n}\n\n.clappr-watermark[data-watermark-bottom-right] {\n bottom: 10px;\n right: 42px;\n}\n\n.clappr-watermark[data-watermark-top-left] {\n top: 10px;\n left: 10px;\n}\n\n.clappr-watermark[data-watermark-top-right] {\n top: 10px;\n right: 37px;\n}",{baseUrl:this.options.baseUrl}),e={position:this.position,imageUrl:this.imageUrl,imageLink:this.imageLink};return this.$el.html(this.template(e)),this.$el.append(t[0]),this.container.$el.append(this.$el),this}}])}($t)},xe=0,Me=Object.values(Oe);xe<Me.length;xe++){var Ne=Me[xe];xt.registerPlugin(Ne)}var Fe=Oe.ClickToPause,Be=Oe.ClosedCaptions,$e=Oe.DVRControls,Ue=Oe.EndVideo,Ge=Oe.ErrorScreen,Ve=Oe.Favicon,Ke=Oe.GoogleAnalytics,He=Oe.MediaControl,Ye=Oe.Poster,je=Oe.SeekTime,We=Oe.SpinnerThreeBounce,ze=Oe.Stats,qe=Oe.WaterMark,Xe=i(i({},Xt),{},{ClickToPause:Fe,ClosedCaptions:Be,DVRControls:$e,EndVideo:Ue,ErrorScreen:Ge,Favicon:Ve,GoogleAnalytics:Ke,MediaControl:He,Poster:Ye,SeekTime:je,SpinnerThreeBounce:We,Stats:ze,WaterMark:qe,Vendor:Ee,Plugins:Oe,version:"0.14.3"});const Qe=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},Ze=Number.isSafeInteger||function(t){return"number"==typeof t&&Math.abs(t)<=Je},Je=Number.MAX_SAFE_INTEGER||9007199254740991;let ti=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}({}),ei=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.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",t.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",t.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",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.PLAYLIST_UNCHANGED_ERROR="playlistUnchangedError",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_APPEND_NO_PROGRESS="bufferAppendNoProgress",t.BUFFER_STALLED_ERROR="bufferStalledError",t.BUFFER_FULL_ERROR="bufferFullError",t.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",t.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",t.ASSET_LIST_LOAD_ERROR="assetListLoadError",t.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",t.ASSET_LIST_PARSING_ERROR="assetListParsingError",t.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.ATTACH_MEDIA_ERROR="attachMediaError",t.MEDIA_SOURCE_REQUIRES_RESET="mediaSourceRequiresReset",t.UNKNOWN="unknown",t}({}),ii=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.MEDIA_ENDED="hlsMediaEnded",t.STALL_RESOLVED="hlsStallResolved",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.BUFFERED_TO_END="hlsBufferedToEnd",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.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",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_TRACK_UPDATED="hlsSubtitleTrackUpdated",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.ASSET_LIST_LOADING="hlsAssetListLoading",t.ASSET_LIST_LOADED="hlsAssetListLoaded",t.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",t.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",t.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",t.INTERSTITIAL_STARTED="hlsInterstitialStarted",t.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",t.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",t.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",t.INTERSTITIAL_ENDED="hlsInterstitialEnded",t.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",t.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",t.EVENT_CUE_ENTER="hlsEventCueEnter",t}({});function ni(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var ri,si={exports:{}};var ai=(ri||(ri=1,function(t){var e,i,n,r,s;e=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,r=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,s={buildAbsoluteURL:function(t,e,n){if(n=n||{},t=t.trim(),!(e=e.trim())){if(!n.alwaysNormalize)return t;var r=s.parseURL(t);if(!r)throw new Error("Error trying to parse base URL.");return r.path=s.normalizePath(r.path),s.buildURLFromParts(r)}var a=s.parseURL(e);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return n.alwaysNormalize?(a.path=s.normalizePath(a.path),s.buildURLFromParts(a)):e;var o=s.parseURL(t);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=i.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var h={scheme:o.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(h.netLoc=o.netLoc,"/"!==a.path[0]))if(a.path){var c=o.path,u=c.substring(0,c.lastIndexOf("/")+1)+a.path;h.path=s.normalizePath(u)}else h.path=o.path,a.params||(h.params=o.params,a.query||(h.query=o.query));return null===h.path&&(h.path=n.alwaysNormalize?s.normalizePath(a.path):a.path),s.buildURLFromParts(h)},parseURL:function(t){var i=e.exec(t);return i?{scheme:i[1]||"",netLoc:i[2]||"",path:i[3]||"",params:i[4]||"",query:i[5]||"",fragment:i[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(n,"");t.length!==(t=t.replace(r,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}},t.exports=s}(si)),si.exports);class oi{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 li="manifest",hi="level",ci="audioTrack",ui="subtitleTrack",di="media-fragment",fi="key",gi="steering-manifest",pi="server-certificate",mi="interstitial-asset-list",vi="main",yi="audio",Ai="subtitle",Ei="audio",Ti="video",bi="audiovideo";class Si{constructor(t){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof t&&(t={url:t}),this.base=t,function(t,e){const i=Ci(t,e);i&&(i.enumerable=!0,Object.defineProperty(t,e,i))}(this,"stats")}setByteRange(t,e){const i=t.split("@",2);let n;n=1===i.length?(null==e?void 0:e.byteRangeEndOffset)||0:parseInt(i[1]),this._byteRange=[n,parseInt(i[0])+n]}get baseurl(){return this.base.url}get byteRange(){return null===this._byteRange?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return null===this._streams&&(this._streams={[Ei]:null,[Ti]:null,[bi]:null}),this._streams}set elementaryStreams(t){this._streams=t}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new oi),this._stats}set stats(t){this._stats=t}get url(){return!this._url&&this.relurl&&(this._url=ai.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[Ei]=null,t[Ti]=null,t[bi]=null,this.url=null}}function ki(t){return"initSegment"!==t.sn}function _i(t,e){return t.sn===(null==e?void 0:e.sn)&&t.level===e.level}function Li(t,e){return t.sn===(null==e?void 0:e.sn)&&t.level===e.level&&t.cc===e.cc}class Ri extends Si{constructor(t,e){super(e),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=t}get byteLength(){if(this.hasStats){const t=this.stats.total;if(t)return t}if(this.byteRange.length){const t=this.byteRange[0],e=this.byteRange[1];if(Qe(t)&&Qe(e))return e-t}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(t){this._bitrate=t}get decryptdata(){var t;const{levelkeys:e}=this;if(!e||e.NONE)return null;if(e.identity)this._decryptdata||(this._decryptdata=e.identity.getDecryptData(this.sn));else if(null==(t=this._decryptdata)||!t.keyId){const t=Object.keys(e);if(1===t.length){const i=this._decryptdata=e[t[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,e))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;const t=Qe(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){var e;const t=Object.keys(this.levelkeys),i=t.length;if(i>1||1===i&&null!=(e=this.levelkeys[t[0]])&&e.encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(t){Qe(t)?this._programDateTime=t:this._programDateTime=this.rawProgramDateTime=null}get ref(){return ki(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(t){this.setStart(this.start+t)}setStart(t){this.start=t,this._ref&&(this._ref.start=t)}setDuration(t){this.duration=t,this._ref&&(this._ref.duration=t)}setKeyFormat(t){const e=this.levelkeys;if(e){var i;const n=e[t];!n||null!=(i=this._decryptdata)&&i.keyId||(this._decryptdata=n.getDecryptData(this.sn,e))}}abortRequests(){var t,e;null==(t=this.loader)||t.abort(),null==(e=this.keyLoader)||e.abort()}setElementaryStreamInfo(t,e,i,n,r,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,n),o.endDTS=Math.max(o.endDTS,r)):a[t]={startPTS:e,endPTS:i,startDTS:n,endDTS:r,partial:s}}}class Ii extends Si{constructor(t,e,i,n,r){super(i),this.fragOffset=0,this.duration=0,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.gap=!1,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=n;const s=t.enumeratedString("BYTERANGE");s&&this.setByteRange(s,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||this.fragment.type===Ai&&this.stats.loaded)}}function Ci(t,e){const i=Object.getPrototypeOf(t);if(i){const t=Object.getOwnPropertyDescriptor(i,e);return t||Ci(i,e)}}function Pi(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var n=i.call(t,e);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function Di(){return Di=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var n in i)({}).hasOwnProperty.call(i,n)&&(t[n]=i[n])}return t},Di.apply(null,arguments)}function wi(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),i.push.apply(i,n)}return i}function Oi(t){for(var e=1;e<arguments.length;e++){var i=null!=arguments[e]?arguments[e]:{};e%2?wi(Object(i),!0).forEach(function(e){Pi(t,e,i[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):wi(Object(i)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))})}return t}function xi(t,e){if(null==t)return{};var i,n,r=function(t,e){if(null==t)return{};var i={};for(var n in t)if({}.hasOwnProperty.call(t,n)){if(-1!==e.indexOf(n))continue;i[n]=t[n]}return i}(t,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(n=0;n<s.length;n++)i=s[n],-1===e.indexOf(i)&&{}.propertyIsEnumerable.call(t,i)&&(r[i]=t[i])}return r}function Mi(t){switch(t.details){case ei.FRAG_LOAD_TIMEOUT:case ei.KEY_LOAD_TIMEOUT:case ei.LEVEL_LOAD_TIMEOUT:case ei.MANIFEST_LOAD_TIMEOUT:case ei.AUDIO_TRACK_LOAD_TIMEOUT:case ei.SUBTITLE_TRACK_LOAD_TIMEOUT:case ei.ASSET_LIST_LOAD_TIMEOUT:return!0}return!1}function Ni(t){return t.details.startsWith("key")}function Fi(t){return Ni(t)&&!!t.frag&&!t.frag.decryptdata}function Bi(t,e){const i=Mi(e);return t.default[(i?"timeout":"error")+"Retry"]}function $i(t,e){const i="linear"===t.backoff?1:Math.pow(2,e);return Math.min(i*t.retryDelayMs,t.maxRetryDelayMs)}function Ui(t){return Oi(Oi({},t),{errorRetry:null,timeoutRetry:null})}function Gi(t,e,i,n){if(!t)return!1;const r=null==n?void 0:n.code,s=e<t.maxNumRetry&&(function(t){return Vi(t)||!!t&&(t<400||t>499)}(r)||!!i);return t.shouldRetry?t.shouldRetry(t,e,i,n,s):s}function Vi(t){return 0===t&&!1===navigator.onLine}function Ki(t,e){return e>0&&t.loadError>0&&0!==t.loadErrorTime&&self.performance.now()-t.loadErrorTime>e}class Hi{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 Yi{constructor(t,e,i,n=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 Hi(t),this.fast_=new Hi(e),this.defaultTTFB_=n,this.ttfb_=new Hi(t)}update(t,e){const{slow_:i,fast_:n,ttfb_:r}=this;i.halfLife!==t&&(this.slow_=new Hi(t,i.getEstimate(),i.getTotalWeight())),n.halfLife!==e&&(this.fast_=new Hi(e,n.getEstimate(),n.getTotalWeight())),r.halfLife!==t&&(this.ttfb_=new Hi(t,r.getEstimate(),r.getTotalWeight()))}sample(t,e){if(e<=0)return;const i=Math.min(this.minDelayMs_,e/1e5),n=8*e,r=Math.max(t,i)/1e3,s=n/r;this.fast_.sample(r,s),this.slow_.sample(r,s)}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_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}class ji{constructor(t,e){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const i=`[${t}]:`;this.trace=Wi,this.debug=e.debug.bind(null,i),this.log=e.log.bind(null,i),this.warn=e.warn.bind(null,i),this.info=e.info.bind(null,i),this.error=e.error.bind(null,i)}}const Wi=function(){},zi={trace:Wi,debug:Wi,log:Wi,warn:Wi,info:Wi,error:Wi};function qi(){return Di({},zi)}function Xi(t,e,i){return e[t]?e[t].bind(e):function(t,e){const i=self.console[t];return i?i.bind(self.console,`${e?"["+e+"] ":""}[${t}] >`):Wi}(t,i)}const Qi=qi();const Zi=Qi;function Ji(t=!0){if("undefined"==typeof self)return;return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function tn(t,e){const i=Object.keys(t),n=Object.keys(e),r=i.length,s=n.length;return!r||!s||r===s&&!i.some(t=>-1===n.indexOf(t))}function en(t){return t instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&t instanceof SharedArrayBuffer}const nn="utf-16be",rn="utf-16le",sn="utf-8";function an(t,e){if(t<0)return-an(-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 on(){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)})}}}function ln(t,e){return 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}function hn(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}function cn(t,e){return ln(t,e)&&hn(t,e+6)+10<=t.length-e}function un(t,e){return 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}function dn(t,e){const i=e;let n=0;for(;ln(t,e);){n+=10;n+=hn(t,e+6),un(t,e+10)&&(n+=10),e+=n}if(n>0)return t.subarray(i,i+n)}function fn(t,e=0,i=1/0){return function(t,e,i,n){const r=(s=t,en(s)?s:s.buffer);var s;let a=1;"BYTES_PER_ELEMENT"in n&&(a=n.BYTES_PER_ELEMENT);const o=(u=t,u&&en(u.buffer)&&void 0!==u.byteLength&&void 0!==u.byteOffset?t.byteOffset:0),l=(o+t.byteLength)/a,h=(o+e)/a,c=Math.floor(Math.max(0,Math.min(h,l)));var u;return new n(r,c,Math.floor(Math.min(c+Math.max(i,0),l))-c)}(t,e,i,Uint8Array)}function gn(t,e=!1){const i=e?t.indexOf(0):t.length,n=function(t,e={}){let i;i=en(t)?new DataView(t):new DataView(t.buffer,t.byteOffset,t.byteLength);let n=0,{encoding:r}=e;if(!r){const t=i.getUint8(0),e=i.getUint8(1);239==t&&187==e&&191==i.getUint8(2)?(r=sn,n=3):254==t&&255==e?(r=nn,n=2):255==t&&254==e?(r=rn,n=2):r=sn}if("undefined"!=typeof TextDecoder)return new TextDecoder(r).decode(i);const{byteLength:s}=i,a=r!==nn;let o,l="";for(;n<s;){switch(r){case sn:if(o=i.getUint8(n),o<128)n++;else if(o>=194&&o<=223)if(n+1<s){const t=i.getUint8(n+1);t>=128&&t<=191?(o=(31&o)<<6|63&t,n+=2):n++}else n++;else if(o>=224&&o<=239)if(n+2<=s-1){const t=i.getUint8(n+1),e=i.getUint8(n+2);t>=128&&t<=191&&e>=128&&e<=191?(o=(15&o)<<12|(63&t)<<6|63&e,n+=3):n++}else n++;else if(o>=240&&o<=244)if(n+3<=s-1){const t=i.getUint8(n+1),e=i.getUint8(n+2),r=i.getUint8(n+3);t>=128&&t<=191&&e>=128&&e<=191&&r>=128&&r<=191?(o=(7&o)<<18|(63&t)<<12|(63&e)<<6|63&r,n+=4):n++}else n++;else n++;break;case nn:case"utf-16":case rn:o=i.getUint16(n,a),n+=2}l+=String.fromCodePoint(o)}return l}(new DataView(t.buffer,t.byteOffset,i),{encoding:sn});return e?n:n.replace(/\0/g,"")}function pn(t){const e={key:t.type,description:"",data:"",mimeType:null,pictureType:null};if(t.size<2)return;if(3!==t.data[0])return void console.log("Ignore frame with unrecognized character encoding");const i=t.data.subarray(1).indexOf(0);if(-1===i)return;const n=gn(fn(t.data,1,i)),r=t.data[2+i],s=t.data.subarray(3+i).indexOf(0);if(-1===s)return;const a=gn(fn(t.data,3+i,s));let o;var l;return"--\x3e"===n?o=gn(fn(t.data,4+i+s)):o=en(l=t.data.subarray(4+i+s))?l:0==l.byteOffset&&l.byteLength==l.buffer.byteLength?l.buffer:new Uint8Array(l).buffer,e.mimeType=n,e.pictureType=r,e.description=a,e.data=o,e}function mn(t){return"PRIV"===t.type?function(t){if(t.size<2)return;const e=gn(t.data,!0),i=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:i.buffer}}(t):"W"===t.type[0]?function(t){if("WXXX"===t.type){if(t.size<2)return;let e=1;const i=gn(t.data.subarray(e),!0);e+=i.length+1;const n=gn(t.data.subarray(e));return{key:t.type,info:i,data:n}}const e=gn(t.data);return{key:t.type,info:"",data:e}}(t):"APIC"===t.type?pn(t):function(t){if(t.size<2)return;if("TXXX"===t.type){let e=1;const{data:i}=t,n=gn(i.subarray(e),!0);e+=n.length+1;const r=gn(i.subarray(e));return{key:t.type,info:n,data:r}}const e=gn(t.data.subarray(1));return{key:t.type,info:"",data:e}}(t)}function vn(t){const e=String.fromCharCode(t[0],t[1],t[2],t[3]),i=hn(t,4);return{type:e,size:i,data:t.subarray(10,10+i)}}function yn(t){let e=0;const i=[];for(;ln(t,e);){const n=hn(t,e+6);t[e+5]>>6&1&&(e+=10),e+=10;const r=e+n;for(;e+10<r;){const n=vn(t.subarray(e)),r=mn(n);r&&i.push(r),e+=n.size+10}un(t,e)&&(e+=10)}return i}function An(t){return t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info}function En(t){if(8===t.data.byteLength){const e=new Uint8Array(t.data),i=1&e[3];let n=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return n/=45,i&&(n+=47721858.84),Math.round(n)}}function Tn(t){const e=yn(t);for(const t of e)if(An(t))return En(t)}function bn(t){let e="";for(let i=0;i<t.length;i++){let n=t[i].toString(16);n.length<2&&(n="0"+n),e+=n}return e}function Sn(t){return Uint8Array.from(t.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function kn(t){return Uint8Array.from(atob(t),t=>t.charCodeAt(0))}function _n(t){return String.fromCharCode.apply(null,t)}const Ln=Math.pow(2,32)-1,Rn={avc1:1635148593,avcC:1635148611,hvc1:1752589105,hvcC:1752589123,btrt:1651798644,dinf:1684631142,dref:1685218662,esds:1702061171,free:1718773093,ftyp:1718909296,hdlr:1751411826,mdat:1835295092,mdhd:1835296868,mdia:1835297121,mfhd:1835427940,minf:1835626086,moof:1836019558,moov:1836019574,mp4a:1836069985,".mp3":778924083,dac3:1684103987,"ac-3":1633889587,mvex:1836475768,mvhd:1836476516,pasp:1885434736,sdtp:1935963248,stbl:1937007212,stco:1937007471,stsc:1937011555,stsd:1937011556,stsz:1937011578,stts:1937011827,tfdt:1952867444,tfhd:1952868452,traf:1953653094,trak:1953653099,trun:1953658222,trex:1953654136,tkhd:1953196132,vmhd:1986881636,smhd:1936549988},In={video:1,audio:2,id3:3,text:4};function Cn(t,e){const i=t[e]<<8|t[e+1];return i<0?65536+i:i}function Pn(t,e){const i=t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3];return i<0?4294967296+i:i}function Dn(t,e){let i=Pn(t,e);return i*=Math.pow(2,32),i+=Pn(t,e+4),i}function wn(t,e){let i="";for(let n=e;n<t.length;n++)if(i+=String.fromCharCode(t[n]),0===t[n])return i;return null}function On(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function xn(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 Mn(t,e,i){const n=e.byteOffset-t.byteOffset-8,r=8+i,s=e.byteLength+8-r;s<8||(xn(t,n,r),xn(t,n+r,s),xn(t,n+r+4,Rn.free))}function Nn(t,e){return[t.byteOffset-e-8,t.byteOffset-e+t.byteLength]}function Fn(t,e){e.sort((t,e)=>t[0]-e[0]);const i=e.reduce((t,[e,i])=>t+i-e,0),n=new Uint8Array(t.byteLength-i);let r=0,s=0;for(let i=0;i<e.length;i++){const[a,o]=e[i];n.set(t.subarray(r,a),s),s+=a-r,r=o}n.set(t.subarray(r),s);return{result:n,dropped:i,droppedBefore:t=>e.reduce((e,[i,n])=>n<=t?e+n-i:e,0)}}function Bn(t,e){const i=[];return e.length?($n(t,e,0,0,t.byteLength,i),i):i}function $n(t,e,i,n,r,s){const a=e[i];if(4!==(null==a?void 0:a.length))return;const o=a.charCodeAt(0),l=a.charCodeAt(1),h=a.charCodeAt(2),c=a.charCodeAt(3),u=e.length-1;for(let a=n;a<r;){const n=a+8<=r,d=a+4<=r?16777216*t[a]+(t[a+1]<<16|t[a+2]<<8|t[a+3]):Pn(t,a),f=d>1?a+d:r;if(n&&t[a+4]===o&&t[a+5]===l&&t[a+6]===h&&t[a+7]===c){const n=Math.min(f,r);i===u?s.push(t.subarray(a+8,n)):$n(t,e,i+1,a+8,n,s)}a=f}}function Un(t){const e=[],i=t[0];let n=8;const r=Pn(t,n);n+=4;let s=0,a=0;0===i?(s=Pn(t,n),a=Pn(t,n+4),n+=8):(s=Dn(t,n),a=Dn(t,n+8),n+=16),n+=2;let o=t.length+a;const l=Cn(t,n);n+=2;for(let i=0;i<l;i++){let i=n;const s=Pn(t,i);i+=4;const a=2147483647&s;if(1===(2147483648&s)>>>31)return Zi.warn("SIDX has hierarchical references (not supported)"),null;const l=Pn(t,i);i+=4,e.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/r,start:o,end:o+a-1}}),o+=a,i+=4,n=i}return{earliestPresentationTime:s,timescale:r,version:i,referencesCount:l,references:e}}function Gn(t){const e=[],i=Bn(t,["moov","trak"]);for(let t=0;t<i.length;t++){const n=i[t],r=Bn(n,["tkhd"])[0];if(r){let t=r[0];const i=Pn(r,0===t?12:20),s=Bn(n,["mdia","mdhd"])[0];if(s){t=s[0];const r=Pn(s,0===t?12:20),a=Bn(n,["mdia","hdlr"])[0];if(a){const t=_n(a.subarray(8,12)),s={soun:Ei,vide:Ti}[t],o=Vn(Bn(n,["mdia","minf","stbl","stsd"])[0]);s?(e[i]={timescale:r,type:s,stsd:o},e[s]=Oi({timescale:r,id:i},o)):e[i]={timescale:r,type:t,stsd:o}}}}}return Bn(t,["moov","mvex","trex"]).forEach(t=>{const i=Pn(t,4),n=e[i];n&&(n.default={duration:Pn(t,12),sampleSize:Pn(t,16),flags:Pn(t,20)})}),e}function Vn(t){const e=t.subarray(8),i=e.subarray(86),n=_n(e.subarray(4,8));let r,s=n;const a="enca"===n||"encv"===n;if(a){const t=Bn(e,[n])[0];Bn(t.subarray("enca"===n?28:78),["sinf"]).forEach(t=>{const e=Bn(t,["schm"])[0];if(e){const i=_n(e.subarray(4,8));if("cbcs"===i||"cenc"===i){const e=Bn(t,["frma"])[0];e&&(s=_n(e))}}})}const o=s;switch(s){case"avc1":case"avc2":case"avc3":case"avc4":{const t=Bn(i,["avcC"])[0];t&&t.length>3&&(s+="."+Yn(t[1])+Yn(t[2])+Yn(t[3]),r=Kn("avc1"===o?"dva1":"dvav",i));break}case"mp4a":{const t=Bn(e,[n])[0],i=Bn(t.subarray(28),["esds"])[0];if(i&&i.length>7){let t=4;if(3!==i[t++])break;t=Hn(i,t),t+=2;const e=i[t++];if(128&e&&(t+=2),64&e&&(t+=i[t++]),4!==i[t++])break;t=Hn(i,t);const n=i[t++];if(64!==n)break;if(s+="."+Yn(n),t+=12,5!==i[t++])break;t=Hn(i,t);const r=i[t++];let a=(248&r)>>3;31===a&&(a+=1+((7&r)<<3)+((224&i[t])>>5)),s+="."+a}break}case"hvc1":case"hev1":{const t=Bn(i,["hvcC"])[0];if(t&&t.length>12){const e=t[1],i=["","A","B","C"][e>>6],n=31&e,r=Pn(t,2),a=(32&e)>>5?"H":"L",o=t[12],l=t.subarray(6,12);s+="."+i+n,s+="."+function(t){let e=0;for(let i=0;i<32;i++)e|=(t>>i&1)<<31-i;return e>>>0}(r).toString(16).toUpperCase(),s+="."+a+o;let h="";for(let t=l.length;t--;){const e=l[t];if(e||h){h="."+e.toString(16).toUpperCase()+h}}s+=h}r=Kn("hev1"==o?"dvhe":"dvh1",i);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":s=Kn(s,i)||s;break;case"vp09":{const t=Bn(i,["vpcC"])[0];if(t&&t.length>6){const e=t[4],i=t[5],n=t[6]>>4&15;s+="."+jn(e)+"."+jn(i)+"."+jn(n)}break}case"av01":{const t=Bn(i,["av1C"])[0];if(t&&t.length>2){const e=t[1]>>>5,n=31&t[1],a=t[2]>>>7?"H":"M",o=(64&t[2])>>6,l=(32&t[2])>>5,h=2===e&&o?l?12:10:o?10:8,c=(16&t[2])>>4,u=(8&t[2])>>3,d=(4&t[2])>>2,f=3&t[2],g=1,p=1,m=1,v=0;s+="."+e+"."+jn(n)+a+"."+jn(h)+"."+c+"."+u+d+f+"."+jn(g)+"."+jn(p)+"."+jn(m)+"."+v,r=Kn("dav1",i)}break}}return{codec:s,encrypted:a,supplemental:r}}function Kn(t,e){const i=Bn(e,["dvvC"]),n=i.length?i[0]:Bn(e,["dvcC"])[0];if(n){const e=n[2]>>1&127,i=n[2]<<5&32|n[3]>>3&31;return t+"."+jn(e)+"."+jn(i)}}function Hn(t,e){const i=e+5;for(;128&t[e++]&&e<i;);return e}function Yn(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function jn(t){return(t<10?"0":"")+t}function Wn(t,e){Bn(t,["moov","trak"]).forEach(t=>{const i=Bn(t,["mdia","minf","stbl","stsd"])[0];if(!i)return;const n=i.subarray(8);let r=Bn(n,["enca"]);const s=r.length>0;s||(r=Bn(n,["encv"])),r.forEach(t=>{Bn(s?t.subarray(28):t.subarray(78),["sinf"]).forEach(t=>{const i=zn(t);i&&e(i,s)})})})}function zn(t){const e=Bn(t,["schm"])[0];if(e){const i=_n(e.subarray(4,8));if("cbcs"===i||"cenc"===i){const e=Bn(t,["schi","tenc"])[0];if(e)return e}}}let qn;function Xn(t){if("undefined"==typeof TextDecoder)return gn(t);return(qn||(qn=new TextDecoder("utf-8"))).decode(t).replace(/\0/g,"")}function Qn(t,e,i,n,r){const s={};let a=!1;const o=function(t){const e=t.byteLength,i=[];for(let n=0;n<e;){const r=n+8<=e,s=n+4<=e?16777216*t[n]+(t[n+1]<<16|t[n+2]<<8|t[n+3]):Pn(t,n),a=s>1?n+s:e;if(r&&109===t[n+4]&&111===t[n+5]&&111===t[n+6]&&102===t[n+7]){const r=Math.min(a,e);for(let e=n+8;e<r;){const s=e+8<=r,a=e+4<=r?16777216*t[e]+(t[e+1]<<16|t[e+2]<<8|t[e+3]):Pn(t,e),o=a>1?e+a:r;if(s&&116===t[e+4]&&114===t[e+5]&&97===t[e+6]&&102===t[e+7]){const s=Math.min(o,r);let a,l;const h=[];for(let i=e+8;i<s;){const e=i+8<=s,n=i+4<=s?16777216*t[i]+(t[i+1]<<16|t[i+2]<<8|t[i+3]):Pn(t,i),r=n>1?i+n:s;if(e&&116===t[i+4]){const e=Math.min(r,s);102===t[i+5]&&104===t[i+6]&&100===t[i+7]?l||(l=t.subarray(i+8,e)):102===t[i+5]&&100===t[i+6]&&116===t[i+7]?a||(a=t.subarray(i+8,e)):114===t[i+5]&&117===t[i+6]&&110===t[i+7]&&h.push(t.subarray(i+8,e))}i=r}i.push({moofOffset:t.byteOffset+n,tfdt:a,tfhd:l,truns:h})}e=o}}n=a}return i}(t),l=t.byteLength;for(let u=0;u<o.length;u++){const{moofOffset:d,tfdt:f,tfhd:g,truns:p}=o[u],m=Pn(g,4),v=e[m];if(!v)continue;const y=s[m]||(s[m]={start:NaN,duration:0,sampleCount:0,trun:[],timescale:v.timescale,type:v.type});let A;if(f){const t=f[0];A=Pn(f,4),1===t&&(A===Ln?i.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(A*=Ln+1,A+=Pn(f,8))),Qe(A)&&(!Qe(y.start)||A<y.start)&&(y.start=A),r&&Qe(A)&&(r.timeOffset=A/r.timescale)}const E=(null==r?void 0:r.trackId)===m&&v.type===Ti,T=v.default,b=16777215&Pn(g,0);let S,k=(null==T?void 0:T.duration)||0,_=(null==T?void 0:T.sampleSize)||0,L=8;1&b&&(L+=8),2&b&&(L+=4),8&b&&(k=Pn(g,L),S=g.byteOffset-t.byteOffset+L,L+=4),16&b&&(_=Pn(g,L));let R=0;const I=!!(1&b),C=!I&&!!(131072&b);I?(R=Pn(g,8),R*=Math.pow(2,32),R+=Pn(g,12)):C&&(R=d);let P=A||0,D=0,w=k;for(let e=0;e<p.length;e++){const i=p[e],s=Pn(i,4),a=y.sampleCount;y.sampleCount+=s;const o=1&i[3];let u=0;const d=4&i[3],f=1&i[2],g=2&i[2],m=4&i[2],v=8&i[2];let A=8;if(o&&(u=On(i,A),A+=4),d){1&i[A+1]||void 0!==y.keyFrameIndex||(y.keyFrameIndex=a),A+=4}let T,b,L,I=R+u;if(!n&&0===i[1]&&6===i[2]&&1===i[3]){var h,c;const e=P,n=I,a=A;let o=-1,u=0,d=0,f=null!=(h=null==r?void 0:r.timeOffset)?h:0;const g=k/(null!=(c=null==r?void 0:r.timescale)?c:1),p=!0===(null==r?void 0:r.isHEVCFlavor),m=p?2:1;for(let e=0;e<s;e++){const n=0===i[A]?i[A+1]<<16|i[A+2]<<8|i[A+3]:Pn(i,A),s=-1===o&&void 0===y.keyFrameIndex&&!(1&i[A+5]);A+=8;const a=I+n;if(E){if(n>0){let e=I;do{const i=0===t[e]?t[e+1]<<16|t[e+2]<<8|t[e+3]:Pn(t,e);e+=4;const n=t[e],s=p?n>>1&63:31&n;(p?39===s||40===s:6===s)&&er(t.subarray(e,e+i),m,f,r.samples),e+=i}while(e<a)}f+=g}I=a,s&&(o=e,u=I)}if(I<=l)d=s;else{let t=n,e=a;for(let n=0;n<s;n++){if(t+=0===i[e]?i[e+1]<<16|i[e+2]<<8|i[e+3]:Pn(i,e),t>l)break;d=n+1,e+=8}}if(E&&(r.timeOffset=f),-1!==o&&u<=l&&void 0===y.keyFrameIndex&&(y.keyFrameIndex=o,y.keyFrameStart=e+o*k),d){(!Qe(y.ptsMin)||e<y.ptsMin)&&(y.ptsMin=e);const t=e+d*k;(!Qe(y.ptsMax)||t>y.ptsMax)&&(y.ptsMax=t)}const v=k*s;P=e+v,D+=v;continue}n&&(T=[],b={sampleOffset:I,samples:T,defaultSampleDurationOffset:S},I<=l&&y.trun.push(b));for(let e=0;e<s;e++){let s,a,o;f?(n&&(s=i.byteOffset-t.byteOffset+A),w=Pn(i,A),A+=4):w=k,g?(L=Pn(i,A),A+=4):L=_,m&&(o=1&i[A+1]?1:0,n&&(a={isNonSync:o,dependsOn:1==(3&i[A])?1:2}),A+=4);let h=0;if(v){h=0===i[0]?Pn(i,A):On(i,A),A+=4}if(E){let e=I,i=0;for(;i<L;){const n=Pn(t,e);e+=4,tr(r.isHEVCFlavor,t[e])&&er(t.subarray(e,e+n),r.isHEVCFlavor?2:1,r.timeOffset+h/r.timescale,r.samples),e+=n,i+=n+4}r.timeOffset+=w/r.timescale}if(I+=L,I<=l){b&&void 0!==s&&(b.lastSampleDurationOffset=s),0===o&&void 0===y.keyFrameIndex&&(y.keyFrameIndex=e,y.keyFrameStart=P);const t=P+h;(!Qe(y.ptsMin)||t<y.ptsMin)&&(y.ptsMin=t),(!Qe(y.ptsMax)||t+w>y.ptsMax)&&(y.ptsMax=t+w),T&&(T[e]={cts:h,duration:w,flags:a,size:L})}P+=w,D+=w}!D&&k&&(D+=k*s)}y.duration+=D,y.duration&&(a=!0)}if(!a){let e=1/0,i=0;const n=Bn(t,["sidx"]);for(let t=0;t<n.length;t++){const r=Un(n[t]);if(null!=r&&r.references){e=Math.min(e,r.earliestPresentationTime/r.timescale);const t=r.references.reduce((t,e)=>t+e.info.duration||0,0);i=Math.max(i,t+r.earliestPresentationTime/r.timescale)}}i&&Qe(i)&&Object.keys(s).forEach(t=>{s[t].duration||(s[t].duration=i*s[t].timescale-s[t].start)})}return s}function Zn(t,e){const i=new Uint8Array(t.length+e.length);return i.set(t),i.set(e,t.length),i}function Jn(t){if(!t)return!1;const e=t.substring(0,4);return"hvc1"===e||"hev1"===e||"dvh1"===e||"dvhe"===e}function tr(t,e){if(t){const t=e>>1&63;return 39===t||40===t}return 6===(31&e)}function er(t,e,i,n){const r=ir(t);let s=0;s+=e;let a=0,o=0,l=0;for(;s<r.length;){a=0;do{if(s>=r.length)break;l=r[s++],a+=l}while(255===l);o=0;do{if(s>=r.length)break;l=r[s++],o+=l}while(255===l);const t=r.length-s;let e=s;if(o<t)s+=o;else if(o>t){Zi.error(`Malformed SEI payload. ${o} is too small, only ${t} bytes left to parse.`);break}if(4===a){if(181===r[e++]){const t=Cn(r,e);if(e+=2,49===t){const t=Pn(r,e);if(e+=4,1195456820===t){const t=r[e++];if(3===t){const s=r[e++],o=64&s,l=o?2+3*(31&s):0,h=new Uint8Array(l);if(o){h[0]=s;for(let t=1;t<l;t++)h[t]=r[e++]}n.push({type:t,payloadType:a,pts:i,bytes:h})}}}}}else if(5===a&&o>16){const t=[];for(let i=0;i<16;i++){const n=r[e++].toString(16);t.push(1==n.length?"0"+n:n),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]=r[e++];n.push({payloadType:a,pts:i,uuid:t.join(""),userData:Xn(l),userDataBytes:l})}}}function ir(t){const e=t.byteLength;let i,n=t.indexOf(3,3);for(;-1!==n;)0===t[n-1]&&0===t[n-2]&&(i||(i=[])).push(n),n=t.indexOf(3,n+1);if(!i)return t;const r=e-i.length,s=new Uint8Array(r);let a=0,o=0;for(let e=0;e<r;o++,e++)o===i[a]&&(o++,a++),s[e]=t[o];return s}function nr(t,e,i){if(16!==t.byteLength)throw new RangeError("Invalid system id");let n,r,s;n=0,r=new Uint8Array,s=new Uint8Array;const a=new Uint8Array(4);return i.byteLength>0&&new DataView(a.buffer).setUint32(0,i.byteLength,!1),function(t,...e){const i=e.length;let n=8,r=i;for(;r--;)n+=e[r].byteLength;const s=new Uint8Array(n);for(s[0]=n>>24&255,s[1]=n>>16&255,s[2]=n>>8&255,s[3]=255&n,s.set(t,4),r=0,n=8;r<i;r++)s.set(e[r],n),n+=e[r].byteLength;return s}([112,115,115,104],new Uint8Array([0,0,0,0]),t,s,r,a,i)}function rr(t){const e=[];if(t instanceof ArrayBuffer){const i=t.byteLength;let n=0;for(;n+32<i;){const i=sr(new DataView(t,n));e.push(i),n+=i.size}}return e}function sr(t){const e=t.getUint32(0),i=t.byteOffset,n=t.byteLength;if(n<e)return{offset:i,size:n};if(1886614376!==t.getUint32(4))return{offset:i,size:e};const r=t.getUint32(8)>>>24;if(0!==r&&1!==r)return{offset:i,size:e};const s=t.buffer,a=bn(new Uint8Array(s,i+12,16));let o=null,l=null,h=0;if(0===r)h=28;else{const r=t.getUint32(28);if(!r||n<32+16*r)return{offset:i,size:e};o=[];for(let t=0;t<r;t++)o.push(new Uint8Array(s,i+32+16*t,16));h=32+16*r}if(!h)return{offset:i,size:e};const c=t.getUint32(h);return e-32<c?{offset:i,size:e}:(l=new Uint8Array(s,i+h+4,c),0===r&&(o=function(t){const e=[];for(let i=0;i<t.length;){const n=t[i++],r=7&n;if(0===r){for(;128&t[i++];);continue}if(2!==r){i+=1===r?8:4;continue}let s=0;for(let e=0,n=128;128&n;e+=7)s|=(127&(n=t[i++]))<<e;if(n>>3==2)if(32===s){const n=new Uint8Array(16);for(let e=0;e<16;e++)n[e]=parseInt(String.fromCharCode(t[i+2*e],t[i+2*e+1]),16);e.push(n)}else 16===s&&e.push(t.subarray(i,i+16));i+=s}return e}(l)),{version:r,systemId:a,kids:o,data:l,offset:i,size:e})}const ar=ur("userAgent"),or=ur("vendor");let lr,hr,cr;function ur(t){try{return navigator[t]||""}catch(t){}return""}function dr(){if(void 0===lr){const t=ar.match(/Chrome\/(\d+)/i);lr=t?parseInt(t[1]):0}return lr}function fr(){return/\(Windows.+Firefox\//i.test(ar)}const gr={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1},image:{mjpg:1}};function pr(t,e){const i=gr[e];return!!i&&!!i[t.slice(0,4)]}function mr(t,e,i=!0){return!t.split(",").some(t=>!vr(t,e,i))}function vr(t,e,i=!0){var n;const r=Ji(i);return null!=(n=null==r?void 0:r.isTypeSupported(yr(t,e)))&&n}function yr(t,e){return`${e}/mp4;codecs=${t}`}function Ar(t){if(t){const e=t.substring(0,4);return gr.video[e]}return 2}function Er(t){const e=fr();return t.split(",").reduce((t,i)=>{const n=e&&Jn(i)?9:gr.video[i];return n?(2*n+t)/(t?3:2):(gr.audio[i]+t)/(t?2:1)},0)}const Tr={};const br=/flac|opus|mp4a\.40\.34/i;function Sr(t,e=!0){return t.replace(br,t=>function(t,e=!0){if(Tr[t])return Tr[t];const i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[t];for(let r=0;r<i.length;r++){var n;if(vr(i[r],"audio",e))return Tr[t]=i[r],i[r];if("mp3"===i[r]&&null!=(n=Ji(e))&&n.isTypeSupported("audio/mpeg"))return""}return t}(t.toLowerCase(),e))}function kr(t,e){if(t&&(t.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(t))&&(_r(t,"audio")||_r(t,"video")))return t;if(e){const i=e.split(",");if(i.length>1){if(t)for(let e=i.length;e--;)if(i[e].substring(0,4)===t.substring(0,4))return i[e];return i[0]}}return e||t}function _r(t,e){return pr(t,e)&&vr(t,e)}function Lr(t){if(t.startsWith("av01.")){const e=t.split("."),i=["0","111","01","01","01","0"];for(let t=e.length;t>4&&t<10;t++)e[t]=i[t-4];return e.join(".")}return t}function Rr(t){const e=Ji(t)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Ir(t){return t.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const Cr={supported:!1,smooth:!1,powerEfficient:!1},Pr={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function Dr(t,e){return{supported:!1,configurations:e,decodingInfoResults:[Cr],error:t}}function wr(t,e,i,n,r,s){const a=t.videoCodec,o=t.audioCodec?t.audioGroups:null,l=null==s?void 0:s.audioCodec,h=null==s?void 0:s.channels,c=h?parseInt(h):l?1/0:2;let u=null;if(null!=o&&o.length)try{u=1===o.length&&o[0]?e.groups[o[0]].channels:o.reduce((t,i)=>{if(i){const n=e.groups[i];if(!n)throw new Error(`Audio track group ${i} not found`);Object.keys(n.channels).forEach(e=>{t[e]=(t[e]||0)+n.channels[e]})}return t},{2:0})}catch(t){return!0}return void 0!==a&&(a.split(",").some(t=>Jn(t))||t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(n,30)||"SDR"!==t.videoRange&&t.videoRange!==i||t.bitrate>Math.max(r,8e6))||!!u&&Qe(c)&&Object.keys(u).some(t=>parseInt(t)>c)}function Or(t,e,i,n={}){const r=t.videoCodec;if(!r&&!t.audioCodec||!i)return Promise.resolve(Pr);const s=[],a=function(t){var e;const i=null==(e=t.videoCodec)?void 0:e.split(","),n=Mr(t),r=t.width||640,s=t.height||480,a=t.frameRate||30,o=t.videoRange.toLowerCase();return i?i.map(t=>{const e={contentType:yr(Lr(t),"video"),width:r,height:s,bitrate:n,framerate:a};return"sdr"!==o&&(e.transferFunction=o),e}):[]}(t),o=a.length,l=function(t,e,i){var n;const r=null==(n=t.audioCodec)?void 0:n.split(","),s=Mr(t);if(r&&t.audioGroups)return t.audioGroups.reduce((t,n)=>{var a;const o=n?null==(a=e.groups[n])?void 0:a.tracks:null;return o?o.reduce((t,e)=>{if(e.groupId===n){const n=parseFloat(e.channels||"");r.forEach(e=>{const r={contentType:yr(e,"audio"),bitrate:i?xr(e,s):s};n&&(r.channels=""+n),t.push(r)})}return t},t):t},[]);return[]}(t,e,o>0),h=l.length;for(let t=o||1*h||1;t--;){const e={type:"media-source"};if(o&&(e.video=a[t%o]),h){e.audio=l[t%h];const i=e.audio.bitrate;e.video&&i&&(e.video.bitrate-=i)}s.push(e)}if(r){const t=navigator.userAgent;if(r.split(",").some(t=>Jn(t))&&fr())return Promise.resolve(Dr(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${t})`),s))}return Promise.all(s.map(t=>{const e=function(t){let e="";const{audio:i,video:n}=t;if(n){e+=`${Ir(n.contentType)}_r${n.height}x${n.width}f${Math.ceil(n.framerate)}${n.transferFunction||"sd"}_${Math.ceil(n.bitrate/1e5)}`}if(i){e+=`${n?"_":""}${Ir(i.contentType)}_c${i.channels}`}return e}(t);return n[e]||(n[e]=i.decodingInfo(t))})).then(t=>({supported:!t.some(t=>!t.supported),configurations:s,decodingInfoResults:t})).catch(t=>({supported:!1,configurations:s,decodingInfoResults:[],error:t}))}function xr(t,e){if(e<=1)return 1;let i=128e3;return"ec-3"===t?i=768e3:"ac-3"===t&&(i=64e4),Math.min(e/2,i)}function Mr(t){return 1e3*Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)/1e3)||1}function Nr(t,e,i){const n=encodeURIComponent(e),r=`${n}=${encodeURIComponent(i)}`;let s=!1;const a=[];t.search.substring(1).split("&").forEach(t=>{t===n||t.startsWith(n+"=")?s||(a.push(r),s=!0):t&&a.push(t)}),s||a.push(r),t.search=a.join("&")}const Fr=["NONE","TYPE-0","TYPE-1",null];const Br=["SDR","PQ","HLG"];var $r="",Ur="YES",Gr="v2";function Vr(t){const{canSkipUntil:e,canSkipDateRanges:i,age:n}=t;return e&&n<e/2?i?Gr:Ur:$r}class Kr{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&&Nr(e,"_HLS_msn",this.msn.toString()),void 0!==this.part&&Nr(e,"_HLS_part",this.part.toString()),this.skip&&Nr(e,"_HLS_skip",this.skip),e.href}}class Hr{constructor(t){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.imageCodec=void 0,this.iframes=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loadErrorTime=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,"imageCodec"in t&&(this.imageCodec=t.imageCodec),this.codecSet=[t.videoCodec,t.audioCodec].filter(t=>!!t).map(t=>t.substring(0,4)).join(","),"supplemental"in t){var e;this.supplemental=t.supplemental;const i=null==(e=t.supplemental)?void 0:e.videoCodec;i&&i!==t.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}"iframes"in t&&t.iframes?this.iframes=!0:(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 Yr(this._audioGroups,t)}hasSubtitleGroup(t){return Yr(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 Yr(t,e){return!(!e||!t)&&-1!==t.indexOf(e)}function jr(t,e){let i=!1,n=[];if(t&&(i="SDR"!==t,n=[t]),e){n=e.allowedVideoRanges||Br.slice(0);const t="SDR"!==n.join("")&&!e.videoCodec;i=void 0!==e.preferHDR?e.preferHDR:t&&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||(n=["SDR"])}return{preferHDR:i,allowedVideoRanges:n}}const Wr=(t,e)=>JSON.stringify(t,(t=>{const e=new WeakSet;return(i,n)=>{if(t&&(n=t(i,n)),"object"==typeof n&&null!==n){if(e.has(n))return;e.add(n)}return n}})(e));function zr(t,e){Zi.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function qr(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 n=e.channels||"2";return i.channels[n]=(i.channels[n]||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:{}})}function Xr(t){if(!t)return t;const{lang:e,assocLang:i,characteristics:n,channels:r,audioCodec:s}=t;return{lang:e,assocLang:i,characteristics:n,channels:r,audioCodec:s}}function Qr(t,e,i){if("attrs"in t){const i=e.indexOf(t);if(-1!==i)return i}for(let n=0;n<e.length;n++){if(Zr(t,e[n],i))return n}return-1}function Zr(t,e,i){const{groupId:n,name:r,lang:s,assocLang:a,default:o}=t,l=t.forced;return(void 0===n||e.groupId===n)&&(void 0===r||e.name===r)&&(void 0===s||function(t,e="--"){if(t.length===e.length)return t===e;return t.startsWith(e)||e.startsWith(t)}(s,e.lang))&&(void 0===s||e.assocLang===a)&&(void 0===o||e.default===o)&&(void 0===l||e.forced===l)&&(!("characteristics"in t)||function(t,e=""){const i=t.split(","),n=e.split(",");return i.length===n.length&&!i.some(t=>-1===n.indexOf(t))}(t.characteristics||"",e.characteristics))&&(void 0===i||i(t,e))}function Jr(t,e){const{audioCodec:i,channels:n}=t;return!(void 0!==i&&(e.audioCodec||"").substring(0,4)!==i.substring(0,4)||void 0!==n&&n!==(e.channels||"2"))}function ts(t,e,i){for(let n=e;n>-1;n--)if(i(t[n]))return n;for(let n=e+1;n<t.length;n++)if(i(t[n]))return n;return-1}function es(t,e){var i;return!!t&&t!==(null==(i=e.loadLevelObj)?void 0:i.uri)}function is(t,e){return!e||-1!==e.indexOf(t)}function ns(t,e){if(e||t){const i=Di({},e);return t&&(t.videoCodec&&(i.videoCodec=t.videoCodec),t.videoRange&&(i.allowedVideoRanges=[t.videoRange])),i}}const rs=function(t,e){let i=0,n=t.length-1,r=null,s=null;for(;i<=n;){r=(i+n)/2|0,s=t[r];const a=e(s);if(a>0)i=r+1;else{if(!(a<0))return s;n=r-1}}return null};function ss(t,e,i=0,n=0,r=.005){let s=null;if(t){s=e[1+t.sn-e[0].sn]||null;const n=t.endDTS-i;n>0&&n<15e-7&&(i+=15e-7),s&&t.level!==s.level&&s.end<=t.end&&(s=e[2+t.sn-e[0].sn]||null)}else 0===i&&0===e[0].start&&(s=e[0]);if(s&&((!t||t.level===s.level)&&0===as(i,n,s)||function(t,e,i){if(0===(null==e?void 0:e.start)&&e.level<t.level&&(e.endPTS||0)>0){const n=e.tagList.reduce((t,e)=>("INF"===e[0]&&(t+=parseFloat(e[1])),t),i);return t.start<=n}return!1}(s,t,Math.min(r,n))))return s;const a=rs(e,as.bind(null,i,n));return!a||a===t&&s?s:a}function as(t=0,e=0,i){if(i.start<=t&&i.start+i.duration>t)return 0;const n=Math.min(e,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-n<=t?1:i.start-n>t&&i.start?-1:0}function os(t,e,i){const n=1e3*Math.min(e,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-n>t}function ls(t,e,i){if(t&&t.startCC<=e&&t.endCC>=e){let n=t.fragments;const{fragmentHint:r}=t;let s;return r&&(n=n.concat(r)),rs(n,t=>t.cc<e?1:t.cc>e?-1:(s=t,t.end<=i?1:t.start>i?-1:0)),s||null}return null}function hs(t,e,i){return i&&e===t.endSN&&t.fragmentHint?t.fragmentHint:t.fragments[1+e-t.startSN]||null}var cs=0,us=2,ds=3,fs=5,gs=0,ps=1,ms=2,vs=4,ys=8,As=16;function Es(t){const e=t.details;return e===ei.BUFFER_ADD_CODEC_ERROR||e===ei.MEDIA_SOURCE_REQUIRES_RESET||e===ei.BUFFER_APPEND_ERROR&&!Ts(t)}function Ts(t){return t.details===ei.BUFFER_APPEND_ERROR&&("QuotaExceededError"===t.error.name||"InvalidStateError"===t.error.name)}function bs(t){const e={action:cs,flags:gs};return t&&(e.resolved=!0),e}var Ss="NOT_LOADED",ks="APPENDING",_s="PARTIAL",Ls="OK";class Rs{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&&(t.on(ii.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ii.BUFFER_APPENDED,this.onBufferAppended,this),t.on(ii.FRAG_BUFFERED,this.onFragBuffered,this),t.on(ii.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(ii.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ii.BUFFER_APPENDED,this.onBufferAppended,this),t.off(ii.FRAG_BUFFERED,this.onFragBuffered,this),t.off(ii.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=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 n=i[e];if(!n)break;if(n.start<=t&&t<=n.end&&n.loaded)return n}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){return this.getFragAtPos(t,e,!0)}getFragAtPos(t,e,i){const{fragments:n}=this,r=Object.keys(n);for(let s=r.length;s--;){const a=n[r[s]];if((null==a?void 0:a.body.type)===e&&(!i||a.buffered)){const e=a.body;if(e.start<=t&&t<=e.end)return e}}return null}detectEvictedFragments(t,e,i,n,r,s){this.timeRanges&&(this.timeRanges[t]=e);const a=(null==r?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach(r=>{const o=this.fragments[r];if(!o||!this.hls)return;const l=o.body;if(a>=l.sn)return;if(!o.buffered&&(!o.loaded||s))return void(l.type===i&&this.removeFragment(l));const h=o.range[t];if(h)if(0!==h.time.length){if(h.time.some(t=>{const i=!this.isTimeBuffered(t.startPTS,t.endPTS,e);return i&&this.removeFragment(l),i}),n&&n!==l&&dr()){const t=n.endPTS,e=l.startPTS;if(t&&e&&o.range.video){const i=e-t;i<0&&i>-.1&&(this.removeFragment(l),this.hls.trigger(ii.BUFFER_FLUSHING,{startOffset:t+.004,endOffset:1/0,type:"video"}))}}}else this.removeFragment(l)})}detectPartialFragments(t){const e=this.timeRanges,{frag:i,part:n,id:r}=t;if(!e||!ki(i))return;const s=Cs(i),a=this.fragments[s];if(!a||a.buffered&&i.gap)return;const o=!i.relurl;Object.keys(e).forEach(t=>{const s=i.elementaryStreams[t];if(!s)return;const l=e[t],h=o||!0===s.partial;a.range[t]=this.getBufferedTimes(i,n,h,l),this.detectEvictedFragments(t,l,r,i,n)}),a.loaded=null;const l=Object.keys(a.range);if(l.length){if(this.bufferedEnd(a,i),Is(a)||this.removeParts(i.sn-1,i.type),!n){const t=Math.min(.004,i.duration);l.some(e=>{var n;const r=null==(n=a.range[e])?void 0:n.time,s=0===r.length||1===r.length&&r[0].endPTS-r[0].startPTS<t;return s&&this.addAsGap(i),s})}}else this.removeFragment(i)}addAsGap(t){t.gap=!0,this.removeFragment(t),this.fragBuffered(t,!0)}bufferedEnd(t,e){t.buffered=!0;(t.body.endList=e.endList||t.body.endList)&&(this.endListFragments[t.body.type]=t)}removeParts(t,e){const i=this.activePartLists[e];i&&(this.activePartLists[e]=Ps(i,e=>e.fragment.sn>=t))}fragBuffered(t,e){const i=Cs(t);let n=this.fragments[i];return!n&&e&&(n=this.fragments[i]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),n&&(n.loaded=null,this.bufferedEnd(n,t)),n}getBufferedTimes(t,e,i,n){const r={time:[],partial:i},s=t.start,a=t.end,o=t.minEndPTS||a,l=t.maxStartPTS||s;for(let t=0;t<n.length;t++){const e=n.start(t)-this.bufferPadding,i=n.end(t)+this.bufferPadding;if(l>=e&&o<=i){r.time.push({startPTS:Math.max(s,n.start(t)),endPTS:Math.min(a,n.end(t))});break}if(s<i&&a>e){const e=Math.max(s,n.start(t)),i=Math.min(a,n.end(t));i>e&&(r.partial=!0,r.time.push({startPTS:e,endPTS:i}))}else if(a<=e)break}return r}getPartialFragment(t){let e,i,n,r=null,s=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach(l=>{const h=o[l];h&&Is(h)&&(i=h.body.start-a,n=h.body.end+a,t>=i&&t<=n&&(e=Math.min(t-i,n-t),s<=e&&(r=h.body,s=e)))}),r}isEndListAppended(t){const e=this.endListFragments[t];return void 0!==e&&(e.buffered||Is(e))}getState(t){const e=Cs(t),i=this.fragments[e];return i?i.buffered?Is(i)?_s:Ls:ks:Ss}isTimeBuffered(t,e,i){let n,r;for(let s=0;s<i.length;s++){if(n=i.start(s)-this.bufferPadding,r=i.end(s)+this.bufferPadding,t>=n&&e<=r)return!0;if(e<=n)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(t,e){if(!ki(e.frag)||e.frag.bitrateTest)return;const i=e.frag,n=e.part?null:e,r=Cs(i);this.fragments[r]={body:i,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:i,part:n,timeRanges:r}=e;if(!ki(i))return;const s=i.type;if(n){let t=this.activePartLists[s];t||(this.activePartLists[s]=t=[]),t.push(n)}this.timeRanges=r}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=Cs(t);return!!this.fragments[e]}hasFragments(t){const{fragments:e}=this,i=Object.keys(e);if(!t)return i.length>0;for(let n=i.length;n--;){const r=e[i[n]];if((null==r?void 0:r.body.type)===t)return!0}return!1}hasParts(t){var e;return!(null==(e=this.activePartLists[t])||!e.length)}getBackBufferEvictionEnd(t,e,i){const{fragments:n}=this;let r=0,s=0;const a=Object.keys(n);for(let o=0;o<a.length;o++){const l=n[a[o]];if(!l||!l.buffered||l.body.type!==e)continue;const h=l.body;if(h.gap)return 0;const c=h.hasStats&&h.stats.loaded||h.byteLength||h.bitrate&&8*h.bitrate*h.duration;if(h.end<=t&&c&&(r+=c,s=Math.max(s,h.end),r>=i))return s}return s>0?s:0}removeFragmentsInRange(t,e,i,n,r){n&&!this.hasGaps||Object.keys(this.fragments).forEach(s=>{const a=this.fragments[s];if(!a)return;const o=a.body;o.type!==i||n&&!o.gap||o.start<e&&o.end>t&&(a.buffered||r)&&this.removeFragment(o)})}removeFragment(t){const e=Cs(t);t.clearElementaryStreamInfo();const i=this.activePartLists[t.type];if(i){const e=t.sn;this.activePartLists[t.type]=Ps(i,t=>t.fragment.sn!==e)}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){var t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const e=null==(t=this.hls)||null==(t=t.latestLevelDetails)?void 0:t.partList;e&&e.forEach(t=>t.clearElementaryStreamInfo())}}function Is(t){var e,i,n,r;return t.buffered&&!!(t.body.gap||null!=(e=t.range.video)&&e.partial||null!=(i=t.range.audio)&&i.partial||null!=(n=t.range.audiovideo)&&n.partial||null!=(r=t.range.subs)&&r.partial)}function Cs(t){return`${t.type}_${t.level}_${t.sn}`}function Ps(t,e){return t.filter(t=>{const i=e(t);return i||t.clearElementaryStreamInfo(),i})}var Ds=0,ws=1;class Os{constructor(t,e,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=e,this.aesMode=i}decrypt(t,e){switch(this.aesMode){case Ds:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t);case ws:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},e,t);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}class xs{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,n=i[0],r=i[1],s=i[2],a=i[3],o=this.invSubMix,l=o[0],h=o[1],c=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 v=257*d[i]^16843008*i;n[f]=v<<24|v>>>8,r[f]=v<<16|v>>>16,s[f]=v<<8|v>>>24,a[f]=v,v=16843009*m^65537*p^257*o^16843008*f,l[i]=v<<24|v>>>8,h[i]=v<<16|v>>>16,c[i]=v<<8|v>>>24,u[i]=v,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,n=0;for(;n<e.length&&i;)i=e[n]===this.key[n],n++;if(i)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 s=this.ksRows=4*(r+6+1);let a,o;const l=this.keySchedule=new Uint32Array(s),h=this.invKeySchedule=new Uint32Array(s),c=this.sBox,u=this.rcon,d=this.invSubMix,f=d[0],g=d[1],p=d[2],m=d[3];let v,y;for(a=0;a<s;a++)a<r?v=l[a]=e[a]:(y=v,a%r===0?(y=y<<8|y>>>24,y=c[y>>>24]<<24|c[y>>>16&255]<<16|c[y>>>8&255]<<8|c[255&y],y^=u[a/r|0]<<24):r>6&&a%r===4&&(y=c[y>>>24]<<24|c[y>>>16&255]<<16|c[y>>>8&255]<<8|c[255&y]),l[a]=v=(l[a-r]^y)>>>0);for(o=0;o<s;o++)a=s-o,y=3&o?l[a]:l[a-4],h[o]=o<4||a<=4?y:f[c[y>>>24]]^g[c[y>>>16&255]]^p[c[y>>>8&255]]^m[c[255&y]],h[o]=h[o]>>>0}networkToHostOrderSwap(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24}decrypt(t,e,i){const n=this.keySize+6,r=this.invKeySchedule,s=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],h=a[2],c=a[3],u=this.uint8ArrayToUint32Array_(i);let d=u[0],f=u[1],g=u[2],p=u[3];const m=new Int32Array(t),v=new Int32Array(m.length);let y,A,E,T,b,S,k,_,L,R,I,C,P,D;const w=this.networkToHostOrderSwap;for(;e<m.length;){for(L=w(m[e]),R=w(m[e+1]),I=w(m[e+2]),C=w(m[e+3]),b=L^r[0],S=C^r[1],k=I^r[2],_=R^r[3],P=4,D=1;D<n;D++)y=o[b>>>24]^l[S>>16&255]^h[k>>8&255]^c[255&_]^r[P],A=o[S>>>24]^l[k>>16&255]^h[_>>8&255]^c[255&b]^r[P+1],E=o[k>>>24]^l[_>>16&255]^h[b>>8&255]^c[255&S]^r[P+2],T=o[_>>>24]^l[b>>16&255]^h[S>>8&255]^c[255&k]^r[P+3],b=y,S=A,k=E,_=T,P+=4;y=s[b>>>24]<<24^s[S>>16&255]<<16^s[k>>8&255]<<8^s[255&_]^r[P],A=s[S>>>24]<<24^s[k>>16&255]<<16^s[_>>8&255]<<8^s[255&b]^r[P+1],E=s[k>>>24]<<24^s[_>>16&255]<<16^s[b>>8&255]<<8^s[255&S]^r[P+2],T=s[_>>>24]<<24^s[b>>16&255]<<16^s[S>>8&255]<<8^s[255&k]^r[P+3],v[e]=w(y^d),v[e+1]=w(T^f),v[e+2]=w(E^g),v[e+3]=w(A^p),d=L,f=R,g=I,p=C,e+=4}return v.buffer}}class Ms{constructor(t,e,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=t,this.key=e,this.aesMode=i}expandKey(){const t=function(t){switch(t){case Ds:return"AES-CBC";case ws:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${t}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:t},!1,["encrypt","decrypt"])}}class Ns{constructor(t,e){if(this.logEnabled=!0,this.decryptRange=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=t.enableSoftwareAES,!0!==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);this.reset();const n=this.decryptRange;return n?0===n.start&&n.end>=i.length?i:i.slice(n.start,n.end):function(t){const e=t.byteLength,i=e&&new DataView(t.buffer).getUint8(e-1);return i?t.slice(0,e-i):t}(i)}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,e,i,n,r){return this.decryptRange=r,this.useSoftware||r?new Promise((r,s)=>{const a=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(a,e,i,n);const o=this.flush();o?r(o.buffer):s(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(t),e,i,n)}softwareDecrypt(t,e,i,n){const{currentIV:r,currentResult:s,remainderData:a}=this;if(n!==Ds||16!==e.byteLength)return Zi.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(t=Zn(a,t),this.remainderData=null);const o=this.getValidChunk(t);if(!o.length)return null;r&&(i=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new xs),l.expandKey(e);const h=s;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=o.slice(-16).buffer,h||null}webCryptoDecrypt(t,e,i,n){if(this.key!==e||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,e,i,n));this.key=e,this.fastAesKey=new Ms(this.subtle,e,n)}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 Os(this.subtle,new Uint8Array(i),n).decrypt(t.buffer,e)}).catch(r=>(Zi.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(t,e,i,n)))}onWebCryptoError(t,e,i,n){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,i,n);const r=this.flush();if(r)return r.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(t){let e=t;const i=t.length-t.length%16;return i!==t.length&&(e=t.slice(0,i),this.remainderData=t.slice(i)),e}logOnce(t){this.logEnabled&&(Zi.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const Fs=Math.pow(2,17);class Bs{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,i,n){const r=t.url;if(!r)return Promise.reject(new Vs({type:ti.NETWORK_ERROR,details:ei.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error("Fragment does not have a "+(r?"part list":"url")),networkDetails:null}));this.abort();const s=this.config,a=s.fLoader,o=s.loader;return new Promise((l,h)=>{if(this.loader&&this.loader.destroy(),t.gap){if(t.tagList.some(t=>"GAP"===t[0]))return void h(Gs(t));t.gap=!1}const c=this.loader=a?new a(s):new o(s),u=$s(t,null,e);t.loader=c;const d=Ui(s.fragLoadPolicy.default),f={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:Fs};c.stats.retry=t.stats.retry,t.stats=c.stats;const g={onSuccess:(e,i,n,r)=>{this.resetLoader(t,c);let s=e.data;n.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(s.slice(0,16)),s=s.slice(16)),l({frag:t,part:null,payload:s,networkDetails:r})},onError:(e,i,n,s)=>{this.resetLoader(t,c),h(new Vs({type:ti.NETWORK_ERROR,details:ei.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:Oi({url:r,data:void 0},e),error:new Error(`HTTP Error ${e.code} ${e.text}`),networkDetails:n,stats:s}))},onAbort:(e,i,n)=>{this.resetLoader(t,c),h(new Vs({type:ti.NETWORK_ERROR,details:ei.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:n,stats:e}))},onTimeout:(e,i,n)=>{this.resetLoader(t,c),h(new Vs({type:ti.NETWORK_ERROR,details:ei.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${f.timeout}ms`),networkDetails:n,stats:e}))}};if(i){const e=this.gateProgress(i,n);g.onProgress=(i,n,r,s)=>e({frag:t,part:null,payload:r,networkDetails:s})}c.load(u,f,g)})}gateProgress(t,e){let i=t;if(e){const n=[];let r=!1;e.then(()=>{r=!0,n.forEach(e=>t(e)),n.length=0}).catch(()=>{}),i=e=>{r?t(e):n.push(e)}}return i}loadPart(t,e,i){this.abort();const n=this.config,r=n.fLoader,s=n.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap)return void o(Gs(t,e));const l=this.loader=r?new r(n):new s(n),h=$s(t,e);t.loader=l;const c=Ui(n.fragLoadPolicy.default),u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Fs};e.stats=l.stats,l.load(h,u,{onSuccess:(n,r,s,o)=>{this.resetLoader(t,l),this.updateStatsFromPart(t,e);const h={frag:t,part:e,payload:n.data,networkDetails:o};i(h),a(h)},onError:(i,n,r,s)=>{this.resetLoader(t,l),o(new Vs({type:ti.NETWORK_ERROR,details:ei.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:Oi({url:h.url,data:void 0},i),error:new Error(`HTTP Error ${i.code} ${i.text}`),networkDetails:r,stats:s}))},onAbort:(i,n,r)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,l),o(new Vs({type:ti.NETWORK_ERROR,details:ei.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:r,stats:i}))},onTimeout:(i,n,r)=>{this.resetLoader(t,l),o(new Vs({type:ti.NETWORK_ERROR,details:ei.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:r,stats:i}))}})})}updateStatsFromPart(t,e){const i=t.stats,n=e.stats,r=n.total;if(i.loaded+=n.loaded,r){const n=Math.round(t.duration/e.duration),s=Math.min(Math.round(i.loaded/r),n),a=(n-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=n.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,t.url=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()}}function $s(t,e=null,i){const n={type:di,frag:t,part:e,responseType:"arraybuffer",url:(e||t).url,headers:{},rangeStart:0,rangeEnd:0},r=Us(t,e,i);return r.resetIV&&(n.resetIV=!0),r.byteRange&&(n.rangeStart=r.byteRange.start,n.rangeEnd=r.byteRange.end),n}function Us(t,e=null,i){const n={},r=e||t,s=r.byteRangeStartOffset,a=r.byteRangeEndOffset;var o,l;if(Qe(s)&&Qe(a))if("initSegment"!==t.sn&&!i||"AES-128"!==(l=null==(o=t.decryptdata)?void 0:o.method)&&"AES-256"!==l)n.byteRange={start:s,end:a};else{let t=16*Math.floor(s/16);const e=16*Math.ceil(a/16);n.decryptRange={start:s-t,end:a-t},t>=16&&(n.resetIV=!0,t-=16),n.byteRange={start:t,end:e}}return n}function Gs(t,e){const i=new Error(`GAP ${t.gap?"tag":"attribute"} found`),n={type:ti.MEDIA_ERROR,details:ei.FRAG_GAP,fatal:!1,frag:t,error:i,networkDetails:null};return e&&(n.part=e),(e||t).stats.aborted=!0,new Vs(n)}class Vs extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class Ks extends ji{constructor(t,e){super(t,e),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):(this.log(`possible exception thrown in task-loop (${this.constructor.name}.doTick)`),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class Hs{constructor(t,e,i,n=0,r=-1,s=!1,a,o,l){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.iframe=void 0,this.duration=void 0,this.decryptRange=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=n,this.part=r,this.partial=s,this.duration=a||0,this.decryptRange=l,this.iframe=o||!1}}const Ys={length:0,start:()=>0,end:()=>0};class js{static isBuffered(t,e){if(t){const i=js.getBuffered(t);for(let t=i.length;t--;)if(e>=i.start(t)&&e<=i.end(t))return!0}return!1}static bufferedRanges(t){if(t){const e=js.getBuffered(t);return js.timeRangesToArray(e)}return[]}static timeRangesToArray(t){const e=[];for(let i=0;i<t.length;i++)e.push({start:t.start(i),end:t.end(i)});return e}static bufferInfo(t,e,i){if(t){const n=js.bufferedRanges(t);if(n.length)return js.bufferedInfo(n,e,i)}return{len:0,start:e,end:e,bufferedIndex:-1}}static bufferedInfo(t,e,i){e=Math.max(0,e),t.length>1&&t.sort((t,e)=>t.start-e.start||e.end-t.end);let n=-1,r=[];if(i)for(let s=0;s<t.length;s++){e>=t[s].start&&e<=t[s].end&&(n=s);const a=r.length;if(a){const e=r[a-1].end;t[s].start-e<i?t[s].end>e&&(r[a-1].end=t[s].end):r.push(t[s])}else r.push(t[s])}else r=t;let s,a=0,o=e,l=e;for(let t=0;t<r.length;t++){const h=r[t].start,c=r[t].end;if(-1===n&&e>=h&&e<=c&&(n=t),e+i>=h&&e<c)o=h,l=c,a=l-e;else if(e+i<h){s=h;break}}return{len:a,start:o||0,end:l||0,nextStart:s,buffered:t,bufferedIndex:n}}static getBuffered(t){try{return t.buffered||Ys}catch(t){return Zi.log("failed to get media.buffered",t),Ys}}}const Ws=/\{\$([a-zA-Z0-9-_]+)\}/g;function zs(t){return Ws.test(t)}function qs(t,e){if(null!==t.variableList||t.hasVariableRefs){const i=t.variableList;return e.replace(Ws,e=>{const n=e.substring(2,e.length-1),r=null==i?void 0:i[n];return void 0===r?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${n}"`)),e):r})}return e}function Xs(t,e,i){let n,r,s=t.variableList;if(s||(t.variableList=s={}),"QUERYPARAM"in e){n=e.QUERYPARAM;try{const t=new self.URL(i).searchParams;if(!t.has(n))throw new Error(`"${n}" does not match any query parameter in URI: "${i}"`);r=t.get(n)}catch(e){t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${e.message}`))}}else n=e.NAME,r=e.VALUE;n in s?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${n}"`)):s[n]=r||""}function Qs(t,e,i){const n=e.IMPORT;if(i&&n in i){let e=t.variableList;e||(t.variableList=e={}),e[n]=i[n]}else t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${n}"`))}const Zs=/^(\d+)x(\d+)$/,Js=/(.+?)=(".*?"|.*?)(?:,|$)/g;class ta{constructor(t,e){"string"==typeof t&&(t=ta.parseAttrList(t,e)),Di(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]}enumeratedStringList(t,e){const i=this[t];return(i?i.split(/[ ,]+/):[]).reduce((t,e)=>(t[e.toLowerCase()]=!0,t),e)}bool(t){return"YES"===this[t]}decimalResolution(t){const e=Zs.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t,e){let i;const n={};for(Js.lastIndex=0;null!==(i=Js.exec(t));){const r=i[1].trim();let s=i[2];const a=0===s.indexOf('"')&&s.lastIndexOf('"')===s.length-1;let o=!1;if(a)s=s.slice(1,-1);else switch(r){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(e&&(a||o))s=qs(e,s);else if(!o&&!a)switch(r){case"CLOSED-CAPTIONS":if("NONE"===s)break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":Zi.warn(`${t}: attribute ${r} is missing quotes`)}n[r]=s}return n}}function ea(t){return"ID"!==t&&"CLASS"!==t&&"CUE"!==t&&"START-DATE"!==t&&"DURATION"!==t&&"END-DATE"!==t&&"END-ON-NEXT"!==t}function ia(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t||"SCTE35-CMD"===t}class na{constructor(t,e,i=0){var n;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==e?void 0:e.tagAnchor)||null,this.tagOrder=null!=(n=null==e?void 0:e.tagOrder)?n:i,e){const i=e.attr;for(const e in i)if(Object.prototype.hasOwnProperty.call(t,e)&&t[e]!==i[e]){Zi.warn(`DATERANGE tag attribute: "${e}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=e;break}t=Di(new ta({}),i,t)}if(this.attr=t,e?(this._startDate=e._startDate,this._cue=e._cue,this._endDate=e._endDate,this._dateAtEnd=e._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in t){const i=(null==e?void 0:e.endDate)||new Date(t["END-DATE"]);Qe(i.getTime())&&(this._endDate=i)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const t=this._cue;return void 0===t?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):t}get startTime(){const{tagAnchor:t}=this;return null===t||null===t.programDateTime?(Zi.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${t}`),NaN):t.start+(this.startDate.getTime()-t.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const t=this._endDate||this._dateAtEnd;if(t)return t;const e=this.duration;return null!==e?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*e):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(Qe(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 isInterstitial(){return"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&Qe(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}get invalidReason(){return this.id?this._badValueForSameId?`Date range ${this._badValueForSameId} mismatch`:Qe(this.startDate.getTime())?!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr?this.isValid?null:"Unknown (check DURATION(|END|NEXT), CLASS, and CUE)":"Interstitial Date range missing X-ASSET-(LIST|URI)":"Date range invalid start date":"Missing ID"}}class ra{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.dateRangeTagCount=0,this.live=!0,this.iframesOnly=!1,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=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=0:this.misses=t.misses+1}hasKey(t){return this.encryptedFragments.some(e=>{let i=e.decryptdata;return i||(e.setKeyFormat(t.keyFormat),i=e.decryptdata),!!i&&t.matches(i)})}get hasProgramDateTime(){return!!this.fragments.length&&Qe(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(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const t=this.partList;if(t){const e=this.lastPartIndex;if(-1!==e){for(let i=t.length;i--;)if(t[i].index>e)return t[i].index;return e}}return 0}get lastPartSn(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const t=this.partEnd-this.fragmentStart;return this.age>Math.max(t,this.totalduration)+this.levelTargetDuration}return!1}}function sa(t,e){return t.length===e.length&&!t.some((t,i)=>t!==e[i])}function aa(t,e){return!t&&!e||!(!t||!e)&&sa(t,e)}function oa(t){return"AES-128"===t||"AES-256"===t||"AES-256-CTR"===t}function la(t){switch(t){case"AES-128":case"AES-256":return Ds;case"AES-256-CTR":return ws;default:throw new Error(`invalid full segment method ${t}`)}}function ha(t){return Uint8Array.from(unescape(encodeURIComponent(t)),t=>t.charCodeAt(0))}function ca(t){const e=function(t,e,i){const n=t[e];t[e]=t[i],t[i]=n};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}function ua(t){const e=t.split(":");let i=null;if("data"===e[0]&&2===e.length){const t=e[1].split(";"),n=t[t.length-1].split(",");if(2===n.length){const e="base64"===n[0],r=n[1];e?(t.splice(-1,1),i=kn(r)):i=function(t){const e=ha(t).subarray(0,16),i=new Uint8Array(16);return i.set(e,16-e.length),i}(r)}}return i}const da="undefined"!=typeof self?self:void 0;var fa={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},ga="org.w3.clearkey",pa="com.apple.streamingkeydelivery",ma="com.microsoft.playready",va="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function ya(t){switch(t){case pa:return fa.FAIRPLAY;case ma:return fa.PLAYREADY;case va:return fa.WIDEVINE;case ga:return fa.CLEARKEY}}var Aa="edef8ba979d64acea3c827dcd51d21ed";function Ea(t){switch(t){case fa.FAIRPLAY:return pa;case fa.PLAYREADY:return ma;case fa.WIDEVINE:return va;case fa.CLEARKEY:return ga}}function Ta(t){const{drmSystems:e,widevineLicenseUrl:i}=t,n=e?[fa.FAIRPLAY,fa.WIDEVINE,fa.PLAYREADY,fa.CLEARKEY].filter(t=>!!e[t]):[];return!n[fa.WIDEVINE]&&i&&n.push(fa.WIDEVINE),n}const ba=null!=da&&null!=(Sa=da.navigator)&&Sa.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var Sa;function ka(t){const e=_n(new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2)),i=e.substring(e.indexOf("<"),e.length),n=(new DOMParser).parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(n){const t=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(t){const e=kn(t).subarray(0,16);return ca(e),e}}return null}let _a={};class La{static clearKeyUriToKeyIdMap(){_a={}}static setKeyIdForUri(t,e){_a[t]=e}static addKeyIdForUri(t){const e=Object.keys(_a).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,e),_a[t]=i,i}constructor(t,e,i,n=[1],r=null,s){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.scheme=void 0,this.method=t,this.uri=e,this.keyFormat=i,this.keyFormatVersions=n,this.iv=r,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&!oa(t),null!=s&&s.startsWith("0x")&&(this.keyId=new Uint8Array(Sn(s)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&sa(t.keyFormatVersions,this.keyFormatVersions)&&aa(t.iv,this.iv)&&aa(t.keyId,this.keyId)}isSupported(){if(this.method){if(oa(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case pa:case va:case ma:case ga:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(t,e){var i;if(!this.encrypted||!this.uri)return null;if(oa(this.method)){let e=this.iv;e||("number"!=typeof t&&(Zi.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),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 La(this.method,this.uri,"identity",this.keyFormatVersions,e)}if(this.keyId){const t=_a[this.uri];if(t&&!sa(this.keyId,t)&&La.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const n=ua(this.uri);if(n)switch(this.keyFormat){case va:if(this.pssh=n,!this.keyId){const t=rr(n.buffer).filter(t=>t.systemId===Aa);if(t.length){var r;const e=t[0];this.keyId=null!=(r=e.kids)&&r.length?e.kids[0]:null}}this.keyId||(this.keyId=Ra(e));break;case ma:{const t=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=nr(t,0,n),this.keyId=ka(n);break}default:{let t=n.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(16!==(null==(i=this.keyId)?void 0:i.byteLength)){let t;t=function(t){const e=null==t?void 0:t[va];if(e)return e.keyId;return null}(e),t||(t=Ra(e),t||(t=_a[this.uri])),t&&(this.keyId=t,La.setKeyIdForUri(this.uri,t))}return this}}function Ra(t){const e=null==t?void 0:t[ma];if(e){const t=ua(e.uri);if(t)return ka(t)}return null}const Ia=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(I-FRAME-STREAM-INF|SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)(?:[\r\n]+|$)/g,Ca=/#EXT-X-MEDIA:(.*)/g,Pa=/^#EXT(?:INF|-X-TARGETDURATION):/m,Da=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),wa=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS|I-FRAMES-ONLY)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class Oa{static findGroup(t,e){for(let i=0;i<t.length;i++){const n=t[i];if(n.id===e)return n}}static resolve(t,e){return ai.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return Pa.test(t)}static parseMasterPlaylist(t,e){const i={contentSteering:null,levels:[],iframeVariants:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:zs(t)},n=[];if(Ia.lastIndex=0,!t.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let r;for(;null!=(r=Ia.exec(t));)if(r[1]){const t=xa(new ta(r[1],i),r[2],e,i,n);t&&i.levels.push(t)}else if(r[3]){const t=r[3],s=r[4];switch(t){case"I-FRAME-STREAM-INF":{const t=new ta(s,i),r=xa(t,t.URI,e,i,n,!0);r&&i.iframeVariants.push(r)}break;case"SESSION-DATA":{const t=new ta(s,i),e=t["DATA-ID"];e&&(null===i.sessionData&&(i.sessionData={}),i.sessionData[e]=t);break}case"SESSION-KEY":{const t=Fa(s,e,i);t.encrypted&&t.isSupported()?(null===i.sessionKeys&&(i.sessionKeys=[]),i.sessionKeys.push(t)):Zi.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${s}"`);break}case"DEFINE":Xs(i,new ta(s,i),e);break;case"CONTENT-STEERING":{const t=new ta(s,i);i.contentSteering={uri:Oa.resolve(t["SERVER-URI"],e),pathwayId:t["PATHWAY-ID"]||"."};break}case"START":i.startTimeOffset=Ba(s)}}const s=n.length>0&&n.length<i.levels.length;return i.levels=s?n:i.levels,0===i.levels.length&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(t,e,i){let n;const r={},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(Ca.lastIndex=0;null!==(n=Ca.exec(t));){const t=new ta(n[1],i),s=t.TYPE;if(s){const i=a[s],n=r[s]||[];r[s]=n;const l=t.LANGUAGE,h=t["ASSOC-LANGUAGE"],c=t.CHANNELS,u=t.CHARACTERISTICS,d=t["INSTREAM-ID"],f={attrs:t,bitrate:0,id:o++,groupId:t["GROUP-ID"]||"",name:t.NAME||l||"",type:s,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:l,url:t.URI?Oa.resolve(t.URI,e):""};if(h&&(f.assocLang=h),c&&(f.channels=c),u&&(f.characteristics=u),d&&(f.instreamId=d),null!=i&&i.length){const t=Oa.findGroup(i,f.groupId)||i[0];Ua(f,t,"audioCodec"),Ua(f,t,"textCodec")}n.push(f)}}return r}static parseLevelPlaylist(t,e,i,n,r,s){var a;const o={url:e},l=new ra(e),h=l.fragments,c=[];let u,d,f,g,p=null,m=0,v=0,y=0,A=0,E=0,T=null,b=new Ri(n,o),S=-1,k=!1,_=null;if(Da.lastIndex=0,l.m3u8=t,l.hasVariableRefs=zs(t),"#EXTM3U"!==(null==(a=Da.exec(t))?void 0:a[0]))return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;null!==(u=Da.exec(t));){k&&(k=!1,b=new Ri(n,o),b.playlistOffset=y,b.setStart(y),b.sn=m,b.cc=A,E&&(b.bitrate=E),b.level=i,p&&(b.initSegment=p,p.rawProgramDateTime&&(b.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null),_&&(b.setByteRange(_),_=null)));const t=u[1];if(t){b.duration=parseFloat(t);const e=(" "+u[2]).slice(1);b.title=e||null,b.tagList.push(e?["INF",t,e]:["INF",t])}else if(u[3]){if(Qe(b.duration)){var L;b.playlistOffset=y,b.setStart(y),f&&Ka(b,f,l),b.sn=m,b.level=i,b.cc=A;const t=(" "+u[3]).slice(1);b.relurl=qs(l,t),Ga(b,T,c),T=b,y+=b.duration,m++,v=0;const e=b.byteRange;if(2===e.length&&(b.bitrate=8*(e[1]-e[0])/b.duration|0),l.iframesOnly&&e[0]&&(null==(L=p)?void 0:L.cc)!==A){const t=new Ri(n,o);t.relurl=b.relurl,t.setByteRange(`${Math.min(e[0],1316)}@0`),t.level=i,t.sn="initSegment",f&&(t.levelkeys=f,f.identity&&(t._decryptdata=f.identity.getDecryptData(0))),p=t,b.initSegment=p}h.push(b),k=!0}}else{if(u=u[0].match(wa),!u){Zi.warn("No matches on slow regex match for level playlist!");continue}for(d=1;d<u.length&&void 0===u[d];d++);const t=(" "+u[d]).slice(1),r=(" "+u[d+1]).slice(1),a=u[d+2]?(" "+u[d+2]).slice(1):null;switch(t){case"BYTERANGE":T?b.setByteRange(r,T):b.setByteRange(r);break;case"PROGRAM-DATE-TIME":b.rawProgramDateTime=r,b.tagList.push(["PROGRAM-DATE-TIME",r]),-1===S&&(S=h.length);break;case"PLAYLIST-TYPE":l.type&&Ha(l,t,u),l.type=r.toUpperCase();break;case"MEDIA-SEQUENCE":0!==l.startSN?Ha(l,t,u):null!==T&&Ya(l,t,u),l.startSN=parseInt(r),m=l.startSN+l.skippedSegments;break;case"SKIP":{l.skippedSegments&&Ha(l,t,u);const e=new ta(r,l),i=e.decimalInteger("SKIPPED-SEGMENTS");if(Qe(i)){l.skippedSegments+=i;for(let t=i;t--;)h.push(null);m+=i}const n=e.enumeratedString("RECENTLY-REMOVED-DATERANGES");n&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(n.split("\t")));break}case"TARGETDURATION":0!==l.targetduration&&Ha(l,t,u),l.targetduration=Math.max(parseInt(r),1);break;case"VERSION":null!==l.version&&Ha(l,t,u),l.version=parseInt(r);break;case"INDEPENDENT-SEGMENTS":break;case"I-FRAMES-ONLY":l.iframesOnly=!0;break;case"ENDLIST":l.live||Ha(l,t,u),l.live=!1;break;case"#":(r||a)&&b.tagList.push(a?[r,a]:[r]);break;case"DISCONTINUITY":A++,b.tagList.push(["DIS"]);break;case"GAP":b.gap=!0,b.tagList.push([t]);break;case"BITRATE":b.tagList.push([t,r]),E=1e3*parseInt(r),Qe(E)?b.bitrate=E:E=0;break;case"DATERANGE":{const t=new ta(r,l),e=new na(t,l.dateRanges[t.ID],l.dateRangeTagCount);l.dateRangeTagCount++,e.isValid||l.skippedSegments?l.dateRanges[e.id]=e:Zi.log(`Ignoring invalid DATERANGE tag: ${e.invalidReason}: ${r}`),b.tagList.push(["EXT-X-DATERANGE",r]);break}case"DEFINE":{const t=new ta(r,l);"IMPORT"in t?Qs(l,t,s):Xs(l,t,e)}break;case"DISCONTINUITY-SEQUENCE":0!==l.startCC&&Ha(l,t,u),l.startCC=A=parseInt(r),h.forEach(t=>t&&(t.cc=A));break;case"KEY":{const t=Fa(r,e,l);if(t.isSupported()){if("NONE"===t.method){f=void 0;break}f||(f={});const e=f[t.keyFormat];null!=e&&e.matches(t)||(e&&(f=Di({},f)),f[t.keyFormat]=t)}else Zi.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${r}"`);break}case"START":l.startTimeOffset=Ba(r);break;case"MAP":{const t=new ta(r,l);if(b.duration){const e=new Ri(n,o);Va(e,t,i,f),p=e,b.initSegment=p,p.rawProgramDateTime&&!b.rawProgramDateTime&&(b.rawProgramDateTime=p.rawProgramDateTime)}else{const e=b.byteRangeEndOffset;if(e){const t=b.byteRangeStartOffset;_=`${e-t}@${t}`}else _=null;Va(b,t,i,f),p=b,k=!0}p.cc=A;break}case"SERVER-CONTROL":g&&Ha(l,t,u),g=new ta(r),l.canBlockReload=g.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=g.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&g.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=g.optionalFloat("PART-HOLD-BACK",0),l.holdBack=g.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{l.partTarget&&Ha(l,t,u);const e=new ta(r);l.partTarget=e.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=l.partList;t||(t=l.partList=[]);const e=v>0?t[t.length-1]:void 0,i=v++,n=new ta(r,l),s=new Ii(n,b,o,i,e);t.push(s),b.duration+=s.duration;break}case"PRELOAD-HINT":{const t=new ta(r,l);l.preloadHint=t;break}case"RENDITION-REPORT":{const t=new ta(r,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(t);break}default:Zi.warn(`line parsed but not handled: ${u}`)}}}T&&!T.relurl?(h.pop(),y-=T.duration,l.partList&&(l.fragmentHint=T)):l.partList&&(Ga(b,T,c),b.cc=A,l.fragmentHint=b,f&&Ka(b,f,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const R=h.length,I=h[0],C=h[R-1];if(y+=l.skippedSegments*l.targetduration,y>0&&R&&C){l.averagetargetduration=y/R;const t=C.sn;l.endSN="initSegment"!==t?t:0,l.live||(C.endList=!0),S>0&&(!function(t,e,i){if(i||(i=t[e]),!i)return;for(let n=e;n--;){const e=t[n];if(!e)return;e.programDateTime=i.programDateTime-1e3*e.duration,i=e}}(h,S,S>R-1?b:null),I&&c.unshift(I))}return l.fragmentHint&&(y+=l.fragmentHint.duration),l.totalduration=y,c.length&&l.dateRangeTagCount&&I&&Ma(c,l),l.endCC=A,l}}function xa(t,e,i,n,r,s){var a;if(void 0===e)return null;const o=qs(n,e),l={attrs:t,bitrate:t.decimalInteger("BANDWIDTH")||t.decimalInteger("AVERAGE-BANDWIDTH"),name:t.NAME,url:Oa.resolve(o,i)},h=t.decimalResolution("RESOLUTION");h&&(l.width=h.width,l.height=h.height),$a(t.CODECS,l);const c=t["SUPPLEMENTAL-CODECS"];return c&&(l.supplemental={},$a(c,l.supplemental)),null!=(a=l.unknownCodecs)&&a.length||r.push(l),s&&(l.iframes=!0),l}function Ma(t,e){let i=t.length;if(!i){if(!e.hasProgramDateTime)return;{const n=e.fragments[e.fragments.length-1];t.push(n),i++}}const n=t[i-1],r=e.live?1/0:e.totalduration,s=Object.keys(e.dateRanges);for(let o=s.length;o--;){const l=e.dateRanges[s[o]],h=l.startDate.getTime();l.tagAnchor=n.ref;for(let n=i;n--;){var a;if((null==(a=t[n])?void 0:a.sn)<e.startSN)break;const i=Na(e,h,t,n,r);if(-1!==i){l.tagAnchor=e.fragments[i].ref;break}}}}function Na(t,e,i,n,r){const s=i[n];if(s){const o=s.programDateTime;if(e>=o||0===n){var a;if(e<=o+1e3*(((null==(a=i[n+1])?void 0:a.start)||r)-s.start)){const r=i[n].sn-t.startSN;if(r<0)return-1;const s=t.fragments;if(s.length>i.length){for(let a=(i[n+1]||s[s.length-1]).sn-t.startSN;a>r;a--){const t=s[a].programDateTime;if(e>=t&&e<t+1e3*s[a].duration)return a}}return r}}}return-1}function Fa(t,e,i){var n,r;const s=new ta(t,i),a=null!=(n=s.METHOD)?n:"",o=s.URI,l=s.hexadecimalInteger("IV"),h=s.KEYFORMATVERSIONS,c=null!=(r=s.KEYFORMAT)?r:"identity";o&&s.IV&&!l&&Zi.error(`Invalid IV: ${s.IV}`);const u=o?Oa.resolve(o,e):"",d=(h||"1").split("/").map(Number).filter(Number.isFinite);return new La(a,u,c,d,l,s.KEYID)}function Ba(t){const e=new ta(t).decimalFloatingPoint("TIME-OFFSET");return Qe(e)?e:null}function $a(t,e){let i=(t||"").split(/[ ,]+/).filter(t=>t);["video","audio","text","image"].forEach(t=>{const n=i.filter(e=>pr(e,t));n.length&&(e[`${t}Codec`]=n.map(t=>t.split("/")[0]).join(","),i=i.filter(t=>-1===n.indexOf(t)))}),e.unknownCodecs=i}function Ua(t,e,i){const n=e[i];n&&(t[i]=n)}function Ga(t,e,i){t.rawProgramDateTime?i.push(t):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime)}function Va(t,e,i,n){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=i,t.sn="initSegment",n&&(t.levelkeys=n),t.initSegment=null}function Ka(t,e,i){t.levelkeys=e;const{encryptedFragments:n}=i;n.length&&n[n.length-1].levelkeys===e||!Object.keys(e).some(t=>e[t].isCommonEncryption)||n.push(t)}function Ha(t,e,i){t.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${i[0]})`)}function Ya(t,e,i){t.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${i[0]})`)}function ja(t,e){const i=e.startPTS;if(Qe(i)){let n,r=0;e.sn>t.sn?(r=i-t.start,n=t):(r=t.start-i,n=e),n.duration!==r&&n.setDuration(r)}else if(e.sn>t.sn){t.cc===e.cc&&t.minEndPTS?e.setStart(t.start+(t.minEndPTS-t.start)):e.setStart(t.start+t.duration)}else e.setStart(Math.max(t.start-e.duration,0))}function Wa(t,e,i,n,r,s,a,o){n-i<=0&&(o.warn("Fragment should have a positive duration",e),n=i+e.duration,s=r+e.duration);let l=i,h=n;const c=e.startPTS,u=e.endPTS;if(Qe(c)){const a=Math.abs(c-i);t&&a>t.totalduration?o.warn(`media timestamps and playlist times differ by ${a}s for level ${e.level} ${t.url}`):Qe(e.deltaPTS)?e.deltaPTS=Math.max(a,e.deltaPTS):e.deltaPTS=a,l=Math.max(i,c),i=Math.min(i,c),r=void 0!==e.startDTS?Math.min(r,e.startDTS):r,h=Math.min(n,u),n=Math.max(n,u),s=void 0!==e.endDTS?Math.max(s,e.endDTS):s}const d=i-e.start;0!==e.start&&e.setStart(i),e.setDuration(n-e.start),e.startPTS=i,e.maxStartPTS=l,e.startDTS=r,e.endPTS=n,e.minEndPTS=h,e.endDTS=s;const f=e.sn;if(!t||f<t.startSN||f>t.endSN)return 0;let g;const p=f-t.startSN,m=t.fragments;for(m[p]=e,g=p;g>0;g--)ja(m[g],m[g-1]);for(g=p;g<m.length-1;g++)ja(m[g],m[g+1]);return t.fragmentHint&&ja(m[m.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,d}function za(t,e,i){if(t===e)return;let n=null;const r=t.fragments;for(let t=r.length-1;t>=0;t--){const e=r[t].initSegment;if(e){n=e;break}}let s;t.fragmentHint&&delete t.fragmentHint.endPTS,function(t,e,i){var n;const r=e.skippedSegments,s=Math.max(t.startSN,e.startSN)-e.startSN,a=(t.fragmentHint?1:0)+(r?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,o=e.startSN-t.startSN,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,h=null!=(n=t.fragmentHint)&&n.duration?t.fragments.concat(t.fragmentHint):t.fragments;for(let n=s;n<=a;n++){const s=h[o+n];let a=l[n];if(r&&!a&&s&&(a=e.fragments[n]=s),s&&a){i(s,a,n,l);const r=s.relurl,o=a.relurl;if(r&&io(r,o))return void(e.playlistParsingError=qa(`media sequence mismatch ${a.sn}:`,t,e,s,a));if(s.cc!==a.cc)return void(e.playlistParsingError=qa(`discontinuity sequence mismatch (${s.cc}!=${a.cc})`,t,e,s,a))}}}(t,e,(t,i,r,a)=>{if((!e.startCC||e.skippedSegments)&&i.cc!==t.cc){const n=t.cc-i.cc;for(let t=r;t<a.length;t++)a[t].cc+=n;e.endCC=a[a.length-1].cc}Qe(t.startPTS)&&Qe(t.endPTS)&&(i.setStart(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.setDuration(t.endPTS-t.startPTS),i.duration&&(s=i),e.PTSKnown=e.alignedSliding=!0),t.hasStreams&&(i.elementaryStreams=t.elementaryStreams),i.loader=t.loader,t.hasStats&&(i.stats=t.stats),t.initSegment&&(i.initSegment=t.initSegment,n=t.initSegment)});const a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(n&&o.forEach(t=>{var e;!t||t.initSegment&&t.initSegment.relurl!==(null==(e=n)?void 0:e.relurl)||(t.initSegment=n)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(t=>!t),e.deltaUpdateFailed){i.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let t=e.skippedSegments;t--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=function(t,e,i){const{dateRanges:n,recentlyRemovedDateranges:r}=e,s=Di({},t);r&&r.forEach(t=>{delete s[t]});const a=Object.keys(s).length;if(!a)return n;return Object.keys(n).forEach(t=>{const e=s[t],r=new na(n[t].attr,e);r.isValid?(s[t]=r,e||(r.tagOrder+=a)):i.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Wr(n[t].attr)}"`)}),s}(t.dateRanges,e,i));const n=t.fragments.filter(t=>t.rawProgramDateTime);if(t.hasProgramDateTime&&!e.hasProgramDateTime)for(let t=1;t<o.length;t++)null===o[t].programDateTime&&Ga(o[t],o[t-1],n);Ma(n,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var l;const i=Za(t,e.startSN-1);e.startCC=null!=(l=null==i?void 0:i.cc)?l:a[0].cc}if(function(t,e,i){if(t&&e){let n=0;for(let r=0,s=t.length;r<s;r++){const s=t[r],a=e[r+n];s&&a&&s.index===a.index&&s.fragment.sn===a.fragment.sn?i(s,a):n--}}}(t.partList,e.partList,(t,e)=>{e.elementaryStreams=t.elementaryStreams,e.stats=t.stats,e.gap=t.gap||e.gap}),s){e.iframesOnly&&s.type;Wa(e,s,s.startPTS,s.endPTS,s.startDTS,s.endDTS,0,i)}else Xa(t,e);a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;const h=e.advancedDateTime;if(e.advanced&&h){const t=e.edge;e.driftStart||(e.driftStartTime=h,e.driftStart=t),e.driftEndTime=h,e.driftEnd=t}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime;-1===e.requestScheduled&&(e.requestScheduled=t.requestScheduled)}function qa(t,e,i,n,r){return new Error(`${t} ${r.url}\nPlaylist starting @${e.startSN}\n${e.m3u8}\n\nPlaylist starting @${i.startSN}\n${i.m3u8}`)}function Xa(t,e,i=!0,n){const r=e.startSN+e.skippedSegments-t.startSN,s=t.fragments,a=r>=0;let o=0;if(a&&r<s.length)o=s[r].start,null==n||n.log(`Aligning playlists based on SN ${e.startSN} (diff: ${o})`);else if(a&&e.startSN===t.endSN+1)o=t.fragmentEnd,null==n||n.log(`Aligning playlists based on first/last SN ${e.startSN} (diff: ${o})`);else if(a&&i)o=t.fragmentStart+r*e.levelTargetDuration;else{if(e.skippedSegments||0!==e.fragmentStart)return o;o=t.fragmentStart,null==n||n.log(`Aligning playlists based on first SN ${e.startSN} (diff: ${o})`)}return function(t,e){if(e){const i=t.fragments;for(let n=t.skippedSegments;n<i.length;n++)i[n].addStart(e);t.fragmentHint&&t.fragmentHint.addStart(e)}}(e,o),o}function Qa(t,e=1/0){let i=1e3*t.targetduration;if(t.updated){const n=t.fragments,r=4;if(n.length&&i*r>e){const t=1e3*n[n.length-1].duration;t<i&&(i=t)}}else i/=2;return Math.round(i)}function Za(t,e,i){var n;if(!t)return null;let r=t.fragments[e-t.startSN];return r||(r=t.fragmentHint,(null==(n=r)?void 0:n.sn)===e?r:i&&e<t.startSN&&i.sn===e?i:null)}function Ja(t,e,i){return t?to(t.partList,e,i):null}function to(t,e,i){if(t)for(let n=t.length;n--;){const r=t[n];if(r.index===i&&r.fragment.sn===e)return r}return null}function eo(t){t.forEach((t,e)=>{var i;null==(i=t.details)||i.fragments.forEach(t=>{t.level=e,t.initSegment&&(t.initSegment.level=e)})})}function io(t,e){return!(t===e||!e)&&no(t)!==no(e)}function no(t){return t.replace(/\?[^?]*$/,"")}function ro(t,e){for(let n=0,r=t.length;n<r;n++){var i;if((null==(i=t[n])?void 0:i.cc)===e)return t[n]}return null}function so(t,e){const i=t.start+e;t.setStart(i)}function ao(t,e){const i=e.fragments;for(let e=0,n=i.length;e<n;e++)so(i[e],t);e.fragmentHint&&so(e.fragmentHint,t),e.alignedSliding=!0}function oo(t,e,i){t&&(!function(t,e,i){if(!function(t,e){return!!(t&&e.startCC<t.endCC&&e.endCC>t.startCC)}(e,t))return;const n=Math.min(e.endCC,t.endCC),r=ro(e.fragments,n),s=ro(t.fragments,n);if(!r||!s)return;const a=r.start-s.start;i.log(`Aligning playlists using dicontinuity sequence ${n} (diff: ${a})`),ao(a,t)}(e,t,i),e.alignedSliding||function(t,e,i){if(!t.hasProgramDateTime||!e.hasProgramDateTime)return;const n=t.fragments,r=e.fragments;if(!n.length||!r.length)return;let s,a;const o=Math.min(e.endCC,t.endCC);e.startCC<o&&t.startCC<o&&(s=ro(r,o),a=ro(n,o));s&&a||(s=r[Math.floor(r.length/2)]||r.filter(t=>!!t)[0],a=ro(n,s.cc)||n[Math.floor(n.length/2)]);const l=s.programDateTime,h=a.programDateTime;if(!l||!h)return;const c=(h-l)/1e3;if(Math.abs(c)>Math.max(60,t.totalduration))return void i.log(`Cannot align playlists using PDT without overlap (${Math.abs(c)} > ${t.totalduration})`);const u=c-(a.start-s.start);i.log(`Aligning playlists using PDT (diff: ${u})`),ao(u,t)}(e,t,i),e.alignedSliding||e.skippedSegments||Xa(t,e,!1,i))}function lo(t,e,i){ho(t,e,i),t.addEventListener(e,i)}function ho(t,e,i){t.removeEventListener(e,i)}function co(t){let e="";const i=t.length;for(let n=0;n<i;n++)e+=`[${t.start(n).toFixed(3)}-${t.end(n).toFixed(3)}]`;return e}const uo="STOPPED",fo="IDLE",go="KEY_LOADING",po="FRAG_LOADING",mo="FRAG_LOADING_WAITING_RETRY",vo="WAITING_TRACK",yo="PARSING",Ao="PARSED",Eo="ENDED",To="ERROR",bo="WAITING_INIT_PTS",So="WAITING_LEVEL";class ko extends Ks{constructor(t,e,i,n,r){super(n,t.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragPlaying=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=uo,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=-1,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.initFragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:t,fragCurrent:e,media:i,mediaBuffer:n,state:r}=this,s=i?i.currentTime:0,a=js.bufferInfo(n||i,s,t.maxBufferHole),o=a.len;if(this.log(`Media seeking to ${s}, state: ${r}, ${o?"in":"out of"} buffer`),this.state===Eo)this.resetLoadingState();else if(e){const i=t.maxFragLookUpTolerance,n=e.start-i,r=e.start+e.duration+i;if(!o||r<a.start||n>a.end){const t=s<n,i=s>r;(t||i)&&(!e.loader||!i&&this.isFragmentNearlyDownloaded(e)?this.fragPrevious=null:(this.log(`Cancelling fragment load for seek (sn: ${e.sn}) - ${t?"backward":"forward"} seek`),e.abortRequests(),this.resetLoadingState()))}}if(i){this.fragmentTracker.removeFragmentsInRange(s,1/0,this.playlistType,!0);if(s>this.lastCurrentTime&&(this.lastCurrentTime=s),!this.loadingParts){const t=Math.max(a.end,s),e=this.shouldLoadParts(this.getLevelDetails(),t);e&&(this.log(`LL-Part loading ON after seeking to ${s} with buffer @${t}`),this.loadingParts=e)}}const l=!js.isBuffered(i,s);this.hls.hasEnoughToStart&&!l||(this.log(`Setting ${l?"startPosition":"nextLoadPosition"} to ${s} for seek without enough to start`),this.nextLoadPosition=s,l&&(this.startPosition=s)),o<1&&this.state===fo&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=t,this.fragmentLoader=new Bs(t.config),this.initFragmentLoader=new Bs(t.config),this.keyLoader=i,this.fragmentTracker=e,this.config=t.config,this.decrypter=new Ns(t.config)}registerListeners(){const{hls:t}=this;t.on(ii.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(ii.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(ii.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ii.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(ii.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(ii.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(ii.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(ii.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ii.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(ii.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===uo)return;this.fragmentLoader.abort(),this.initFragmentLoader.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=uo}get startPositionValue(){const{nextLoadPosition:t,startPosition:e}=this;if(-1===e&&t){const e=this.getLevelDetails();if(null!=e&&e.live){return(this.hls.liveSyncPosition||e.fragmentStart)+this.timelineOffset}return t}return e}get bufferingEnabled(){return this.buffering}get backtrackFragment(){}set backtrackFragment(t){}get couldBacktrack(){return!1}set couldBacktrack(t){}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(t,e){if(e.live||!this.media)return!1;const i=t.end||0,n=this.config.timelineOffset||0;if(i<=n)return!1;const r=t.buffered;this.config.maxBufferHole&&r&&r.length>1&&(t=js.bufferedInfo(r,t.start,0));const s=t.nextStart;if(s&&s>n&&s<e.edge)return!1;if(this.media.currentTime<t.start)return!1;const a=e.partList;if(null!=a&&a.length){const t=a[a.length-1];return js.isBuffered(this.media,t.start+t.duration/2)}const o=e.fragments[e.fragments.length-1];return this.fragmentTracker.isEndListAppended(o.type)}getLevelDetails(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}get timelineOffset(){const t=this.config.timelineOffset;var e;return t?(null==(e=this.getLevelDetails())?void 0:e.appliedTimelineOffset)||t:0}onMediaAttached(t,e){const i=this.media=this.mediaBuffer=e.media;lo(i,"seeking",this.onMediaSeeking),lo(i,"ended",this.onMediaEnded);const n=this.config;this.levels&&n.autoStartLoad&&this.state===uo&&this.startLoad(n.startPosition)}onMediaDetaching(t,e){this.fragPlaying=null;const i=!!e.transferMedia,n=this.media;if(null!==n){if(n.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),ho(n,"seeking",this.onMediaSeeking),ho(n,"ended",this.onMediaEnded),this.media=this.mediaBuffer=null,this.loopSn=void 0,i)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.fragPlaying=this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=0,this.startPosition=-1,this.startFragRequested=!1}onError(t,e){}onManifestLoaded(t,e){this.startTimeOffset=e.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=uo,this.fragmentLoader&&this.fragmentLoader.destroy(),this.initFragmentLoader&&this.initFragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.decrypter=this.keyLoader=null,this.fragmentLoader=this.initFragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(t,e,i){this.startFragRequested=!0,this._loadFragForPlayback(t,e,i)}_loadFragForPlayback(t,e,i){this._doFragLoad(t,e,i,t=>{const e=t.frag;if(this.fragContextChanged(e))return this.warn(`${e.type} sn: ${e.sn}${t.part?" part: "+t.part.index:""} of ${this.fragInfo(e,!1,t.part)} was dropped during download.`),void this.fragmentTracker.removeFragment(e);const i=++e.stats.chunkCount;this.log(`load progress ${e.type} sn: ${e.sn}${t.part?" part: "+t.part.index:""} of ${this.fragInfo(e,!1,t.part)} chunk: ${i}`),this._handleFragmentLoadProgress(t)}).then(t=>{if(!t)return;const e=this.state,i=t.frag;this.fragContextChanged(i)?(e===po||!this.fragCurrent&&e===yo)&&(this.fragmentTracker.removeFragment(i),this.state=fo):("payload"in t&&(this.log(`Loaded ${i.type} sn: ${i.sn} of ${this.playlistLabel()} ${i.level} (bytes ${i.stats.loaded})`),this.hls.trigger(ii.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t))}).catch(e=>{this.state!==uo&&this.state!==To&&(this.log(`Frag error ${t.type} sn:${t.sn} cc:${t.cc}: ${(null==e?void 0:e.message)||e}`),this.resetFragmentLoading(t))})}clearTrackerIfNeeded(t){var e;const{fragmentTracker:i}=this;if(i.getState(t)===ks){const e=t.type,n=this.getFwdBufferInfo(this.mediaBuffer,e),r=Math.max(t.duration,n?n.len:this.config.maxBufferLength),s=this.backtrackFragment;(1===(s?t.sn-s.sn:0)||this.reduceMaxBufferLength(r,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)===_s&&i.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const e=this.fragmentTracker,i=t.fragments[t.fragments.length-1];if(i.endList&&!e.isEndListAppended(this.playlistType)){const t=e.getPartialFragment(i.end);t&&(e.removeFragment(t),e.fragBuffered(i,!0))}e.detectPartialFragments({frag:i,part:null,stats:i.stats,id:i.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}waitForLive(t){const e=t.details;return(null==e?void 0:e.live)&&"EVENT"!==e.type&&(this.levelLastLoaded!==t||e.expired)}flushMainBuffer(t,e,i=null){if(!(t-e))return;const n={startOffset:t,endOffset:e,type:i};this.hls.trigger(ii.BUFFER_FLUSHING,n)}_loadInitSegment(t){const{hls:e}=this;return this.initFragmentLoader.abort(),e.trigger(ii.FRAG_LOADING,{frag:t,targetBufferTime:0}),this.initFragmentLoader.load(t).then(t=>{var e;const i=t.frag;if(!this.levels||!Li(i,null==(e=this.fragCurrent)?void 0:e.initSegment))throw new Vs({type:ti.NETWORK_ERROR,details:ei.INTERNAL_ABORTED,error:new Error("init load aborted"),fatal:!1,frag:i,networkDetails:null});return t}).then(t=>{const{frag:i,payload:n}=t,r=i.decryptdata;if(n&&n.byteLength>0&&null!=r&&r.key&&r.iv&&oa(r.method)){const s=self.performance.now(),{decryptRange:a}=Us(i,null,this.iframesOnly);return this.decrypter.decrypt(new Uint8Array(n),r.key.buffer,r.iv.buffer,la(r.method),a).catch(t=>{throw e.trigger(ii.ERROR,{type:ti.MEDIA_ERROR,details:ei.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:i}),this.fragmentLoader.abort(),t}).then(n=>{const r=self.performance.now();return e.trigger(ii.FRAG_DECRYPTED,{frag:i,part:null,payload:n,stats:{tstart:s,tdecrypt:r}}),t.payload=n,this.completeInitSegmentLoad(t)})}return this.completeInitSegmentLoad(t)})}completeInitSegmentLoad(t){const e=t.frag.stats;t.frag.data=new Uint8Array(t.payload),e.parsing.start=e.buffering.start=self.performance.now(),e.parsing.end=e.buffering.end=self.performance.now()}loadInitSegmentIfNeeded(t){const{initSegment:e}=t;if(!this.bitrateTest&&ki(t)&&e&&!e.data){var i;return(!e.encrypted||null!=(i=e.decryptdata)&&i.key?this._loadInitSegment(e):this.keyLoader.load(e).then(()=>this._loadInitSegment(e))).catch(e=>{if(this.state===uo||this.state===To)throw e;throw"data"in e&&(e.data.frag=t,this.fragmentLoader.abort(),this.handleFragLoadError(e)),this.resetFragmentLoading(t),e})}}unhandledEncryptionError(t,e){var i,n;const r=t.tracks;if(r&&!e.encrypted&&(null!=(i=r.audio)&&i.encrypted||null!=(n=r.video)&&n.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const t=this.media,i=new Error(`Encrypted track with no key in ${this.fragInfo(e)} (media ${t?"attached mediaKeys: "+t.mediaKeys:"detached"})`);return this.warn(i.message),!t||t.mediaKeys?!1:(this.hls.trigger(ii.ERROR,{type:ti.KEY_SYSTEM_ERROR,details:ei.KEY_SYSTEM_NO_KEYS,fatal:!1,error:i,frag:e}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(t){const{fragCurrent:e}=this;return!t||!Li(t,e)}fragBufferedComplete(t,e){const i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)} > buffer:${i?co(js.getBuffered(i)):"(detached)"})`),ki(t)){var n;if(t.type!==Ai){const e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return void(this.state=fo)}const i=null==(n=this.levels)?void 0:n[t.level];null!=i&&i.fragmentError&&(e||this.fragmentTracker.getState(t)!==_s)&&(this.log(`Resetting level fragment error count of ${i.fragmentError} on frag buffered`),i.fragmentError=0,t.stats.retry=0)}this.state=fo}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const i=t.frag,{part:n,partsLoaded:r}=t,s=!r||0===r.length||r.some(t=>!t),{decryptRange:a}=Us(i,n),o=new Hs(i.level,i.sn,i.stats.chunkCount+1,0,n?n.index:-1,!s,i.duration,this.iframesOnly,a);this.log(`load complete ${i.type} sn: ${i.sn}${n?" part: "+n.index:""} of ${this.fragInfo(i,!1,n)}`),e.flush(o)}_handleFragmentLoadProgress(t){}loadKeyFor(t,e,i){var n;let r=null;return!t.encrypted||null!=(n=t.decryptdata)&&n.key?t.encrypted||(r=this.keyLoader.loadClear(t,e.encryptedFragments,this.startFragRequested),r&&this.log(`[eme] blocking frag sn: ${t.sn} load until media-keys acquired`)):(this.log(`Loading key for ${t.sn} of [${e.startSN}-${e.endSN}], ${this.playlistLabel()} ${t.level}`),this.state=go,r=this.keyLoader.load(t,i).then(t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(ii.KEY_LOADED,t),this.state===go&&(this.state=fo),t}),this.hls.trigger(ii.KEY_LOADING,{frag:t})),r}_doFragLoad(t,e,i=null,n){this.fragCurrent=t;const r=e.details;if(!this.levels||!r)throw new Error(`frag load aborted, missing level${r?"":" detail"}s`);const s=this.fragPrevious;if(!_i(t,s)){const i=this.shouldLoadParts(e.details,t.end);i!==this.loadingParts&&(this.log(`LL-Part loading ${i?"ON":"OFF"} loading sn ${null==s?void 0:s.sn}->${t.sn}`),this.loadingParts=i)}if(i=Math.max(t.start,i||0),this.loadingParts){const a=r.partList;if(a&&n){i>r.fragmentEnd&&r.fragmentHint&&(t=r.fragmentHint);const o=this.getNextPart(a,t,i);if(o>-1){const l=a[o];if(!_i(t=this.fragCurrent=l.fragment,s)&&!this.shouldLoadParts(e.details,t.end))return this.log(`LL-Part loading OFF @${this.playhead} next part: ${this.fragInfo(t,!1,l)}`),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(l,e.details))return Promise.resolve(null);const h=this.loadKeyFor(t,r);if(this.fragContextChanged(t))return Promise.resolve(null);let c;this.log(`Loading ${t.type} sn: ${t.sn} part: ${l.index} (${o}/${a.length-1}) of ${this.fragInfo(t,!1,l)} cc: ${t.cc} [${r.startSN}-${r.endSN}], target: ${i}${l.byteRange.length?` range:${l.byteRange.join("-")}`:""}`),this.nextLoadPosition=l.start+l.duration,this.state=po;const u=this.loadInitSegmentIfNeeded(t);if(h||u){const i=!!h;c=Promise.all([h,u]).then(([r])=>!i||r&&!this.fragContextChanged(r.frag)?this.doFragPartsLoad(t,l,e,n):null).catch(t=>this.handleFragLoadError(t))}else c=this.doFragPartsLoad(t,l,e,n).catch(t=>this.handleFragLoadError(t));return this.hls.trigger(ii.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(a,i))return Promise.resolve(null)}}var a;if(this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${i} Check buffer at sn: ${t.sn} loaded parts: ${null==(a=r.partList)?void 0:a.filter(t=>t.loaded).map(t=>`[${t.start}-${t.end}]`)}`),this.loadingParts=!1;else if(!t.url)return Promise.resolve(null);if(!this.filterReplacedPrimary(t,e.details))return Promise.resolve(null);const o=this.loadInitSegmentIfNeeded(t),l=this.loadKeyFor(t,r,o);var h;if(this.fragContextChanged(t))return this.log(`Context changed in KEY_LOADING sn: ${t.sn} ${t.relurl} > ${null==(h=this.fragCurrent)?void 0:h.relurl}`),null==o||o.catch(()=>null),null==l||l.catch(()=>null),Promise.resolve(null);this.log(`Loading ${t.type} sn: ${t.sn} of ${this.fragInfo(t,!1)} cc: ${t.cc} ${"["+r.startSN+"-"+r.endSN+"]"}, target: ${i}${t.byteRange.length?` range:${t.byteRange.join("-")}`:""}`),Qe(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=po;const c=this.config.progressive&&t.type!==Ai;let u;return u=c&&l?l.then(e=>!e||this.fragContextChanged(e.frag)?null:this.fragmentLoader.load(t,this.iframesOnly,n,o)).catch(t=>this.handleFragLoadError(t)):Promise.all([this.fragmentLoader.load(t,this.iframesOnly,c?n:void 0,c?o:void 0),l,o]).then(([t])=>(!c&&n&&n(t),t)).catch(t=>this.handleFragLoadError(t)),this.hls.trigger(ii.FRAG_LOADING,{frag:t,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):Promise.all([u,o]).then(([t])=>t)}doFragPartsLoad(t,e,i,n){return new Promise((r,s)=>{var a;const o=[],l=null==(a=i.details)?void 0:a.partList,h=e=>{this.fragmentLoader.loadPart(t,e,n).then(n=>{o[e.index]=n;const s=n.part;this.hls.trigger(ii.FRAG_LOADED,n);const a=Ja(i.details,t.sn,e.index+1)||to(l,t.sn,e.index+1);if(!a)return r({frag:t,part:s,partsLoaded:o});h(a)}).catch(s)};h(e)})}handleFragLoadError(t){if("data"in t){const e=t.data;e.frag&&e.details===ei.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):e.frag&&e.type===ti.KEY_SYSTEM_ERROR&&!e.fatal&&(e.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(e.frag)),this.hls.trigger(ii.ERROR,e)}else this.hls.trigger(ii.ERROR,{type:ti.OTHER_ERROR,details:ei.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==yo)return void(this.fragCurrent||this.state===uo||this.state===To||(this.state=fo));const{frag:i,part:n,level:r}=e,s=self.performance.now();i.stats.parsing.end=s,n&&(n.stats.parsing.end=s);const a=this.getLevelDetails(),o=a&&i.sn>a.endSN||this.shouldLoadParts(a,i.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${i.end}`),this.loadingParts=o),this.updateLevelTiming(i,n,r,t)}shouldLoadParts(t,e){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(t.partList&&!this.iframesOnly){var i;const n=t.partList[0];if(e>=n.end+((null==(i=t.fragmentHint)?void 0:i.duration)||0)){if(this.playhead>n.start-n.fragment.duration)return!0}}}return!1}getCurrentContext(t){const{levels:e,fragCurrent:i}=this,{level:n,sn:r,part:s}=t;if(null==e||!e[n])return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${n}. The current chunk will not be buffered.`),null;const a=e[n],o=a.details,l=s>-1?Ja(o,r,s):null,h=l?l.fragment:Za(o,r,i);return h?(i&&i!==h&&(h.stats=i.stats),{frag:h,part:l,level:a}):null}bufferFragmentData(t,e,i,n,r){if(this.state!==yo)return;ki(e)&&!this.fragContextChanged(e)&&(this.fragPrevious=e);const{data1:s,data2:a}=t;let o=s;if(a&&(o=Zn(s,a)),!o.length)return;const l=this.initPTS[e.cc],h=l?-l.baseTime/l.timescale:void 0,c={type:t.type,frag:e,part:i,chunkMeta:n,offset:h,parent:e.type,data:o};if(this.hls.trigger(ii.BUFFER_APPENDING,c),t.dropped&&t.independent&&!i){if(r)return;this.flushBufferGap(e)}}flushBufferGap(t){const e=this.media;if(!e)return;if(!js.isBuffered(e,e.currentTime))return void this.flushMainBuffer(0,t.start);const i=e.currentTime,n=js.bufferInfo(e,i,0),r=t.duration,s=Math.min(2*this.config.maxFragLookUpTolerance,.25*r),a=Math.max(Math.min(t.start-s,n.end-s),i+s);t.start-a>s&&this.flushMainBuffer(a,t.start)}getFwdBufferInfo(t,e){var i;const n=this.playhead,r=this.lastCurrentTime>n||null!=(i=this.media)&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,n,e,r)}getFwdBufferInfoAtPos(t,e,i,n){const r=js.bufferInfo(t,e,n);if(0===r.len&&void 0!==r.nextStart){const s=this.fragmentTracker.getBufferedFrag(e,i);if(s&&(r.nextStart<=s.end||s.gap)){const i=Math.max(Math.min(r.nextStart,s.end)-e,n);return js.bufferInfo(t,e,i)}}return r}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)}exceedsMaxBuffer(t,e,i){const n=t.nextStart;if(n&&i.start>n){const n=t.buffered;if(n){let r=t.len;const s=t.bufferedIndex;for(let t=n.length-1;t>s;t--)n[t].start<i.start&&(r+=n[t].end-n[t].start);return r>=e}}return!1}reduceMaxBufferLength(t,e){const i=this.config,n=Math.max(Math.min(t-e,i.maxBufferLength),e/2),r=Math.max(t-3*e,i.maxMaxBufferLength/2,n);return r>=n&&(i.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0)}getAppendedFrag(t){const e=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(t,this.playlistType):null;return e&&"fragment"in e?e.fragment:e}getNextFragment(t,e){const i=e.fragments,n=i.length;if(!n)return null;const{config:r}=this,s=e.fragmentStart,a=r.lowLatencyMode&&!!e.partList;let o=null;if(e.live){const i=r.initialLiveManifestSize;if(n<i)return this.warn(`Not enough fragments to start playback (have: ${n}, need: ${i})`),null;if(this.startFragRequested||!a||this.loadingParts||(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),!e.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||t<s){var l;o=this.getInitialLiveFragment(e);const i=this.config.startPosition,n=this.hls.startPosition,r=this.hls.liveSyncPosition,a=(null==(l=o)?void 0:l.start)||0;let h,c;if(-1!==n&&n>=s?(h=n,c=n===i?"config":"next load start"):r?(h=r,c="live edge"):(h=t,c="buffer pos"),h<a&&(h=a,c="live frag start"),h<s&&(h=s,c="playlist start"),this.startPosition!=h||this.nextLoadPosition!=h){const l=e.live&&!this.filterReplacedPrimary(o,e)?-1:h;this.log(`Setting startPosition to ${l} next load ${h} ${-1===n?"":`(from ${i}) `}based on ${c}. live edge: ${r} live frag start: ${a} playlist start: ${s} buffer pos: ${t}`),this.startPosition=l,this.nextLoadPosition=h}}}else t<=s&&(o=i[0]);if(!o){const i=this.loadingParts?e.partEnd:e.fragmentEnd;o=this.getFragmentAtPosition(t,i,e)}let h=this.filterReplacedPrimary(o,e);return!h&&o&&(h=hs(e,o.sn,this.loadingParts),h&&(this.nextLoadPosition=h.start)),h}isLoopLoading(t,e){if(this.nextLoadPosition<=e)return!1;const i=this.fragmentTracker.getState(t);if(i===Ls)return!0;if(i===_s){if(t.gap)return!0;if(t.stats.retry>1)return!0}return!1}getNextFragmentLoopLoading(t,e,i,n,r){let s=null;if(t.gap&&(s=this.getNextFragment(this.nextLoadPosition,e),s&&!s.gap&&i.nextStart)){const t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,n,0);if(null!==t&&i.len+t.len>=r){const t=s.sn;return this.loopSn!==t&&(this.log(`buffer full after gaps in "${n}" playlist starting at sn: ${t}`),this.loopSn=t),null}}return this.loopSn=void 0,s}get primaryPrefetch(){if(Lo(this.config)){var t;if(null==(t=this.hls.interstitialsManager)||null==(t=t.playingItem)?void 0:t.event)return!0}return!1}filterReplacedPrimary(t,e){if(!t)return t;if(Lo(this.config)&&("type"in t?t:t.fragment).type!==Ai){const i=this.hls.interstitialsManager,n=null==i?void 0:i.bufferingItem;if(n){const i=n.event;if(i){if(!i.appendInPlace&&(Math.abs(t.start-n.start)>1||0===n.start))return null}else{if(t.end<=n.start&&!1===(null==e?void 0:e.live))return null;if(t.start>=n.end&&n.nextEvent&&(n.nextEvent.appendInPlace&&!n.nextEvent.hasPlayed||t.start-n.end>1))return null}}if(_o(t,null==i?void 0:i.playerQueue,this.playhead))return null}return t}getNextPart(t,e,i){let n=-1,r=!1,s=!0;for(let a=0,o=t.length;a<o;a++){const o=t[a];if(s=s&&!o.independent,n>-1&&i<o.start)break;const l=o.loaded||o.gap;l?n=-1:(r||(o.independent||s)&&o.fragment===e)&&(n=a),r=l&&!o.gap}const a=t[n];return a&&a.fragment!==e&&this.log(`Need buffer at ${i} but next unloaded part starts at ${a.start} (sn: ${e.sn} -> ${a.fragment.sn})`),n}loadedEndOfParts(t,e){let i;for(let n=t.length;n--;){if(i=t[n],!i.loaded)return!1;if(e>i.start)return!0}return!1}getInitialLiveFragment(t){const e=t.fragments,i=this.fragPrevious;let n=null;if(i){if(t.hasProgramDateTime&&(n=function(t,e,i){if(null===e||!Array.isArray(t)||!t.length||!Qe(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;for(let n=0;n<t.length;++n){const r=t[n];if(os(e,i,r))return r}return null}(e,i.endProgramDateTime,this.config.maxFragLookUpTolerance),n&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`)),!n){const r=i.sn+1;if(r>=t.startSN&&r<=t.endSN){const s=e[r-t.startSN];i.cc===s.cc&&(n=s,this.log(`Live playlist, switching playlist, load frag with next SN: ${n.sn}`))}n||(n=ls(t,i.cc,i.end),n&&this.log(`Live playlist, switching playlist, load frag with same CC: ${n.sn}`))}}else{const e=this.hls.liveSyncPosition;null!==e&&(n=this.getFragmentAtPosition(e,this.bitrateTest?t.fragmentEnd:t.edge,t))}return n}getFragmentAtPosition(t,e,i){const{config:n}=this;let{fragPrevious:r}=this,{fragments:s,endSN:a}=i;const{fragmentHint:o}=i,{maxFragLookUpTolerance:l}=n,h=i.partList,c=!!(this.loadingParts&&null!=h&&h.length&&o);let u;if(c&&!this.bitrateTest&&h[h.length-1].fragment.sn===o.sn&&(s=s.concat(o),a=o.sn),r&&this.fragmentTracker.getState(r)===Ss&&(r=null),t<e){var d;u=ss(r,s,t,t<this.lastCurrentTime||t>e-l||null!=(d=this.media)&&d.paused||!this.startFragRequested?0:l)}else u=s[s.length-1];if(u){const t=u.sn-i.startSN,e=this.fragmentTracker.getState(u);if((e===Ls||e===_s&&u.gap)&&(r=u),_i(u,r)&&(!c||h[0].fragment.sn>u.sn||!i.live)){const e=s[t+1];u=u.sn<a&&this.fragmentTracker.getState(e)!==Ls?e:null}}return u}alignPlaylists(t,e,i){const n=t.fragments.length;if(!n)return this.warn("No fragments in live playlist"),0;const r=t.fragmentStart,s=!e,a=t.alignedSliding&&Qe(r);if(s||!a&&!r){oo(i,t,this);const r=t.fragmentStart;return this.log(`Live playlist sliding: ${r} start-sn: ${e?e.startSN:"na"}->${t.startSN} fragments: ${n}`),r}return r}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;i<e&&(i=-1);const n=this.timelineOffset;if(-1===i){const r=null!==this.startTimeOffset,s=r?this.startTimeOffset:t.startTimeOffset;if(null!==s&&Qe(s))i=e+s,s<0&&(i+=t.edge),i=Math.min(Math.max(e,i),e+t.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${s} found in ${r?"multivariant":"media"} playlist`),this.startPosition=i;else if(t.live){const t=this.hls.liveSyncPosition;i=t||e,this.log(`Setting startPosition to -1 to start at ${t?"live edge":"playlist start"} ${i}`),this.startPosition=-1}else this.log("setting startPosition to 0 by default"),this.startPosition=i=0;this.lastCurrentTime=i+n}this.nextLoadPosition=i+n}getLoadPosition(){var t;const{media:e}=this;let i=0;return null!=(t=this.hls)&&t.hasEnoughToStart&&e&&!this.iframesOnly?i=e.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}get playhead(){var t;if(null!=(t=this.hls)&&t.hasEnoughToStart){var e;const t=null==(e=this.media)?void 0:e.currentTime;return Qe(t)?t:this.lastCurrentTime}return this.getLoadPosition()}get iframesOnly(){var t;if(this.playlistType!==vi)return!1;const e=this.getLevelDetails();return e?e.iframesOnly:null==(t=this.levelLastLoaded)?void 0:t.iframes}handleFragLoadAborted(t,e){this.transmuxer&&t.type===this.playlistType&&ki(t)&&t.stats.aborted&&(this.log(`Fragment ${t.sn}${e?" part "+e.index:""} of ${this.playlistLabel()} ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){this.fragCurrent&&(this.fragContextChanged(t)||this.state===mo)||(this.state=fo)}onFragmentOrKeyLoadError(t,e){if(e.chunkMeta&&!e.frag){const t=this.getCurrentContext(e.chunkMeta);t&&(e.frag=t.frag)}const{frag:i,part:n}=e;if(!i||!this.levels||i.type!==t)return;var r;if(this.fragContextChanged(i))return void this.warn(`Frag load error must match current frag to retry ${i.relurl} > ${null==(r=this.fragCurrent)?void 0:r.relurl}`);const s=e.details===ei.FRAG_GAP;s&&this.fragmentTracker.addAsGap(i);const a=e.errorAction;if(!a)return void(this.state=To);const{action:o,flags:l,retryCount:h=0,retryConfig:c}=a,u=!!c,d=u&&o===fs,f=u&&!a.resolved&&l&ps,g=this.hls.latestLevelDetails,p=null==g?void 0:g.live;if(!d&&f&&ki(i)&&p&&i.sn<g.endSN&&!Fi(e))this.resetFragmentErrors(t),n?n.gap=!0:this.treatAsGap(i),a.resolved=!0;else if((d||f)&&h<c.maxNumRetry){var m;const n=Vi(null==(m=e.response)?void 0:m.code),r=$i(c,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+r,this.state=mo,a.resolved=!0,n)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(e.reason="offline");this.warn(`Fragment ${i.sn} of ${t} ${i.level} errored with ${e.details}, retrying loading ${h+1}/${c.maxNumRetry} in ${r}ms`)}else if(c){if(this.resetFragmentErrors(t),!(h<c.maxNumRetry))return void this.warn(`${e.details} reached or exceeded max retry (${h})`);s||o===ds||(a.resolved=!0)}else this.state=o===us?So:To;this.tickImmediate()}checkRetryDate(){const t=self.performance.now(),e=this.retryDate,i=e===1/0;(!e||t>=e||i&&!Vi(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=fo)}reduceLengthAndFlushBuffer(t){if(this.state===yo||this.state===Ao){const e=t.frag,i=t.parent,n=this.getFwdBufferInfo(this.mediaBuffer,i),r=n&&n.len>.5;r&&this.reduceMaxBufferLength(n.len,(null==e?void 0:e.duration)||10);const s=!r;return s?this.warn(`Buffer full error while media.currentTime (${this.playhead}) is not buffered, flush ${i} buffer`):n.nextStart&&e&&n.nextStart>e.start&&this.flushMainBuffer(n.nextStart,Number.POSITIVE_INFINITY,i===yi?i:void 0),e&&(this.fragmentTracker.removeFragment(e),this.nextLoadPosition=e.start),this.resetLoadingState(),s}return!1}resetFragmentErrors(t){t===yi&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==uo&&(this.state=fo)}afterBufferFlushed(t,e){if(!t)return;const i=js.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,i,this.playlistType),this.state===Eo&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==uo&&(this.state=fo)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=this.getLevelDetails();null!=t&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.log(`Loading context changed while buffering sn ${t.sn} of ${this.playlistLabel()} ${-1===t.level?"<removed>":t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,e,i,n){const r=i.details;if(!r)return void this.warn("level.details undefined");this.log(`update level timing ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)}`);if(!Object.keys(t.elementaryStreams).reduce((e,s)=>{const a=t.elementaryStreams[s];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${t.sn} ${s} duration reliably (${o})`),e||!1;const l=n.partial?0:Wa(r,t,a.startPTS,a.endPTS,a.startDTS,a.endDTS,this.iframesOnly,this);return this.hls.trigger(ii.LEVEL_PTS_UPDATED,{details:r,level:i,drift:l,type:s,frag:t,start:a.startPTS,end:a.endPTS}),!0}return e},!1)){var s,a,o,l;const n=null===(null==(s=this.transmuxer)?void 0:s.error),r=null!=(null==(a=this.transmuxer)?void 0:a.error),h=(null!=(o=null==(l=this.levels)?void 0:l.length)?o:0)>1;if((0===i.fragmentError||n&&(i.fragmentError<2||t.endList)||r&&h)&&this.treatAsGap(t,i),n){const n=new Error(`Found no media in ${this.playlistLabel()} ${t.level} ${e?`part: ${e.index} of `:""}sn: ${t.sn} at playlist time: ${t.start}. Resetting transmuxer to fallback to playlist timing`);if(this.warn(n.message),this.hls.trigger(ii.ERROR,{type:ti.MEDIA_ERROR,details:ei.FRAG_PARSING_ERROR,fatal:!1,error:n,frag:t,reason:`Found no media in msn ${t.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=Ao,this.log(`Parsed ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)}`),this.hls.trigger(ii.FRAG_PARSED,{frag:t,part:e,chunkMeta:n})}playlistLabel(){return`${this.playlistType} playlist`}fragInfo(t,e=!0,i){var n,r;return`${this.playlistLabel()} ${t.level} (${i?"part":"frag"}:[${null!=(n=e&&!i?t.startPTS:(i||t).start)?n:NaN}-${null!=(r=e&&!i?t.endPTS:(i||t).end)?r:NaN}]${i&&"main"===t.type?"INDEPENDENT="+(i.independent?"YES":"NO"):""})`}treatAsGap(t,e){e&&e.fragmentError++,this.fragmentTracker.addAsGap(t)}resetTransmuxer(){var t;null==(t=this.transmuxer)||t.reset()}isFragmentNearlyDownloaded(t){var e;const i=null==(e=t.loader)?void 0:e.stats;if(!i)return!1;const n=i.loading.first>0,r=(i.total-i.loaded)/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return n&&r<=.15}recoverWorkerError(t){"demuxerWorker"===t.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`))}get state(){return this._state}calculateOptimalSwitchPoint(t,e){let i=0;const{hls:n,media:r,config:s,levels:a,playlistType:o}=this,l=this.getLevelDetails();if(r&&!r.paused&&a){var h;const e=o===yi?xr(t.audioCodec,128e3):t.maxBitrate,r=1+n.ttfbEstimate/1e3,a=n.bandwidthEstimate*s.abrBandWidthUpFactor;i=r+e*(l&&(this.loadingParts?l.partTarget:l.averagetargetduration)||(null==(h=this.fragCurrent)?void 0:h.duration)||6)/a,t.details||(i+=r)}const c=this.playhead;return{fetchdelay:i,okToFlushForwardBuffer:!(null!=l&&l.live)||e.end-c>1.5*i}}scheduleTrackSwitch(t,e,i){const{media:n,playlistType:r}=this;if(!n||!t)return;const s=i?this.getBufferedFrag(this.playhead+e):null;if(s){const t=this.followingBufferedFrag(s);if(t){var a;this.abortCurrentFrag();const e=t.maxStartPTS?t.maxStartPTS:t.start,i=t.duration,n=Math.max(s.end,e+Math.min(Math.max(i-this.config.maxFragLookUpTolerance,i*(this.couldBacktrack?.5:.125)),i*(this.couldBacktrack?.75:.25)));if(((null==(a=this.getLevelDetails())?void 0:a.fragmentStart)||0)>n)return;const o=r===vi?null:"audio";this.flushMainBuffer(n,Number.POSITIVE_INFINITY,o),this.cleanupBackBuffer()}}}cleanupBackBuffer(){const{media:t,playlistType:e}=this;if(!t)return;const i=this.getAppendedFrag(this.playhead);if(i&&i.start>1){const t=e===yi;this.flushMainBuffer(0,i.start-(t?0:1),t?"audio":null)}}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,this.playlistType)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}abortCurrentFrag(){const t=this.fragCurrent;switch(this.fragCurrent=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.state){case go:case po:case mo:case yo:case Ao:this.state=fo}this.nextLoadPosition=this.playhead}checkFragPlaying(){const t=this.media;let e=null;if(t&&t.readyState>1&&!1===t.seeking){const i=t.currentTime;if(js.isBuffered(t,i)?e=this.getAppendedFrag(i):js.isBuffered(t,i+.1)&&(e=this.getAppendedFrag(i+.1)),e&&(this.backtrackFragment=void 0,!_i(e,this.fragPlaying)))return this.fragPlaying=e,!0}return!1}getBufferOutput(){return null}nextLevelSwitch(){const{levels:t,media:e,hls:i,config:n,playlistType:r}=this;if(null!=e&&e.readyState&&t&&i&&n){const e=this.getBufferOutput(),n=this.getFwdBufferInfo(e,r);if(!n)return;const s=t[r===yi?i.nextAudioTrack:i.nextLoadLevel],{fetchdelay:a,okToFlushForwardBuffer:o}=this.calculateOptimalSwitchPoint(s,n);this.scheduleTrackSwitch(n,a,o)}this.tickImmediate()}}function _o(t,e,i){if(e)for(let n=e.length;n--;){const r=e[n].interstitial,s=r.startTime,a=Math.min(s+r.duration,r.resumeTime);if(r.appendInPlace){if(t.start>=s&&t.end<=a)return!0;if(i>t.start&&t.end>s&&t.start<a)return!0}}return!1}function Lo(t){return!!t.interstitialsController&&!1!==t.enableInterstitialPlayback}class Ro{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 n=0;for(let e=0;e<t.length;e++){const r=t[e];i.set(r,n),n+=r.length}return i}(t,e),this.reset(),i):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}var Io,Co={exports:{}};var Po=(Io||(Io=1,function(t){var e=Object.prototype.hasOwnProperty,i="~";function n(){}function r(t,e,i){this.fn=t,this.context=e,this.once=i||!1}function s(t,e,n,s,a){if("function"!=typeof n)throw new TypeError("The listener must be a function");var o=new r(n,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 n:delete t._events[e]}function o(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(i=!1)),o.prototype.eventNames=function(){var t,n,r=[];if(0===this._eventsCount)return r;for(n in t=this._events)e.call(t,n)&&r.push(i?n.slice(1):n);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},o.prototype.listeners=function(t){var e=i?i+t:t,n=this._events[e];if(!n)return[];if(n.fn)return[n.fn];for(var r=0,s=n.length,a=new Array(s);r<s;r++)a[r]=n[r].fn;return a},o.prototype.listenerCount=function(t){var e=i?i+t:t,n=this._events[e];return n?n.fn?1:n.length:0},o.prototype.emit=function(t,e,n,r,s,a){var o=i?i+t:t;if(!this._events[o])return!1;var l,h,c=this._events[o],u=arguments.length;if(c.fn){switch(c.once&&this.removeListener(t,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,n),!0;case 4:return c.fn.call(c.context,e,n,r),!0;case 5:return c.fn.call(c.context,e,n,r,s),!0;case 6:return c.fn.call(c.context,e,n,r,s,a),!0}for(h=1,l=new Array(u-1);h<u;h++)l[h-1]=arguments[h];c.fn.apply(c.context,l)}else{var d,f=c.length;for(h=0;h<f;h++)switch(c[h].once&&this.removeListener(t,c[h].fn,void 0,!0),u){case 1:c[h].fn.call(c[h].context);break;case 2:c[h].fn.call(c[h].context,e);break;case 3:c[h].fn.call(c[h].context,e,n);break;case 4:c[h].fn.call(c[h].context,e,n,r);break;default:if(!l)for(d=1,l=new Array(u-1);d<u;d++)l[d-1]=arguments[d];c[h].fn.apply(c[h].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,n,r){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||r&&!o.once||n&&o.context!==n||a(this,s);else{for(var l=0,h=[],c=o.length;l<c;l++)(o[l].fn!==e||r&&!o[l].once||n&&o[l].context!==n)&&h.push(o[l]);h.length?this._events[s]=1===h.length?h[0]:h: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 n,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}(Co)),Co.exports),Do=ni(Po);const wo="1.7.0",Oo={};function xo(t,e){return 255===t[e]&&240==(246&t[e+1])}function Mo(t,e){return 1&t[e+1]?7:9}function No(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function Fo(t,e){return e+1<t.length&&xo(t,e)}function Bo(t,e){if(Fo(t,e)){const i=Mo(t,e);if(e+i>=t.length)return!1;const n=No(t,e);if(n<=i)return!1;const r=e+n;return r===t.length||Fo(t,r)}return!1}function $o(t,e,i,n,r){if(!t.samplerate){const s=function(t,e,i,n){const r=e[i+2],s=r>>2&15;if(s>12){const e=new Error(`invalid ADTS sampling index:${s}`);return void t.emit(ii.ERROR,ii.ERROR,{type:ti.MEDIA_ERROR,details:ei.FRAG_PARSING_ERROR,fatal:!0,error:e,reason:e.message})}const a=1+(r>>6&3),o=e[i+3]>>6&3|(1&r)<<2,l=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][s];let h,c=s;5!==a&&29!==a||(c-=3);const u=(14&c)>>1,d=(1&c)<<7|o<<3;let f=0;if(1===a&&s>=6){f=5;const t=s-3;h=[f<<3|u,d|(14&t)>>1,(1&t)<<7|8,0]}else h=[a<<3|u,d];const g="mp4a.40."+(f||a);return Zi.log(`manifest codec:${n}, parsed codec:${g}, channels:${o}, rate:${l} (ADTS object type:${a} sampling index:${s} esds config:[${h.join(",")}])`),{config:h,samplerate:l,channelCount:o,codec:g,parsedCodec:g,manifestCodec:n}}(e,i,n,r);if(!s)return;Di(t,s)}}function Uo(t){return 9216e4/t}function Go(t,e,i,n,r){const s=n+r*Uo(t.samplerate),a=function(t,e){const i=Mo(t,e);if(e+i<=t.length){const n=No(t,e)-i;if(n>0)return{headerLength:i,frameLength:n}}}(e,i);let o;if(a){const{frameLength:n,headerLength:r}=a,l=r+n,h=Math.max(0,i+l-e.length);h?(o=new Uint8Array(l-r),o.set(e.subarray(i+r,e.length),0)):o=e.subarray(i+r,i+l);const c={unit:o,pts:s};return h||t.samples.push(c),{sample:c,length:l,missing:h}}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 Vo=function(t){return t.audioId3="org.id3",t.dateRange="com.apple.quicktime.HLS",t.emsg="https://aomedia.org/emsg/ID3",t.misbklv="urn:misb:KLV:bin:1910.1",t}({});function Ko(t="",e=9e4){return{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Ho{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,n){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=Zn(this.cachedData,t),this.cachedData=null);let i,n=dn(t,0),r=n?n.length:0;const s=this._audioTrack,a=this._id3Track,o=n?Tn(n):void 0,l=t.length;for((null===this.basePTS||0===this.frameIndex&&Qe(o))&&(this.basePTS=Yo(o,e,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),n&&n.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:Vo.audioId3,duration:Number.POSITIVE_INFINITY});r<l;){if(this.canParse(t,r)){const e=this.appendFrame(s,t,r);e?(this.frameIndex++,this.lastPTS=e.sample.pts,r+=e.length,i=r):r=l}else cn(t,r)?(n=dn(t,r),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:Vo.audioId3,duration:Number.POSITIVE_INFINITY}),r+=n.length,i=r):r++;if(r===l&&i!==l){const e=t.slice(i);this.cachedData?this.cachedData=Zn(this.cachedData,e):this.cachedData=e}}return{audioTrack:s,videoTrack:Ko(),id3Track:a,textTrack:Ko()}}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:Ko(),id3Track:this._id3Track,textTrack:Ko()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const Yo=(t,e,i)=>{if(Qe(t))return 90*t;return 9e4*e+(i?9e4*i.baseTime/i.timescale:0)},jo=[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],Wo=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],zo=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],qo=[0,1,1,4];function Xo(t,e,i,n,r){if(i+24>e.length)return;const s=Qo(e,i);if(s&&i+s.frameLength<=e.length){const a=n+r*(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 Qo(t,e){const i=t[e+1]>>3&3,n=t[e+1]>>1&3,r=t[e+2]>>4&15,s=t[e+2]>>2&3;if(1!==i&&0!==r&&15!==r&&3!==s){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*jo[14*(3===i?3-n:3===n?3:4)+r-1],h=Wo[3*(3===i?0:2===i?1:2)+s],c=3===o?1:2,u=zo[i][n],d=qo[n],f=8*u*d,g=Math.floor(u*l/h+a)*d,p=dr();return!!p&&p<=87&&2===n&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:h,channelCount:c,frameLength:g,samplesPerFrame:f}}}function Zo(t,e){return!(255!==t[e]||224&~t[e+1]||!(6&t[e+1]))}function Jo(t,e){return e+1<t.length&&Zo(t,e)}function tl(t,e){if(e+1<t.length&&Zo(t,e)){const i=4,n=Qo(t,e);let r=i;null!=n&&n.frameLength&&(r=n.frameLength);const s=e+r;return s===t.length||Jo(t,s)}return!1}class el{constructor(t,e,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Ns(e,!0)}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,Ds,{start:0,end:t.byteLength})}decryptAacSample(t,e,i){const n=t[e].unit;if(n.length<=16)return;const r=n.subarray(16,n.length-n.length%16),s=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(s).then(r=>{const s=new Uint8Array(r);n.set(s,16),this.decrypter.isSync()||this.decryptAacSamples(t,e+1,i)}).catch(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 n=0;for(let e=32;e<t.length-16;e+=160,n+=16)i.set(t.subarray(e,e+16),n);return i}getAvcDecryptedUnit(t,e){const i=new Uint8Array(e);let n=0;for(let e=32;e<t.length-16;e+=160,n+=16)t.set(i.subarray(n,n+16),e);return t}decryptAvcSample(t,e,i,n,r){const s=ir(r.data),a=this.getAvcEncryptedData(s);this.decryptBuffer(a.buffer).then(a=>{r.data=this.getAvcDecryptedUnit(s,a),this.decrypter.isSync()||this.decryptAvcSamples(t,e,i+1,n)}).catch(n)}decryptAvcSamples(t,e,i,n){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,i=0){if(e>=t.length)return void n();const r=t[e].units;for(;!(i>=r.length);i++){const s=r[i];if(!(s.data.length<=48||1!==s.type&&5!==s.type||(this.decryptAvcSample(t,e,i,n,s),this.decrypter.isSync())))return}}}}const il=(t,e)=>{let i=0,n=5;e+=n;const r=new Uint32Array(1),s=new Uint32Array(1),a=new Uint8Array(1);for(;n>0;){a[0]=t[e];const o=Math.min(n,8),l=8-o;s[0]=4278190080>>>24+l<<l,r[0]=(a[0]&s[0])>>l,i=i?i<<o|r[0]:r[0],e+=1,n-=o}return i};class nl extends Ho{constructor(t){super(),this.observer=void 0,this.observer=t}resetInitSegment(t,e,i,n){super.resetInitSegment(t,e,i,n),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:e,duration:n,inputTimeScale:9e4,dropped:0}}canParse(t,e){return e+64<t.length}appendFrame(t,e,i){const n=rl(t,e,i,this.basePTS,this.frameIndex);if(-1!==n){return{sample:t.samples[t.samples.length-1],length:n,missing:0}}}static probe(t){if(!t)return!1;const e=dn(t,0);if(!e)return!1;const i=e.length;if(11===t[i]&&119===t[i+1]&&void 0!==Tn(e)){if(il(t,i)<16)return!0;throw new Error("Containerless ec-3 is not supported")}return!1}}function rl(t,e,i,n,r){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 h=e[i+6]>>5;let c=0;2===h?c+=2:(1&h&&1!==h&&(c+=2),4&h&&(c+=2));const u=(e[i+6]<<8|e[i+7])>>12-c&1,d=[2,1,2,3,3,4,4,5][h]+u,f=e[i+5]>>3,g=7&e[i+5],p=new Uint8Array([s<<6|f<<1|g>>2,(3&g)<<6|h<<3|u<<2|o>>4,o<<4&224]),m=n+r*(1536/a*9e4),v=e.subarray(i,i+l);return t.config=p,t.channelCount=d,t.samplerate=a,t.samples.push({unit:v,pts:m}),l}const sl=/\/emsg[-/]ID3/i;function al(t,e){return Qe(t.presentationTime)?t.presentationTime/t.timeScale:e+t.presentationTimeDelta/t.timeScale}class ol{constructor(){this.VideoSample=null}createVideoSample(t,e,i){return{key:t,frame:!1,pts:e,dts:i,units:[],length:0}}getLastNalUnit(t){var e;let i,n=this.VideoSample;if(n&&0!==n.units.length||(n=t[t.length-1]),null!=(e=n)&&e.units){const t=n.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,n=i.length;if(!n)return void e.dropped++;{const e=i[n-1];t.pts=e.pts,t.dts=e.dts}}e.samples.push(t)}}parseNALu(t,e,i){const n=e.byteLength;if(0===n)return[];const r=t.naluState||0,s=-1===r?0:r,a=[];let o=0,l=0,h=-1,c=0;for(-1===r&&(h=0,c=this.getNALuType(e,0),l=1);l<n;){const i=e.indexOf(1,l);if(-1===i)break;l=i+1;let r=i;for(;r>0&&0===e[r-1];)r--;if(!(i-r+(0===r?s:0)<2)){if(h>=0)a.push({data:e.subarray(h,r),type:c});else{const i=this.getLastNalUnit(t.samples);i&&(r>0?i.data=Zn(i.data,e.subarray(0,r)):s>0&&(i.data=i.data.subarray(0,i.data.byteLength-s)),i.state=0)}if(!(l<n)){o=-1,h=-1;break}h=l,c=this.getNALuType(e,l)}}if(-1!==o){let t=n;for(;t>0&&0===e[t-1];)t--;o=n-t+(0===t?s:0)}if(h>=0)a.push({data:e.subarray(h),type:c,state:o});else if(0===a.length&&-1!==o){const i=this.getLastNalUnit(t.samples);i&&(i.data=Zn(i.data,e),i.state=o)}return t.naluState=o,a}}class ll{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,n=new Uint8Array(4),r=Math.min(4,e);if(0===r)throw new Error("no bytes available");n.set(t.subarray(i,i+r)),this.word=new DataView(n.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 i=this.word>>>32-e;if(t>32&&Zi.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)}}class hl extends ol{parsePES(t,e,i,n,r){const s=r.iframe,a=this.parseNALu(t,i.data,n);let o,l=this.VideoSample,h=!1;i.data=null,l&&a.length&&!t.audFound&&(this.pushAccessUnit(l,t),l=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),a.forEach(n=>{var r,a;switch(n.type){case 1:{if(s)break;let e=!1;o=!0;const r=n.data;if(h&&r.length>4){const t=this.readSliceType(r);2!==t&&4!==t&&7!==t&&9!==t||(e=!0)}var c;if(e)null!=(c=l)&&c.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null);l||(l=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),l.frame=!0,l.key=e;break}case 5:o=!0,null!=(r=l)&&r.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),l.key=!0,l.frame=!0;break;case 6:if(s)break;o=!0,er(n.data,1,i.pts,e.samples);break;case 7:{var u,d;o=!0,h=!0;const e=n.data,i=this.readSPS(e);if(!t.sps||t.width!==i.width||t.height!==i.height||(null==(u=t.pixelRatio)?void 0:u[0])!==i.pixelRatio[0]||(null==(d=t.pixelRatio)?void 0:d[1])!==i.pixelRatio[1]){t.width=i.width,t.height=i.height,t.pixelRatio=i.pixelRatio,t.sps=[e];const n=e.subarray(1,4);let r="avc1.";for(let t=0;t<3;t++){let e=n[t].toString(16);e.length<2&&(e="0"+e),r+=e}t.codec=r}break}case 8:o=!0,t.pps=[n.data];break;case 9:o=!0,t.audFound=!0,null!=(a=l)&&a.frame&&(this.pushAccessUnit(l,t),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:o=!0;break;default:o=!1}if(l&&o){l.units.push(n)}}),n&&l&&(this.pushAccessUnit(l,t),this.VideoSample=null)}getNALuType(t,e){return 31&t[e]}readSliceType(t){const e=new ll(t);return e.readUByte(),e.readUEG(),e.readUEG()}skipScalingList(t,e){let i,n=8,r=8;for(let s=0;s<t;s++)0!==r&&(i=e.readEG(),r=(n+i+256)%256),n=0===r?n:r}readSPS(t){const e=new ll(t);let i,n,r,s=0,a=0,o=0,l=0;const h=e.readUByte.bind(e),c=e.readBits.bind(e),u=e.readUEG.bind(e),d=e.readBoolean.bind(e),f=e.skipBits.bind(e),g=e.skipEG.bind(e),p=e.skipUEG.bind(e),m=this.skipScalingList.bind(this);h();const v=h();if(c(5),f(3),h(),p(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){const t=u();if(3===t&&f(1),p(),p(),f(1),d())for(n=3!==t?8:12,r=0;r<n;r++)d()&&m(r<6?16:64,e)}p();const y=u();if(0===y)u();else if(1===y)for(f(1),g(),g(),i=u(),r=0;r<i;r++)g();p(),f(1);const A=u(),E=u(),T=c(1);0===T&&f(1),f(1),d()&&(s=u(),a=u(),o=u(),l=u());let b=[1,1];if(d()&&d()){switch(h()){case 1:b=[1,1];break;case 2:b=[12,11];break;case 3:b=[10,11];break;case 4:b=[16,11];break;case 5:b=[40,33];break;case 6:b=[24,11];break;case 7:b=[20,11];break;case 8:b=[32,11];break;case 9:b=[80,33];break;case 10:b=[18,11];break;case 11:b=[15,11];break;case 12:b=[64,33];break;case 13:b=[160,99];break;case 14:b=[4,3];break;case 15:b=[3,2];break;case 16:b=[2,1];break;case 255:b=[h()<<8|h(),h()<<8|h()]}}return{width:Math.ceil(16*(A+1)-2*s-2*a),height:(2-T)*(E+1)*16-(T?2:4)*(o+l),pixelRatio:b}}}class cl extends ol{constructor(...t){super(...t),this.initVPS=null}parsePES(t,e,i,n){const r=this.parseNALu(t,i.data,n);let s,a=this.VideoSample,o=!1;i.data=null;const l=t=>(a=this.VideoSample=this.createVideoSample(t,i.pts,i.dts),a);r.forEach((n,r)=>{var h,c;if(this.startsNewAccessUnit(a,t,n,r)){this.pushAccessUnit(a,t);const e=n.type>=16&&n.type<=23;a=l(e),o=!1}switch(n.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=l(!1)),a.frame=!0,s=!0;break;case 16:case 17:case 18:case 21:case 22:case 23:var u;if(s=!0,o)null!=(u=a)&&u.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null);a||(a=l(!0)),a.key=!0,a.frame=!0;break;case 19:case 20:s=!0,null!=(h=a)&&h.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null),a||(a=l(!0)),a.key=!0,a.frame=!0;break;case 39:s=!0,er(n.data,2,i.pts,e.samples);break;case 32:s=!0,t.vps||("object"!=typeof t.params&&(t.params={}),t.params=Di(t.params,this.readVPS(n.data)),this.initVPS=n.data),t.vps=[n.data];break;case 33:if(s=!0,o=!0,void 0===t.vps||t.vps[0]===this.initVPS||void 0===t.sps||this.matchSPS(t.sps[0],n.data)||(this.initVPS=t.vps[0],t.sps=t.pps=void 0),!t.sps){const e=this.readSPS(n.data);t.width=e.width,t.height=e.height,t.pixelRatio=e.pixelRatio,t.codec=e.codecString,t.sps=[],"object"!=typeof t.params&&(t.params={});for(const i in e.params)t.params[i]=e.params[i]}this.pushParameterSet(t.sps,n.data,t.vps),a||(a=l(!1));break;case 34:if(s=!0,"object"==typeof t.params){if(!t.pps){t.pps=[];const e=this.readPPS(n.data);for(const i in e)t.params[i]=e[i]}this.pushParameterSet(t.pps,n.data,t.vps)}break;case 35:s=!0,t.audFound=!0,null!=(c=a)&&c.frame&&(this.pushAccessUnit(a,t),a=null),a||(a=l(!1));break;default:s=!1}if(a&&s){a.units.push(n)}}),n&&a&&(this.pushAccessUnit(a,t),this.VideoSample=null)}pushParameterSet(t,e,i){(i&&i[0]===this.initVPS||!i&&!t.length)&&t.push(e)}startsNewAccessUnit(t,e,i,n){if(!t)return!1;if(!e.audFound&&0===n)return!0;if(!t.frame)return!1;const{type:r,data:s}=i;return!!(r>=32&&r<=35||39===r||r>=41&&r<=44||r>=48&&r<=55)||r<=31&&s.length>2&&!!(128&s[2])}getNALuType(t,e){return(126&t[e])>>>1}ebsp2rbsp(t){const e=new Uint8Array(t.byteLength);let i=0;for(let n=0;n<t.byteLength;n++)n>=2&&3===t[n]&&0===t[n-1]&&0===t[n-2]||(e[i]=t[n],i++);return new Uint8Array(e.buffer,0,i)}pushAccessUnit(t,e){super.pushAccessUnit(t,e),this.initVPS&&(this.initVPS=null)}readVPS(t){const e=new ll(t);e.readUByte(),e.readUByte(),e.readBits(4),e.skipBits(2),e.readBits(6);return{numTemporalLayers:e.readBits(3)+1,temporalIdNested:e.readBoolean()}}readSPS(t){const e=new ll(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.readBits(4);const i=e.readBits(3);e.readBoolean();const n=e.readBits(2),r=e.readBoolean(),s=e.readBits(5),a=e.readUByte(),o=e.readUByte(),l=e.readUByte(),h=e.readUByte(),c=e.readUByte(),u=e.readUByte(),d=e.readUByte(),f=e.readUByte(),g=e.readUByte(),p=e.readUByte(),m=e.readUByte(),v=[],y=[];for(let t=0;t<i;t++)v.push(e.readBoolean()),y.push(e.readBoolean());if(i>0)for(let t=i;t<8;t++)e.readBits(2);for(let t=0;t<i;t++)v[t]&&(e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte()),y[t]&&e.readUByte();e.readUEG();const A=e.readUEG();3==A&&e.skipBits(1);const E=e.readUEG(),T=e.readUEG(),b=e.readBoolean();let S=0,k=0,_=0,L=0;b&&(S+=e.readUEG(),k+=e.readUEG(),_+=e.readUEG(),L+=e.readUEG());const R=e.readUEG(),I=e.readUEG(),C=e.readUEG();for(let t=e.readBoolean()?0:i;t<=i;t++)e.skipUEG(),e.skipUEG(),e.skipUEG();e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG();if(e.readBoolean()){if(e.readBoolean())for(let t=0;t<4;t++)for(let i=0;i<(3===t?2:6);i++){if(e.readBoolean()){const i=Math.min(64,1<<4+(t<<1));t>1&&e.readEG();for(let t=0;t<i;t++)e.readEG()}else e.readUEG()}}e.readBoolean(),e.readBoolean();e.readBoolean()&&(e.readUByte(),e.skipUEG(),e.skipUEG(),e.readBoolean());const P=e.readUEG();let D=0;for(let t=0;t<P;t++){let i=!1;if(0!==t&&(i=e.readBoolean()),i){t===P&&e.readUEG(),e.readBoolean(),e.readUEG();let i=0;for(let t=0;t<=D;t++){const t=e.readBoolean();let n=!1;t||(n=e.readBoolean()),(t||n)&&i++}D=i}else{const t=e.readUEG(),i=e.readUEG();D=t+i;for(let i=0;i<t;i++)e.readUEG(),e.readBoolean();for(let t=0;t<i;t++)e.readUEG(),e.readBoolean()}}if(e.readBoolean()){const t=e.readUEG();for(let i=0;i<t;i++){for(let t=0;t<C+4;t++)e.readBits(1);e.readBits(1)}}let w=0,O=1,x=1,M=!0,N=1,F=0;e.readBoolean(),e.readBoolean();let B=!1;if(e.readBoolean()){if(e.readBoolean()){const t=e.readUByte();t>0&&t<16?(O=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][t-1],x=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][t-1]):255===t&&(O=e.readBits(16),x=e.readBits(16))}e.readBoolean()&&e.readBoolean();if(e.readBoolean()){e.readBits(3),e.readBoolean();e.readBoolean()&&(e.readUByte(),e.readUByte(),e.readUByte())}e.readBoolean()&&(e.readUEG(),e.readUEG()),e.readBoolean(),e.readBoolean(),e.readBoolean(),B=e.readBoolean(),B&&(e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG());if(e.readBoolean()){N=e.readBits(32),F=e.readBits(32);e.readBoolean()&&e.readUEG();if(e.readBoolean()){const t=e.readBoolean(),n=e.readBoolean();let r=!1;(t||n)&&(r=e.readBoolean(),r&&(e.readUByte(),e.readBits(5),e.readBoolean(),e.readBits(5)),e.readBits(4),e.readBits(4),r&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let s=0;s<=i;s++){M=e.readBoolean();let i=!1;M||e.readBoolean()?e.readEG():i=e.readBoolean();const s=i?1:e.readUEG()+1;if(t)for(let t=0;t<s;t++)e.readUEG(),e.readUEG(),r&&(e.readUEG(),e.readUEG()),e.skipBits(1);if(n)for(let t=0;t<s;t++)e.readUEG(),e.readUEG(),r&&(e.readUEG(),e.readUEG()),e.skipBits(1)}}}e.readBoolean()&&(e.readBoolean(),e.readBoolean(),e.readBoolean(),w=e.readUEG())}let $=E,U=T;if(b){let t=1,e=1;1===A?t=e=2:2==A&&(t=2),$=E-t*k-t*S,U=T-e*L-e*_}const G=n?["A","B","C"][n]:"",V=a<<24|o<<16|l<<8|h;let K=0;for(let t=0;t<32;t++)K=(K|(V>>t&1)<<31-t)>>>0;let H=K.toString(16);1===s&&"2"===H&&(H="6");return{codecString:`hvc1.${G}${s}.${H}.${r?"H":"L"}${m}.B0`,params:{general_tier_flag:r,general_profile_idc:s,general_profile_space:n,general_profile_compatibility_flags:[a,o,l,h],general_constraint_indicator_flags:[c,u,d,f,g,p],general_level_idc:m,bit_depth:R+8,bit_depth_luma_minus8:R,bit_depth_chroma_minus8:I,min_spatial_segmentation_idc:w,chroma_format_idc:A,frame_rate:{fixed:M,fps:F/N}},width:$,height:U,pixelRatio:[O,x]}}readPPS(t){const e=new ll(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.skipUEG(),e.skipUEG(),e.skipBits(2),e.skipBits(3),e.skipBits(2),e.skipUEG(),e.skipUEG(),e.skipEG(),e.skipBits(2);e.readBoolean()&&e.skipUEG(),e.skipEG(),e.skipEG(),e.skipBits(4);const i=e.readBoolean(),n=e.readBoolean();let r=1;return n&&i?r=0:n?r=3:i&&(r=2),{parallelismType:r}}matchSPS(t,e){return _n(t).substring(3)===_n(e).substring(3)}}const ul=188;class dl{constructor(t,e,i,n){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this._klvPid=-1,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.videoIntegrityChecker=null,this.observer=t,this.config=e,this.typeSupported=i,this.logger=n,this.videoParser=null}static probe(t,e){const i=dl.syncOffset(t);return i>0&&e.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),-1!==i}static syncOffset(t){const e=t.length;let i=Math.min(940,e-ul)+1,n=0;for(;n<i;){let r=!1,s=-1,a=0;for(let o=n;o<e;o+=ul){if(71!==t[o]||e-o!==ul&&71!==t[o+ul]){if(a)return-1;break}if(a++,-1===s&&(s=o,0!==s&&(i=Math.min(s+18612,t.length-ul)+1)),r||(r=0===fl(t,o)),r&&a>1&&(0===s&&a>2||o+ul>i))return s}n++}return-1}static createTrack(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:In[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}}resetInitSegment(t,e,i,n,r,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=dl.createTrack("video"),this._videoTrack.duration=n,this.videoIntegrityChecker="skip"===this.config.handleMpegTsVideoIntegrityErrors?new Al(this.logger):null,this._audioTrack=dl.createTrack("audio",n),this._id3Track=dl.createTrack("id3"),this._txtTrack=dl.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=i,t&&this.demux(t,0,s,"SAMPLE-AES"===(null==r?void 0:r.method))}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,n=!1,r=!1){let s;n||(this.sampleAes=null);const a=this._videoTrack,o=this.videoIntegrityChecker,l=this._audioTrack,h=this._id3Track,c=this._txtTrack,u=i.iframe;let d=a.pid,f=a.pesData,g=l.pid,p=h.pid,m=this._klvPid,v=l.pesData,y=h.pesData,A=null,E=null,T=this.pmtParsed,b=this._pmtId,S=t.length;if(this.remainderData&&(S=(t=Zn(this.remainderData,t)).length,this.remainderData=null),S<ul&&!r)return this.remainderData=t,{audioTrack:l,videoTrack:a,id3Track:h,textTrack:c};const k=Math.max(0,dl.syncOffset(t));S-=(S-k)%ul,S<t.byteLength&&!r&&(this.remainderData=new Uint8Array(t.buffer,S,t.buffer.byteLength-S));let _=0;for(let e=k;e<S;e+=ul)if(71===t[e]){const r=!!(64&t[e+1]),S=fl(t,e);let _;if((48&t[e+3])>>4>1){if(_=e+5+t[e+4],_===e+ul)continue}else _=e+4;switch(S){case d:r&&(!f||null!=o&&o.isCorrupted||!(s=yl(f,this.logger))||(this.readyVideoParser(a.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(a,c,s,!1,i)),f={data:[],size:0},null==o||o.reset(d)),null==o||o.handlePacket(t.subarray(e)),f&&(f.data.push(t.subarray(_,e+ul)),f.size+=e+ul-_);break;case g:if(u)break;if(r){if(v&&(s=yl(v,this.logger)))switch(l.segmentCodec){case"aac":this.parseAACPES(l,s,i);break;case"mp3":this.parseMPEGPES(l,s);break;case"ac3":this.parseAC3PES(l,s)}v={data:[],size:0}}v&&(v.data.push(t.subarray(_,e+ul)),v.size+=e+ul-_);break;case p:if(u)break;r&&(y&&(s=yl(y,this.logger))&&this.parseID3PES(h,s),y={data:[],size:0}),y&&(y.data.push(t.subarray(_,e+ul)),y.size+=e+ul-_);break;case m:if(u)break;r&&(A&&(s=yl(A,this.logger))&&this.parseKlvPES(h,s),A={data:[],size:0}),A&&(A.data.push(t.subarray(_,e+ul)),A.size+=e+ul-_);break;case 0:r&&(_+=t[_]+1),b=this._pmtId=gl(t,_);break;case b:{r&&(_+=t[_]+1);const s=pl(t,_,this.typeSupported,n,this.observer,this.logger,this.config,i);d=s.videoPid,d>0&&(a.pid=d,a.segmentCodec=s.segmentVideoCodec),g=s.audioPid,g>0&&(l.pid=g,l.segmentCodec=s.segmentAudioCodec),p=s.id3Pid,p>0&&(h.pid=p),m=s.klvPid,m>0&&(this._klvPid=m),null===E||T||(this.logger.warn(`MPEG-TS PMT found at ${e} after unknown PID '${E}'. Backtracking to sync byte @${k} to parse all TS packets.`),E=null,e=k-188),T=this.pmtParsed=!0;break}case 17:case 8191:break;default:E=S}}else _++;_>0&&ml(this.observer,new Error(`Found ${_} TS packet/s that do not start with 0x47`),i,void 0,this.logger),a.pesData=f,l.pesData=v,h.pesData=y;const L={audioTrack:l,videoTrack:a,id3Track:h,textTrack:c};return r&&this.extractRemainingSamples(L,i),L}flush(t,e){const{remainderData:i}=this;let n;return this.remainderData=null,n=i?this.demux(i,0,e,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(n,e),this.sampleAes?this.decrypt(n,this.sampleAes):n}extractRemainingSamples(t,e){const{audioTrack:i,videoTrack:n,id3Track:r,textTrack:s}=t,a=n.pesData,o=i.pesData,l=r.pesData,h=this.videoIntegrityChecker;let c;if(!a||null!=h&&h.isCorrupted||!(c=yl(a,this.logger))?n.pesData=a:(this.readyVideoParser(n.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(n,s,c,!0,e),n.pesData=null)),o&&(c=yl(o,this.logger))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,c,e);break;case"mp3":this.parseMPEGPES(i,c);break;case"ac3":this.parseAC3PES(i,c)}i.pesData=null}else null!=o&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=o;l&&(c=yl(l,this.logger))?(this.parseID3PES(r,c),r.pesData=null):r.pesData=l}demuxSampleAes(t,e,i,n){const r=this.demux(t,i,n,!0,!this.config.progressive),s=this.sampleAes=new el(this.observer,this.config,e);return this.decrypt(r,s)}readyVideoParser(t){null===this.videoParser&&("avc"===t?this.videoParser=new hl:"hevc"===t&&(this.videoParser=new cl))}decrypt(t,e){return new Promise(i=>{const{audioTrack:n,videoTrack:r}=t;n.samples&&"aac"===n.segmentCodec?e.decryptAacSamples(n.samples,0,()=>{r.samples?e.decryptAvcSamples(r.samples,0,0,()=>{i(t)}):i(t)}):r.samples&&e.decryptAvcSamples(r.samples,0,0,()=>{i(t)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0,this.videoIntegrityChecker=null}parseAACPES(t,e,i){let n=0;const r=this.aacOverFlow;let s,a,o,l=e.data;if(r){this.aacOverFlow=null;const e=r.missing,i=r.sample.unit.byteLength;if(-1===e)l=Zn(r.sample.unit,l);else{const s=i-e;r.sample.unit.set(l.subarray(0,e),s),t.samples.push(r.sample),n=r.missing}}for(s=n,a=l.length;s<a-1&&!Fo(l,s);s++);if(s!==n){let t;const e=s<a-1;if(t=e?`AAC PES did not start with ADTS header,offset:${s}`:"No ADTS header found in AAC PES",ml(this.observer,new Error(t),i,e,this.logger),!e)return}if($o(t,this.observer,l,s,this.audioCodec),void 0!==e.pts)o=e.pts;else{if(!r)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const e=Uo(t.samplerate);o=r.sample.pts+e}}let h,c=0;for(;s<a;){if(h=Go(t,l,s,o,c),s+=h.length,h.missing){this.aacOverFlow=h;break}for(c++;s<a-1&&!Fo(l,s);s++);}}parseMPEGPES(t,e){const i=e.data,n=i.length;let r=0,s=0;const a=e.pts;if(void 0!==a)for(;s<n;)if(Jo(i,s)){const e=Xo(t,i,s,a,r);if(!e)break;s+=e.length,r++}else s++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(t,e){{const i=e.data,n=e.pts;if(void 0===n)return void this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");const r=i.length;let s,a=0,o=0;for(;o<r&&(s=rl(t,i,o,n,a++))>0;)o+=s}}parseID3PES(t,e){if(void 0===e.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const i=Di({},e,{type:this._videoTrack?Vo.emsg:Vo.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(i)}parseKlvPES(t,e){var i;const n=null!=(i=e.pts)?i:e.dts;if(void 0===n)return void this.logger.warn("[tsdemuxer]: KLV PES unknown PTS and DTS");const r=e.data;if(r.length<16)return void this.logger.warn("[tsdemuxer]: KLV PES payload too short");let s=0;for(;s<r.length;){var a;if(s+16>r.length)break;const i=s;if(s+=16,s>=r.length)break;const o=r[s];s+=1;let l=0;if(128&o){const t=127&o;if(0===t||t>4||s+t>r.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(let e=0;e<t;e++)l=l<<8|r[s+e];s+=t}else l=o;if(s+l>r.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}const h=s+l,c=r.subarray(i,h),u={data:c,len:c.byteLength,pts:n,dts:null!=(a=e.dts)?a:n,type:Vo.misbklv,duration:Number.POSITIVE_INFINITY};t.samples.push(u),s=h}}}function fl(t,e){return((31&t[e+1])<<8)+t[e+2]}function gl(t,e){return(31&t[e+10])<<8|t[e+11]}function pl(t,e,i,n,r,s,a,o){const l={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},h=e+3+((15&t[e+1])<<8|t[e+2])-4;for(e+=12+((15&t[e+10])<<8|t[e+11]);e<h;){const h=fl(t,e),c=(15&t[e+3])<<8|t[e+4];switch(t[e]){case 207:if(!n){vl("ADTS AAC",s);break}case 15:-1===l.audioPid&&(l.audioPid=h);break;case 21:-1===l.id3Pid&&(l.id3Pid=h);break;case 219:if(!n){vl("H.264",s);break}case 27:-1===l.videoPid&&(l.videoPid=h);break;case 3:case 4:i.mpeg||i.mp3?-1===l.audioPid&&(l.audioPid=h,l.segmentAudioCodec="mp3"):s.log("MPEG audio found, not supported in this browser");break;case 193:if(!n){vl("AC-3",s);break}case 129:i.ac3?-1===l.audioPid&&(l.audioPid=h,l.segmentAudioCodec="ac3"):s.log("AC-3 audio found, not supported in this browser");break;case 6:if(c>0){let n=e+5,r=c;for(;r>2;){switch(t[n]){case 106:-1===l.audioPid&&(!0!==i.ac3?s.log("AC-3 audio found, not supported in this browser for now"):(l.audioPid=h,l.segmentAudioCodec="ac3"));break;case 5:-1===l.klvPid&&a.enableEmsgKLVMetadata&&(l.klvPid=h,s.log(`KLV metadata PID found: ${h}`))}const e=t[n+1]+2;n+=e,r-=e}}break;case 194:case 135:return ml(r,new Error("Unsupported EC-3 in M2TS found"),o,void 0,s),l;case 36:-1===l.videoPid&&(l.videoPid=h,l.segmentVideoCodec="hevc",s.log("HEVC in M2TS found"))}e+=c+5}return l}function ml(t,e,i,n,r){r.warn(`parsing error: ${e.message}`),t.emit(ii.ERROR,ii.ERROR,{type:ti.MEDIA_ERROR,details:ei.FRAG_PARSING_ERROR,fatal:!1,levelRetry:n,chunkMeta:i,error:e,reason:e.message})}function vl(t,e){e.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function yl(t,e){let i,n,r,s,a,o=0;const l=t.data;if(!t||0===t.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=Zn(l[0],l[1]),l.splice(1,1);i=l[0];if(1===(i[0]<<16)+(i[1]<<8)+i[2]){if(n=(i[4]<<8)+i[5],n&&n>t.size-6)return null;const h=i[7];192&h&&(s=536870912*(14&i[9])+4194304*(255&i[10])+16384*(254&i[11])+128*(255&i[12])+(254&i[13])/2,64&h?(a=536870912*(14&i[14])+4194304*(255&i[15])+16384*(254&i[16])+128*(255&i[17])+(254&i[18])/2,s-a>54e5&&(e.warn(`${Math.round((s-a)/9e4)}s delta between PTS and DTS, align them`),s=a)):a=s),r=i[8];let c=r+9;if(t.size<=c)return null;t.size-=c;const u=new Uint8Array(t.size);for(let t=0,e=l.length;t<e;t++){i=l[t];let e=i.byteLength;if(c){if(c>e){c-=e;continue}i=i.subarray(c),e-=c,c=0}u.set(i,o),o+=e}return n&&(n-=r+3),{data:u,pts:s,dts:a,len:n}}return null}class Al{constructor(t){this.logger=void 0,this.pid=0,this.lastContinuityCounter=-1,this.integrityState="ok",this.logger=t}get isCorrupted(){return"ok"!==this.integrityState}reset(t){this.pid=t,this.lastContinuityCounter=-1,this.integrityState="ok"}handlePacket(t){if(t.byteLength<4)return;const e=fl(t,0);if(e!==this.pid)return void this.logger.debug(`Packet PID mismatch, expected ${this.pid} got ${e}`);const i=(48&t[3])>>4;if(0===i)return;const n=15&t[3],r=this.lastContinuityCounter;this.lastContinuityCounter=n;const s=!!(1&i);if(!!(2&i)&&0!=t[4]&&!!(128&t[5]))return;if(r<0)return;const a=s?r+1&15:r;return n!==a?(this.logger.warn(`MPEG-TS Continuity Counter check failed for PID='${e}', CC=${n}, Expected-CC=${a} Last-CC=${r}`),void(this.integrityState="cc-failed")):128&t[1]?(this.logger.warn(`MPEG-TS Packet had TEI flag set for PID='${e}'`),void(this.integrityState="tei-bit")):void 0}}class El{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])}}}var Tl;const bl={video: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]),audio: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])},Sl=new Uint8Array([0,0,0,0,0,0,0,0]),kl=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),_l=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Ll=new Uint8Array([0,0,0,0,0,0,0,0]),Rl=new Uint8Array([0,0,0,0,0,0,0,1]),Il=new Uint8Array([105,115,111,109]),Cl=new Uint8Array([97,118,99,49]),Pl=new Uint8Array([0,0,0,1]);class Dl{static box(t,...e){let i=8,n=e.length;const r=n;for(;n--;)i+=e[n].byteLength;const s=new Uint8Array(i);for(xn(s,0,i),xn(s,4,t),n=0,i=8;n<r;n++)s.set(e[n],i),i+=e[n].byteLength;return s}static hdlr(t){return Dl.box(Rn.hdlr,bl[t])}static mdat(t){return Dl.box(Rn.mdat,t)}static mdhd(t,e){e*=t;const i=Math.floor(e/(Ln+1)),n=Math.floor(e%(Ln+1));return Dl.box(Rn.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,n>>24,n>>16&255,n>>8&255,255&n,85,196,0,0]))}static mdia(t){return Dl.box(Rn.mdia,Dl.mdhd(t.timescale||0,t.duration||0),Dl.hdlr(t.type),Dl.minf(t))}static mfhd(t){return Dl.box(Rn.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}static minf(t){return"audio"===t.type?Dl.box(Rn.minf,Dl.box(Rn.smhd,Ll),Dl.DINF,Dl.stbl(t)):Dl.box(Rn.minf,Dl.box(Rn.vmhd,_l),Dl.DINF,Dl.stbl(t))}static moof(t,e,i){return Dl.box(Rn.moof,Dl.mfhd(t),Dl.traf(i,e))}static moov(t){let e=t.length;const i=[];for(;e--;)i[e]=Dl.trak(t[e]);return Dl.box.apply(null,[Rn.moov,Dl.mvhd(t[0].timescale||0,t[0].duration||0)].concat(i).concat(Dl.mvex(t)))}static mvex(t){let e=t.length;const i=[];for(;e--;)i[e]=Dl.trex(t[e]);return Dl.box.apply(null,[Rn.mvex,...i])}static mvhd(t,e){e*=t;const i=Math.floor(e/(Ln+1)),n=Math.floor(e%(Ln+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,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,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 Dl.box(Rn.mvhd,r)}static sdtp(t){const e=t.samples||[],i=new Uint8Array(4+e.length);let n,r;for(n=0;n<e.length;n++)r=e[n].flags,i[n+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return Dl.box(Rn.sdtp,i)}static stbl(t){return Dl.box(Rn.stbl,Dl.stsd(t),Dl.box(Rn.stts,Sl),Dl.box(Rn.stsc,Sl),Dl.box(Rn.stsz,kl),Dl.box(Rn.stco,Sl))}static avc1(t){let e,i,n,r=[],s=[];for(e=0;e<t.sps.length;e++)i=t.sps[e],n=i.byteLength,r.push(n>>>8&255),r.push(255&n),r=r.concat(Array.prototype.slice.call(i));for(e=0;e<t.pps.length;e++)i=t.pps[e],n=i.byteLength,s.push(n>>>8&255),s.push(255&n),s=s.concat(Array.prototype.slice.call(i));const a=Dl.box(Rn.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|t.sps.length].concat(r).concat([t.pps.length]).concat(s))),o=t.width,l=t.height,h=t.pixelRatio[0],c=t.pixelRatio[1];return Dl.box(Rn.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,Dl.box(Rn.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Dl.box(Rn.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,c>>24,c>>16&255,c>>8&255,255&c])))}static esds(t){const e=t.config,i=e.length;return new Uint8Array([0,0,0,0,3,23+i,0,1,0,4,15+i,64,21,0,0,0,0,0,0,0,0,0,0,0,5,i,...e,6,1,2])}static audioStsd(t){const e=t.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount||0,0,16,0,0,0,0,e>>8&255,255&e,0,0])}static mp4a(t){return Dl.box(Rn.mp4a,Dl.audioStsd(t),Dl.box(Rn.esds,Dl.esds(t)))}static mp3(t){return Dl.box(Rn[".mp3"],Dl.audioStsd(t))}static ac3(t){return Dl.box(Rn["ac-3"],Dl.audioStsd(t),Dl.box(Rn.dac3,t.config))}static stsd(t){const{segmentCodec:e}=t;if("audio"===t.type){if("aac"===e)return Dl.box(Rn.stsd,Rl,Dl.mp4a(t));if("ac3"===e&&t.config)return Dl.box(Rn.stsd,Rl,Dl.ac3(t));if("mp3"===e&&"mp3"===t.codec)return Dl.box(Rn.stsd,Rl,Dl.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===e)return Dl.box(Rn.stsd,Rl,Dl.avc1(t));if("hevc"===e&&t.vps)return Dl.box(Rn.stsd,Rl,Dl.hvc1(t))}throw new Error(`unsupported ${t.type} segment codec (${e}/${t.codec})`)}static tkhd(t){const e=t.id,i=(t.duration||0)*(t.timescale||0),n=t.width||0,r=t.height||0,s=Math.floor(i/(Ln+1)),a=Math.floor(i%(Ln+1));return Dl.box(Rn.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,n>>8&255,255&n,0,0,r>>8&255,255&r,0,0]))}static traf(t,e){const i=Dl.sdtp(t),n=t.id,r=Math.floor(e/(Ln+1)),s=Math.floor(e%(Ln+1));return Dl.box(Rn.traf,Dl.box(Rn.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n])),Dl.box(Rn.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,s>>24,s>>16&255,s>>8&255,255&s])),Dl.trun(t,i.length+16+20+8+16+8+8),i)}static trak(t){return t.duration=t.duration||4294967295,Dl.box(Rn.trak,Dl.tkhd(t),Dl.mdia(t))}static trex(t){const e=t.id;return Dl.box(Rn.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||[],n=i.length,r=12+16*n,s=new Uint8Array(r);let a,o,l,h,c,u;for(e+=8+r,s.set(["video"===t.type?1:0,0,15,1,n>>>24&255,n>>>16&255,n>>>8&255,255&n,e>>>24&255,e>>>16&255,e>>>8&255,255&e],0),a=0;a<n;a++)o=i[a],l=o.duration,h=o.size,c=o.flags,u=o.cts,s.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,h>>>24&255,h>>>16&255,h>>>8&255,255&h,c.isLeading<<2|c.dependsOn,c.isDependedOn<<6|c.hasRedundancy<<4|c.paddingValue<<1|c.isNonSync,61440&c.degradPrio,15&c.degradPrio,u>>>24&255,u>>>16&255,u>>>8&255,255&u],12+16*a);return Dl.box(Rn.trun,s)}static initSegment(t){const e=Dl.moov(t);return Zn(Dl.FTYP,e)}static hvc1(t){const e=t.params,i=[t.vps,t.sps,t.pps],n=new Uint8Array([1,e.general_profile_space<<6|(e.general_tier_flag?32:0)|e.general_profile_idc,e.general_profile_compatibility_flags[0],e.general_profile_compatibility_flags[1],e.general_profile_compatibility_flags[2],e.general_profile_compatibility_flags[3],e.general_constraint_indicator_flags[0],e.general_constraint_indicator_flags[1],e.general_constraint_indicator_flags[2],e.general_constraint_indicator_flags[3],e.general_constraint_indicator_flags[4],e.general_constraint_indicator_flags[5],e.general_level_idc,240|e.min_spatial_segmentation_idc>>8,255&e.min_spatial_segmentation_idc,252|e.parallelismType,252|e.chroma_format_idc,248|e.bit_depth_luma_minus8,248|e.bit_depth_chroma_minus8,0,parseInt(e.frame_rate.fps),3|e.temporal_id_nested<<2|e.num_temporal_layers<<3|(e.frame_rate.fixed?64:0),i.length]);let r=n.length;for(let t=0;t<i.length;t+=1){r+=3;for(let e=0;e<i[t].length;e+=1)r+=2+i[t][e].length}const s=new Uint8Array(r);s.set(n,0),r=n.length;const a=i.length-1;for(let t=0;t<i.length;t+=1){s.set(new Uint8Array([32+t|(t===a?128:0),0,i[t].length]),r),r+=3;for(let e=0;e<i[t].length;e+=1)s.set(new Uint8Array([i[t][e].length>>8,255&i[t][e].length]),r),r+=2,s.set(i[t][e],r),r+=i[t][e].length}const o=Dl.box(Rn.hvcC,s),l=t.width,h=t.height,c=t.pixelRatio[0],u=t.pixelRatio[1];return Dl.box(Rn.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,h>>8&255,255&h,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,Dl.box(Rn.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Dl.box(Rn.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,255&c,u>>24,u>>16&255,u>>8&255,255&u])))}}Tl=Dl,Dl.FTYP=Tl.box(Rn.ftyp,Il,Pl,Il,Cl),Dl.DINF=Tl.box(Rn.dinf,Tl.box(Rn.dref,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1])));function wl(t,e,i=1,n=!1){const r=t*e*i;return n?Math.round(r):r}function Ol(t,e=!1){return wl(t,1e3,1/9e4,e)}function xl(t){const{baseTime:e,timescale:i,trackId:n}=t;return`${e/i} (${e}/${i}) trackId: ${n}`}const Ml=8589934592;function Nl(t,e,i,n){return{duration:e,size:i,cts:n,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1,paddingValue:0}}}class Fl extends ji{constructor(t,e,i,n){super("mp4-remuxer",n),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=t,this.config=e,this.typeSupported=i,this.ISGenerated=!1}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){const e=this._initPTS;e&&t&&t.trackId===e.trackId&&t.baseTime===e.baseTime&&t.timescale===e.timescale||this.log(`Reset initPTS: ${e?xl(e):e} > ${t?xl(t):t}`),this._initPTS=this._initDTS=t}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let e=!1;const i=t[0].pts,n=t.reduce((t,n)=>{let r=n.pts,s=r-t;return s<-4294967296&&(e=!0,r=Bl(r,i),s=r-t),s>0?t:r},i);return e&&this.debug("PTS rollover detected"),n}remux(t,e,i,n,r,s,a,o,l){let h,c,u,d,f,g,p=r,m=r;const v=!l.iframe&&t.pid>-1,y=e.pid>-1,A=e.samples.length,E=t.samples.length>0,T=a&&A>0||A>1;if((!v||E)&&(!y||T)||this.ISGenerated||a){if(this.ISGenerated){var b,S,k,_;const t=this.videoTrackConfig;(t&&(e.width!==t.width||e.height!==t.height||(null==(b=e.pixelRatio)?void 0:b[0])!==(null==(S=t.pixelRatio)?void 0:S[0])||(null==(k=e.pixelRatio)?void 0:k[1])!==(null==(_=t.pixelRatio)?void 0:_[1]))||!t&&T||null===this.nextAudioTs&&E)&&this.resetInitSegment()}this.ISGenerated||(u=this.generateIS(t,e,r,s));const i=this.isVideoContiguous;let n,a=-1;if(T&&(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(g=!0,a>0){this.warn(`Dropped ${a} out of ${A} 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,n=m}else-1===a&&(this.warn(`No keyframe found out of ${A} video samples`),g=!1);if(this.ISGenerated){if(E&&T&&r){const i=this.getVideoStartPts(e.samples),n=(Bl(t.samples[0].pts,i)-i)/e.inputTimeScale;p+=Math.max(0,n),m+=Math.max(0,-n)}if(E){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),u=this.generateIS(t,e,r,s)),c=this.remuxAudio(t,p,this.isAudioContiguous,s,y||T||o===yi?m:void 0,l),T){const n=c?c.endPTS-c.startPTS:0;e.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),u=this.generateIS(t,e,r,s)),h=this.remuxVideo(e,m,i,n,l)}}else T&&(h=this.remuxVideo(e,m,i,0,l));h&&(h.firstKeyFrame=a,h.independent=-1!==a,h.firstKeyFramePTS=n)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(f=$l(i,r,this._initPTS,this._initDTS)),n.samples.length&&(d=Ul(n,r,this._initPTS))),{audio:c,video:h,initSegment:u,independent:g,text:d,id3:f}}computeInitPts(t,e,i,n){const r=Math.round(i*e);let s=Bl(t,r);if(s<r)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-s)/e} ${n}`);s<r;)s+=Ml;return s-r}generateIS(t,e,i,n){const r=t.samples,s=e.samples,a=this.typeSupported,o={},l=this._initPTS,h=!l||n;let c,u,d,f="audio/mp4",g=-1;if(h&&(c=u=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"}if(o.audio={id:"audio",container:f,codec:t.codec,initSegment:"mp3"===t.segmentCodec&&a.mpeg?new Uint8Array(0):Dl.initSegment([t]),metadata:{channelCount:t.channelCount}},h){g=t.id,d=t.inputTimeScale;const e=this.computeInitPts(r[0].pts,d,i,"audio");(!l||d!==l.timescale||0===i&&e<l.baseTime)&&(c=u=e)}}if(e.sps&&e.pps&&s.length){if(e.timescale=e.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:Dl.initSegment([e]),metadata:{width:e.width,height:e.height}},h){g=e.id,d=e.inputTimeScale;const t=this.getVideoStartPts(s),n=Bl(s[0].dts,t),r=this.computeInitPts(n,d,i,"video"),a=this.computeInitPts(t,d,i,"video");(!l||d!==l.timescale||Qe(c)||0===i&&a<l.baseTime)&&(u=Math.min(u,r),c=Math.min(c,r))}this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,h&&Qe(c)?(l&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${i} ${c/d} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${c/d} (${c}/${d}) trackId: ${g}`),this._initPTS={baseTime:c,timescale:d,trackId:g},this._initDTS={baseTime:u,timescale:d,trackId:g}):c=d=void 0,{tracks:o,initPTS:c,timescale:d,trackId:g}}remuxVideo(t,e,i,n,r){const s=t.inputTimeScale,a=t.samples,o=[],l=a.length,h=this._initPTS,c=h.baseTime*s/h.timescale;let u,d,f=this.nextVideoTs,g=8,p=this.videoSampleDuration,m=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY,y=!1;if(!i||null===f){const t=c+e*s,n=a[0].pts-Bl(a[0].dts,a[0].pts);dr()&&null!==f&&Math.abs(t-n-(f+c))<15e3?i=!0:f=t-n-c}const A=f+c;for(let t=0;t<l;t++){const e=a[t];e.pts=Bl(e.pts,A),e.dts=Bl(e.dts,A),e.dts<a[t>0?t-1:t].dts&&(y=!0)}y&&a.sort(function(t,e){const i=t.dts-e.dts,n=t.pts-e.pts;return i||n}),u=a[0].dts,d=a[a.length-1].dts;const E=d-u,T=E?Math.round(E/(l-1)):p||t.inputTimeScale/30;if(i){const i=u-A,n=i>T,r=i<-1;if((n||r)&&(n?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${Ol(i,!0)} ms (${i}dts) hole between fragments detected at ${e.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${Ol(-i,!0)} ms (${i}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!r||A>=a[0].pts||dr())){u=A;const t=a[0].pts-i;if(n)a[0].dts=u,a[0].pts=t;else{let e=!0;for(let n=0;n<a.length&&!(a[n].dts>t&&e);n++){const t=a[n].pts;if(a[n].dts-=i,a[n].pts-=i,n<a.length-1){const i=a[n+1].pts;e=i<=a[n].pts==i<=t}}}this.log(`Video: Initial PTS/DTS adjusted: ${Ol(t,!0)}/${Ol(u,!0)}, delta: ${Ol(i,!0)} ms`)}}u=Math.max(0,u);let b=0,S=0,k=u;for(let t=0;t<l;t++){const e=a[t],i=e.units,n=i.length;let r=0;for(let t=0;t<n;t++)r+=i[t].data.length;S+=r,b+=n,e.length=r,e.dts<k?(e.dts=k,k+=T/4|0||1):k=e.dts,m=Math.min(e.pts,m),v=Math.max(e.pts,v)}d=a[l-1].dts;const _=S+4*b+8;let L;try{L=new Uint8Array(_)}catch(t){return void this.observer.emit(ii.ERROR,ii.ERROR,{type:ti.MUX_ERROR,details:ei.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:r,error:t,bytes:_,reason:`fail allocating video mdat ${_}`})}xn(L,0,_),xn(L,4,Rn.mdat);let R=!1,I=Number.POSITIVE_INFINITY,C=Number.POSITIVE_INFINITY,P=Number.NEGATIVE_INFINITY,D=Number.NEGATIVE_INFINITY;for(let t=0;t<l;t++){const e=a[t],h=e.units;let u,d=0;for(let t=0,e=h.length;t<e;t++){const e=h[t],i=e.data,n=e.data.byteLength;xn(L,g,n),g+=4,L.set(i,g),g+=n,d+=4+n}if(t<l-1)p=a[t+1].dts-e.dts,u=a[t+1].pts-e.pts;else{const i=this.config,r=t>0?e.dts-a[t-1].dts:T;if(u=t>0?e.pts-a[t-1].pts:T,i.stretchShortVideoTrack&&null!==this.nextAudioTs){const t=Math.floor(i.maxBufferHole*s),a=(n?m+n*s:this.nextAudioTs+c)-e.pts;a>t?(p=a-r,p<0?p=r:R=!0,this.log(`It is approximately ${a/90} ms to the next segment; using duration ${p/90} ms for the last video frame.`)):p=r}else p=r}let f=Math.round(e.pts-e.dts);if(I=Math.min(I,p),P=Math.max(P,p),C=Math.min(C,u),D=Math.max(D,u),!i&&0===t&&f>p){const t=Math.round(f/T)*T;t-f===1&&(this.log(`pad first CTS ${f} -> ${t} of sn: ${r.sn}`),f=t)}o.push(Nl(e.key,p,d,f))}if(o.length){const t=dr();if(t){if(t<70){const t=o[0].flags;t.dependsOn=2,t.isNonSync=0}}else if(function(){if(void 0===cr){const t=ar.match(/Safari\/(\d+)/i);cr=t?parseInt(t[1]):0}return cr}()&&D-C<P-I&&T/P<.025&&0===o[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let t=u;for(let e=0,i=o.length;e<i;e++){const n=t+o[e].duration,r=t+o[e].cts;if(e<i-1){const t=n+o[e+1].cts;o[e].duration=t-r}else o[e].duration=e?o[e-1].duration:T;o[e].cts=0,t=n}}}p=R||!p?T:p;const w=d+p;this.nextVideoTs=f=w-c,this.videoSampleDuration=p,this.isVideoContiguous=!0,r.iframe&&(1===o.length?(o[0].duration=p=r.duration*s,this.nextVideoTs=f=u+p-c):this.warn(`Not adjusting IFrame duration (sample count ${o.length})`));const O={data1:Dl.moof(r.sn,u,Di(t,{samples:o})),data2:L,startPTS:(m-c)/s,endPTS:(v+p-c)/s,startDTS:(u-c)/s,endDTS:f/s,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:t.dropped};return t.samples=[],t.dropped=0,O}getSamplesPerFrame(t){switch(t.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(t,e,i,n,r,s){const a=t.inputTimeScale,o=a/(t.samplerate?t.samplerate:a),l=this.getSamplesPerFrame(t),h=l*o,c=this._initPTS,u="mp3"===t.segmentCodec&&this.typeSupported.mpeg,d=[],f=void 0!==r;let g=t.samples,p=u?0:8,m=this.nextAudioTs||-1;const v=c.baseTime*a/c.timescale,y=v+e*a;if(this.isAudioContiguous=i=i||g.length&&m>0&&(n&&Math.abs(y-(m+v))<9e3||Math.abs(Bl(g[0].pts,y)-(m+v))<20*h),g.forEach(function(t){t.pts=Bl(t.pts,y)}),!i||m<0){const t=g.length;if(g=g.filter(t=>t.pts>=0),t!==g.length&&this.warn(`Removed ${g.length-t} of ${t} samples (initPTS ${v} / ${a})`),!g.length)return;m=0===r?0:n&&!f?Math.max(0,y-v):g[0].pts-v}if("aac"===t.segmentCodec){const e=this.config.maxAudioFramesDrift;for(let i=0,n=m+v;i<g.length;i++){const r=g[i],s=r.pts,o=s-n,l=Math.abs(1e3*o/a);if(o<=-e*h&&f)0===i&&(this.warn(`Audio frame @ ${(s/a).toFixed(3)}s overlaps marker by ${Math.round(1e3*o/a)} ms.`),this.nextAudioTs=m=s-v,n=s);else if(o>=e*h&&l<1e4&&f){let e=Math.round(o/h);for(n=s-e*h;n<0&&e&&h;)e--,n+=h;0===i&&(this.nextAudioTs=m=n-v),this.warn(`Injecting ${e} audio frames @ ${((n-v)/a).toFixed(3)}s due to ${Math.round(1e3*o/a)} ms gap.`);for(let s=0;s<e;s++){let e=El.getSilentFrame(t.parsedCodec||t.manifestCodec||t.codec,t.channelCount);e||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),e=r.unit.subarray()),g.splice(i,0,{unit:e,pts:n}),n+=h,i++}}r.pts=n,n+=h}}let A,E=null,T=null,b=0,S=g.length;for(;S--;)b+=g[S].unit.byteLength;for(let e=0,n=g.length;e<n;e++){const n=g[e],r=n.unit;let a=n.pts;if(null!==T){d[e-1].duration=Math.round((a-T)/o)}else{if(i&&"aac"===t.segmentCodec&&(a=m+v),E=a,!(b>0))return;b+=p;try{A=new Uint8Array(b)}catch(t){return void this.observer.emit(ii.ERROR,ii.ERROR,{type:ti.MUX_ERROR,details:ei.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:s,error:t,bytes:b,reason:`fail allocating audio mdat ${b}`})}u||(xn(A,0,b),xn(A,4,Rn.mdat))}A&&A.set(r,p);const h=r.byteLength;p+=h,d.push(Nl(!0,l,h,0)),T=a}const k=d.length;if(!k)return;const _=d[d.length-1];m=T-v,this.nextAudioTs=m+o*_.duration;const L=u?new Uint8Array(0):Dl.moof(t.sequenceNumber++,E/o,Di({},t,{samples:d}));t.samples=[];const R=(E-v)/a,I=this.nextAudioTs/a,C={data1:L,data2:A,startPTS:R,endPTS:I,startDTS:R,endDTS:I,type:"audio",hasAudio:!0,hasVideo:!1,nb:k};return this.isAudioContiguous=!0,C}}function Bl(t,e){let i;if(null===e)return t;for(i=e<t?-8589934592:Ml;Math.abs(t-e)>4294967296;)t+=i;return t}function $l(t,e,i,n){const r=t.samples.length;if(!r)return;const s=t.inputTimeScale;for(let a=0;a<r;a++){const r=t.samples[a];r.pts=Bl(r.pts-i.baseTime*s/i.timescale,e*s)/s,r.dts=Bl(r.dts-n.baseTime*s/n.timescale,e*s)/s}const a=t.samples;return t.samples=[],{samples:a}}function Ul(t,e,i){const n=t.samples.length;if(!n)return;const r=t.inputTimeScale;for(let s=0;s<n;s++){const n=t.samples[s];n.pts=Bl(n.pts-i.baseTime*r/i.timescale,e*r)/r}t.samples.sort((t,e)=>t.pts-e.pts);const s=t.samples;return t.samples=[],{samples:s}}function Gl(t,e,i=!1){return void 0!==(null==t?void 0:t.start)?(t.start+(i?t.duration:0))/t.timescale:e}function Vl(t,e,i){const n=t.codec;if(n&&n.length>4)return n;if(e===Ei){if("ec-3"===n||"ac-3"===n||"alac"===n)return n;if("fLaC"===n||"Opus"===n){return Sr(n,!1)}return i.warn(`Unhandled audio codec "${n}" in mp4 MAP`),n||"mp4a"}return"mjpg"===n?n:(i.warn(`Unhandled video codec "${n}" in mp4 MAP`),n||"avc1")}let Kl;try{Kl=self.performance.now.bind(self.performance)}catch(t){Kl=Date.now}const Hl=[{demux:class{constructor(t,e,i,n=Zi){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.initData=void 0,this.logger=void 0,this.config=e,this.logger=n}resetTimeStamp(){}resetInitSegment(t,e,i,n){const r=this.videoTrack=Ko("video",1),s=this.audioTrack=Ko("audio",1),a=this.txtTrack=Ko("text",1);if(this.id3Track=Ko("id3",1),this.initData=void 0,this.timeOffset=0,null==t||!t.byteLength)return;const o=this.initData=Gn(t);if(o.video){const{id:t,timescale:e,codec:i,supplemental:n}=o.video;r.id=t,r.timescale=a.timescale=e,r.codec=i,r.supplemental=n}if(o.audio){const{id:t,timescale:e,codec:i}=o.audio;s.id=t,s.timescale=e,s.codec=i}a.id=In.text,r.sampleDuration=0,r.duration=s.duration=n}resetContiguity(){this.remainderData=null}static probe(t){return function(t,e){const i=t.byteLength;for(let n=0;n<i;){const r=Pn(t,n);if(r>8&&Pn(t,n+4)===Rn[e])return!0;n=r>1?n+r:i}return!1}(t,"moof")}demux(t,e,i){this.timeOffset=e;let n=t;const r=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(n=Zn(this.remainderData,t));const e=function(t){const e={valid:null,remainder:null},i=Bn(t,["moof"]);if(i.length<2)return e.remainder=t,e;const n=i[i.length-1];return e.valid=t.slice(0,n.byteOffset-8),e.remainder=t.slice(n.byteOffset-8),e}(n);this.remainderData=e.remainder,r.samples=e.valid||new Uint8Array}else r.samples=n;const a=this.extractID3Track(r,e),o=this.parseFragment(r,s,e,i);return{videoTrack:r,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack,initData:this.initData,sampleData:o}}flush(t,e){const i=this.timeOffset,n=this.videoTrack,r=this.txtTrack;n.samples=this.remainderData||new Uint8Array,this.remainderData=null;const s=this.extractID3Track(n,this.timeOffset),a=this.parseFragment(n,r,i,e);return{videoTrack:n,audioTrack:Ko(),id3Track:s,textTrack:Ko(),initData:this.initData,sampleData:a}}parseFragment(t,e,i,n){const r=this.initData;if(r&&n){const{samples:s,sampleData:a}=function(t,e,i,n,r=!1){const s=[];return{samples:s,sampleData:{includeSampleDetails:r,tracks:Qn(e.samples,i,n,r,{isHEVCFlavor:Jn(e.codec),samples:s,timeOffset:t,timescale:e.timescale,trackId:e.id})}}}(i,t,r,this.logger,n.iframe);return e.samples=s,a}e.samples=function(t,e){const i=[],n=e.samples,r=e.timescale,s=e.id;let a=!1;return Bn(n,["moof"]).map(o=>{const l=o.byteOffset-8;Bn(o,["traf"]).map(o=>{const h=Bn(o,["tfdt"]).map(t=>{const e=t[0];let i=Pn(t,4);return 1===e&&(i*=Math.pow(2,32),i+=Pn(t,8)),i/r})[0];return void 0!==h&&(t=h),Bn(o,["tfhd"]).map(h=>{const c=Pn(h,4),u=16777215&Pn(h,0),d=!!(1&u);let f=0;const g=!!(2&u),p=!!(8&u);let m=0;const v=!!(16&u);let y=0;const A=!!(32&u),E=!d&&!!(131072&u);let T=8;c===s&&(d?(f=Pn(h,T),T+=4,f*=Math.pow(2,32),f+=Pn(h,T),T+=4):E&&(f=l),g&&(T+=4),p&&(m=Pn(h,T),T+=4),v&&(y=Pn(h,T),T+=4),A&&(T+=4),"video"===e.type&&(a=Jn(e.codec)),Bn(o,["trun"]).map(s=>{const o=s[0],l=16777215&Pn(s,0),h=!!(1&l);let c=0;const u=!!(4&l),d=!!(256&l);let g=0;const p=!!(512&l);let v=0;const A=!!(1024&l),E=!!(2048&l);let T=0;const b=Pn(s,4);let S=8;h&&(c=Pn(s,S),S+=4),u&&(S+=4);let k=f+c;for(let l=0;l<b;l++){if(d?(g=Pn(s,S),S+=4):g=m,p?(v=Pn(s,S),S+=4):v=y,A&&(S+=4),E&&(T=0===o?Pn(s,S):On(s,S),S+=4),e.type===Ti){let e=0;for(;e<v;){const s=Pn(n,k);k+=4,tr(a,n[k])&&er(n.subarray(k,k+s),a?2:1,t+T/r,i),k+=s,e+=s+4}}t+=g/r}}))})})}),i}(i,t)}extractID3Track(t,e){const i=this.id3Track;if(t.samples.length){const n=Bn(t.samples,["emsg"]);n&&n.forEach(t=>{const n=function(t){const e=t[0];let i,n="",r="",s=0,a=0,o=0,l=0,h=4;if(0===e){const e=wn(t,h),i=null!==e?wn(t,h+e.length):null;null!==e&&null!==i?(n=e,r=i,h+=e.length+i.length,s=Pn(t,h),h+=4,a=Pn(t,h),h+=4,o=Pn(t,h),h+=4,l=Pn(t,h),h+=4):(Zi.warn(`Unterminated ${null===e?"scheme_id_uri":"value"} in parsing emsg box: version 0 box ends inside a string, dropping all of its fields`),h=t.length)}else if(1===e){s=Pn(t,h),h+=4;const e=Pn(t,h);h+=4;const a=Pn(t,h);h+=4,i=2**32*e+a,Ze(i)||(i=Number.MAX_SAFE_INTEGER,Zi.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Pn(t,h),h+=4,l=Pn(t,h),h+=4;const c=wn(t,h),u=null!==c?wn(t,h+c.length):null;null!==c&&(n=c,h+=c.length),null!==u?(r=u,h+=u.length):(Zi.warn(`Unterminated ${null===c?"scheme_id_uri":"value"} in parsing emsg box: version 1 box ends inside a string, dropping its ${null===c?"strings and payload":"value and payload"}`),h=t.length)}return{schemeIdUri:n,value:r,timeScale:s,presentationTime:i,presentationTimeDelta:a,eventDuration:o,id:l,payload:t.subarray(h,t.byteLength)}}(t);if(sl.test(n.schemeIdUri)){const t=al(n,e);let r=4294967295===n.eventDuration?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;r<=.001&&(r=Number.POSITIVE_INFINITY);const s=n.payload;i.samples.push({data:s,len:s.byteLength,dts:t,pts:t,type:Vo.emsg,duration:r})}else if(this.config.enableEmsgKLVMetadata){const t=this.config.emsgKLVSchemaUri||Vo.misbklv;if(n.schemeIdUri.startsWith(t)){const t=al(n,e);i.samples.push({data:n.payload,len:n.payload.byteLength,dts:t,pts:t,type:Vo.misbklv,duration:Number.POSITIVE_INFINITY})}}})}return i}demuxSampleAes(t,e,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0,this.initData=void 0}},remux:class extends ji{constructor(t,e,i,n){super("passthrough-remuxer",n),this.observer=void 0,this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1,this.videoOnlyRemux=!1,this.decryptdata=null,this.pendingInitSegment=void 0,this.observer=t}destroy(){this.observer&&this.observer.removeAllListeners(),this.observer=null}resetTimeStamp(t){this.lastEndTime=null;const e=this.initPTS;e&&t&&e.baseTime===t.baseTime&&e.timescale===t.timescale||(this.initPTS=t)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(t,e,i,n){this.audioCodec=e,this.videoCodec=i,this.decryptdata=n,this.pendingInitSegment=t,this.videoOnlyRemux=!1,this.initTracks=void 0,this.initData=void 0,this.emitInitSegment=!0}generateInitSegment(t,e,i){this.videoOnlyRemux=!1;let{audioCodec:n,videoCodec:r}=this;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const{audio:s,video:a}=this.initData=i||Gn(t);if(e)!function(t,e){if(!t||!e)return;const i=e.keyId;16===(null==i?void 0:i.byteLength)&&e.isCommonEncryption&&Wn(t,(t,e)=>{const n=t.subarray(8,24);n.some(t=>0!==t)||(Zi.log(`[eme] Patching keyId in 'enc${e?"a":"v"}>sinf>>tenc' box: ${bn(n)} -> ${bn(i)}`),t.set(i,8))})}(t,e);else{const t=s||a;null!=t&&t.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${t.codec}")!`)}s&&(n=Vl(s,Ei,this)),a&&(r=Vl(a,Ti,this));const o={};s&&a?o.audiovideo={container:"video/mp4",codec:n+","+r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:t,id:"main"}:s?o.audio={container:"audio/mp4",codec:n,encrypted:s.encrypted,initSegment:t,id:"audio"}:a?o.video={container:"video/mp4",codec:r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:t,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(t,e,i,n,r,s,a,o,l,h,c){var u,d;let{initPTS:f,lastEndTime:g}=this;const p={audio:void 0,video:void 0,text:void 0,id3:i,initSegment:void 0};Qe(g)||(g=this.lastEndTime=r||0);const m=e.samples;if(!m.length)return p;const v=this.pendingInitSegment;v&&(this.pendingInitSegment=void 0,this.generateInitSegment(v,this.decryptdata,h));const y={initPTS:void 0,timescale:void 0,trackId:void 0};let A=this.initData;if(null!=(u=A)&&u.length||(this.generateInitSegment(m),A=this.initData),null==(d=A)||!d.length)return this.warn("Failed to generate initSegment."),p;if(l.iframe&&A.audio&&A.video){var E;const t=null==(E=this.initTracks)||null==(E=E.audiovideo)?void 0:E.initSegment,e=t?function(t){const e=Bn(t,["moov"]);if(1!==e.length||Bn(t,["moof"]).length)return null;const i=t.byteOffset,n=[],r=[];let s=!1;const a=Bn(e[0],["trak"]);for(let t=0;t<a.length;t++){const e=a[t],o=Bn(e,["mdia","hdlr"])[0];if("vide"===(o?_n(o.subarray(8,12)):"")){s=!0;continue}const l=Bn(e,["tkhd"])[0];if(!l)return null;const h=l[0];r.push(Pn(l,0===h?12:20)),n.push(Nn(e,i))}if(!s||!n.length)return null;const o=Bn(e[0],["mvex"])[0];let l=0;if(o){const t=Bn(o,["trex"]);for(let e=0;e<t.length;e++){const s=t[e];-1!==r.indexOf(Pn(s,4))&&(n.push(Nn(s,i)),l+=s.byteLength+8)}}const{result:h,dropped:c,droppedBefore:u}=Fn(t,n);if(xn(h,e[0].byteOffset-i-8,e[0].byteLength+8-c),o&&l){const t=o.byteOffset-i-8;xn(h,t-u(t),o.byteLength+8-l)}return h}(t):null;var T;if(e)this.log("Converted muxed init segment to video-only for I-Frame playback"),this.generateInitSegment(e,this.decryptdata),null!=(T=this.initData)&&T.length&&(A=this.initData,this.emitInitSegment=!0,this.videoOnlyRemux=!0)}this.emitInitSegment&&(y.tracks=this.initTracks,p.initSegment=y,this.emitInitSegment=!1);const b=l.iframe,S=!c||b&&!c.includeSampleDetails?function(t,e,i,n,r=!0){return Qn(t,e,n,r)}(m,A,0,this,b):c.tracks,k=A.audio?S[A.audio.id]:null,_=A.video?S[A.video.id]:null,L=!!A.audio,R=!!A.video;let I="";L&&(I+="audio"),R&&(I+="video");const C=Gl(_,1/0),P=Gl(k,1/0),D=Gl(_,0,!0),w=Gl(k,0,!0);let O=r,x=0;_&&k&&A.audio&&(P>D||C>w)&&this.warn(`audio and video track sample timestamps do not overlap. v: ${C}-${D} a: ${P}-${w}}`,_,k);const M=!!k&&(!_||!f&&P<C||!!f&&f.trackId===A.audio.id),N=M?k:_;if(!N)return this.log(`No media samples found in ${o} ${l.level} ${-1===l.part?"":`part: ${l.part} of`} sn: ${l.sn} at playlist time: ${r}`),p;let F,B=m;if(_&&_.sampleCount>=1&&A.video&&l.iframe){const{trun:t,start:e}=_,i=1===t.length,n=t.length?i?t[0].samples:t[0].samples.concat(...t.slice(1).map(t=>t.samples)):[];if(n.length){const r=t[0];let s=r;for(let e=t.length;e--;)if(t[e].samples.length){s=t[e];break}const a=s.lastSampleDurationOffset,{defaultSampleDurationOffset:o}=r,h=Math.abs(l.duration-(D-C))>.05,c=n.length<_.sampleCount;if(h||c||this.videoOnlyRemux||!i){const t=c?s.sampleOffset+s.samples.reduce((t,e)=>t+e.size,0):void 0,i=h?l.duration:D-C,r=function(t,e,i,n){if(void 0!==i){const n=t[t.length-1];let r=e;for(let e=0;e<t.length-1;e++)r-=t[e].duration;return r<=0&&(r=n.duration),n.duration=r,{durationOffset:i,value:r}}if(void 0===n)return;const r=Math.round(e/t.length);for(let e=0;e<t.length;e++)t[e].duration=r;return{durationOffset:n,value:r}}(n,i*A.video.timescale,a,o),u=function(t,e,i,n,r){if(i<1)return null;const s=Bn(t,["moof"]);if(1!==s.length)return null;const a=s[0],o=t.byteOffset,l=[],h=[],c=Bn(a,["traf"]);let u=!0;for(let t=0;t<c.length;t++){const i=c[t],n=Bn(i,["tfhd"])[0];if(!n)return null;Pn(n,4)===e?(l.push(i),131072&Pn(n,0)||(u=!1)):h.push(Nn(i,o))}if(!l.length)return null;if(h.length&&!u)return null;if(void 0!==n){let e=i;for(let i=0;i<l.length;i++){const n=l[i];let r=0;const s=Bn(n,["trun"]);for(let i=0;i<s.length;i++){const n=s[i],a=Math.min(e,Pn(n,4));if(a){xn(t,n.byteOffset-o+4,a);const e=16777215&Pn(n,0);Mn(t,n,8+(1&e?4:0)+(4&e?4:0)+a*((256&e?4:0)+(512&e?4:0)+(1024&e?4:0)+(2048&e?4:0)))}else xn(t,n.byteOffset-o-4,Rn.free);e-=a,r+=a}const a=Bn(n,["senc"])[0];a&&xn(t,a.byteOffset-o+4,r);const h=Bn(n,["saiz"])[0];if(h){let e=4;1&(h[1]<<16|h[2]<<8|h[3])&&(e+=8);const i=h[e];e+=1,xn(t,h.byteOffset-o+e,r),Mn(t,h,e+4+(0===i?r:0))}}const r=Bn(t,["mdat"]);if(1===r.length){const e=r[0].byteOffset-o-8;xn(t,e,n-e)}}let d=t,f=0,g=()=>0;if(h.length){({result:d,dropped:f,droppedBefore:g}=Fn(t,h)),xn(d,a.byteOffset-o-8,a.byteLength+8-f);for(let t=0;t<l.length;t++){const e=l[t],i=g(e.byteOffset-o),n=Bn(e,["trun"]);for(let t=0;t<n.length;t++){const e=n[t];1&Pn(e,0)&&xn(d,e.byteOffset-o-i+8,Pn(e,8)-f)}if(i){const t=Bn(e,["saio"]);for(let e=0;e<t.length;e++){const n=t[e],r=0===n[0]?4:8;let s=1&Pn(n,0)?12:4,a=Pn(n,s);for(s+=4;a--;s+=r){const t=s+r-4;xn(d,n.byteOffset-o-i+t,Pn(n,t)-i)}}}}}if(r){const{durationOffset:t,value:e}=r;xn(d,t-g(t),e)}return void 0!==n?d.subarray(0,n-f):d}(m,A.video.id,n.length,t,r);u?(B=u,F=function(t,e){let i=t,n=t;for(let t=0;t<e.length;t++){const{cts:r,duration:s}=e[t];n=Math.max(n,i+(r||0)+s),i+=s}return n}(e,n)):this.warn(`IFrame remux skipped (sn ${l.sn}); using native sample duration`),x=u&&r?i:D-C}else x=D-C}else this.warn(`Could not remux IFrame track fragment (no samples in range, trun count ${t.length})`),x=D-C}else x=M?w-P:D-C;if(this.videoOnlyRemux&&B===m)return this.warn(`Dropping muxed I-Frame fragment that could not be remuxed to video-only (sn: ${l.sn})`),p;const $=N.timescale,U=N.start-r*$,G=M?A.audio.id:A.video.id;if(O=N.start/$,(s||!f)&&(function(t,e,i,n){if(null===t)return!0;const r=Math.max(n,1),s=e-t.baseTime/t.timescale;return Math.abs(s-i)>=r}(f,O,r,x)||$!==f.timescale)){let t=!1;const e=M?"audio":"video";if(f){const i=0!==r?O/r:1+O/1;t=O>=0&&Math.abs(1-i)<.001,this.log(`${e} timestamps in track ${G} at playlist time: ${s?"":"~"}${r} maps to ${O} with initPTS: ${f.baseTime/f.timescale} (${U/$-f.baseTime/f.timescale}s diff) (${I}) drift estimate: ${i} ${t?"(ignoring drift)":"remapping timestamps (initPTS)"}`)}t||(this.log(`Found initPTS in ${e} track ${G} at playlist time: ${r} offset: ${O-r} (${U}/${$})`),f=null,y.initPTS=U,y.timescale=$,y.trackId=G)}f?(y.initPTS=f.baseTime,y.timescale=f.timescale,y.trackId=f.trackId):(y.timescale&&void 0!==y.trackId&&void 0!==y.initPTS||(this.warn("Could not set initPTS"),y.initPTS=O,y.timescale=1,y.trackId=-1),this.initPTS=f={baseTime:y.initPTS,timescale:y.timescale,trackId:y.trackId});const V=O-f.baseTime/f.timescale,K=V+x,H=R&&void 0!==(null==N?void 0:N.ptsMin)?N.ptsMin/N.timescale-f.baseTime/f.timescale:V,Y=void 0!==F&&_?F/_.timescale-f.baseTime/f.timescale:R&&null!=N&&N.ptsMax?N.ptsMax/N.timescale-f.baseTime/f.timescale:K;x>0?this.lastEndTime=K:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const j={data1:B,data2:void 0,startPTS:H,startDTS:V,endPTS:Y,endDTS:K,type:I,hasAudio:L,hasVideo:R,nb:1,dropped:0,encrypted:!!A.audio&&A.audio.encrypted||!!A.video&&A.video.encrypted};p.audio=L&&!R?j:void 0,p.video=R?j:void 0;const W=this.isVideoContiguous,z=null==_?void 0:_.sampleCount;if(z){const t=_.keyFrameIndex,e=-1!==t;j.nb=z,j.dropped=0===t||W?0:e?t:z,j.independent=e,j.firstKeyFrame=t,e&&_.keyFrameStart&&(j.firstKeyFramePTS=(_.keyFrameStart-f.baseTime)/f.timescale),W||(p.independent=e),this.isVideoContiguous||(this.isVideoContiguous=e),j.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${t}/${z} dropped: ${j.dropped} start: ${j.firstKeyFramePTS||"NA"}`)}return p.initSegment=y,p.id3=$l(i,r,f,f),n.samples.length&&(p.text=Ul(n,r,f)),p}}},{demux:dl,remux:Fl},{demux:class extends Ho{constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.sampleAes=null,this.observer=t,this.config=e}resetInitSegment(t,e,i,n){super.resetInitSegment(t,e,i,n),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:n,inputTimeScale:9e4,dropped:0}}static probe(t,e){if(!t)return!1;const i=dn(t,0);let n=(null==i?void 0:i.length)||0;if(tl(t,n))return!1;for(let i=t.length;n<i;n++)if(Bo(t,n))return e.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)&&xo(t,e)&&No(t,e)<=t.length-e}(t,e)}appendFrame(t,e,i){$o(t,this.observer,e,i,t.manifestCodec);const n=Go(t,e,i,this.basePTS,this.frameIndex);if(0===(null==n?void 0:n.missing))return n}demuxSampleAes(t,e,i){const n=this.demux(t,i),r=this.sampleAes=new el(this.observer,this.config,e);return new Promise(t=>{r.decryptAacSamples(n.audioTrack.samples,0,()=>{t(n)})})}},remux:Fl},{demux:class extends Ho{resetInitSegment(t,e,i,n){super.resetInitSegment(t,e,i,n),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:n,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=dn(t,0);let i=(null==e?void 0:e.length)||0;if(e&&11===t[i]&&119===t[i+1]&&void 0!==Tn(e)&&il(t,i)<=16)return!1;for(let e=t.length;i<e;i++)if(tl(t,i))return Zi.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return Zo(t,e)&&4<=t.length-e}(t,e)}appendFrame(t,e,i){if(null!==this.basePTS)return Xo(t,e,i,this.basePTS,this.frameIndex)}},remux:Fl}];Hl.splice(2,0,{demux:nl,remux:Fl});class Yl{constructor(t,e,i,n,r,s){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=t,this.typeSupported=e,this.config=i,this.id=r,this.logger=s}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,i,n){if(!this.observer)return jl(i);const r=i.transmuxing;r.executeStart=Kl();const s=new Uint8Array(t),{currentTransmuxState:a,transmuxConfig:o}=this;n&&(this.currentTransmuxState=n);const{contiguous:l,discontinuity:h,trackSwitch:c,accurateTimeOffset:u,timeOffset:d,initSegmentChange:f}=n||a,{audioCodec:g,videoCodec:p,defaultInitPts:m,duration:v,initSegmentData:y}=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&&oa(A.method)){const t=this.getDecrypter(),e=la(A.method);return this.asyncResult=!0,this.decryptionPromise=t.decrypt(s,A.key.buffer,A.iv.buffer,e,i.decryptRange).then(t=>{const e=this.push(t,null,i);return this.decryptionPromise=null,e}),this.decryptionPromise}const E=this.needsProbing(h,c);if(E){const t=i.iframe&&y&&dl.probe(y,this.logger)?y:s,e=this.configureTransmuxer(t);if(e)return this.logger.warn(`[transmuxer] ${e.message}`),this.observer.emit(ii.ERROR,ii.ERROR,{type:ti.MEDIA_ERROR,details:ei.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),r.executeEnd=Kl(),jl(i)}(h||c||f||E)&&this.resetInitSegment(y,g,p,v,e,i),(h||f||E)&&this.resetInitialTimestamp(m),l||this.resetContiguity();const T=this.transmux(s,A,d,u,i);this.asyncResult=Wl(T);const b=this.currentTransmuxState;return b.contiguous=!0,b.discontinuity=!1,b.trackSwitch=!1,r.executeEnd=Kl(),T}flush(t){const e=t.transmuxing;e.executeStart=Kl();const{decrypter:i,currentTransmuxState:n,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(t));const s=[],{timeOffset:a}=n;if(i){const e=i.flush();e&&s.push(this.push(e.buffer,null,t))}const{demuxer:o,remuxer:l}=this;if(!o||!l){e.executeEnd=Kl();const i=[jl(t)];return this.asyncResult?Promise.resolve(i):i}const h=o.flush(a,t);return Wl(h)?(this.asyncResult=!0,h.then(e=>(this.flushRemux(s,e,t),s))):(this.flushRemux(s,h,t),this.asyncResult?Promise.resolve(s):s)}flushRemux(t,e,i){if(!this.remuxer)return;const{audioTrack:n,videoTrack:r,id3Track:s,textTrack:a}=e,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id} playlist ${i.level}`);const h=this.remuxer.remux(n,r,s,a,l,o,!0,this.id,i,e.initData,e.sampleData);t.push({remuxResult:h,chunkMeta:i}),i.transmuxing.executeEnd=Kl()}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,n,r,s){const{demuxer:a,remuxer:o}=this;a&&o&&(a.resetInitSegment(t,e,i,n,r,s),o.resetInitSegment(t,e,i,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0),this.observer&&this.observer.removeAllListeners(),this.decryptionPromise=null,this.decrypter=this.observer=void 0,this.logger=this.config=this.probe=void 0}transmux(t,e,i,n,r){let s;return s="SAMPLE-AES"===(null==e?void 0:e.method)?this.transmuxSampleAes(t,e,i,n,r):this.transmuxUnencrypted(t,i,n,r),s}transmuxUnencrypted(t,e,i,n){const{demuxer:r,remuxer:s}=this;if(!r||!s)return jl(n);const a=r.demux(t,e,n,!1,!this.config.progressive),{audioTrack:o,videoTrack:l,id3Track:h,textTrack:c}=a;return{remuxResult:s.remux(o,l,h,c,e,i,!1,this.id,n,a.initData,a.sampleData),chunkMeta:n}}transmuxSampleAes(t,e,i,n,r){return this.demuxer?this.demuxer.demuxSampleAes(t,e,i,r).then(t=>({remuxResult:this.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,i,n,!1,this.id,r,t.initData,t.sampleData),chunkMeta:r})):Promise.reject(new Error("no demuxer"))}configureTransmuxer(t){const{config:e,observer:i,typeSupported:n}=this;if(!i)return;let r;try{for(let e=0,i=Hl.length;e<i;e++){var s;if(null!=(s=Hl[e].demux)&&s.probe(t,this.logger)){r=Hl[e];break}}}catch(t){return t}if(!r)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=r.demux,h=r.remux;a&&a instanceof l||(this.logger.log(`Using ${l.name}`),this.demuxer=new l(i,e,n,this.logger),this.probe=l.probe),o&&o instanceof h||(this.logger.log(`Using ${h.name}`),this.remuxer=new h(i,e,n,this.logger))}needsProbing(t,e){return!this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new Ns(this.config)),t}}const jl=t=>({remuxResult:{},chunkMeta:t});function Wl(t){return"then"in t&&t.then instanceof Function}class zl{constructor(t,e,i,n,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=i,this.duration=n,this.defaultInitPts=r||null}}class ql{constructor(t,e,i,n,r,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=n,this.timeOffset=r,this.initSegmentChange=s}}let Xl=0;class Ql{constructor(t,e,i,n){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Xl++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=t=>{const e=t.data,i=this.hls;if(i&&null!=e&&e.event&&e.instanceNo===this.instanceNo)switch(e.event){case"init":{var n;const t=null==(n=this.workerContext)?void 0:n.objectURL;t&&self.URL.revokeObjectURL(t);break}case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;case"workerLog":i.logger[e.data.logType]&&i.logger[e.data.logType](e.data.message);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.part=this.part,e.data.id=this.id,i.trigger(e.event,e.data)}},this.onWorkerError=t=>{if(!this.hls)return;const e=new Error(`${t.message} (${t.filename}:${t.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(ii.ERROR,{type:ti.OTHER_ERROR,details:ei.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:e})};const r=t.config;this.hls=t,this.id=e,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=i,this.onFlush=n;const s=(t,e)=>{(e=e||{}).frag=this.frag||void 0,t===ii.ERROR&&(e.parent=this.id,e.part=this.part,this.error=e.error),this.hls.trigger(t,e)};this.observer=new Do,this.observer.on(ii.FRAG_DECRYPTED,s),this.observer.on(ii.ERROR,s);const a=Rr(r.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const i=this.hls.logger;if(r.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{r.workerPath?(i.log(`loading Web Worker ${r.workerPath} for "${e}"`),this.workerContext=function(t){const e=Oo[t];if(e)return e.clientCount++,e;const i=new self.URL(t,self.location.href).href,n={worker:new self.Worker(i),scriptURL:i,clientCount:1};return Oo[t]=n,n}(r.workerPath)):(i.log(`injecting Web Worker for "${e}"`),this.workerContext=function(){const t=Oo[wo];if(t)return t.clientCount++,t;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),i=self.URL.createObjectURL(e),n={worker:new self.Worker(i),objectURL:i,clientCount:1};return Oo[wo]=n,n}());const{worker:t}=this.workerContext;t.addEventListener("message",this.onWorkerMessage),t.addEventListener("error",this.onWorkerError),t.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:e,config:Wr(r)})}catch(n){i.warn(`Error setting up "${e}" Web Worker, fallback to inline`,n),this.terminateWorker(),this.error=null,this.transmuxer=new Yl(this.observer,a,r,"",e,t.logger)}return}}this.transmuxer=new Yl(this.observer,a,r,"",e,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=Xl++;const e=this.hls.config,i=Rr(e.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:i,id:this.id,config:Wr(e)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),function(t){const e=Oo[t||wo];if(e&&1===e.clientCount--){const{worker:i,objectURL:n}=e;delete Oo[t||wo],n&&self.URL.revokeObjectURL(n),i.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(t,e,i,n,r,s,a,o,l,h){var c,u;l.transmuxing.start=self.performance.now();const{instanceNo:d,transmuxer:f}=this,g=s?s.start:r.start,p=r.decryptdata,m=this.frag,v=!m||r.cc!==m.cc,y=!m||l.level!==m.level,A=m?l.sn-m.sn:-1,E=this.part?l.part-this.part.index:-1,T=0===A&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),b=!y&&(1===A||0===A&&(1===E||T&&E<=0)),S=self.performance.now();(y||A||0===r.stats.parsing.start)&&(r.stats.parsing.start=S),!s||!E&&b||(s.stats.parsing.start=S);const k=!(m&&(null==(c=r.initSegment)?void 0:c.url)===(null==(u=m.initSegment)?void 0:u.url)),_=new ql(v,b,o,y,g,k);if(!b||v||k){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id} playlist: ${l.level} id: ${l.id}\n discontinuity: ${v}\n trackSwitch: ${y}\n contiguous: ${b}\n accurateTimeOffset: ${o}\n timeOffset: ${g}\n initSegmentChange: ${k}`);const t=new zl(i,n,e,a,h);this.configureTransmuxer(t)}if(this.frag=r,this.part=s,this.workerContext)this.workerContext.worker.postMessage({instanceNo:d,cmd:"demux",data:t,decryptdata:p,chunkMeta:l,state:_},t instanceof ArrayBuffer?[t]:[]);else if(f){const e=f.push(t,p,l,_);Wl(e)?e.then(t=>{this.handleTransmuxComplete(t)}).catch(t=>{this.transmuxerError(t,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(e)}}flush(t){t.transmuxing.start=self.performance.now();const{instanceNo:e,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:e,cmd:"flush",chunkMeta:t});else if(i){const e=i.flush(t);Wl(e)?e.then(e=>{this.handleFlushResult(e,t)}).catch(e=>{this.transmuxerError(e,t,"transmuxer-interface flush error")}):this.handleFlushResult(e,t)}}transmuxerError(t,e,i){this.hls&&(this.error=t,this.hls.trigger(ii.ERROR,{type:ti.MEDIA_ERROR,details:ei.FRAG_PARSING_ERROR,chunkMeta:e,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:t,err:t,reason:i}))}handleFlushResult(t,e){t.forEach(t=>{this.handleTransmuxComplete(t)}),this.onFlush(e)}configureTransmuxer(t){const{instanceNo:e,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:e,cmd:"configure",config:t}):i&&i.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}class Zl extends ji{constructor(t,e){super(e,t.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=t}destroy(){this.clearTimer(),this.hls=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,e,i){const n=null==e?void 0:e.renditionReports;if(n){let r=-1;for(let i=0;i<n.length;i++){const s=n[i];let a;try{a=new self.URL(s.URI,e.url).href}catch(t){this.warn(`Could not construct new URL for Rendition Report: ${t}`),a=s.URI||""}if(a===t){r=i;break}a===t.substring(0,a.length)&&(r=i)}if(-1!==r){const t=n[r],s=parseInt(t["LAST-MSN"])||e.lastPartSn;let a=parseInt(t["LAST-PART"])||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&&Vr(i);return new Kr(s,a>=0?a:void 0,o)}}}loadPlaylist(t){this.clearTimer()}loadingPlaylist(t,e){this.clearTimer()}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}getUrlWithDirectives(t,e){if(e)try{return e.addDirectives(t)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}return t}playlistLoaded(t,e,i){const{details:n,stats:r}=e,s=n.fragments,a=self.performance.now(),o=r.loading.first?Math.max(0,Math.floor(a-r.loading.first)):0;n.advancedDateTime=Date.now()-o;const l=this.hls.config.timelineOffset;if(l!==n.appliedTimelineOffset){const t=Math.max(l||0,0);n.appliedTimelineOffset=t,s.forEach(e=>{null==e||e.setStart(e.playlistOffset+t)})}if(n.live||null!=i&&i.live){var h;const l="levelInfo"in e?e.levelInfo:e.track;n.reloaded(i);const c=null==(h=s[s.length-1])?void 0:h.type;if(n.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){const t=new Error(`${c} playlist ${l.id} hit max allowed unchanged reloads.`);this.warn(t);const{networkDetails:i,context:s}=e;return void this.hls.trigger(ii.ERROR,{type:ti.NETWORK_ERROR,details:ei.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:n.url,error:t,reason:t.message,level:e.level,parent:c,context:s,networkDetails:i,stats:r})}if(i){za(i,n,this);const t=n.playlistParsingError;if(t){this.warn(t);const i=this.hls;if(!i.config.ignorePlaylistParsingErrors){const{networkDetails:s}=e;return void i.trigger(ii.ERROR,{type:ti.NETWORK_ERROR,details:ei.LEVEL_PARSING_ERROR,fatal:!1,url:n.url,error:t,reason:t.message,level:e.level,parent:c,networkDetails:s,stats:r})}n.playlistParsingError=null}}-1===n.requestScheduled&&(n.requestScheduled=r.loading.start);const u=this.hls.mainForwardBufferInfo,d=u?u.end-u.len:0,f=Qa(n,1e3*(n.edge-d));n.requestScheduled+f<a?n.requestScheduled=a:n.requestScheduled<=a&&(n.requestScheduled+=f);const g=e.deliveryDirectives;if(this.log(`live playlist ${t} ${n.advanced?`REFRESHED ${n.lastPartSn} - ${n.lastPartIndex}`:n.updated?"UPDATED":`MISSED (received ${n.lastPartSn} - ${n.lastPartIndex}${g?` | requested ${g.msn} - ${g.part}`:""})`}`),!this.canLoad||!n.live)return;let p,m,v;if(n.canBlockReload&&n.endSN&&n.advanced){const t=this.hls.config.lowLatencyMode,r=n.lastPartSn,s=n.endSN,o=n.lastPartIndex,h=r===s;-1!==o?h?(m=s+1,v=t?0:o):(m=r,v=t?o+1:n.maxPartIndex):m=s+1;const c=n.age,u=c+n.ageHeader;let d=Math.min(u-n.partTarget,1.5*n.targetduration);if(d>0){if(u>3*n.targetduration)this.log(`Playlist last advanced ${c.toFixed(2)}s ago. Omitting segment and part directives.`),m=void 0,v=void 0;else if(null!=i&&i.tuneInGoal&&u-n.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${d} with playlist age: ${n.age}`),d=0;else{const t=Math.floor(d/n.targetduration);if(m+=t,void 0!==v){v+=Math.round(d%n.targetduration/n.partTarget)}this.log(`CDN Tune-in age: ${n.ageHeader}s last advanced ${c.toFixed(2)}s goal: ${d} skip sn ${t} to part ${v}`)}n.tuneInGoal=d}if(p=this.getDeliveryDirectives(n,e.deliveryDirectives,m,v),t||!h)return n.requestScheduled=a,void this.loadingPlaylist(l,p)}else(n.canBlockReload||n.canSkipUntil)&&(p=this.getDeliveryDirectives(n,e.deliveryDirectives,m,v));p&&void 0!==m&&n.canBlockReload&&(n.requestScheduled=r.loading.first+Math.max(f-2*o,f/2)),this.scheduleLoading(l,p,n)}else this.clearTimer()}scheduleLoading(t,e,i){const n=i||t.details;if(!n)return void this.loadingPlaylist(t,e);const r=self.performance.now(),s=n.requestScheduled;if(r>=s)return void this.loadingPlaylist(t,e);const a=s-r;this.log(`reload live playlist ${t.name||t.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(t,e),a)}getDeliveryDirectives(t,e,i,n){let r=Vr(t);return null!=e&&e.skip&&t.deltaUpdateFailed&&(i=e.msn,n=e.part,r=$r),new Kr(i,n,r)}checkRetry(t){const e=t.details,i=Mi(t),n=t.errorAction,{action:r,retryCount:s=0,retryConfig:a}=n||{},o=!!n&&!!a&&(r===fs||!n.resolved&&r===us);if(o){var l;if(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{var h;const i=Vi(null==(h=t.response)?void 0:h.code);if(this.clearTimer(),i)this.log("Waiting for connection (offline)"),t.reason="offline",this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3);else{const t=$i(a,s);this.warn(`Retrying playlist loading ${s+1}/${a.maxNumRetry} after "${e}" in ${t}ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(),t)}}t.levelRetry=!0,n.resolved=!0}return o}checkOfflineStatus(){this.clearTimer(),Vi(0)?this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3):(this.log("Connection restored (online)"),this.loadPlaylist())}}function Jl(t,e){if(t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(!th(t[i].attrs,e[i].attrs))return!1;return!0}function th(t,e,i){const n=t["STABLE-RENDITION-ID"];return n&&!i?n===e["STABLE-RENDITION-ID"]:!(i||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>t[i]!==e[i])}class eh{constructor(t){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=t}destroy(){this.tracks=this.queues=null}append(t,e,i){if(null===this.queues||null===this.tracks)return;const n=this.queues[e];n.push(t),1!==n.length||i||this.executeNext(e)}appendBlocker(t){return new Promise(e=>{const i={label:"async-blocker",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,t)})}prependBlocker(t){return new Promise(e=>{if(this.queues){const i={label:"async-blocker-prepend",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[t].unshift(i)}})}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(t=>{var e;const i=null==(e=t[0])?void 0:e.label;"async-blocker"===i||"async-blocker-prepend"===i?(t[0].execute(),t.splice(0,1)):"block-audio"===i&&t.splice(0,1)})}insertNext(t,e){null!==this.queues&&this.queues[e].splice(1,0,...t)}unblockAudio(){var t;null!==this.queues&&"block-audio"===(null==(t=this.current("audio"))?void 0:t.label)&&this.shiftAndExecuteNext("audio")}audioBlocking(){return null!==this.queues&&this.queues.audio.some(t=>"block-audio"===t.label)}executeNext(t){if(null===this.queues||null===this.tracks)return;const e=this.queues[t];if(e.length){const n=e[0];try{n.execute()}catch(e){var i;if(n.onError(e),null===this.queues||null===this.tracks)return;const r=null==(i=this.tracks[t])?void 0:i.buffer;null!=r&&r.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){null!==this.queues&&(this.queues[t].shift(),this.executeNext(t))}current(t){var e;return(null==(e=this.queues)?void 0:e[t][0])||null}toString(){const{queues:t,tracks:e}=this;return null===t||null===e?"<destroyed>":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(t){var e,i;return null!=(e=this.queues)&&e[t]||null!=(i=this.tracks)&&i[t]?`${t}: (${this.listSbInfo(t)}) ${this.listOps(t)}`:""}listSbInfo(t){var e;const i=null==(e=this.tracks)?void 0:e[t],n=null==i?void 0:i.buffer;return n?`SourceBuffer${n.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(t){var e;return(null==(e=this.queues)?void 0:e[t].map(t=>t.label).join(", "))||""}}const ih=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,nh="HlsJsTrackRemovedError";class rh extends Error{constructor(t){super(t),this.name=nh}}function sh(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach(e=>{t.removeChild(e)})}function ah(t){return"audio"===t?1:0}function oh(t,e){return`${t?"":" - triggering recovery"}${e?" with HTMLMediaElement Error: "+e.message:""}`}function lh(t){return`${t.type}_${t.sn}_${t.level}`}function hh(t,e){const{start:i,end:n}=e;let r=0;for(let e=0;e<t.length;e++){const s=t[e];if(s.start>=n)break;const a=Math.max(i,s.start),o=Math.min(n,s.end);o>a&&(r+=o-a)}return r}function ch(t,e){return e.duration-t<=.001}class uh{constructor(t){this.hls=null,this.autoLevelCapping=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.observer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.media=null,this.restrictedLevels=[],this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),(this.timer||this.observer)&&this.stopCapping(),this.media=this.clientRect=this.hls=null,this.streamController=void 0}registerListeners(){const{hls:t}=this;t&&(t.on(ii.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(ii.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(ii.MANIFEST_PARSED,this.onManifestParsed,this),t.on(ii.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(ii.BUFFER_CODECS,this.onBufferCodecs,this),t.on(ii.MEDIA_DETACHING,this.onMediaDetaching,this))}unregisterListener(){const{hls:t}=this;t&&(t.off(ii.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(ii.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(ii.MANIFEST_PARSED,this.onManifestParsed,this),t.off(ii.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(ii.BUFFER_CODECS,this.onBufferCodecs,this),t.off(ii.MEDIA_DETACHING,this.onMediaDetaching,this))}onFpsDropLevelCapping(t,e){if(!this.hls)return;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){const i=e.media;this.clientRect=null,this.hls&&(i instanceof HTMLVideoElement?(this.media=i,this.hls.config.capLevelToPlayerSize&&this.observe()):this.media=null,(this.timer||this.observer)&&this.hls.levels.length>1&&this.detectPlayerSize())}onManifestParsed(t,e){this.restrictedLevels=[],e.video&&this.startCapping()}onLevelsUpdated(t,{levels:e}){(this.timer||this.observer)&&Qe(this.autoLevelCapping)?this.detectPlayerSize():void 0===this.observer&&void 0===this.timer&&e.length>1&&e.some(t=>!!t.videoCodec)&&this.startCapping()}onBufferCodecs(t,e){e.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0||!this.hls)return void(this.clientRect=null);const t=this.hls.levels;if(t.length>1){const e=this.hls,i=this.getMaxLevel(t.length-1);i!==this.autoLevelCapping&&e.logger.log(`Setting autoLevelCapping to ${i}: ${t[i].height}p@${t[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),e.autoLevelCapping=i,e.autoLevelEnabled&&e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}else 1===t.length&&this.stopCapping()}}getMaxLevel(t){if(!this.hls)return-1;const e=this.hls.levels;if(!e.length)return-1;const i=e.filter((e,i)=>this.isLevelAllowed(e)&&i<=t);return this.observer||(this.clientRect=null),uh.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}observe(){const t=self.ResizeObserver;t&&(this.observer=new t(t=>{var e;const i=null==(e=t[0])?void 0:e.contentRect;i&&(this.clientRect=i,this.detectPlayerSize())})),this.observer&&this.media&&this.observer.observe(this.media)}startCapping(){var t;this.timer||this.observer||null==(t=this.hls)||!t.config.capLevelToPlayerSize||(self.clearInterval(this.timer),this.timer=void 0,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.observe(),this.observer||(this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3)),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0),this.observer&&(this.observer.disconnect(),this.observer=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)return t;const{ignoreDevicePixelRatio:e,maxDevicePixelRatio:i}=this.hls.config;if(!e)try{t=self.devicePixelRatio}catch(t){}return Math.min(t,i)}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;const n=(t,e)=>!e||(t.width!==e.width||t.height!==e.height);let r=t.length-1;const s=Math.max(e,i);for(let e=0;e<t.length;e+=1){const i=t[e];if((i.width>=s||i.height>=s)&&n(i,t[e+1])){r=e;break}}return r}}var dh=class t{constructor(e,i){Array.isArray(e)&&(e=e.map(e=>e instanceof t?e:new t(e))),this.value=e,this.params=i}};function fh(t,e,i,n){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 ${i}`,{cause:n});var r}const gh="Bare Item";const ph=/[\x00-\x1f\x7f]+/;var mh=class{constructor(t){this.description=t}};function vh(t,e,i){return fh("serialize",t,e,i)}function yh(t){if(!1===ArrayBuffer.isView(t))throw vh(t,"Byte Sequence");return`:${e=t,btoa(String.fromCharCode(...e))}:`;var e}function Ah(t){if(function(t){return t<-999999999999999||999999999999999<t}(t))throw vh(t,"Integer");return t.toString()}function Eh(t){const e=an(t,3);if(Math.floor(Math.abs(e)).toString().length>12)throw vh(t,"Decimal");const i=e.toString();return i.includes(".")?i:`${i}.0`}function Th(t){const e=(i=t).description||i.toString().slice(7,-1);var i;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e))throw vh(e,"Token");return e}function bh(t){switch(typeof t){case"number":if(!Qe(t))throw vh(t,gh);return Number.isInteger(t)?Ah(t):Eh(t);case"string":return function(t){if(ph.test(t))throw vh(t,"String");return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(t);case"symbol":return Th(t);case"boolean":return function(t){if("boolean"!=typeof t)throw vh(t,"Boolean");return t?"?1":"?0"}(t);case"object":if(t instanceof Date)return function(t){return`@${Ah(t.getTime()/1e3)}`}(t);if(t instanceof Uint8Array)return yh(t);if(t instanceof mh)return Th(t);default:throw vh(t,gh)}}function Sh(t){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(t))throw vh(t,"Key");return t}function kh(t){return null==t?"":Object.entries(t).map(([t,e])=>!0===e?`;${Sh(t)}`:`;${Sh(t)}=${bh(e)}`).join("")}function _h(t){return t instanceof dh?`${bh(t.value)}${kh(t.params)}`:bh(t)}function Lh(t,e={whitespace:!0}){if("object"!=typeof t||null==t)throw vh(t,"Dict");const i=t instanceof Map?t.entries():Object.entries(t),n=null!=e&&e.whitespace?" ":"";return Array.from(i).map(([t,e])=>{e instanceof dh==!1&&(e=new dh(e));let i=Sh(t);var n;return!0===e.value?i+=kh(e.params):(i+="=",Array.isArray(e.value)?i+=`(${(n=e).value.map(_h).join(" ")})${kh(n.params)}`:i+=_h(e)),i}).join(`,${n}`)}function Rh(t,e){return Lh(t,e)}const Ih=["url"],Ch=["version","eventTargets","sid","transmissionMode"],Ph=["customData","headers"],Dh=t=>t instanceof dh?new dh(Math.round(t.value),t.params):Math.round(t),wh=t=>Array.isArray(t)?t.map(Dh):Dh(t),Oh=(t,e)=>Array.isArray(t)?t.map(t=>Oh(t,e)):t instanceof dh&&"string"==typeof t.value?new dh(Oh(t.value,e),t.params):(e.baseUrl&&(t=function(t,e){let i;try{i=new URL(t)}catch(e){return t}const n=new URL(e);if(i.origin!==n.origin)return t;const r=i.pathname.split("/").slice(1),s=n.pathname.split("/").slice(1,-1),a=Math.min(r.length,s.length);for(let t=0;t<a&&r[t]===s[t];t++)r.shift(),s.shift();for(;s.length;)s.shift(),r.unshift("..");return r.join("/")+i.search+i.hash}(t,function(t){const e="string"==typeof t?new URL(t):t;return e.origin+e.pathname.substring(0,e.pathname.lastIndexOf("/")+1)}(e.baseUrl))),1===e.version?encodeURIComponent(t):t),xh=t=>t instanceof dh?new dh(100*Math.round(t.value/100),t.params):100*Math.round(t/100),Mh=t=>Array.isArray(t)?t.map(xh):xh(t),Nh={br:wh,d:wh,bl:Mh,dl:Mh,mtp:Mh,nor:(t,e)=>{let i=t;return e.version>=2&&(t instanceof dh&&"string"==typeof t.value?i=new dh([t]):"string"==typeof t&&(i=[t])),Oh(i,e)},rtp:Mh,tb:wh},Fh=2,Bh="rr",$h="bc",Uh="e",Gh=Bh,Vh="ce",Kh=new Map([["ps","sta"],["pr","pr"],["c","cid"],["b","bg"],["bc","br"]]),Hh="event",Yh="request",jh=["cen","e","h","ts"],Wh=["ab","bg","bl","br","bs","bsa","bsd","bsda","cdn","cid","cs","d","dfa","dl","ec","lab","lb","ltc","msd","mtp","nor","nr","ot","pb","pr","pt","rtp","sf","sid","sn","st","sta","su","tab","tb","tbl","tpb","v"],zh=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function qh(t){return zh.test(t)}const Xh=new Set(Wh);function Qh(t){return Xh.has(t)||qh(t)}const Zh=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],Jh=new Set(Zh);function tc(t){return Jh.has(t)}const ec=new Set(jh);const ic=new Set(["ab","bl","br","bsa","bsd","bsda","lab","lb","mtp","pb","tab","tb","tbl","tpb"]),nc=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"],rc=new Set(nc);function sc(t){return rc.has(t)||qh(t)}const ac=new Set(["ot","sf","st","e","sta"]);function oc(t){return ac.has(t)}function lc(t){return"number"==typeof t?Qe(t):null!=t&&""!==t&&!1!==t}const hc={[Hh]:function(t){return Qh(t)||tc(t)||ec.has(t)},[Yh]:Qh};function cc(t,e){if(Array.isArray(t)){let i;return e&&(i=t.find(t=>{var i;return(null==(i=t.params)?void 0:i.ot)===e})),i||(i=t[0]),cc(i)}return t instanceof dh?t.value:t}function uc(t,e={}){const i={};if(null==t||"object"!=typeof t)return i;const n=e.version||t.v||Fh,r=e.reportingMode||Yh,s=1===n?function(t){const e={};for(const[n,r]of Object.entries(t))if(null!=r)if("nor"===n){const t=(Array.isArray(r)?r:[r])[0];var i;t instanceof dh?(e.nor=t.value,null!=(i=t.params)&&i.r&&(e.nrr=t.params.r)):e.nor=t}else ic.has(n)?e[n]=cc(r,t.ot):e[n]=r;else e[n]=r;return e}(t):t,a=1===n?sc:hc[r];let o=Object.keys(s).filter(a);s.e&&s.e!==Bh&&(o=o.filter(t=>!tc(t)));const l=e.filter;"function"==typeof l&&(o=o.filter(l));const h=r===Hh;if(h){const t=s.e;o.includes("e")||null==t||o.push("e"),o.includes("ts")||o.push("ts"),o.includes("cen")||null==s.cen||"ce"!==t||o.push("cen");const e=t?Kh.get(t):void 0;e&&null!=s[e]&&!o.includes(e)&&o.push(e)}if(0===o.length)return i;n>1&&!o.includes("v")&&o.push("v");const c={version:n,reportingMode:r,baseUrl:e.baseUrl};o.sort();for(const t of o){var u,d;let r=s[t];const a=null!=(u=null==(d=e.formatters)?void 0:d[t])?u:Nh[t];if("function"==typeof a&&(r=a(r,c)),"v"===t){if(1===n)continue;r=n}if("pr"===t&&1===r&&(!h||"pr"!==s.e))continue;h&&"ts"===t&&!Qe(r)&&(r=Date.now());const o=h&&!1===r&&"bg"===t&&"b"===s.e;(lc(r)||o)&&(oc(t)&&"string"==typeof r&&(r=new mh(r)),i[t]=r)}return i}const dc="CMCD-Object",fc="CMCD-Request",gc="CMCD-Session",pc="CMCD-Status",mc=fc,vc={ab:dc,br:dc,d:dc,lab:dc,lb:dc,ot:dc,tab:dc,tb:dc,tpb:dc,bl:fc,cs:fc,dfa:fc,dl:fc,ltc:fc,mtp:fc,nor:fc,nrr:fc,pb:fc,sn:fc,sta:fc,su:fc,tbl:fc,cid:gc,msd:gc,sf:gc,sid:gc,st:gc,v:gc,bg:pc,bs:pc,bsa:pc,bsd:pc,bsda:pc,cdn:pc,ec:pc,nr:pc,pr:pc,pt:pc,rtp:pc};function yc(t,e){const i={};if(!t)return i;const n=Object.keys(t),r=e?(s=e,Object.keys(s).reduce((t,e)=>{var i;return null==(i=s[e])||i.forEach(i=>t[i]=e),t},{})):{};var s;for(const e of n){var a;const n=vc[e]||r[e]||mc;(null!=(a=i[n])?a:i[n]={})[e]=t[e]}return i}const Ac="CMCD";function Ec(t){return Rh(t,{whitespace:!1})}const Tc=[...nc,...Wh,...Zh,...jh].filter((t,e,i)=>i.indexOf(t)===e),bc="m",Sc="a",kc="v",_c="av",Lc="i",Rc="tt",Ic="s",Cc="p",Pc="k",Dc="r",wc="a",Oc="e",xc="f",Mc="d",Nc="query",Fc="headers";function Bc(t,e,i){var n;const r=new Set(null!=(n=e.enabledKeys)?n:[]);return{version:e.version||Fh,reportingMode:t,filter:t=>r.has(t),baseUrl:i}}const $c=Object.is,Uc=t=>t,Gc=Array.from(Kh,([t,e])=>"br"===e?{event:t,field:e,equal:(t,e)=>void 0===t||void 0===e?t===e:function(t,e){if(t===e)return!0;if(t.length!==e.length)return!1;for(let i=0;i<t.length;i++){const n=t[i],r=e[i];if(n===r)continue;if("number"==typeof n||"number"==typeof r)return!1;if(n.value!==r.value)return!1;const s=n.params,a=r.params,o=s&&Object.keys(s)[0],l=a&&Object.keys(a)[0];if(o!==l)return!1;if(void 0!==o&&void 0!==l&&s&&a&&s[o]!==a[l])return!1}return!0}(t,e),snapshot:t=>t.slice()}:{event:t,field:e,equal:$c,snapshot:Uc}),Vc=new Map(Gc.map(t=>[t.event,t]));function Kc(t){const{url:e}=t,i=xi(t,Ih);return fetch(e,i)}var Hc=class{constructor(t,e=Kc){var i;this.timeOrigin=performance.timeOrigin||(null==(i=performance.timing)?void 0:i.fetchStart)||Date.now()-performance.now(),this.data={},this.msd=NaN,this.eventTargets=new Map,this.lastEmitted={},this.requestTarget={sn:0,msdSent:!1},this.config=function(t){const{version:e=Fh,eventTargets:i=[],sid:n=on(),transmissionMode:r=Nc}=t;return Oi(Oi({},xi(t,Ch)),{},{version:e,transmissionMode:r,sid:n,eventTargets:i.reduce((t,e)=>{var i,n,r;return null!=e&&e.url&&null!=(i=e.events)&&i.length&&t.push({version:e.version||Fh,enabledKeys:(null==(n=e.enabledKeys)?void 0:n.slice())||[],url:e.url,events:e.events.slice(),interval:null!=(r=e.interval)?r:30,batchSize:e.batchSize||1}),t},[])})}(t),this.data={cid:this.config.cid,sid:this.config.sid,v:this.config.version},this.requester=e;for(const t of this.config.eventTargets)this.eventTargets.set(t,{intervalId:void 0,sn:0,msdSent:!1,queue:[]})}start(){this.eventTargets.forEach((t,e)=>{if(this.disarmInterval(t),0===e.interval||!e.events.includes("t"))return;const i=()=>{this.recordTargetEvent(t,e,"t"),this.processEventTargets()};t.intervalId=setInterval(i,1e3*e.interval),i()})}stop(t=!1){t&&this.flush(),this.eventTargets.forEach(t=>{this.disarmInterval(t)})}flush(){this.processEventTargets(!0)}update(t){t.sid&&t.sid!==this.data.sid&&this.resetSession(),t.msd&&!isNaN(t.msd)&&(this.msd=t.msd),this.data=Oi(Oi(Oi({},this.data),t),{},{msd:void 0});for(const e of Gc)e.field in t&&!e.equal(this.data[e.field],this.lastEmitted[e.field])&&this.recordEvent(e.event)}recordEvent(t,e={}){const i=Vc.get(t);if(i){const t=i.field,n=e[t];void 0!==n&&Di(this.data,{[t]:n});const r=this.data[t];if(void 0===r)return;if(i.equal(r,this.lastEmitted[t]))return;Di(this.lastEmitted,{[t]:i.snapshot(r)})}this.eventTargets.forEach((i,n)=>{this.recordTargetEvent(i,n,t,e)}),this.processEventTargets()}recordTargetEvent(t,e,i,n={}){var r;if(!e.events.includes(i))return;const s=Oi(Oi(Oi({},this.data),n),{},{e:i,ts:null!=(r=n.ts)?r:Date.now(),sn:t.sn++});isNaN(this.msd)||t.msdSent||(s.msd=this.msd,t.msdSent=!0),t.queue.push(s)}recordResponseReceived(t,e={}){var i,n,r;const{request:s}=t,a=null!=(i=e.url)?i:null==s?void 0:s.url;if(!a)return;const o=new URL(a);o.searchParams.delete(Ac);const l={url:o.toString(),rc:t.status},h=t.resourceTiming;h&&(null!=h.startTime&&(l.ts=Math.round(this.timeOrigin+h.startTime),null!=h.responseStart&&(l.ttfb=Math.round(h.responseStart-h.startTime))),null!=h.duration&&(l.ttlb=Math.round(h.duration)));const c=null!=(n=null==(r=s.customData)?void 0:r.cmcd)?n:{};this.recordEvent(Bh,Oi(Oi(Oi({},c),l),e))}applyRequestReport(t){var e;return null!=(e=this.createRequestReport(t))?e:t}isRequestReportingEnabled(){var t;return!(null==(t=this.config.enabledKeys)||!t.length)}createRequestReport(t,e){var i;const{customData:n={},headers:r={}}=t,s=Oi(Oi({},xi(t,Ph)),{},{headers:Oi({},r),customData:Oi(Oi({},n),{},{cmcd:{}})});if(null==(i=this.config.enabledKeys)||!i.length||!s.url)return s;const a=new URL(s.url),o=Oi(Oi(Oi({},this.data),e),{},{sn:this.requestTarget.sn++}),l=Bc(Yh,this.config,s.url);isNaN(this.msd)||this.requestTarget.msdSent||(o.msd=this.msd,this.requestTarget.msdSent=!0);const h=s.customData.cmcd=uc(o,l);switch(this.config.transmissionMode){case Nc:const t=Ec(h);t&&(a.searchParams.set(Ac,t),s.url=a.toString());break;case Fc:Di(s.headers,function(t,e){const i={},n=yc(t,e);for(const[t,e]of Object.entries(n)){const n=Rh(e,{whitespace:!1});n&&(i[t]=n)}return i}(h,l.customHeaderMap))}return s}processEventTargets(t=!1){let e=!1;this.eventTargets.forEach((i,n)=>{const{queue:r}=i;if(!r.length)return;if(r.length<n.batchSize&&!t)return;const s=t?r.length:n.batchSize,a=r.splice(0,s);this.sendEventReport(n,a).catch(()=>{i.queue.unshift(...a)}),e||(e=r.length>0)}),e&&this.processEventTargets()}async sendEventReport(t,e){const i=Bc(Hh,t),{status:n}=await this.requester({url:t.url,method:"POST",headers:{"Content-Type":"application/cmcd"},body:e.map(t=>function(t,e={}){return t?Ec(uc(t,e)):""}(t,i)).join("\n")+"\n"});if(410===n)this.disposeEventTarget(t);else if(429===n||n>499&&n<600)throw new Error(`Event report failed with status ${n}`)}disarmInterval(t){clearInterval(t.intervalId),t.intervalId=void 0}disposeEventTarget(t){const e=this.eventTargets.get(t);e&&(this.disarmInterval(e),this.eventTargets.delete(t))}resetSession(){this.eventTargets.forEach(t=>t.sn=0),this.requestTarget.sn=0,this.lastEmitted={}}};const Yc="h",jc="v",Wc="l",zc="ll";new Set(nc),new Set(Tc);const qc=["includeKeys"];function Xc(t){return Object.keys(t).every(qh)}function Qc(t,e,i,n){t&&Object.keys(e).forEach(r=>{const s=t.filter(t=>t.groupId===r).map(t=>{const s=Di({},t);return s.details=void 0,s.attrs=new ta(s.attrs),s.url=s.attrs.URI=Zc(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),s.groupId=s.attrs["GROUP-ID"]=e[r],s.attrs["PATHWAY-ID"]=n,s});t.push(...s)})}function Zc(t,e,i,n){if(e){const{[i]:t}=n;if(t){const i=t[e];if(i)return i}}const{HOST:r,PARAMS:s}=n,a=new self.URL(t);return r&&(a.hostname=r),s&&Object.keys(s).sort().forEach(t=>{t&&Nr(a,t,s[t])}),a.href}class Jc 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}}class tu extends ji{constructor(t){super("eme",t.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this.sessionSetupByUri={},this.mediaKeySessions=[],this.activeKeys={},this.mediaKeys=null,this.setMediaKeysQueue=tu.CDMCleanupPromise?[tu.CDMCleanupPromise]:[],this.onMediaEncrypted=t=>{const{initDataType:e,initData:i}=t,n=`"${t.type}" event: init data type: "${e}"`;if(this.log(n),null!==i){if(!this.keyFormatPromise){let t=Object.keys(this.keySystemAccessPromises);t.length||(t=Ta(this.config));const e=t.map(Ea).filter(t=>!!t);this.keyFormatPromise=this.getKeyFormatPromise(e)}this.keyFormatPromise.then(r=>{let s;const a=ya(r),o=this.activeLevelKeys();if(a===fa.FAIRPLAY&&"sinf"===e)try{const t=_n(new Uint8Array(i)),e=zn(kn(JSON.parse(t).sinf));if(!e)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");s=new Uint8Array(e.subarray(8,24))}catch(t){return void this.warn(`${n} Failed to parse sinf: ${t}`)}else if(a===fa.PLAYREADY)s=ka(new Uint8Array(i));else if(a===fa.WIDEVINE){const t=rr(i).filter(t=>t.systemId===Aa);if(t.length){var l;const e=t[0];s=null!=(l=e.kids)&&l.length?e.kids[0]:null}}let h;if(s){const t=bn(s);for(let n=0;n<o.length;n++){const r=o[n];if(r.keyId&&(sa(s,r.keyId)||-1!==r.uri.replace(/-/g,"").indexOf(t))){r.pssh||(r.scheme=e,r.pssh=new Uint8Array(i),r.keyId=s,La.setKeyIdForUri(r.uri,s)),h=this.getSessionForKey(r,"encrypted-event-key-match");break}}}if(!h){var c,u;if(o.length)return(c=o[0]).scheme||(c.scheme=e),(u=o[0]).pssh||(u.pssh=new Uint8Array(i)),this.getSessionForKey(o[0],"encrypted-event-no-match");if(s)throw new Error(`Key ID ${bn(s)} not encountered in playlist`);this.log(`Ignoring "${t.type}" event - could not determine keyId`)}return h}).catch(t=>this.handleError(t))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){const{hls:t}=this;t&&(t.on(ii.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(ii.MEDIA_DETACHED,this.onMediaDetached,this),t.on(ii.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ii.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(ii.DESTROYING,this.onDestroying,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(ii.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(ii.MEDIA_DETACHED,this.onMediaDetached,this),t.off(ii.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ii.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(ii.DESTROYING,this.onDestroying,this))}attemptKeySystemAccess(t){if(!this.hls)return Promise.reject(new Error("destroyed"));const e=this.hls.levels,i=(t,e,i)=>!!t&&i.indexOf(t)===e,n=e.map(t=>t.audioCodec).filter(i),r=e.map(t=>t.videoCodec).filter(i);return n.length+r.length===0&&r.push("avc1.42e01e"),new Promise((e,i)=>{const s=t=>{const a=t.shift();this.getMediaKeysPromise(a,n,r).then(t=>e({keySystem:a,mediaKeys:t})).catch(e=>{t.length?s(t):i(e instanceof Jc?e:new Jc({type:ti.KEY_SYSTEM_ERROR,details:ei.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===ba&&"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){var n;const r=function(t,e,i,n){let r;switch(t){case fa.FAIRPLAY:r=["cenc","sinf"];break;case fa.WIDEVINE:case fa.PLAYREADY:r=["cenc"];break;case fa.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${t}`)}return function(t,e,i,n){return[{initDataTypes:t,persistentState:n.persistentState||"optional",distinctiveIdentifier:n.distinctiveIdentifier||"optional",sessionTypes:n.sessionTypes||[n.sessionType||"temporary"],audioCapabilities:e.map(t=>({contentType:`audio/mp4; codecs=${t}`,robustness:n.audioRobustness||"",encryptionScheme:n.audioEncryptionScheme||null})),videoCapabilities:i.map(t=>({contentType:`video/mp4; codecs=${t}`,robustness:n.videoRobustness||"",encryptionScheme:n.videoEncryptionScheme||null}))}]}(r,e,i,n)}(t,e,i,this.config.drmSystemOptions||{});let s=this.keySystemAccessPromises[t],a=null==(n=s)?void 0:n.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${t}" key-system access with config: ${Wr(r)}`),a=this.requestMediaKeySystemAccess(t,r);const e=s=this.keySystemAccessPromises[t]={keySystemAccess:a};return a.catch(e=>{this.log(`Failed to obtain access to key-system "${t}": ${e}`)}),a.then(i=>{this.throwIfDestroyed(),this.log(`Access for key-system "${i.keySystem}" obtained`);const n=this.fetchServerCertificate(t);this.log(`Create media-keys for "${t}"`);const r=e.mediaKeys=i.createMediaKeys().then(i=>(this.log(`Media-keys created for "${t}"`),e.hasMediaKeys=!0,n.then(e=>e?this.setMediaKeysServerCertificate(i,t,e):i)));return r.catch(e=>{this.error(`Failed to create media-keys for "${t}"}: ${e}`)}),r})}return a.then(()=>s.mediaKeys)}getMediaKeySessionContext(t,e,i,n){const{mediaKeySessions:r}=this,s=` key-session "${t}" keyId: ${bn(i.keyId||[])} keyUri: ${i.uri} for "${n}"`;for(let t=0;t<r.length;t++){const e=r[t];if(!e.initialized&&e.createdFor.levelKey.uri===i.uri)return this.log(`Reusing${s}`),e}this.log(`Creating${s}`);const a=e.createSession(),o={keySystem:t,mediaKeys:e,mediaKeysSession:a,keyRequests:{},keyStatuses:{},createdFor:{levelKey:i,reason:n},initialized:!1};return r.push(o),o}resetMediaKeys(){var t;const e=null==(t=this.mediaKeySessions[0])?void 0:t.keySystem,i=this.keySystemAccessPromises[e];i&&(this.log("reset mediaKeys"),this.mediaKeys=null,i.hasMediaKeys=!1,delete i.mediaKeys,delete this.keySystemAccessPromises[e])}updateKeySession(t,e,i){const n=t.mediaKeysSession;return this.log(`Updating key-session "${n.sessionId}" for keyId ${bn(e.keyId||[])}\n } (data length: ${i.byteLength})`),n.update(i)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(t=>({keySystem:t,hasMediaKeys:this.keySystemAccessPromises[t].hasMediaKeys})).filter(({hasMediaKeys:t})=>!!t).map(({keySystem:t})=>Ea(t)).filter(t=>!!t)}getKeySystemAccess(t){return this.getKeySystemSelectionPromise(t).then(({keySystem:t,mediaKeys:e})=>this.attemptSetMediaKeys(t,e))}selectKeySystem(t){return this.getKeySystemSelectionPromise(t).then(({keySystem:t})=>{const e=Ea(t);if(!e)throw new Error(`Unable to find format for key-system "${t}"`);return 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){const e=Ta(this.config),i=t.map(ya).filter(t=>!!t&&-1!==e.indexOf(t));return this.selectKeySystem(i)}loadClear(t,e,i){if(this.config.emeEnabled&&!this.getSelectedKeySystemFormats().length){if(e.length)for(let n=0,r=e.length;n<r;n++){const s=e[n];if(t.cc<=s.cc&&(!ki(t)||!ki(s)||t.sn<s.sn)||!i&&n==r-1)return this.selectKeySystemFormat(s).then(t=>{if(!this.hls)return;s.setKeyFormat(t);const e=ya(t);return e?this.getKeySystemAccess([e]):void 0})}if(this.config.requireKeySystemAccessOnStart){const t=Ta(this.config);if(t.length)return this.getKeySystemAccess(t)}}return null}getKeyStatus(t){const{mediaKeySessions:e}=this;for(let i=0;i<e.length;i++){const n=eu(t,e[i]);if(n)return n}}loadKey(t){const e=t.decryptdata,i=this.getKeyStatus(e);if("internal-error"===i){const n=iu(i,e);return n.data.frag=t,this.error(`${n.message} (${bn(e.keyId||[])})`),Promise.reject(n)}const n=t.type,r=this.activeKeys,s=r[n];s&&!e.matches(s.decryptdata)&&(r.previous||(r.previous=[]),r.previous.push(s),delete r[n]),r[n]||(r[n]=t);for(let t=this.mediaKeySessions.length;t--;){const i=this.mediaKeySessions[t];if(e.keyId&&"expired"===i.keyStatuses[bn(e.keyId)])return this.renewKeySession(e,i)}return this.updateUsablePromise(e,"playlist-key",t)}renewKeySession(t,e){return this.resetMediaKeys(),this.removeSession(e).then(()=>(this.throwIfDestroyed(),this.updateUsablePromise(t,"expired")))}updateUsablePromise(t,e,i){const n=this.getSessionForKey(t,e);return n.catch(t=>this.handleError(t,i)),n.then(e=>t)}getSessionForKey(t,e){const i=this.findContextForKey(t);if(void 0!==i)return Promise.resolve(i);const n=t.uri,r=this.sessionSetupByUri[n];let s;s=void 0===r?this.resolveSessionForKey(t,e):r.catch(()=>{}).then(()=>(this.throwIfDestroyed(),this.resolveSessionForKey(t,e))),this.sessionSetupByUri[n]=s;const a=()=>{this.sessionSetupByUri[n]===s&&delete this.sessionSetupByUri[n]};return s.then(a,a),s}findContextForKey(t){const{mediaKeySessions:e}=this;for(let i=e.length;i--;){const n=e[i];if(eu(t,n))return n}}resolveSessionForKey(t,e){return this.getKeySystemForKeyPromise(t).then(({keySystem:i,mediaKeys:n})=>{this.throwIfDestroyed();for(let i=this.mediaKeySessions.length;i--;){const n=this.mediaKeySessions[i];if(eu(t,n))return n;const r=this.getUsableKeyPromise(n,t,e);if(r)return r}return this.attemptSetMediaKeys(i,n).then(()=>(this.throwIfDestroyed(),this.getMediaKeySessionContext(i,n,t,e))).then(i=>{this.throwIfDestroyed();const n=t.scheme||"cenc",r=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(i,t,n,r,e)})})}getUsableKeyPromise(t,e,i){const n=t.keyRequests[e.uri];if(n)return this.log(`Waiting for usable key (${i} keyId: ${function(t){if(t.keyFormat===pa)return t.uri;if(null===t.keyId)throw new Error("keyId is null");return bn(t.keyId)}(e)} format: "${e.keyFormat}" URI: ${e.uri})`),nu(n).then(()=>t)}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t,e){if(this.hls)if(t instanceof Jc){e&&(t.data.frag=e);const i=t.data.decryptdata;this.error(`${t.message}${i?` (${bn(i.keyId||[])})`:""}`),this.hls.trigger(ii.ERROR,t.data)}else this.error(t.message),this.hls.trigger(ii.ERROR,{type:ti.KEY_SYSTEM_ERROR,details:ei.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0})}getKeySystemForKeyPromise(t){const e=ya(t.keyFormat),i=e?[e]:Ta(this.config);return this.attemptKeySystemAccess(i)}getKeySystemSelectionPromise(t){if(t.length||(t=Ta(this.config)),0===t.length)throw new Jc({type:ti.KEY_SYSTEM_ERROR,details:ei.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${Wr({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}activeLevelKeys(){const t=this.activeKeys,e=(t.previous||[]).map(t=>t.decryptdata);return t.audio&&e.unshift(t.audio.decryptdata),t.main&&e.unshift(t.main.decryptdata),e}attemptSetMediaKeys(t,e){if(this.mediaResolved=void 0,this.mediaKeys===e)return Promise.resolve();const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const n=Promise.all(i).then(()=>this.media?this.media.setMediaKeys(e):new Promise((t,i)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return i(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=e,this.media.setMediaKeys(e).then(t).catch(i)}}));return this.mediaKeys=e,this.setMediaKeysQueue.push(n),n.then(()=>{this.log(`Media-keys set for "${t}"`),i.push(n),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(t=>-1===i.indexOf(t))})}filterInitData(t,e,i,n,r){var s;const a=null==(s=this.config.drmSystems)||null==(s=s[t.keySystem])?void 0:s.generateRequest;if(a)try{const s=a.call(this.hls,i,n,Di({},t,{decryptdata:e,reason:r}),r);if(!s)throw new Error("Invalid response from configured generateRequest filter");e.scheme=s.initDataType?s.initDataType:"cenc";const o=s.initData?s.initData:null;return e.pssh=o?new Uint8Array(o):null,s}catch(t){var o;if(this.warn(t.message),null!=(o=this.hls)&&o.config.debug)throw t}return{initDataType:i,initData:n}}generateRequestWithPreferredKeySession(t,e,i,n,r){const s=this.getUsableKeyPromise(t,e,r);if(s)return s;const a=this.filterInitData(t,e,i,n,r);if(a&&(n=a.initData?a.initData:null,i=a.initDataType),null===n)return r.startsWith("encrypted-event")?Promise.reject(new Error(`missing initialization data for "${r}"`)):(this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(t));const o=e.uri,l=new Do;l.status="initialized",l.requestErrors=[],t.keyRequests[o]=l;const h=i=>{const n=t.mediaKeysSession;if(!n){const t=new Error("invalid state");return l.errored=t,void l.emit("error",t)}const{messageType:r,message:s}=i;l.status=r,this.log(`"${r}" message event for session "${n.sessionId}" message size: ${s.byteLength}`),"license-request"===r||"license-renewal"===r?this.renewLicense(t,e,s).catch(e=>{l.errored=e,l.eventNames().length?l.emit("error",e):this.handleError(e),this.removeSession(t)}):"license-release"===r?t.keySystem===fa.FAIRPLAY&&this.updateKeySession(t,e,ha("acknowledged")).then(()=>this.removeSession(t)).catch(t=>this.handleError(t)):this.warn(`unhandled media key message type "${r}"`)};l.onmessage=h,lo(t.mediaKeysSession,"message",h);return this.generateRequest(t,e,i,n,r,!1)}generateRequest(t,e,i,n,r,s){if(s){const s=this.filterInitData(t,e,i,n,r);s&&(n=s.initData?s.initData:n,i=s.initDataType)}const a=e.uri,o=t.keyRequests[a],l=bn(e.keyId||[]),h=t=>{let i;t.startsWith("usable")?(o.resolved=!0,o.emit("resolved")):"internal-error"===t||"output-restricted"===t||"output-downscaled"===t?i=iu(t,e):"expired"===t?i=new Error(`key expired (keyId: ${l})`):"released"===t?i=new Error("key released"):"status-pending"===t||this.warn(`unhandled key status change "${t}" (keyId: ${l})`),i&&(o.errored=i,o.eventNames().length?o.emit("error",i):this.handleError(i))},c=i=>{if(!t.mediaKeysSession){const t=new Error("invalid state");return o.errored=t,void o.emit("error",t)}const n=t.keyStatuses=this.getKeyStatuses(t);if(!Object.keys(n).some(t=>"status-pending"!==n[t]))return;const r=this.activeLevelKeys();for(let i=0;i<r.length;i++){const a=bn(r[i].keyId||[]);if("expired"===n[a]){var s;this.log(`Expired key ${Wr(n)} in key-session "${null==(s=t.mediaKeysSession)?void 0:s.sessionId}"`),this.renewKeySession(e,t).catch(t=>this.handleError(t));break}}let a=n[l];if(a)h(a);else{var c;const i=1e3;t.keyStatusTimeouts||(t.keyStatusTimeouts={}),(c=t.keyStatusTimeouts)[l]||(c[l]=self.setTimeout(()=>{var n;if(!t.mediaKeysSession)return;const r=this.getKeyStatus(e);var s;if(r&&"status-pending"!==r)return this.log(`No status for keyId ${l} in key-session "${null==(s=t.mediaKeysSession)?void 0:s.sessionId}". Using session key-status ${r} from other session.`),h(r);this.log(`key status for ${l} in key-session "${null==(n=t.mediaKeysSession)?void 0:n.sessionId}" timed out after ${i}ms`),a="internal-error",h(a)},i)),this.log(`No status for keyId ${l} (${Wr(n)}).`)}};o.onkeystatuseschange=c,lo(t.mediaKeysSession,"keystatuseschange",c);const u=nu(o);return this.log(`Generating key-session request for "${r}" keyId: ${l} URI: ${a} (init data type: ${i} length: ${n.byteLength})`),o.status="started",t.initialized=!0,t.mediaKeysSession.generateRequest(i,n).then(()=>{var e;o.status="generated",this.log(`Request generated for key-session "${null==(e=t.mediaKeysSession)?void 0:e.sessionId}" keyId: ${l} URI: ${a}`)}).catch(t=>{throw this.log(`mediaKeysSession.generateRequest failed: ${t}`),new Jc({type:ti.KEY_SYSTEM_ERROR,details:ei.KEY_SYSTEM_NO_SESSION,error:t,decryptdata:e,fatal:!1},`Error generating key-session request: ${t}`)}).then(()=>u).catch(e=>{var i;this.log(`mediaKeysSession.generateRequest failed: ${e}`);const n=null==(i=e.data)?void 0:i.details;return n!==ei.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED&&n!==ei.KEY_SYSTEM_STATUS_INTERNAL_ERROR||!Object.keys(t.keyStatuses).some(e=>"usable"===t.keyStatuses[e])?(o.removeAllListeners(),this.removeSession(t).then(()=>{throw e})):(this.handleError(e),t)}).then(()=>t)}getKeyStatuses(t){const e={},i=t.mediaKeysSession.sessionId;return t.mediaKeysSession.keyStatuses.forEach((n,r)=>{if("string"==typeof r&&"object"==typeof n){const t=r;r=n,n=t}const s="buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);if(t.keySystem===fa.PLAYREADY&&16===s.length){const t=bn(s);e[t]=n,ca(s)}const a=bn(s);this.log(`key status change "${n}" for keyStatuses keyId: ${a} key-session "${i}"`),e[a]=n}),e}fetchServerCertificate(t){const e=this.config,i=new(0,e.loader)(e),n=function(t,e){const{drmSystems:i}=e,n=null==i?void 0:i[t];if(n)return n.serverCertificateUrl}(t,e);return n?(this.log(`Fetching server certificate for "${t}"`),new Promise((r,s)=>{const a={type:pi,responseType:"arraybuffer",url:n},o=e.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(t,e,i,n)=>{r(t.data)},onError:(e,i,r,o)=>{s(new Jc({type:ti.KEY_SYSTEM_ERROR,details:ei.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:Oi({url:a.url,data:void 0},e)},`"${t}" certificate request failed (${n}). Status: ${e.code} (${e.text})`))},onTimeout:(e,i,r)=>{s(new Jc({type:ti.KEY_SYSTEM_ERROR,details:ei.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:{url:a.url,data:void 0}},`"${t}" certificate request timed out (${n})`))},onAbort:(t,e,i)=>{s(new Error("aborted"))}};i.load(a,l,h)})):(this.log(`No Server Certificate in config.drmSystems["${t}"]`),Promise.resolve())}setMediaKeysServerCertificate(t,e,i){return new Promise((n,r)=>{t.setServerCertificate(i).then(r=>{this.log(`setServerCertificate ${r?"success":"not supported by CDM"} (${i.byteLength}) on "${e}"`),n(t)}).catch(t=>{r(new Jc({type:ti.KEY_SYSTEM_ERROR,details:ei.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:t,fatal:!0},t.message))})})}renewLicense(t,e,i){return this.requestLicense(t,e,new Uint8Array(i)).then(i=>this.updateKeySession(t,e,new Uint8Array(i)).catch(t=>{throw new Jc({type:ti.KEY_SYSTEM_ERROR,details:ei.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e,error:t,fatal:!1},t.message)}))}unpackPlayReadyKeyMessage(t,e){const i=_n(new Uint16Array(e.buffer));if(!i.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),e;const n=(new DOMParser).parseFromString(i,"application/xml"),r=n.querySelectorAll("HttpHeader");if(r.length>0){let e;for(let i=0,n=r.length;i<n;i++){var s,a;e=r[i];const n=null==(s=e.querySelector("name"))?void 0:s.textContent,o=null==(a=e.querySelector("value"))?void 0:a.textContent;n&&o&&t.setRequestHeader(n,o)}}const o=n.querySelector("Challenge"),l=null==o?void 0:o.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return ha(atob(l))}setupLicenseXHR(t,e,i,n,r){const s=this.config.licenseXhrSetup;return s?Promise.resolve().then(()=>(this.throwIfDestroyed(),s.call(this.hls,t,e,Oi(Oi({},i),{},{decryptdata:n}),r))).catch(a=>{if(!i.mediaKeysSession)throw a;return t.open("POST",e,!0),s.call(this.hls,t,e,Oi(Oi({},i),{},{decryptdata:n}),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,i){return new Promise((n,r)=>{const s=function(t,e){const{drmSystems:i,widevineLicenseUrl:n}=e,r=null==i?void 0:i[t];if(r)return r.licenseUrl;if(t===fa.WIDEVINE&&n)return n}(t.keySystem,this.config);if(!s)return r(new Error(`no license server URL configured for key-system "${t.keySystem}"`));const a=t.keyRequests[e.uri];if(!a)return r(new Error("License emitter removed"));this.log(`Sending license request to URL: ${s}`);const o=this.config.keyLoadPolicy.default,l=new XMLHttpRequest;l.responseType="arraybuffer",l.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return r(new Error("invalid state"));if(4===l.readyState)if(200===l.status){a.requestErrors=[];let i=l.response;this.log(`License received ${i instanceof ArrayBuffer?i.byteLength:i}`);const r=this.config.licenseResponseCallback;if(r)try{i=r.call(this.hls,l,s,Oi(Oi({},t),{},{decryptdata:e}))}catch(t){this.error(t)}n(i)}else{const h=o.errorRetry,c=h?h.maxNumRetry:0;if(a.requestErrors.push({status:l.status,message:l.statusText}),a.requestErrors.length>c||l.status>=400&&l.status<500)r(new Jc({type:ti.KEY_SYSTEM_ERROR,details:ei.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e,fatal:!0,networkDetails:l,response:{url:s,data:void 0,code:l.status,text:l.statusText}},`License Request XHR failed (${s}). Status: ${l.status} (${l.statusText})`));else{const s=c-a.requestErrors.length;this.warn(`Retrying license request, ${s} attempts left`),this.requestLicense(t,e,i).then(n,r)}}},a.licenseXhr&&a.licenseXhr.readyState!==XMLHttpRequest.DONE&&a.licenseXhr.abort(),a.licenseXhr=l,this.setupLicenseXHR(l,s,t,e,i).then(({xhr:e,licenseChallenge:i})=>{t.keySystem==fa.PLAYREADY&&(i=this.unpackPlayReadyKeyMessage(e,i)),e.send(i)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(t,e){if(!this.config.emeEnabled)return;const i=e.media;this.media=i,lo(i,"encrypted",this.onMediaEncrypted),lo(i,"waitingforkey",this.onWaitingForKey);const n=this.mediaResolved;n?n():this.mediaKeys=i.mediaKeys}onMediaDetached(){const t=this.media;t&&(ho(t,"encrypted",this.onMediaEncrypted),ho(t,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var t;this.keyFormatPromise=null,this.keySystemAccessPromises={},this.activeKeys={},this.sessionSetupByUri={};const e=this.mediaResolved;if(e&&e(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const i=this.media,n=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,La.clearKeyUriToKeyIdMap();const r=n.length;tu.CDMCleanupPromise=Promise.all(n.map(t=>this.removeSession(t)).concat((null==i||null==(t=i.setMediaKeys(null))?void 0:t.catch(t=>{this.log(`Could not clear media keys: ${t}`),this.hls&&this.hls.trigger(ii.ERROR,{type:ti.OTHER_ERROR,details:ei.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${t}`)})}))||Promise.resolve())).catch(t=>{this.log(`Could not close sessions and clear media keys: ${t}`),this.hls&&this.hls.trigger(ii.ERROR,{type:ti.OTHER_ERROR,details:ei.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${t}`)})}).then(()=>{r&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear(),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),this.keyFormatPromise.catch(()=>{})}}removeSession(t){const{mediaKeysSession:e}=t;if(e){this.log(`Remove licenses and keys and close session "${e.sessionId}"`),Object.keys(t.keyRequests).forEach(i=>{const n=t.keyRequests[i];n.onmessage&&(e.removeEventListener("message",n.onmessage),n.onmessage=void 0),n.onkeystatuseschange&&(e.removeEventListener("keystatuseschange",n.onkeystatuseschange),n.onkeystatuseschange=void 0);const r=n.licenseXhr;r&&(r.readyState!==XMLHttpRequest.DONE&&r.abort(),n.licenseXhr=void 0),t.keyRequests[i]=void 0}),t.mediaKeysSession=void 0;const i=this.mediaKeySessions.indexOf(t);i>-1&&this.mediaKeySessions.splice(i,1);const{keyStatusTimeouts:n}=t;n&&Object.keys(n).forEach(t=>self.clearTimeout(n[t]));const{drmSystemOptions:r}=this.config,s=function(t){var e;return!(!t||"persistent-license"!==t.sessionType&&(null==(e=t.sessionTypes)||!e.some(t=>"persistent-license"===t)))}(r)?new Promise((t,i)=>{self.setTimeout(()=>i(new Error("MediaKeySession.remove() timeout")),8e3),e.remove().then(t).catch(i)}):Promise.resolve();return s.catch(t=>{this.log(`Could not remove session: ${t}`),this.hls&&this.hls.trigger(ii.ERROR,{type:ti.OTHER_ERROR,details:ei.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${t}`)})}).then(()=>e.close()).then(()=>e.closed).catch(t=>{this.log(`Could not close session: ${t}`),this.hls&&this.hls.trigger(ii.ERROR,{type:ti.OTHER_ERROR,details:ei.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${t}`)})})}return Promise.resolve()}}function eu(t,e){const i=t.keyId,n=e.mediaKeysSession;if(i&&n){const t=e.mediaKeysSession.keyStatuses;if(t.size)return t.has(i)?t.get(i):e.keyStatuses[bn(i)]}}function iu(t,e){const i="output-restricted"===t,n=i?ei.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:ei.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Jc({type:ti.KEY_SYSTEM_ERROR,details:n,fatal:!1,decryptdata:e},i?"HDCP level output restricted":`key status changed to "${t}"`)}function nu(t){return new Promise((e,i)=>t.resolved?e():t.errored?i(t.errored):(t.on("error",i),void t.on("resolved",e)))}tu.CDMCleanupPromise=void 0;var ru=function(){if(null!=da&&da.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 n(t){return i(e,t)}function r(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 h="",c=!1,u=e,d=s,f=a,g=null,p="",m=!0,v="auto",y="start",A=50,E="middle",T=50,b="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 c},set:function(t){c=!!t}})),Object.defineProperty(o,"startTime",r({},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",r({},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",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 p},set:function(e){const n=function(e){return i(t,e)}(e);if(!1===n)throw new SyntaxError("An invalid or illegal string was specified.");p=n,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",r({},l,{get:function(){return m},set:function(t){m=!!t,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",r({},l,{get:function(){return v},set:function(t){if("number"!=typeof t&&"auto"!==t)throw new SyntaxError("An invalid number or illegal string was specified.");v=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",r({},l,{get:function(){return y},set:function(t){const e=n(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");y=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",r({},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",r({},l,{get:function(){return E},set:function(t){const e=n(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 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",r({},l,{get:function(){return b},set:function(t){const e=n(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");b=e,this.hasBeenReset=!0}})),o.displayState=void 0}return s.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},s}();class su{decode(t,e){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function au(t){function e(t,e,i,n){return 3600*(0|t)+60*(0|e)+(0|i)+parseFloat(n||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 ou{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 n=0;n<i.length;++n)if(e===i[n]){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 lu(t,e,i,n){const r=n?t.split(n):[t];for(const t in r){if("string"!=typeof r[t])continue;const n=r[t].split(i);if(2!==n.length)continue;e(n[0],n[1])}}const hu=new ru(0,0,""),cu="middle"===hu.align?"middle":"center";function uu(t,e,i){const n=t;function r(){const e=au(t);if(null===e)throw new Error("Malformed timestamp: "+n);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function s(){t=t.replace(/^\s+/,"")}if(s(),e.startTime=r(),s(),"--\x3e"!==t.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+n);t=t.slice(3),s(),e.endTime=r(),s(),function(t,e){const n=new ou;lu(t,function(t,e){let r;switch(t){case"region":for(let r=i.length-1;r>=0;r--)if(i[r].id===e){n.set(t,i[r].region);break}break;case"vertical":n.alt(t,e,["rl","lr"]);break;case"line":r=e.split(","),n.integer(t,r[0]),n.percent(t,r[0])&&n.set("snapToLines",!1),n.alt(t,r[0],["auto"]),2===r.length&&n.alt("lineAlign",r[1],["start",cu,"end"]);break;case"position":r=e.split(","),n.percent(t,r[0]),2===r.length&&n.alt("positionAlign",r[1],["start",cu,"end","line-left","line-right","auto"]);break;case"size":n.percent(t,e);break;case"align":n.alt(t,e,["start",cu,"end","left","right"])}},/:/,/\s/),e.region=n.get("region",null),e.vertical=n.get("vertical","");let r=n.get("line","auto");"auto"===r&&-1===hu.line&&(r=-1),e.line=r,e.lineAlign=n.get("lineAlign","start"),e.snapToLines=n.get("snapToLines",!0),e.size=n.get("size",100),e.align=n.get("align",cu);let s=n.get("position","auto");"auto"===s&&50===hu.position&&(s="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=s}(t,e)}function du(t){return t.replace(/<br(?: \/)?>/gi,"\n")}class fu{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new su,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=du(t);i<t.length&&"\r"!==t[i]&&"\n"!==t[i];)++i;const n=t.slice(0,i);return"\r"===t[i]&&++i,"\n"===t[i]&&++i,e.buffer=t.slice(i),n}function n(t){lu(t,function(t,e){},/:/)}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 n=t.match(/^()?WEBVTT([ \t].*)?$/);if(null==n||!n[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)?n(t):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 ru(0,0,""),e.state="CUE",-1===t.indexOf("--\x3e")){e.cue.id=t;continue}case"CUE":if(!e.cue){e.state="BADCUE";continue}try{uu(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}}function gu(t){let e=5381,i=t.length;for(;i;)e=33*e^t.charCodeAt(--i);return(e>>>0).toString()}const pu=/\r\n|\n\r|\n|\r/g,mu="Missing initPTS for VTT ";function vu(t,e,i){return gu(t.toString())+gu(e.toString())+gu(i)}function yu(t,e,i,n,r,s,a){const o=new fu,l=gn(new Uint8Array(t)).trim().replace(pu,"\n").split("\n"),h=[],c=e?function(t,e=1){return wl(t,9e4,1/e)}(e.baseTime,e.timescale):0;let u,d="00:00.000",f=0,g=0,p=!1,m=!0;o.oncue=function(t){const s=i[n];let a=i.ccOffset;const o=(f-c)/9e4;if(p){if(null!=s&&s.new&&(a=i.ccOffset=s.start),o){if(!e)return void(u=new Error(mu+"MPEGTS"));a=o-i.presentationOffset}}else{if(!e)return void(u=new Error(mu+"without X-TIMESTAMP-MAP"));a=-e.baseTime/e.timescale}const l=t.endTime-t.startTime,d=Bl(9e4*(t.startTime+a-g),9e4*r)/9e4;t.startTime=Math.max(d,0),t.endTime=Math.max(d+l,0);const m=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(m)),t.id?n&&(t.id=`hlsjscc${n}_${t.id}`):t.id=vu(t.startTime,t.endTime,m),t.endTime>0&&h.push(t)},o.onparsingerror=function(t){u=t},o.onflush=function(){u?a(u):s(h)},l.forEach(t=>{if(m){if(t.startsWith("X-TIMESTAMP-MAP=")){m=!1,p=!0,t.slice(16).split(",").forEach(t=>{t.startsWith("LOCAL:")?d=t.slice(6):t.startsWith("MPEGTS:")&&(f=parseInt(t.slice(7)))});try{g=function(t){let e=parseInt(t.slice(-3));const i=parseInt(t.slice(-6,-4)),n=parseInt(t.slice(-9,-7)),r=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!(Qe(e)&&Qe(i)&&Qe(n)&&Qe(r)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return e+=1e3*i,e+=6e4*n,e+=36e5*r,e}(d)/1e3}catch(t){u=t}return}""===t&&(m=!1)}o.parse(t+"\n")}),o.flush()}const Au="stpp.ttml.im1t",Eu=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Tu=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,bu={left:"start",center:"center",right:"end",start:"start",end:"end"};function Su(t,e,i,n){const r=Bn(new Uint8Array(t),["mdat"]);if(0===r.length)return void n(new Error("Could not parse IMSC1 mdat"));const s=r.map(t=>gn(t)),a=function(t,e,i=1,n=!1){return wl(t,e,1/i,n)}(e.baseTime,1,e.timescale);try{s.forEach(t=>i(function(t,e){const i=(new DOMParser).parseFromString(t,"text/xml"),n=i.getElementsByTagName("tt")[0];if(!n)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},s=Object.keys(r).reduce((t,e)=>(t[e]=n.getAttribute(`ttp:${e}`)||r[e],t),{}),a="preserve"!==n.getAttribute("xml:space"),o=_u(ku(n,"styling","style")),l=_u(ku(n,"layout","region")),h=ku(n,"body","[begin]");return[].map.call(h,t=>{const i=Lu(t,a);if(!i||!t.hasAttribute("begin"))return null;const n=Cu(t.getAttribute("begin"),s),r=Cu(t.getAttribute("dur"),s);let h=Cu(t.getAttribute("end"),s);if(null===n)throw Iu(t);if(null===h){if(null===r)throw Iu(t);h=n+r}const c=new ru(n-e,h-e,i);c.id=vu(c.startTime,c.endTime,c.text);const u=function(t,e,i){const n="http://www.w3.org/ns/ttml#styling";let r=null;const s=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;a&&i.hasOwnProperty(a)&&(r=i[a]);return s.reduce((i,s)=>{const a=Ru(e,n,s)||Ru(t,n,s)||Ru(r,n,s);return a&&(i[s]=a),i},{})}(l[t.getAttribute("region")],o[t.getAttribute("style")],o),{textAlign:d}=u;if(d){const t=bu[d];t&&(c.lineAlign=t),c.align=d}return Di(c,u),c}).filter(t=>null!==t)}(t,a)))}catch(t){n(t)}}function ku(t,e,i){const n=t.getElementsByTagName(e)[0];return n?[].slice.call(n.querySelectorAll(i)):[]}function _u(t){return t.reduce((t,e)=>{const i=e.getAttribute("xml:id");return i&&(t[i]=e),t},{})}function Lu(t,e){return[].slice.call(t.childNodes).reduce((t,i,n)=>{var r;return"br"===i.nodeName&&n?t+"\n":null!=(r=i.childNodes)&&r.length?Lu(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function Ru(t,e,i){return t&&t.hasAttributeNS(e,i)?t.getAttributeNS(e,i):null}function Iu(t){return new Error(`Could not parse ttml timestamp ${t}`)}function Cu(t,e){if(!t)return null;let i=au(t);return null===i&&(Eu.test(t)?i=function(t,e){const i=Eu.exec(t),n=(0|i[4])+(0|i[5])/e.subFrameRate;return 3600*(0|i[1])+60*(0|i[2])+(0|i[3])+n/e.frameRate}(t,e):Tu.test(t)&&(i=function(t,e){const i=Tu.exec(t),n=Number(i[1]);switch(i[2]){case"h":return 3600*n;case"m":return 60*n;case"ms":return 1e3*n;case"f":return n/e.frameRate;case"t":return n/e.tickRate}return n}(t,e))),i}function Pu(t,e,i,n="",r="disabled"){const s=t.ownerDocument.createElement("track");return s.kind=e,s.label=i,n&&(s.srclang=n),s.src="data:,WEBVTT",s.track.mode=r,t.appendChild(s),s}function Du(t){return t.forced&&(or.indexOf("Apple")>-1||/iPhone|iPad|iPod/.test(ar))?"forced":t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles"}function wu(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){Zi.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){Zi.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${t}`)}}"disabled"===i&&(t.mode=i)}function Ou(t,e,i,n){const r=t.mode;if("disabled"===r&&(t.mode="hidden"),t.cues&&t.cues.length>0){const r=function(t,e,i){const n=[],r=function(t,e){if(e<=t[0].startTime)return 0;const i=t.length-1;if(e>t[i].endTime)return-1;let n,r=0,s=i;for(;r<=s;)if(n=Math.floor((s+r)/2),e<t[n].startTime)s=n-1;else{if(!(e>t[n].startTime&&r<i))return n;r=n+1}return t[r].startTime-e<e-t[s].startTime?r:s}(t,e);if(r>-1)for(let s=r,a=t.length;s<a;s++){const r=t[s];if(r.startTime>=e&&r.endTime<=i)n.push(r);else if(r.startTime>i)return n}return n}(t.cues,e,i);for(let e=0;e<r.length;e++)n&&!n(r[e])||t.removeCue(r[e])}"disabled"===r&&(t.mode=r)}function xu(t,e){const i=Mu(t.main);if(i&&i.start<=e)return i;const n=Mu(t.audio);return n&&n.start<=e?n:null}function Mu(t){if(!t)return null;switch(t.state){case fo:case uo:case Eo:case To:return null}return t.frag}function Nu(t,e){return e.getAppendedFrag(t,vi)||e.getPartialFragment(t)}function Fu(t,e,i,n){const r=n.latestLevelDetails,s=Nu(e,i);if(Lo(n.config)&&!t.nextStart&&r&&s&&n.interstitialsManager){const i="type"in s?s:s.fragment,a=hs(r,i.sn,!0);(null==a?void 0:a.level)===i.level&&_o(a,n.interstitialsManager.playerQueue,e)&&(t.nextStart=a.start)}}function Bu(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function $u(t,e,i,n,r){let s=new t(e,i,"");try{s.value=n,r&&(s.type=r)}catch(a){s=new t(e,i,Wr(r?Oi({type:r},n):n))}return s}const Uu=(()=>{const t=Bu();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function Gu(){return self.SourceBuffer||self.WebKitSourceBuffer}function Vu(){if(!Ji())return!1;const t=Gu();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}var Ku=0,Hu=1,Yu=2;class ju extends ko{constructor(t,e,i){super(t,e,i,"stream-controller",vi),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=Ku,this.audioOnly=!1,this._couldBacktrack=!1,this._backtrackFragment=void 0,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const t=this.media,e=t?t.currentTime:null;if(null===e||!Qe(e))return;if(this.log(`Media seeked to ${e}`),!this.getBufferedFrag(e))return;const i=this.getFwdBufferInfoAtPos(t,e,vi,0);i&&0!==i.len?this.tick():this.log(`Main buffer empty at ${e} on "seeked" event: ${i?i.len:i}`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(ii.MANIFEST_PARSED,this.onManifestParsed,this),t.on(ii.LEVEL_LOADING,this.onLevelLoading,this),t.on(ii.LEVEL_LOADED,this.onLevelLoaded,this),t.on(ii.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(ii.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(ii.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(ii.BUFFER_CREATED,this.onBufferCreated,this),t.on(ii.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(ii.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(ii.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(ii.MANIFEST_PARSED,this.onManifestParsed,this),t.off(ii.LEVEL_LOADED,this.onLevelLoaded,this),t.off(ii.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(ii.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(ii.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(ii.BUFFER_CREATED,this.onBufferCreated,this),t.off(ii.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(ii.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(ii.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(t,e){if(this.levels){const{lastCurrentTime:i,hls:n}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let t=n.startLevel;-1===t&&(n.config.testBandwidth&&this.levels.length>1?(t=0,this.bitrateTest=!0):t=n.firstAutoLevel),n.nextLoadLevel=t,this.level=n.loadLevel,this._hasEnoughToStart=!!e}i>0&&-1===t&&!e&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${i}`),t=i),this.state=fo,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,e||this.fragmentTracker.hasFragments(this.playlistType)||(this._hasEnoughToStart=this.startFragRequested=!1),this.tick()}else this._forceStartLoad=!0,this.state=uo}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case So:{const{levels:t,level:e}=this,i=null==t?void 0:t[e],n=null==i?void 0:i.details;if(n&&(!n.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(n))break;this.state=fo;break}if(this.hls.nextLoadLevel!==this.level){this.state=fo;break}break}case mo:this.checkRetryDate()}this.state===fo&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var t;super.onTickEnd(),null!=(t=this.media)&&t.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:i,media:n}=this;if(null===e||!n&&!this.primaryPrefetch&&(this.startFragRequested||!t.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const r=this.buffering?t.nextLoadLevel:t.loadLevel;if(null==i||!i[r])return;const s=i[r],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const t={type:this.targetBufferType()};return this.hls.trigger(ii.BUFFER_EOS,t),void(this.state=Eo)}if(!this.buffering)return;t.loadLevel!==r&&-1===t.manualLevel&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=t.nextLoadLevel=r;const l=s.details;if(!l||this.state===So||this.waitForLive(s))return this.level=r,this.state=So,void(this.startFragRequested=!1);const h=a.len,c=this.getMaxBufferLength(s.maxBitrate);if(h>=c)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=void 0);const u=this.backtrackFragment?this.backtrackFragment.start:a.end;let d=this.getNextFragment(u,l);if(this.couldBacktrack&&!this.fragPrevious&&d&&ki(d)&&this.fragmentTracker.getState(d)!==Ls){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=void 0);if(d&&this.isLoopLoading(d,u)){if(!d.gap){const t=this.audioOnly&&!this.altAudio?Ei:Ti,e=(t===Ti?this.videoBuffer:this.mediaBuffer)||this.media;e&&this.afterBufferFlushed(e,t)}d=this.getNextFragmentLoopLoading(d,l,a,vi,c)}d&&(this.exceedsMaxBuffer(a,c,d)||this.loadFragment(d,s,u))}loadFragment(t,e,i){const n=this.fragmentTracker.getState(t);n===Ss||n===_s?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)):super.loadFragment(t,e,i):this.clearTrackerIfNeeded(t)}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==Ku){var t;((null==(t=this.getLevelDetails())?void 0:t.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}getBufferOutput(){return this.mediaBuffer&&this.altAudio===Yu?this.mediaBuffer:this.media}checkFragmentChanged(){const t=this.fragPlaying;if(!this.checkFragPlaying())return!1;const e=this.fragPlaying;if(e){const i=e.level;this.hls.trigger(ii.FRAG_CHANGED,{frag:e,previousFrag:t}),(null==t?void 0:t.level)!==i&&this.hls.trigger(ii.LEVEL_SWITCHED,{level:i})}return!0}get backtrackFragment(){return this._backtrackFragment}set backtrackFragment(t){this._backtrackFragment=t}get couldBacktrack(){return this._couldBacktrack}set couldBacktrack(t){this._couldBacktrack=t}abortCurrentFrag(){this.backtrackFragment=void 0,super.abortCurrentFrag()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,this.targetBufferType())}targetBufferType(){return this.altAudio!==Yu||this.audioOnly?null:"video"}onMediaAttached(t,e){super.onMediaAttached(t,e);const i=e.media;lo(i,"playing",this.onMediaPlaying),lo(i,"seeked",this.onMediaSeeked)}onMediaDetaching(t,e){const{media:i}=this;i&&(ho(i,"playing",this.onMediaPlaying),ho(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,super.onMediaDetaching(t,e);!!e.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(ii.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=Ku,this.audioOnly=!1}onManifestParsed(t,e){let i=!1,n=!1;for(let t=0;t<e.levels.length;t++){const r=e.levels[t].audioCodec;r&&(i=i||-1!==r.indexOf("mp4a.40.2"),n=n||-1!==r.indexOf("mp4a.40.5"))}this.audioCodecSwitch=i&&n&&!function(){var t;const e=Gu();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!==fo)return;const n=e.levelInfo;(!n.details||n.details.live&&(this.levelLastLoaded!==n||n.details.expired)||this.waitForCdnTuneIn(n.details))&&(this.state=So)}onLevelLoaded(t,e){var i;const{levels:n,startFragRequested:r}=this,s=e.level,a=e.details,o=a.totalduration;if(!n)return void this.warn(`Levels were reset while loading level ${s}`);this.log(`Level ${s} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=e.levelInfo,h=this.fragCurrent;!h||this.state!==po&&this.state!==mo||h.level!==e.level&&h.loader&&this.abortCurrentFrag();let c=0;if(a.live||null!=(i=l.details)&&i.live){var u;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;c=this.alignPlaylists(a,l.details,null==(u=this.levelLastLoaded)?void 0:u.details)}if(l.details=a,this.levelLastLoaded=l,r||this.setStartPosition(a,c),this.hls.trigger(ii.LEVEL_UPDATED,{details:a,level:s}),this.state===So){if(this.waitForCdnTuneIn(a))return;this.state=fo}r&&a.live&&this.synchronizeToLiveEdge(a),this.initPTS.some((t,e)=>{if(e>=a.startCC)return!0;delete this.initPTS[e]}),this.tick()}synchronizeToLiveEdge(t){const{config:e,media:i}=this;if(!i)return;const n=this.hls.liveSyncPosition,r=this.playhead,s=t.fragmentStart,a=t.edge,o=r>=s-e.maxFragLookUpTolerance&&r<=a;if(null!==n&&i.duration>n&&(r<n||!o)){const s=void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;if((!o&&i.readyState<4||r<a-s)&&(this._hasEnoughToStart||(this.nextLoadPosition=n),i.readyState))if(this.warn(`Playback: ${r} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${n}`),"buffered"===this.config.liveSyncMode){var l;const t=js.bufferInfo(i,n,0);if(null==(l=t.buffered)||!l.length)return void(i.currentTime=n);if(t.start<=r)return void(i.currentTime=n);const{nextStart:e}=js.bufferedInfo(t.buffered,r,0);e&&(i.currentTime=e)}else i.currentTime=n}}_handleFragmentLoadProgress(t){var e;const i=t.frag,{part:n,payload:r}=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];if(!a)return void this.warn(`Level ${i.level} not found on progress`);const 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,h=o.PTSKnown||!o.live,c=null==(e=i.initSegment)?void 0:e.data,u=this._getAudioCodec(a),d=this.transmuxer=this.transmuxer||new Ql(this.hls,vi,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=n?n.index:-1,g=-1!==f,{decryptRange:p,byteRange:m}=Us(i,n,this.iframesOnly),v=new Hs(i.level,i.sn,i.stats.chunkCount,m?m.end-m.start:r.byteLength,f,g,i.duration,this.iframesOnly,p),y=this.initPTS[i.cc];d.push(r,c,u,l,i,n,o.totalduration,h,v,y)}onAudioTrackSwitching(t,e){const i=this.hls,n=this.altAudio!==Ku;if(es(e.url,i))this.altAudio=Hu;else{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();if(n)return this.altAudio=Ku,this.fragmentTracker.removeAllFragments(),i.once(ii.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(ii.AUDIO_TRACK_SWITCHED,e)}),void i.trigger(ii.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});i.trigger(ii.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const i=es(e.url,this.hls);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?Yu:Ku,this.tick()}onBufferCreated(t,e){const i=e.tracks;let n,r,s=!1;for(const t in i){const e=i[t];if("main"===e.id){if(r=t,n=e,"video"===t){const e=i[t];e&&(this.videoBuffer=e.buffer)}}else s=!0}s&&n?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=n.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:i,part:n}=e,r=i.type===vi;if(r){if(this.fragContextChanged(i))return this.warn(`Fragment ${i.sn}${n?" p: "+n.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===Ao&&(this.state=fo));let t=!1;if(ki(i)&&(t=!!i.gap&&!i.tagList.some(t=>"GAP"===t[0])),this.fragBufferedComplete(i,n),t){var s;i.stats.retry++;const t=null==(s=this.levels)?void 0:s[i.level];t&&t.fragmentError++}}const a=this.media;a&&(!this._hasEnoughToStart&&js.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,e){var i;if(e.fatal)this.state=To;else switch(e.details){case ei.FRAG_GAP:case ei.FRAG_PARSING_ERROR:case ei.FRAG_DECRYPT_ERROR:case ei.FRAG_LOAD_ERROR:case ei.FRAG_LOAD_TIMEOUT:case ei.KEY_LOAD_ERROR:case ei.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(vi,e);break;case ei.LEVEL_LOAD_ERROR:case ei.LEVEL_LOAD_TIMEOUT:case ei.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==So||(null==(i=e.context)?void 0:i.type)!==hi||(this.state=fo);break;case ei.BUFFER_APPEND_NO_PROGRESS:if("main"!==e.parent)return;e.frag&&(e.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${e.frag.sn} of level ${e.frag.level} as a gap after ${e.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(e.frag));break;case ei.BUFFER_ADD_CODEC_ERROR:case ei.BUFFER_APPEND_ERROR:if("main"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&this.resetLoadingState();break;case ei.BUFFER_FULL_ERROR:if("main"!==e.parent)return;if(this.reduceLengthAndFlushBuffer(e)){!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}break;case ei.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onFragLoadEmergencyAborted(){this.state=fo,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==Ei||!this.altAudio){const t=(e===Ti?this.videoBuffer:this.mediaBuffer)||this.media;t&&(this.afterBufferFlushed(t,e),this.tick())}}onLevelsUpdated(t,e){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),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 n=this.timelineOffset;n&&i&&(i+=n);const r=this.getLevelDetails(),s=js.getBuffered(t),a=s.length?s.start(0):0,o=a-i,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==r?void 0:r.partTarget)||0)))&&(this.log(`adjusting start position by ${o} to match buffer start`),i+=o,this.startPosition=i),e<i&&(this.log(`seek to target start position ${i} from current time ${e} buffer start ${a}`),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(t=>{const{hls:i}=this,n=null==t?void 0:t.frag;if(!n||this.fragContextChanged(n))return;e.fragmentError=0,this.state=fo,this.startFragRequested=!1,this.bitrateTest=!1;const r=n.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),i.trigger(ii.FRAG_LOADED,t),n.bitrateTest=!1}).catch(e=>{this.state!==uo&&this.state!==To&&(this.warn(e),this.resetFragmentLoading(t))})}_handleTransmuxComplete(t){const e=this.playlistType,{hls:i}=this,{remuxResult:n,chunkMeta:r}=t,s=this.getCurrentContext(r);if(!s)return void this.resetWhenMissingContext(r);const{frag:a,part:o,level:l}=s,{video:h,text:c,id3:u,initSegment:d}=n,{details:f}=l,g=this.altAudio?void 0:n.audio;if(this.fragContextChanged(a))this.fragmentTracker.removeFragment(a);else{if(this.state=yo,d){const t=d.tracks;if(t){const n=a.initSegment||a;if(this.unhandledEncryptionError(d,a))return;this._bufferInitSegment(l,t,n,r),i.trigger(ii.FRAG_PARSING_INIT_SEGMENT,{frag:n,id:e,tracks:t})}const n=d.initPTS,s=d.timescale,o=this.initPTS[a.cc];if(Qe(n)&&(!o||o.baseTime!==n||o.timescale!==s)){const t=d.trackId;this.initPTS[a.cc]={baseTime:n,timescale:s,trackId:t};const r=this.initPTS.slice(0);i.trigger(ii.INIT_PTS_FOUND,{timestampOffsets:r,frag:a,id:e,initPTS:n,timescale:s,trackId:t})}}if(h&&f){g&&"audiovideo"===h.type&&this.logMuxedErr(a);const t=f.fragments[a.sn-1-f.startSN],e=a.sn===f.startSN,i=!t||a.cc>t.cc;if(!1!==n.independent){const{startPTS:t,endPTS:n,startDTS:s,endDTS:l}=h;if(o)o.elementaryStreams[h.type]={startPTS:t,endPTS:n,startDTS:s,endDTS:l};else if(h.firstKeyFrame&&h.independent&&1===r.id&&!i&&(this.couldBacktrack=!0),h.dropped&&h.independent){const r=this.getMainFwdBufferInfo(),s=(r?r.end:this.getLoadPosition())+this.config.maxBufferHole,o=h.firstKeyFramePTS?h.firstKeyFramePTS:t;if(!e&&s<o-this.config.maxBufferHole&&!i)return void this.backtrack(a);i&&(a.gap=!0),a.setElementaryStreamInfo(h.type,a.start,n,a.start,l,!0)}else e&&t-(f.appliedTimelineOffset||0)>2&&(a.gap=!0);a.setElementaryStreamInfo(h.type,t,n,s,l),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(h,a,o,r,e||i)}else{if(!e&&!i)return void this.backtrack(a);a.gap=!0}}if(g){const{startPTS:t,endPTS:e,startDTS:i,endDTS:n}=g;o&&(o.elementaryStreams[Ei]={startPTS:t,endPTS:e,startDTS:i,endDTS:n}),a.setElementaryStreamInfo(Ei,t,e,i,n),this.bufferFragmentData(g,a,o,r)}if(f&&null!=u&&u.samples.length){const t={id:e,frag:a,details:f,samples:u.samples};i.trigger(ii.FRAG_PARSING_METADATA,t)}if(f&&c){const t={id:e,frag:a,details:f,samples:c.samples};i.trigger(ii.FRAG_PARSING_USERDATA,t)}}}logMuxedErr(t){this.warn(`${ki(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,e,i,n){if(this.state!==yo)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&(delete e.audio,e.audiovideo&&this.logMuxedErr(i));const{audio:r,video:s,audiovideo:a}=e;if(r){const i=t.audioCodec;let n=kr(r.codec,i);if("mp4a"===n&&(n="mp4a.40.5"),this.audioCodecSwitch){n&&(n=-1!==n.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const t=r.metadata;t&&"channelCount"in t&&1!==(t.channelCount||1)&&!function(){if(void 0===hr){const t=ar.match(/Firefox\/(\d+)/i);hr=t?parseInt(t[1]):0}return hr}()&&(n="mp4a.40.5")}n&&-1!==n.indexOf("mp4a.40.5")&&/Android/.test(ar)&&"audio/mpeg"!==r.container&&(n="mp4a.40.2",this.log(`Android: force audio codec to ${n}`)),i&&i!==n&&this.log(`Swapping manifest audio codec "${i}" for "${n}"`),r.levelCodec=n,r.id=vi,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${n||""}/${i||""}/${r.codec}]`),delete e.audiovideo}if(s){s.levelCodec=t.videoCodec,s.id=vi;const i=s.codec;if(4===(null==i?void 0:i.length))switch(i){case"hvc1":case"hev1":s.codec="hvc1.1.6.L120.90";break;case"av01":s.codec="av01.0.04M.08";break;case"avc1":s.codec="avc1.42e01e"}this.log(`Init video buffer, container:${s.container}, codecs[level/parsed]=[${t.videoCodec||""}/${i}]${s.codec!==i?" parsed-corrected="+s.codec:""}${s.supplemental?" supplemental="+s.supplemental:""}`),delete e.audiovideo}a&&(this.iframesOnly&&this.logMuxedErr(i),this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${t.codecs}/${a.codec}]`),delete e.video,delete e.audio);const o=Object.keys(e);if(o.length){if(this.hls.trigger(ii.BUFFER_CODECS,e),!this.hls)return;o.forEach(t=>{const r=e[t].initSegment;null!=r&&r.byteLength&&this.hls.trigger(ii.BUFFER_APPENDING,{type:t,data:r,frag:i,part:null,chunkMeta:n,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const t=this.getBufferOutput();return this.getFwdBufferInfo(t,vi)}get maxBufferLength(){const{levels:t,level:e}=this,i=null==t?void 0:t[e];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}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=fo}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){var t;if(this.fragPlaying)return this.fragPlaying;const e=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;return Qe(e)?this.getAppendedFrag(e):null}get currentProgramDateTime(){var t;const e=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;if(Qe(e)){const t=this.getLevelDetails(),i=this.currentFrag||(t?ss(null,t.fragments,e):null);if(i){const t=i.programDateTime;if(null!==t){const n=t+1e3*(e-i.start);return new Date(n)}}}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 Wu extends ju{constructor(...t){super(...t),this.currentOp=void 0,this.nextOp=void 0,this.cached=[],this.cachedSize=0,this.cacheFragmentData=!0,this.initDetails=void 0,this.onBufferedToEnd=()=>{const t=this.media;null!=t&&t.seeking&&(t.currentTime=t.currentTime)},this.onMediaSeeking=()=>{}}setInitPts(t){this.initPTS=t.slice()}loadMediaAt(t,e){if(!this.hls)return;const{seekOnAppend:i}=e,n=t+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=n,this.startPosition=t,this.state){case uo:case Eo:case To:this.state=fo}this.state===fo?(this.hls.resumeBuffering(),this.tick(),this.currentOp=[n,e]):this.nextOp=[n,e],this.hls.off(ii.BUFFERED_TO_END,this.onBufferedToEnd);const r=this.media;if(i&&r){this.seekTo(n)&&(this.currentOp=[n,e],this.nextOp=void 0,this.flushPipeline(n,!0))}}seekTo(t){const e=this.media;if(e){var i;const n=null==(i=this.getLevelDetails())?void 0:i.edge,r=void 0!==n?n:e.duration;t>=r&&(t=r-.01);if(js.bufferInfo(e,t,0).len>0&&this.getBufferedAt(t))return e.currentTime=t,!0}return!1}getBufferedAt(t){return this.fragmentTracker.getBufferedFrag(t,vi)}cacheSet(t,e){if(!this.hls)return;t.data=e;const i=this.cached;i.push(t),this.cachedSize+=e.buffer.byteLength;const n=this.hls.config.iframeCacheLimit;for(;this.cachedSize>n&&i.length>1;){const t=i.shift();if(!t.data){this.cached=i.filter(t=>!!t.data),this.cachedSize=i.reduce((t,{data:e})=>e?e.buffer.byteLength:0,0);break}this.cachedSize-=t.data.byteLength,t.data=void 0}}onHandlerDestroying(){this.cached.length=0,this.cachedSize=0,super.onHandlerDestroying()}_handleFragmentLoadProgress(t){const e=t.frag,{part:i,payload:n}=t;this.cacheFragmentData&&!i&&null!=n&&n.byteLength&&!e.data&&ki(e)&&this.cacheSet(e,new Uint8Array(n.slice(0))),super._handleFragmentLoadProgress(t)}loadFragment(t,e,i){const n=this.fragmentTracker.getState(t);n!==Ss&&n!==_s||!this.canReplayCached(t)?super.loadFragment(t,e,i):this.replayCachedFragment(t)}canReplayCached(t){var e;if(!this.cacheFragmentData||null==(e=t.data)||!e.byteLength)return!1;const i=t.decryptdata;return"identity"!==(null==i?void 0:i.keyFormat)||!!i.key}replayCachedFragment(t){const e=t.data.slice().buffer;this.log(`Buffering cached ${t.type} sn: ${t.sn} of level ${t.level} (${e.byteLength} bytes)`),this.fragCurrent=t,this.startFragRequested=!0;const i=t.stats=new oi;i.loading.start=i.loading.first=i.loading.end=self.performance.now(),i.loaded=i.total=e.byteLength,i.chunkCount=1,this.state=po;const n={frag:t,part:null,payload:e,networkDetails:null};this._handleFragmentLoadProgress(n),this.hls.trigger(ii.FRAG_LOADED,n),this._handleFragmentLoadComplete(n)}fragBufferedComplete(t,e){super.fragBufferedComplete(t,e);const{currentOp:i,nextOp:n}=this;this.currentOp=this.nextOp=void 0,this.state=uo,null!=i&&i[1].seekOnAppend&&(this.flushPipeline(i[0],!n),this.seekTo(i[0])||this.log(`Could not seek to ${i[0]} after fragment buffered (superseded or flushed) buffer: ${this.media?co(js.getBuffered(this.media)):"none"}`)),n&&this.loadMediaAt.apply(this,n)}flushPipeline(t,e){if(e){const e=this.media;if(e){const i=js.bufferInfo(e,t,0),n=i.len?i.nextStart:0;n&&(this.fragmentTracker.removeFragmentsInRange(n,1/0,vi),this.flushMainBuffer(n,1/0))}this.hls.once(ii.BUFFERED_TO_END,this.onBufferedToEnd)}this.hls.trigger(ii.BUFFER_EOS,{type:"video"})}get playhead(){return this.nextLoadPosition}startLoad(){if(!this.startFragRequested){const t=this.hls;t.nextLoadLevel=-1===t.startLevel?0:t.firstAutoLevel}}seekToStartPos(){}setStartPosition(){}alignPlaylists(t,e,i){const n=this.initDetails;return this.initDetails=null,super.alignPlaylists(t,e,i||n||void 0)}getMainFwdBufferInfo(){const t=this.playhead,e=this.getBufferedAt(t);if(e){const i=e.duration;return{len:i,start:t,end:t+i,bufferedIndex:-1}}return{len:0,start:t,end:t,bufferedIndex:-1}}_streamEnded(){const t=this.playhead,e=this.fragmentTracker.getBufferedFrag(t,vi);return!(null==e||!e.endList)}}class zu extends Wu{constructor(...t){super(...t),this._img=void 0,this.queued=void 0,this.cacheFragmentData=!1}get image(){return this._img}set image(t){var e;const i=null==(e=this._img)?void 0:e.src;i&&self.URL.revokeObjectURL(i),this._img=t}loadMediaAt(t){if(!this.hls)return;const e=t+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=e,this.startPosition=t,this.state){case uo:case Eo:case To:this.state=fo}if(this.state===fo){if(this.hls.resumeBuffering(),this.media||(this.media={}),this.tick(),this.state===fo){const e=this.getBufferedAt(t);e&&(this.fragCurrent=e,this.updateImage(e,null))}}else{const i=this.fragCurrent;(!i||t>=i.start&&t<i.end)&&(this.queued=[e])}}updateImage(t,e,i){const n=t.data;n||this.fragmentTracker.removeFragment(t);const r=this._img;if(r&&n){const s=self.performance.now();(e?e.stats:t.stats).buffering.start=t.stats.buffering.start=s,r.onload=()=>{if(!this.hls)return;const n=this.hls.levels[t.level];null!=n&&n.fragmentError&&(n.fragmentError=0,t.stats.retry=0);const r=self.performance.now(),s=e?e.stats:t.stats;s.buffering.end=t.stats.buffering.end=r,this.hls.trigger(ii.FRAG_BUFFERED,{frag:t,part:e,stats:s,id:t.type,chunkMeta:i})},r.onerror=()=>{this.handleError("Image decode error",t,e,i)};const a=r.src;a&&self.URL.revokeObjectURL(a);const o=new Blob([n],{type:"image/jpeg"});r.src=self.URL.createObjectURL(o)}else this.state=uo,this.processQueued()}processQueued(){const t=this.queued;this.queued=void 0,t&&this.loadMediaAt.apply(this,t)}handleError(t,e,i,n){if(!this.hls)return;const r=new Error(t);this.hls.trigger(ii.ERROR,{type:ti.MEDIA_ERROR,details:ei.FRAG_PARSING_ERROR,chunkMeta:n,frag:e,part:i,fatal:!1,error:r,err:r})}_bufferInitSegment(){}bufferFragmentData(t,e,i,n){super.bufferFragmentData(t,e,i,n,!0);const r=Bn(new Uint8Array(t.data1),["mdat"]);if(0===r.length)return void this.handleError("Could not find I-Frame mdat",e,i,n);const s=e;this.cacheSet(s,r[0]),this.updateImage(s,i,n)}fragBufferedComplete(t,e){this.fragmentTracker.fragBuffered(t,!0),super.fragBufferedComplete(t,e),this.processQueued()}checkFragPlaying(){var t;const e=null==(t=this.fragPrevious)?void 0:t.start;if(void 0!==e){const t=this.getAppendedFrag(e);if(t&&!_i(t,this.fragPlaying))return this.fragPlaying=t,!0}return!1}getMainFwdBufferInfo(){return{len:0,start:this.playhead,end:this.playhead,bufferedIndex:-1}}}const qu="Image I-Frame player does not accept HTMLMediaElements",Xu={seekOnAppend:!0};let Qu,Zu;const Ju=.025;let td=function(t){return t[t.Point=0]="Point",t[t.Range=1]="Range",t}({});function ed(t,e,i){return`${t.identifier}-${i+1}-${gu(e)}`}class id{constructor(t,e){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=e,this.dateRange=t,this.setDateRange(t)}setDateRange(t){this.dateRange=t,this.resumeOffset=t.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=t.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=t.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=t.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var t;this.appendInPlaceStarted=!1,null==(t=this.assetListLoader)||t.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(t){var e;if(t>0&&t>=this.assetList.length)return!0;const i=this.playoutLimit;if(t<=0||isNaN(i))return!1;if(0===i)return!0;return((null==(e=this.assetList[t])?void 0:e.startOffset)||0)>i}findAssetIndex(t){return this.assetList.indexOf(t)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const t=this.dateRange.startTime;if(this.snapOptions.out){const e=this.dateRange.tagAnchor;if(e)return nd(t,e)}return t}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(0===this.startTime||this.snapOptions.out)return!0;const t=this.dateRange.tagAnchor;if(t){const e=this.dateRange.startTime;return e-nd(e,t)<.1}return!1}get resumptionOffset(){const t=this.resumeOffset,e=Qe(t)?t:this.duration;return this.cumulativeDuration+e}get resumeTime(){const t=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const e=this.resumeAnchor;if(e)return nd(t,e)}return t}get appendInPlace(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<Ju))}set appendInPlace(t){this.appendInPlaceStarted?this.resetOnResume=!t:this.appendInPlaceDisabled=!t}get timelineStart(){return null!==this._timelineStart?this._timelineStart:this.startTime}set timelineStart(t){this._timelineStart=t}get duration(){const t=this.playoutLimit;let e;return e=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(t)&&t<e&&(e=t),e}set duration(t){this._duration=t}get cue(){return this.dateRange.cue}get timelineOccupancy(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?td.Range:td.Point}get supplementsPrimary(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}get contentMayVary(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||null!==this.assetListResponse}toString(){return`["${(t=this).identifier}" ${t.cue.pre?"<pre>":t.cue.post?"<post>":""}${t.timelineStart.toFixed(2)}-${t.resumeTime.toFixed(2)}]`;var t}}function nd(t,e){return t-e.start<e.duration/2&&!(Math.abs(t-(e.start+e.duration))<Ju)?e.start:e.start+e.duration}function rd(t,e,i){const n=new self.URL(t,i);return"data:"!==n.protocol&&Nr(n,"_HLS_primary_id",e),n}function sd(t,e){for(;null!=(i=t.assetList[++e])&&i.error;)var i;return e}function ad(t){const e=t.timelineStart,i=t.duration||0;return`["${t.identifier}" ${e.toFixed(2)}-${(e+i).toFixed(2)}]`}class od{constructor(t,e,i,n){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(ii.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new t(e);this.interstitial=i,this.assetItem=n;const s=()=>{this.hasDetails=!0};r.once(ii.LEVEL_LOADED,s),r.once(ii.AUDIO_TRACK_LOADED,s),r.once(ii.SUBTITLE_TRACK_LOADED,s),r.on(ii.MEDIA_ATTACHING,(t,{media:e})=>{this.removeMediaListeners(),this.mediaAttached=e;this.interstitial.playoutLimit&&(e.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(ii.BUFFER_APPENDED,()=>{const t=this.bufferedEnd;this.reachedPlayout(t)&&(this._bufferedEosTime=t,r.trigger(ii.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const t=this.hls;if(t)if(t.url)t.levels.length&&!t.started&&t.startLoad(-1,!0);else{let e=this.assetItem.uri;try{e=rd(e,t.config.primarySessionId||"").href}catch(t){}t.loadSource(e)}}bufferedInPlaceToEnd(t,e){var i;if(!this.appendInPlace)return!1;if(null!=(i=this.hls)&&i.bufferedToEnd)return!0;if(!t)return!1;const n=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset+(e||0),s=js.bufferInfo(t,r,.02);return this.getAssetTime(s.end)>=n-.02}reachedPlayout(t){const e=this.interstitial.playoutLimit;return this.startOffset+t>=e}get destroyed(){var t;return!(null!=(t=this.hls)&&t.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var t;return(null==(t=this.hls)?void 0:t.media)||null}get bufferedEnd(){const t=this.media||this.mediaAttached;if(!t)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const e=js.bufferInfo(t,t.currentTime,.001);return this.getAssetTime(e.end)}get currentTime(){const t=this.media||this.mediaAttached;return t?this.getAssetTime(t.currentTime):this._currentTime||0}get duration(){const t=this.assetItem.duration;if(!t)return 0;const e=this.interstitial.playoutLimit;if(e){const i=e-this.startOffset;if(i>0&&i<t)return i}return t}get remaining(){const t=this.duration;return t?Math.max(0,t-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var t;return(null==(t=this.hls)?void 0:t.config.timelineOffset)||0}set timelineOffset(t){const e=this.timelineOffset;if(t!==e){const i=t-e;if(Math.abs(i)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=t}}}getAssetTime(t){const e=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,t-e),i)}removeMediaListeners(){const t=this.mediaAttached;t&&(this._currentTime=t.currentTime,this.bufferSnapShot(),t.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){var t;this.mediaAttached&&(null!=(t=this.hls)&&t.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd))}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(t){var e;this.loadSource(),null==(e=this.hls)||e.attachMedia(t)}detachMedia(){var t;this.removeMediaListeners(),this.mediaAttached=null,null==(t=this.hls)||t.detachMedia()}resumeBuffering(){var t;null==(t=this.hls)||t.resumeBuffering()}pauseBuffering(){var t;null==(t=this.hls)||t.pauseBuffering()}transferMedia(){var t;return this.bufferSnapShot(),(null==(t=this.hls)?void 0:t.transferMedia())||null}resetDetails(){const t=this.hls;if(t&&this.hasDetails){t.stopLoad();const e=t=>delete t.details;t.levels.forEach(e),t.allAudioTracks.forEach(e),t.allSubtitleTracks.forEach(e),this.hasDetails=!1}}on(t,e,i){var n;null==(n=this.hls)||n.on(t,e)}once(t,e,i){var n;null==(n=this.hls)||n.once(t,e)}off(t,e,i){var n;null==(n=this.hls)||n.off(t,e)}toString(){var t;return`HlsAssetPlayer: ${ad(this.assetItem)} ${null==(t=this.hls)?void 0:t.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const ld=.033;class hd extends ji{constructor(t,e){super("interstitials-sched",e),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=t}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(t=>t.reset()),this.events=this.items=null}resetErrorsInRange(t,e){return this.events?this.events.reduce((i,n)=>t<=n.startOffset&&e>n.startOffset?(delete n.error,i+1):i,0):0}get duration(){const t=this.items;return t?t[t.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(t){return t&&this.eventMap[t]||null}hasEvent(t){return t in this.eventMap}findItemIndex(t,e){if(t.event)return this.findEventIndex(t.event.identifier);let i=-1;t.nextEvent?i=this.findEventIndex(t.nextEvent.identifier)-1:t.previousEvent&&(i=this.findEventIndex(t.previousEvent.identifier)+1);const n=this.items;if(n)for(n[i]||(void 0===e&&(e=t.start),i=this.findItemIndexAtTime(e));i>=0&&null!=(r=n[i])&&r.event;){var r;i--}return i}findItemIndexAtTime(t,e){const i=this.items;if(i)for(let n=0;n<i.length;n++){let r=i[n];e&&"primary"!==e&&(r=r[e]);const s=r.start,a=i[n].event,o=null!=a&&a.cue.pre?a.duration:r.end;if(t===s||t>s&&t<o)return n}return-1}findJumpRestrictedIndex(t,e){const i=this.items;if(i)for(let n=t;n<=e&&i[n];n++){const t=i[n].event;if(null!=t&&t.restrictions.jump&&!t.appendInPlace)return n}return-1}findEventIndex(t){const e=this.items;if(e)for(let n=e.length;n--;){var i;if((null==(i=e[n].event)?void 0:i.identifier)===t)return n}return-1}findAssetIndex(t,e){const i=t.assetList,n=i.length;if(n>1)for(let t=0;t<n;t++){const r=i[t];if(!r.error){const i=r.timelineStart;if(e===i||e>i&&(e<i+(r.duration||0)||t===n-1))return t}}return 0}get assetIdAtEnd(){var t;const e=null==(t=this.items)||null==(t=t[this.length-1])?void 0:t.event;if(e){const t=e.assetList,i=t[t.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(t,e,i=0){const n=t.main.details,{dateRanges:r}=n,s=this.events,a=this.parseDateRanges(r,{url:n.url},e),o=Object.keys(r),l=s?s.filter(t=>-1===o.indexOf(t.identifier)):[];a.length&&a.sort((t,e)=>{const i=t.cue.pre,n=t.cue.post,r=e.cue.pre,s=e.cue.post;if(i&&!r)return-1;if(r&&!i)return 1;if(n&&!s)return 1;if(s&&!n)return-1;if(!(i||r||n||s)){const i=t.startTime,n=e.startTime;if(i!==n)return i-n}return t.dateRange.tagOrder-e.dateRange.tagOrder}),this.events=a,l.forEach(t=>{this.removeEvent(t)}),this.updateSchedule(t,l,i)}updateSchedule(t,e=[],i=0,n=!1){const r=this.events||[];if(r.length||e.length||this.length<2){const s=this.items,a=this.parseSchedule(r,t,i);(n||e.length||(null==s?void 0:s.length)!==a.length||a.some((t,e)=>Math.abs(t.playout.start-s[e].playout.start)>.005||Math.abs(t.playout.end-s[e].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(e,s))}}parseDateRanges(t,e,i){const n=[],r=Object.keys(t);for(let s=0;s<r.length;s++){const a=r[s],o=t[a];if(o.isInterstitial){let t=this.eventMap[a];t?t.setDateRange(o):(t=new id(o,e),this.eventMap[a]=t,!1===i&&(t.appendInPlace=i)),n.push(t)}}return n}parseSchedule(t,e,i=0){const n=[],r=e.main.details,s=r.live?1/0:r.edge;let a=0;if((t=t.filter(t=>!(t.error||t.cue.once&&t.hasPlayed))).length){this.resolveOffsets(t,e);let l=0,h=0;if(t.forEach((e,o)=>{const c=e.cue.pre,u=e.cue.post,d=t[o-1]||null,f=e.appendInPlace,g=u?s:e.startOffset,p=e.duration,m=e.timelineOccupancy===td.Range?p:0,v=c&&r.live?i+(e.resumeOffset||0):0,y=v||e.resumptionOffset,A=(null==d?void 0:d.startTime)===g,E=g+e.cumulativeDuration;let T=f?E+p:g+y;if(c||!u&&g<=0){const t=h;h+=m,e.timelineStart=E;const i=a;a+=p,n.push({event:e,start:E,end:T,playout:{start:i,end:a},integrated:{start:t,end:h}})}else{if(!(g<=s))return;{if(!A){const i=g-l;if(i>ld){const r=l,s=h;h+=i;const c=a;a+=i;const u={previousEvent:t[o-1]||null,nextEvent:e,start:r,end:r+i,playout:{start:c,end:a},integrated:{start:s,end:h}};n.push(u)}else i>0&&d&&(d.cumulativeDuration+=i,n[n.length-1].end=g)}u&&(T=E),e.timelineStart=E;const i=h;h+=m;const r=a;a+=p,n.push({event:e,start:E,end:T,playout:{start:r,end:a},integrated:{start:i,end:h}})}}const b=v||e.resumeTime;l=u||b>s?s:!c&&T&&e.appendInPlaceStarted&&b-T>ld?T:b}),l<s){var o;const t=l,e=h,i=s-l;h+=i;const r=a;a+=i,n.push({previousEvent:(null==(o=n[n.length-1])?void 0:o.event)||null,nextEvent:null,start:l,end:t+i,playout:{start:r,end:a},integrated:{start:e,end:h}})}this.setDurations(s,a,h)}else{const t=0;n.push({previousEvent:null,nextEvent:null,start:t,end:s,playout:{start:t,end:s},integrated:{start:t,end:s}}),this.setDurations(s,s,s)}return n}setDurations(t,e,i){this.durations={primary:t,playout:e,integrated:i}}resolveOffsets(t,e){const i=e.main.details,n=i.live?1/0:i.edge;let r=0,s=-1;t.forEach((a,o)=>{const l=a.cue.pre,h=a.cue.post,c=l?0:h?n:a.startTime;this.updateAssetDurations(a);if(s===c?a.cumulativeDuration=r:(r=0,s=c),!h&&a.snapOptions.in&&(a.resumeAnchor=ss(null,i.fragments,a.startOffset+a.resumptionOffset,0,0)||void 0),a.appendInPlace&&!a.appendInPlaceStarted){this.primaryCanResumeInPlaceAt(a,e)||(a.appendInPlace=!1)}if(!a.appendInPlace&&o+1<t.length){t[o+1].startTime-t[o].resumeTime<ld&&(t[o+1].appendInPlace=!1,t[o+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${a}`))}const u=Qe(a.resumeOffset)?a.resumeOffset:a.duration;r+=u})}primaryCanResumeInPlaceAt(t,e){const i=t.resumeTime,n=t.startTime+t.resumptionOffset;if(Math.abs(i-n)>Ju)return this.log(`"${t.identifier}" resumption ${i} not aligned with estimated timeline end ${n}`),!1;return!Object.keys(e).some(n=>{const r=e[n].details,s=r.edge;if(i>=s)return this.log(`"${t.identifier}" resumption ${i} past ${n} playlist end ${s}`),!1;const a=ss(null,r.fragments,i);if(!a)return this.log(`"${t.identifier}" resumption ${i} does not align with any fragments in ${n} playlist (${r.fragStart}-${r.fragmentEnd})`),!0;const o="audio"===n?.175:0;return!(Math.abs(a.start-i)<Ju+o||Math.abs(a.end-i)<Ju+o)&&(this.log(`"${t.identifier}" resumption ${i} not aligned with ${n} fragment bounds (${a.start}-${a.end} sn: ${a.sn} cc: ${a.cc})`),!0)})}updateAssetDurations(t){if(!t.assetListLoaded)return;const e=t.timelineStart;let i=0,n=!1,r=!1;for(let s=0;s<t.assetList.length;s++){const a=t.assetList[s],o=e+i;a.startOffset=i,a.timelineStart=o,n||(n=null===a.duration),r||(r=!!a.error);i+=a.error?0:a.duration||0}t.duration=n&&!r?Math.max(i,t.duration):i}removeEvent(t){t.reset(),delete this.eventMap[t.identifier]}}function cd(t){return`[${t.event?'"'+t.event.identifier+'"':"primary"}: ${t.start.toFixed(2)}-${t.end.toFixed(2)}]`}class ud{constructor(t){this.hls=void 0,this.hls=t}destroy(){this.hls=null}loadAssetList(t,e){const i=t.assetListUrl;let n;try{n=rd(i,this.hls.sessionId,t.baseUrl)}catch(e){const n=this.assignAssetListError(t,ei.ASSET_LIST_LOAD_ERROR,e,i);return void this.hls.trigger(ii.ERROR,n)}e&&"data:"!==n.protocol&&Nr(n,"_HLS_start_offset",""+e);const r=this.hls.config,s=new(0,r.loader)(r),a={type:mi,responseType:"json",url:n.href},o=r.interstitialAssetListLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(e,i,n,r)=>{const s=e.data,a=null==s?void 0:s.ASSETS;if(!Array.isArray(a)){const e=this.assignAssetListError(t,ei.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),n.url,i,r);return void this.hls.trigger(ii.ERROR,e)}t.assetListResponse=s,this.hls.trigger(ii.ASSET_LIST_LOADED,{event:t,assetListResponse:s,networkDetails:r})},onError:(e,i,n,r)=>{const s=this.assignAssetListError(t,ei.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${e.code} ${e.text} (${i.url})`),i.url,r,n);this.hls.trigger(ii.ERROR,s)},onTimeout:(e,i,n)=>{const r=this.assignAssetListError(t,ei.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${i.url})`),i.url,e,n);this.hls.trigger(ii.ERROR,r)}};return s.load(a,l,h),this.hls.trigger(ii.ASSET_LIST_LOADING,{event:t}),s}assignAssetListError(t,e,i,n,r,s){return t.error=i,{type:ti.NETWORK_ERROR,details:e,fatal:!1,interstitial:t,url:n,error:i,networkDetails:s,stats:r}}}function dd(t){var e;null==t||null==(e=t.play())||e.catch(()=>{})}function fd(t,e){return`[${t}] Advancing timeline position to ${e}`}class gd{constructor(t){this.buffered=void 0;const e=(e,i,n)=>{if((i>>>=0)>n-1)throw new DOMException(`Failed to execute '${e}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${n})`);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)}}}const pd={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},md=t=>String.fromCharCode(pd[t]||t),vd=15,yd=42,Ad={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Ed={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Td={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},bd={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Sd=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class kd{constructor(){this.time=null,this.verboseLevel=0}log(t,e){if(this.verboseLevel>=t){const i="function"==typeof e?e():e;Zi.log(`${this.time} [${t}] ${i}`)}}}const _d=function(t){const e=[];for(let i=0;i<t.length;i++)e.push(t[i].toString(16));return e},Ld=Object.freeze({foreground:"white",underline:!1,italics:!1,background:"black",flash:!1});class Rd{constructor(){this.styles=Ld}get foreground(){return this.styles.foreground}set foreground(t){const e=this.styles;this.styles={foreground:t,underline:e.underline,italics:e.italics,background:e.background,flash:e.flash}}get underline(){return this.styles.underline}set underline(t){const e=this.styles;this.styles={foreground:e.foreground,underline:t,italics:e.italics,background:e.background,flash:e.flash}}get italics(){return this.styles.italics}set italics(t){const e=this.styles;this.styles={foreground:e.foreground,underline:e.underline,italics:t,background:e.background,flash:e.flash}}get background(){return this.styles.background}set background(t){const e=this.styles;this.styles={foreground:e.foreground,underline:e.underline,italics:e.italics,background:t,flash:e.flash}}get flash(){return this.styles.flash}set flash(t){const e=this.styles;this.styles={foreground:e.foreground,underline:e.underline,italics:e.italics,background:e.background,flash:t}}reset(){this.styles=Ld}setStyles(t){const e=this.styles,i=Object.prototype.hasOwnProperty;this.styles={foreground:i.call(t,"foreground")?t.foreground:e.foreground,underline:i.call(t,"underline")?t.underline:e.underline,italics:i.call(t,"italics")?t.italics:e.italics,background:i.call(t,"background")?t.background:e.background,flash:i.call(t,"flash")?t.flash:e.flash}}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class Id{constructor(){this.uchar=" ",this.penState=new Rd}reset(){this.uchar=" ",this.penState.reset()}setChar(t,e){this.uchar=t,this.penState.styles=e.styles}setPenState(t){this.penState.styles=t.styles}copy(t){this.uchar=t.uchar,this.penState.styles=t.penState.styles}}class Cd{constructor(t){this.chars=[],this.pos=0,this.currPenState=new Rd,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<yd;t++)this.chars.push(new Id);this.logger=t}equals(t){const e=this.chars,i=t.chars;for(let t=0;t<yd;t++){const n=e[t],r=i[t];if(n.uchar!==r.uchar)return!1;const s=n.penState.styles,a=r.penState.styles;if(s!==a&&(s.foreground!==a.foreground||s.underline!==a.underline||s.italics!==a.italics||s.background!==a.background||s.flash!==a.flash))return!1}return!0}copy(t){for(let e=0;e<yd;e++)this.chars[e].copy(t.chars[e])}isEmpty(){const t=this.chars;for(let e=0;e<yd;e++){const i=t[e];if(" "!==i.uchar)return!1;const n=i.penState.styles;if(n!==Ld&&("white"!==n.foreground||n.underline||n.italics||"black"!==n.background||n.flash))return!1}return!0}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>=yd&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=41)}moveCursor(t){const e=Math.min(this.pos+t,yd);if(t>1)for(let t=this.pos+1;t<e;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=md(t);this.pos>=yd?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<yd;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<yd;i++){const n=this.chars[i].uchar;" "!==n&&(e=!1),t.push(n)}return e?"":t.join("")}setPenStyles(t){this.currPenState.setStyles(t);this.chars[this.pos].setPenState(this.currPenState)}}class Pd{constructor(t){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let e=0;e<vd;e++)this.rows.push(new Cd(t));this.logger=t}reset(){for(let t=0;t<vd;t++)this.rows[t].clear();this.currRow=14}equals(t){let e=!0;for(let i=0;i<vd;i++)if(!this.rows[i].equals(t.rows[i])){e=!1;break}return e}copy(t){for(let e=0;e<vd;e++){const i=this.rows[e].chars,n=t.rows[e].chars;for(let t=0;t<yd;t++){const e=i[t],r=n[t];e.uchar=r.uchar,e.penState.styles=r.penState.styles}}}isEmpty(){let t=!0;for(let e=0;e<vd;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 = "+Wr(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<vd;t++)this.rows[t].clear();const t=this.currRow+1-this.nrRollUpRows,i=this.lastOutputScreen;if(i){const n=i.rows[t].cueStartTime,r=this.logger.time;if(null!==n&&null!==r&&n<r)for(let n=0;n<this.nrRollUpRows;n++)this.rows[e-this.nrRollUpRows+n+1].copy(i.rows[t+n])}}this.currRow=e;const i=this.rows[this.currRow];if(null!==t.indent){const e=t.indent,n=Math.max(e-1,0);i.setCursor(t.indent),t.color=i.chars[n].penState.foreground}const n={foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:!1};this.setPen(n)}setBkgData(t){this.logger.log(2,()=>"bkgData = "+Wr(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="",n=-1;for(let i=0;i<vd;i++){const r=this.rows[i].getTextString();r&&(n=i+1,t?e.push("Row "+n+": '"+r+"'"):e.push(r.trim()))}return e.length>0&&(i=t?"["+e.join(" | ")+"]":e.join("\n")),i}getTextAndFormat(){return this.rows}}class Dd{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 Pd(i),this.nonDisplayedMemory=new Pd(i),this.lastOutputScreen=new Pd(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,n=["white","green","blue","cyan","red","yellow","magenta"];e.foreground=n[i]}this.logger.log(2,"MIDROW: "+Wr(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 wd{constructor(t,e,i){this.channels=[null,null,null],this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new kd,this.field=t,this.outputFilters=[null,e,i]}getHandler(t){return this.outputFilters[t]}setHandler(t,e){var i;this.outputFilters[t]=e,null==(i=this.channels[t])||i.setHandler(e)}getChannel(t){let e=this.channels[t];return e||(e=this.channels[t]=new Dd(this.field+t-1,this.outputFilters[t],this.logger)),e}addData(t,e){this.logger.time=t;for(let t=0;t<e.length;t+=2){const i=127&e[t],n=127&e[t+1];let r=!1,s=null;if(0===i&&0===n)continue;this.logger.log(3,()=>"["+_d([e[t],e[t+1]])+"] -> ("+_d([i,n])+")");const a=this.cmdHistory;if(i>=16&&i<=31){if(xd(i,n,a)){Od(null,null,a),this.logger.log(3,()=>"Repeated command ("+_d([i,n])+") is dropped");continue}Od(i,n,this.cmdHistory),r=this.parseCmd(i,n),r||(r=this.parseMidrow(i,n)),r||(r=this.parsePAC(i,n)),r||(r=this.parseBackgroundAttributes(i,n))}else Od(null,null,a);if(!r&&(s=this.parseChars(i,n),s)){const t=this.currentChannel;if(t&&t>0){this.getChannel(t).insertChars(s)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}r||s||this.logger.log(2,()=>"Couldn't parse cleaned data "+_d([i,n])+" orig: "+_d([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,n=this.getChannel(i);return 20===t||21===t||28===t||29===t?32===e?n.ccRCL():33===e?n.ccBS():34===e?n.ccAOF():35===e?n.ccAON():36===e?n.ccDER():37===e?n.ccRU(2):38===e?n.ccRU(3):39===e?n.ccRU(4):40===e?n.ccFON():41===e?n.ccRDC():42===e?n.ccTR():43===e?n.ccRTD():44===e?n.ccEDM():45===e?n.ccCR():46===e?n.ccENM():47===e&&n.ccEOC():n.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 n=this.channels[i];return!!n&&(n.ccMIDROW(e),this.logger.log(3,()=>"MIDROW ("+_d([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 n=t<=23?1:2;i=e>=64&&e<=95?1===n?Ad[t]:Td[t]:1===n?Ed[t]:bd[t];return this.getChannel(n).setPAC(this.interpretPAC(i,e)),this.currentChannel=n,!0}interpretPAC(t,e){let i;const n={color:null,italics:!1,indent:null,underline:!1,row:t};return i=e>95?e-96:e-64,n.underline=!(1&~i),i<=13?n.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(n.italics=!0,n.color="white"):n.indent=4*Math.floor((i-16)/2),n}parseChars(t,e){let i,n=null,r=null;if(t>=25?(i=2,r=t-8):(i=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 '"+md(t)+"' in channel "+i),n=[t]}else t>=32&&t<=127&&(n=0===e?[t]:[t,e]);return n&&this.logger.log(3,()=>"Char codes = "+_d(n).join(",")),n}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 n={};16===t||24===t?(i=Math.floor((e-32)/2),n.background=Sd[i],e%2==1&&(n.background=n.background+"_semi")):45===e?n.background="transparent":(n.foreground="black",47===e&&(n.underline=!0));const r=t<=23?1:2;return this.getChannel(r).setBkgData(n),!0}reset(){for(let t=0;t<Object.keys(this.channels).length;t++){const e=this.channels[t];e&&e.reset()}Od(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 Od(t,e,i){i.a=t,i.b=e}function xd(t,e,i){return i.a===t&&i.b===e}class Md{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}}function Nd(t,e,i,n){return Math.min(e,n)-Math.max(t,i)}const Fd=/\s/,Bd={newCue(t,e,i,n){const r=[];let s,a,o,l,h;const c=self.VTTCue||self.TextTrackCue;for(let d=0;d<n.rows.length;d++)if(s=n.rows[d],o=!0,l=0,h="",!s.isEmpty()){var u;for(let t=0;t<s.chars.length;t++)Fd.test(s.chars[t].uchar)&&o?l++:(h+=s.chars[t].uchar,o=!1);s.cueStartTime=e,e===i&&(i+=1e-4),l>=16?l--:l++;const n=du(h.trim()),f=vu(e,i,n);null!=t&&null!=(u=t.cues)&&u.getCueById(f)||(a=new c(e,i,n),a.id=f,a.line=d+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=>wu(t,e))),r}};class $d{constructor(){this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.stats=new oi}destroy(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}load(t,e,i){const n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=i,this.loadInternal()}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.getNetworkDetails())}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry;if(Gi(t,this.stats.retry,!0))this.retry(t);else{var e;Zi.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.getNetworkDetails()))}}retry(t){const{context:e,stats:i}=this;this.retryDelay=$i(t,i.retry),i.retry++,Zi.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.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(()=>this.loadInternal(),this.retryDelay)}}const Ud=/(\d+)-(\d+)\/(\d+)/;class Gd extends $d{constructor(t){super(),this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=t.fetchSetup||Vd}destroy(){this.request=null,super.destroy(),this.response=null,this.controller=null,this.fetchSetup=null}abortInternal(){self.clearTimeout(this.retryTimeout),this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}getNetworkDetails(){return this.response}resetInternalLoader(){this.response=null}loadInternal(){const{config:t,context:e,stats:i}=this;if(!t||!e)return;i.loading.first=0,i.loaded=0,i.aborted=!1,this.controller=new self.AbortController;const n=function(t,e){const i={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(Di({},t.headers))};t.rangeEnd&&i.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1));return i}(e,this.controller.signal),r="arraybuffer"===e.responseType,s=r?"byteLength":"length",{maxTimeToFirstByteMs:a,maxLoadTimeMs:o}=t.loadPolicy;this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=a&&Qe(a)?a:o,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},t.timeout);(Wl(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(n=>{var s;this.response=n;const a=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=o,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},o-(a-i.loading.start)),!n.ok){const{status:t,statusText:e}=n;throw new Kd(e||"fetch, bad network response",t,n)}i.loading.first=a,i.total=function(t){const e=t.get("Content-Range");if(e){const t=function(t){const e=Ud.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}(e);if(Qe(t))return t}const i=t.get("Content-Length");if(i)return parseInt(i)}(n.headers)||i.total;const l=null==(s=this.callbacks)?void 0:s.onProgress;return l&&Qe(t.highWaterMark)?this.loadProgressively(n,i,e,t.highWaterMark,l):r?n.arrayBuffer():"json"===e.responseType?n.json():n.text()}).then(n=>{var r,a;const o=this.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const l=n[s];l&&(i.loaded=i.total=l);const h={url:o.url,data:n,code:o.status},c=null==(r=this.callbacks)?void 0:r.onProgress;c&&!Qe(t.highWaterMark)&&c(i,e,n,o),null==(a=this.callbacks)||a.onSuccess(h,i,e,o)}).catch(n=>{if(self.clearTimeout(this.requestTimeout),i.aborted)return;const r=n&&n.code||0,s=n?n.message:null,a=t.loadPolicy.errorRetry;var o;Gi(a,i.retry,!1,{url:e.url,data:void 0,code:r})?this.retry(a):(Zi.error(`${r} while loading ${e.url}`),null==(o=this.callbacks)||o.onError({code:r,text:s},e,n?n.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,i,n=0,r){const s=new Ro,a=t.body.getReader(),o=()=>a.read().then(a=>{if(a.done)return s.dataLength&&r(e,i,s.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));const l=a.value,h=l.length;return e.loaded+=h,h<n||s.dataLength?(s.push(l),s.dataLength>=n&&r(e,i,s.flush().buffer,t)):r(e,i,l.buffer,t),o()}).catch(()=>Promise.reject());return o()}}function Vd(t,e){return new self.Request(t.url,e)}class Kd extends Error{constructor(t,e,i){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=i}}const Hd=/^age:\s*[\d.]+\s*$/im;class Yd extends $d{constructor(t){super(),this.xhrSetup=void 0,this.loader=null,this.xhrSetup=t.xhrSetup||null}destroy(){super.destroy(),this.loader=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()))}getNetworkDetails(){return this.loader}resetInternalLoader(){this.loader=null}loadInternal(){const{config:t,context:e}=this;if(!t||!e)return;const i=this.loader=new self.XMLHttpRequest,n=this.stats;n.loading.first=0,n.loaded=0,n.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(this.loader===i&&!this.stats.aborted)return r.call(this,i,e.url,e)}).catch(t=>{if(this.loader===i&&!this.stats.aborted)return i.open("GET",e.url,!0),r.call(this,i,e.url,e)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,e,t)}).catch(t=>{var r;null==(r=this.callbacks)||r.onError({code:i.status,text:t.message},e,i,n)}):this.openAndSendXhr(i,e,t)}openAndSendXhr(t,e,i){t.readyState||t.open("GET",e.url,!0);const n=e.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:s}=i.loadPolicy;if(n)for(const e in n)t.setRequestHeader(e,n[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=r&&Qe(r)?r: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 n=e.readyState,r=this.config;if(!i.aborted&&n>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.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-(i.loading.first-i.loading.start)))),4===n)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;const n=e.status,l="text"===e.responseType?e.responseText:null;if(n>=200&&n<300){const r=null!=l?l:e.response;if(null!=r){var s,a;i.loading.end=Math.max(self.performance.now(),i.loading.first);const o="arraybuffer"===e.responseType?r.byteLength:r.length;i.loaded=i.total=o,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first);const l=null==(s=this.callbacks)?void 0:s.onProgress;l&&l(i,t,r,e);const h={url:e.responseURL,data:r,code:n};return t.rangeEnd&&o!==t.rangeEnd-t.rangeStart&&Zi.warn(`Payload length ${o} does not match requested Range: bytes=${t.rangeStart}-${t.rangeEnd-1}`),void(null==(a=this.callbacks)||a.onSuccess(h,i,t,e))}}const h=r.loadPolicy.errorRetry;var o;if(Gi(h,i.retry,!1,{url:t.url,data:void 0,code:n}))this.retry(h);else Zi.error(`${n} while loading ${t.url}`),null==(o=this.callbacks)||o.onError({code:n,text:e.statusText},t,e,i)}}loadprogress(t){const e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)}getCacheAge(){let t=null;if(this.loader&&Hd.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 jd=Oi(Oi({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,loopBackBufferFlush:void 0,startOnSegmentBoundary:!1,nextAudioTrackBufferFlushForwardOffset:.25,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,skipBufferHolePadding:.1,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveMaxUnchangedPlaylistRefresh: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,appendTimeout:1/0,ignorePlaylistParsingErrors:!1,loader:Yd,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,handleMpegTsVideoIntegrityErrors:"process",abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,abrSwitchInterval:0,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:ba,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2097152,useMediaCapabilities:!0,preserveManualLevelOnError:!1,errorPenaltyExpireMs: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}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3,streamController:ju,abrController:class extends ji{constructor(t){super("abr",t.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var e;const{fragCurrent:i,partCurrent:n,hls:r}=this;if(!r)return;const{autoLevelEnabled:s,media:a}=r;if(!i||!a)return;const o=performance.now(),l=n?n.stats:i.stats,h=n?n.duration:i.duration,c=o-l.loading.start,u=r.minAutoLevel,d=i.level,f=this._nextAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||d<=u)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!s)return;const g=f>-1&&f!==d,p=!!t||g;if(!p&&(a.paused||!a.playbackRate||!a.readyState))return;const m=r.mainForwardBufferInfo;if(!p&&null===m)return;const v=this.bwEstimator.getEstimateTTFB(),y=Math.abs(a.playbackRate);if(c<=Math.max(v,h/(2*y)*1e3))return;const A=m?m.len/y:0,E=l.loading.first?l.loading.first-l.loading.start:-1,T=l.loaded&&E>-1,b=this.getBwEstimate(),S=r.levels,k=S[d],_=Math.max(l.loaded,Math.round(h*(i.bitrate||k.averageBitrate)/8));let L=T?c-E:c;L<1&&T&&(L=Math.min(c,8*l.loaded/b));const R=T?1e3*l.loaded/L:0,I=v/1e3,C=R?(_-l.loaded)/R:8*_/b+I;if(C<=A)return;const P=R?8*R:b,D=!0===(null==(e=(null==t?void 0:t.details)||r.latestLevelDetails)?void 0:e.live),w=r.config.abrBandWidthUpFactor;let O,x=Number.POSITIVE_INFINITY;for(O=d-1;O>u;O--){const t=S[O].maxBitrate,e=!S[O].details||D;if(x=this.getTimeToLoadFrag(I,P,h*t,e),x<Math.min(A,h+I))break}if(x>=C)return;if(x>10*h)return;T?this.bwEstimator.sample(c-Math.min(v,E),l.loaded):this.bwEstimator.sampleTTFB(c);const M=S[O].maxBitrate;this.getBwEstimate()*w>M&&(this.firstAutoFloor=Math.min(O,r.firstLevel),this.resetEstimator(M));const N=this.findBestLevel(M,u,O,0,A,1,1);N>-1&&(O=N),this.warn(`Fragment ${i.sn}${n?" part "+n.index:""} of level ${d} is loading too slowly;\n Fragment duration: ${i.duration.toFixed(3)}\n Time to underbuffer: ${A.toFixed(3)} s\n Estimated load time for current fragment: ${C.toFixed(3)} s\n Estimated load time for down switch fragment: ${x.toFixed(3)} s\n TTFB estimate: ${0|E} ms\n Current BW estimate: ${Qe(b)?0|b:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${O} @ ${0|M} bps`),r.nextLoadLevel=r.nextAutoLevel=O,this.clearTimer();const F=()=>{this.clearTimer();const t=this.hls;if(this.fragCurrent===i&&t.loadLevel===O&&O>0){const e=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${O>0?"and switching down":""}\n Fragment duration: ${i.duration.toFixed(3)} s\n Time to underbuffer: ${e.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,O>u){let i=this.findBestLevel(t.levels[u].bitrate,u,O,0,e,1,1);-1===i&&(i=u),t.nextLoadLevel=t.nextAutoLevel=i,this.firstAutoFloor=Math.min(i,t.firstLevel),this.resetEstimator(t.levels[i].bitrate)}}};g||C>2*x?F():this.timer=self.setInterval(F,1e3*x),r.trigger(ii.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:n,stats:l})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){this.hls&&(t&&(this.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 Yi(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const t=this.hls;t.on(ii.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ii.FRAG_LOADING,this.onFragLoading,this),t.on(ii.FRAG_LOADED,this.onFragLoaded,this),t.on(ii.FRAG_BUFFERED,this.onFragBuffered,this),t.on(ii.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(ii.LEVEL_LOADED,this.onLevelLoaded,this),t.on(ii.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(ii.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(ii.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(ii.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ii.FRAG_LOADING,this.onFragLoading,this),t.off(ii.FRAG_LOADED,this.onFragLoaded,this),t.off(ii.FRAG_BUFFERED,this.onFragBuffered,this),t.off(ii.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(ii.LEVEL_LOADED,this.onLevelLoaded,this),t.off(ii.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(ii.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(ii.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.audioTracksByGroup=this.codecTiers=this.fragCurrent=this.partCurrent=null}onManifestLoading(t,e){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(t,e){const i=e.frag;if(!this.ignoreFragment(i)){var n;if(!i.bitrateTest)this.fragCurrent=i,this.partCurrent=null!=(n=e.part)?n: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 ei.BUFFER_ADD_CODEC_ERROR:case ei.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case ei.FRAG_LOAD_TIMEOUT:{const t=e.frag,{fragCurrent:i,partCurrent:n}=this;if(t&&Li(t,i)){const e=performance.now(),i=n?n.stats:t.stats,r=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(r-Math.min(t,s),i.loaded)}else this.bwEstimator.sampleTTFB(r)}break}}}getTimeToLoadFrag(t,e,i,n){return t+i/e+(n?t+this.lastLevelLoadSec:0)}onLevelLoaded(t,e){const i=this.hls.config,{loading:n}=e.stats,r=n.end-n.first;Qe(r)&&(this.lastLevelLoadSec=r/1e3),e.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(e.levelInfo)}onFragLoaded(t,e){var i;const{frag:n,part:r}=e,s=r?r.stats:n.stats;if(n.type===vi&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(n)){if(this.clearTimer(),n.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,null!=(i=this.hls)&&i.config.abrMaxWithRealBitrate){const t=r?r.duration:n.duration,e=this.hls.levels[n.level],i=(e.loaded?e.loaded.bytes:0)+s.loaded,a=(e.loaded?e.loaded.duration:0)+t;e.loaded={bytes:i,duration:a},e.realBitrate=Math.round(8*i/a)}if(n.bitrateTest){const t={stats:s,frag:n,part:r,id:n.type};this.onFragBuffered(ii.FRAG_BUFFERED,t),n.bitrateTest=!1}else this.lastLoadedFragLevel=n.level}}onFragBuffered(t,e){const{frag:i,part:n}=e,r=null!=n&&n.stats.loaded?n.stats:i.stats;if(r.aborted)return;if(this.ignoreFragment(i))return;const s=((i.bitrate||0)>=1e5?r.parsing.end:r.loading.end)-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(s,r.loaded),r.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=s/1e3:(this.bitrateTestDelay=0,this.firstAutoFloor>-1&&this.bwEstimator.canEstimate()&&(this.firstAutoFloor=-1))}ignoreFragment(t){return t.type!==vi||"initSegment"===t.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{hls:t}=this;if(!t)return 0;const{maxAutoLevel:e,minAutoLevel:i}=t,n=this.getBwEstimate(),r=this.getStarvationDelay(),s=t.config.maxStarvationDelay,a=this.findBestLevel(n,i,e,r/2,s,1,1);if(a>-1)return a;const o=t.firstLevel,l=-1===this.firstAutoFloor?1/0:this.firstAutoFloor,h=Math.min(Math.max(o,i),e,l);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${o} clamped to ${h}`),h}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){if(!this.hls)return-1;const t=this.forcedAutoLevel,e=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(!(-1===t||e&&i&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return t;const n=e&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==t){const e=this.hls.levels;if(e.length>Math.max(t,n)&&e[t].loadError<=e[n].loadError)return t}return this._nextAutoLevel=n,this.nextAutoLevelKey=this.getAutoLevelKey(),n}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:i}=this;if(!i)return-1;if(i.levels.length<=1)return i.loadLevel;const{maxAutoLevel:n,config:r,minAutoLevel:s}=i,a=e?e.duration:t?t.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let h=r.abrBandWidthFactor,c=r.abrBandWidthUpFactor;if(l){const t=this.findBestLevel(o,s,n,l,0,h,c);if(t>=0)return this.rebufferNotice=-1,t}let u=a?Math.min(a,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const t=this.bitrateTestDelay;if(t){u=(a?Math.min(a,r.maxLoadingDelay):r.maxLoadingDelay)-t,this.info(`bitrate test took ${Math.round(1e3*t)}ms, set first fragment max fetchDuration to ${Math.round(1e3*u)} ms`),h=c=1}}const d=this.findBestLevel(o,s,n,l,u,h,c);if(this.rebufferNotice!==d&&(this.rebufferNotice=d,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${d}`)),d>-1)return d;const f=i.levels[s],g=i.loadLevelObj;return g&&(null==f?void 0:f.bitrate)<g.bitrate?s:i.loadLevel}getStarvationDelay(){const t=this.hls,e=null==t?void 0:t.media;if(!e)return 1/0;const i=e&&0!==e.playbackRate?Math.abs(e.playbackRate):1,n=t.mainForwardBufferInfo;return(n?n.len:0)/i}getBwEstimate(){return this.bwEstimator.getEstimate()}findBestLevel(t,e,i,n,r,s,a){const{hls:o,lastLoadedFragLevel:l,fragCurrent:h,partCurrent:c}=this;if(!o)return-1;const u=n+r,d=-1===l?o.firstLevel:l,{levels:f,allAudioTracks:g,loadLevel:p,latestLevelDetails:m,config:v}=o;if(1===f.length)return 0;const y=f[d],A=!(null==m||!m.live),E=-1===p||-1===l;let T,b="SDR",S=(null==y?void 0:y.frameRate)||0;const{audioPreference:k,videoPreference:_}=v,L=this.audioTracksByGroup||(this.audioTracksByGroup=qr(g));let R=-1;if(E){if(-1!==this.firstSelection)return this.firstSelection;const n=this.codecTiers||(this.codecTiers=function(t,e,i,n){return t.slice(i,n+1).reduce((t,i,n)=>{if(!i.codecSet)return t;const r=i.audioGroups;let s=t[i.codecSet];s||(t[i.codecSet]=s={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:n,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!r,fragmentError:0}),s.minBitrate=Math.min(s.minBitrate,i.bitrate);const a=Math.min(i.height,i.width);return s.minHeight=Math.min(s.minHeight,a),s.minFramerate=Math.min(s.minFramerate,i.frameRate),s.minIndex=Math.min(s.minIndex,n),s.maxScore=Math.max(s.maxScore,i.score),s.fragmentError+=i.fragmentError,s.videoRanges[i.videoRange]=(s.videoRanges[i.videoRange]||0)+1,r&&r.forEach(t=>{if(!t)return;const i=e.groups[t];i&&(s.hasDefaultAudio=s.hasDefaultAudio||e.hasDefaultAudio?i.hasDefault:i.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(i.channels).forEach(t=>{s.channels[t]=(s.channels[t]||0)+i.channels[t]}))}),t},{})}(f,L,e,i)),r=function(t,e,i,n,r){const s=Object.keys(t),a=null==n?void 0:n.channels,o=null==n?void 0:n.audioCodec,l=null==r?void 0:r.videoCodec,h=a&&2===parseInt(a);let c=!1,u=!1,d=1/0,f=1/0,g=1/0,p=1/0,m=0,v=[];const{preferHDR:y,allowedVideoRanges:A}=jr(e,r);for(let e=s.length;e--;){const i=t[s[e]];c||(c=i.channels[2]>0),d=Math.min(d,i.minHeight),f=Math.min(f,i.minFramerate),g=Math.min(g,i.minBitrate),A.filter(t=>i.videoRanges[t]>0).length>0&&(u=!0)}d=Qe(d)?d:0,f=Qe(f)?f:0;const E=Math.max(1080,d),T=Math.max(30,f);g=Qe(g)?g:i,i=Math.max(g,i),u||(e=void 0);const b=s.length>1;return{codecSet:s.reduce((e,n)=>{const r=t[n];if(n===e)return e;if(v=u?A.filter(t=>r.videoRanges[t]>0):[],b){if(r.minBitrate>i)return zr(n,`min bitrate of ${r.minBitrate} > current estimate of ${i}`),e;if(!r.hasDefaultAudio)return zr(n,"no renditions with default or auto-select sound found"),e;if(o&&n.indexOf(o.substring(0,4))%5!=0)return zr(n,`audio codec preference "${o}" not found`),e;if(a&&!h){if(!r.channels[a])return zr(n,`no renditions with ${a} channel sound found (channels options: ${Object.keys(r.channels)})`),e}else if((!o||h)&&c&&0===r.channels[2])return zr(n,"no renditions with stereo sound found"),e;if(r.minHeight>E)return zr(n,`min resolution of ${r.minHeight} > maximum of ${E}`),e;if(r.minFramerate>T)return zr(n,`min framerate of ${r.minFramerate} > maximum of ${T}`),e;if(!v.some(t=>r.videoRanges[t]>0))return zr(n,`no variants with VIDEO-RANGE of ${Wr(v)} found`),e;if(l&&n.indexOf(l.substring(0,4))%5!=0)return zr(n,`video codec preference "${l}" not found`),e;if(r.maxScore<m)return zr(n,`max score of ${r.maxScore} < selected max of ${m}`),e}return e&&(Er(n)>=Er(e)||r.fragmentError>t[e].fragmentError)?e:(p=r.minIndex,m=r.maxScore,n)},void 0),videoRanges:v,preferHDR:y,minFramerate:f,minBitrate:g,minIndex:p}}(n,b,t,k,_),{codecSet:s,videoRanges:a,minFramerate:o,minBitrate:l,minIndex:h,preferHDR:c}=r;R=h,T=s,b=c?a[a.length-1]:a[0],S=o,t=Math.max(t,l),this.log(`picked start tier ${Wr(r)}`)}else T=null==y?void 0:y.codecSet,b=null==y?void 0:y.videoRange;const I=c?c.duration:h?h.duration:0,C=this.bwEstimator.getEstimateTTFB()/1e3,P=[];for(let o=i;o>=e;o--){var D;const e=f[o],h=o>d;if(!e)continue;if(v.useMediaCapabilities&&!e.supportedResult&&!e.supportedPromise){const i=navigator.mediaCapabilities;"function"==typeof(null==i?void 0:i.decodingInfo)&&wr(e,L,b,S,t,k)?(e.supportedPromise=Or(e,L,i,this.supportedCache),e.supportedPromise.then(t=>{if(!this.hls)return;e.supportedResult=t;const i=this.hls.levels,n=i.indexOf(e);t.error?this.warn(`MediaCapabilities decodingInfo error: "${t.error}" for level ${n} ${Wr(t)}`):t.supported?t.decodingInfoResults.some(t=>!1===t.smooth||!1===t.powerEfficient)&&this.log(`MediaCapabilities decodingInfo for level ${n} not smooth or powerEfficient: ${Wr(t)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${n} ${Wr(t)}`),n>-1&&i.length>1&&(this.log(`Removing unsupported level ${n}`),this.hls.removeLevel(n),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))}).catch(t=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${t}`)})):e.supportedResult=Pr}if((T&&e.codecSet!==T||b&&e.videoRange!==b||h&&S>e.frameRate||!h&&S>0&&S<e.frameRate||null!=(D=e.supportedResult)&&null!=(D=D.decodingInfoResults)&&D.some(t=>!1===t.smooth))&&(!E||o!==R)){P.push(o);continue}const g=e.details,m=(c?null==g?void 0:g.partTarget:null==g?void 0:g.averagetargetduration)||I||1;let y;y=h?a*t:s*t;const _=I&&n>=2*I&&0===r?e.averageBitrate:e.maxBitrate,w=this.getTimeToLoadFrag(C,y,_*m,!g||g.live);if(y>=_&&(o===l||0===e.loadError&&0===e.fragmentError||Ki(e,v.errorPenaltyExpireMs))&&(w<=C||!Qe(w)||A&&!this.bitrateTestDelay||w<u)){const t=this.forcedAutoLevel;return o===p||-1!==t&&t===p||(P.length&&this.trace(`Skipped level(s) ${P.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${f[P[0]].codecs}" ${f[P[0]].videoRange}; not compatible with "${T}" ${b}`),this.info(`switch candidate:${d}->${o} adjustedbw(${Math.round(y)})-bitrate=${Math.round(y-_)} ttfb:${C.toFixed(1)} avgDuration:${m.toFixed(1)} maxFetchDuration:${u.toFixed(1)} fetchDuration:${w.toFixed(1)} firstSelection:${E} codecSet:${e.codecSet} videoRange:${e.videoRange} hls.loadLevel:${p}`)),E&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(t){const e=this.deriveNextAutoLevel(t);this._nextAutoLevel!==e&&(this.nextAutoLevelKey="",this._nextAutoLevel=e)}deriveNextAutoLevel(t){if(!this.hls)return-1;const{maxAutoLevel:e,minAutoLevel:i}=this.hls;return Math.min(Math.max(t,i),e)}},bufferController:class extends ji{constructor(t,e){var i;super("buffer-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null),this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0,this._quotaEvictionPending={},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=t=>{var e;this.hls&&"open"===(null==(e=this.mediaSource)?void 0:e.readyState)&&this.hls.pauseBuffering()},this._onStartStreaming=t=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=t=>{const{media:e,mediaSource:i}=this;t&&this.log("Media source opened"),e&&i&&(ho(i,"sourceopen",this._onMediaSourceOpen),ho(e,"emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(ii.MEDIA_ATTACHED,{media:e,mediaSource:i}),null!==this.mediaSource&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{if(this.log("Media source closed"),this.media){const t=this.media.error,{appendError:e,appendErrors:i}=this;let n=!1;if(!e&&t){n=Math.max(++i.audio,++i.video,++i.audiovideo)>=this.hls.config.appendErrorMaxRetry}const r=new Error(`MediaSource closed while media attached${oh(n,t)}`);this.warn(r),this.hls.trigger(ii.ERROR,Di({fatal:n},e,{type:ti.MEDIA_ERROR,details:ei.MEDIA_SOURCE_REQUIRES_RESET,error:r}))}},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:t,_objectUrl:e}=this;t!==e&&this.error(`Media element src was set while attaching MediaSource (${e} > ${t})`)},this._onMediaError=()=>{const{media:t}=this;var e,i;t&&this.log(`Media error (code: ${null==(e=t.error)?void 0:e.code}): ${null==(i=t.error)?void 0:i.message}`)},this.hls=t,this.fragmentTracker=e,this.appendSource=(i=Ji(t.config.preferManagedMediaSource),"undefined"!=typeof self&&i===self.ManagedMediaSource),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:t}=this;t.on(ii.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(ii.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(ii.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ii.MANIFEST_PARSED,this.onManifestParsed,this),t.on(ii.BUFFER_RESET,this.onBufferReset,this),t.on(ii.BUFFER_APPENDING,this.onBufferAppending,this),t.on(ii.BUFFER_CODECS,this.onBufferCodecs,this),t.on(ii.BUFFER_EOS,this.onBufferEos,this),t.on(ii.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(ii.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(ii.FRAG_PARSED,this.onFragParsed,this),t.on(ii.FRAG_CHANGED,this.onFragChanged,this),t.on(ii.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(ii.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(ii.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(ii.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ii.MANIFEST_PARSED,this.onManifestParsed,this),t.off(ii.BUFFER_RESET,this.onBufferReset,this),t.off(ii.BUFFER_APPENDING,this.onBufferAppending,this),t.off(ii.BUFFER_CODECS,this.onBufferCodecs,this),t.off(ii.BUFFER_EOS,this.onBufferEos,this),t.off(ii.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(ii.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(ii.FRAG_PARSED,this.onFragParsed,this),t.off(ii.FRAG_CHANGED,this.onFragChanged,this),t.off(ii.ERROR,this.onError,this)}transferMedia(){const{media:t,mediaSource:e}=this;if(!t)return null;const i={};if(this.operationQueue){const t=this.isUpdating();t||this.operationQueue.removeBlockers();const e=this.isQueued();(t||e)&&this.warn(`Transfering MediaSource with${e?" operations in queue":""}${t?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const n=this.transferData;return n&&!this.sourceBufferCount&&n.mediaSource===e?Di(i,n.tracks):this.sourceBuffers.forEach(t=>{const[e]=t;e&&(i[e]=Di({},this.tracks[e]),this.removeBuffer(e)),t[0]=t[1]=null}),{media:t,mediaSource:e,tracks:i}}initTracks(){this.resetAppendProgress(),this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null,this.resetAppendErrors(),this.resetAppendProgress()}onManifestParsed(t,e){var i;let n=2;(e.audio&&!e.video||!e.altAudio)&&(n=1),this.bufferCodecEventsTotal=n,this.log(`${n} bufferCodec event(s) expected.`),null!=(i=this.transferData)&&i.mediaSource&&this.sourceBufferCount&&n&&this.bufferCreated()}onMediaAttaching(t,e){const i=this.media=e.media;this.transferData=this.overrides=void 0;const n=Ji(this.appendSource);if(n){const t=!!e.mediaSource;(t||e.overrides)&&(this.transferData=e,this.overrides=e.overrides);const r=this.mediaSource=e.mediaSource||new n;if(this.assignMediaSource(r),t)this._objectUrl=i.src,this.attachTransferred();else{const t=this._objectUrl=self.URL.createObjectURL(r);if(this.appendSource)try{i.removeAttribute("src");const e=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||e&&r instanceof e,sh(i),function(t,e){const i=self.document.createElement("source");i.type="video/mp4",i.src=e,t.appendChild(i)}(i,t),i.load()}catch(e){i.src=t}else i.src=t}lo(i,"emptied",this._onMediaEmptied),lo(i,"error",this._onMediaError)}}assignMediaSource(t){var e,i;this.log(`${(null==(e=this.transferData)?void 0:e.mediaSource)===t?"transferred":"created"} media source: ${null==(i=t.constructor)?void 0:i.name}`),lo(t,"sourceopen",this._onMediaSourceOpen),lo(t,"sourceended",this._onMediaSourceEnded),lo(t,"sourceclose",this._onMediaSourceClose),this.appendSource&&(lo(t,"startstreaming",this._onStartStreaming),lo(t,"endstreaming",this._onEndStreaming))}attachTransferred(){const t=this.media,e=this.transferData;if(!e||!t)return;const i=this.tracks,n=e.tracks,r=n?Object.keys(n):null,s=r?r.length:0,a=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(n&&r&&s){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})\nrequired tracks: ${Wr(i,(t,e)=>"initSegment"===t?void 0:e)};\ntransfer tracks: ${Wr(n,(t,e)=>"initSegment"===t?void 0:e)}}`),!tn(n,i)){e.mediaSource=null,e.tracks=void 0;const r=t.currentTime,s=this.details,a=Math.max(r,(null==s?void 0:s.fragments[0].start)||0);return a-r>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${r} -> ${a}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(n)}"->"${Object.keys(i)}") start time: ${a} currentTime: ${r}`),this.onMediaDetaching(ii.MEDIA_DETACHING,{}),this.onMediaAttaching(ii.MEDIA_ATTACHING,e),void(t.currentTime=a))}this.transferData=void 0,r.forEach(t=>{const e=t,i=n[e];if(i){const t=i.buffer;if(t){const n=this.fragmentTracker,r=i.id;if(n.hasFragments(r)||n.hasParts(r)){const i=js.getBuffered(t);n.detectEvictedFragments(e,i,r,null,null,!0)}const s=ah(e),a=[e,t];this.sourceBuffers[s]=a,t.updating&&this.operationQueue&&this.operationQueue.prependBlocker(e),this.trackSourceBuffer(e,i)}}}),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var t;const e=null==(t=this.mediaSource)?void 0:t.readyState;return"open"===e||"ended"===e}onMediaDetaching(t,e){const i=!!e.transferMedia;this.transferData=this.overrides=void 0;const{media:n,mediaSource:r,_objectUrl:s}=this;if(r){if(this.log("media source "+(i?"transferring":"detaching")),i)this.sourceBuffers.forEach(([t])=>{t&&this.removeBuffer(t)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const t="open"===r.readyState;try{const e=r.sourceBuffers;for(let i=e.length;i--;)t&&e[i].abort(),r.removeSourceBuffer(e[i]);t&&r.endOfStream()}catch(t){this.warn(`onMediaDetaching: ${t.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}ho(r,"sourceopen",this._onMediaSourceOpen),ho(r,"sourceended",this._onMediaSourceEnded),ho(r,"sourceclose",this._onMediaSourceClose),this.appendSource&&(ho(r,"startstreaming",this._onStartStreaming),ho(r,"endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}n&&(ho(n,"emptied",this._onMediaEmptied),ho(n,"error",this._onMediaError),i||(s&&self.URL.revokeObjectURL(s),this.mediaSrc===s?(n.removeAttribute("src"),this.appendSource&&sh(n),n.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null)}onBufferReset(){this.sourceBuffers.forEach(([t])=>{t&&this.resetBuffer(t)}),this.initTracks()}resetBuffer(t){var e;const i=null==(e=this.tracks[t])?void 0:e.buffer;if(this.removeBuffer(t),i)try{var n;null!=(n=this.mediaSource)&&n.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(e){this.warn(`onBufferReset ${t}`,e)}delete this.tracks[t]}removeBuffer(t){this.removeBufferListeners(t),this.sourceBuffers[ah(t)]=[null,null];const e=this.tracks[t];e&&(this.clearBufferAppendTimeoutId(e),e.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new eh(this.tracks)}onBufferCodecs(t,e){var i;const n=this.tracks,r=Object.keys(e);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const s="audiovideo"in e&&(n.audio||n.video)||n.audiovideo&&("audio"in e||"video"in e),a=!s&&this.sourceBufferCount&&this.media&&r.some(t=>!n[t]);s||a?this.warn(`Unsupported transition between "${Object.keys(n)}" and "${r}" SourceBuffers`):(r.forEach(t=>{var i,r;const s=e[t],{id:a,codec:o,levelCodec:l,container:h,metadata:c,supplemental:u}=s;let d=n[t];const f=null==(i=this.transferData)||null==(i=i.tracks)?void 0:i[t],g=null!=f&&f.buffer?f:d,p=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),m=null==g?void 0:g.levelCodec;d||(d=n[t]={buffer:void 0,listeners:[],codec:o,supplemental:u,container:h,levelCodec:l,metadata:c,id:a});const v=kr(p,m),y=null==v?void 0:v.replace(ih,"$1");let A=kr(o,l);const E=null==(r=A)?void 0:r.replace(ih,"$1");A&&v&&y!==E&&("audio"===t.slice(0,5)&&(A=Sr(A,this.appendSource)),this.log(`switching codec ${p} to ${A}`),A!==(d.pendingCodec||d.codec)&&(d.pendingCodec=A),d.container=h,this.appendChangeType(t,h,A))}),(this.tracksReady||this.sourceBufferCount)&&(e.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!e.video&&"main"===(null==(i=e.audio)?void 0:i.id)&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((t,e)=>{const i=this.tracks[e];return t[e]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},t},{})}appendChangeType(t,e,i){const n=`${e};codecs=${i}`,r={label:`change-type=${n}`,execute:()=>{const r=this.tracks[t];if(r){const s=r.buffer;null!=s&&s.changeType&&(this.log(`changing ${t} sourceBuffer type to ${n}`),s.changeType(n),r.codec=i,r.container=e)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn(`Failed to change ${t} SourceBuffer type`,e)}};this.append(r,t,this.isPending(this.tracks[t]))}blockAudio(t){var e;const i=t.start,n=i+.05*t.duration;if(!0===(null==(e=this.fragmentTracker.getAppendedFrag(i,vi))?void 0:e.gap))return;const r={label:"block-audio",execute:()=>{var t,e;(this.lastVideoAppendEnd>n||js.isBuffered(null==(t=this.tracks.video)?void 0:t.buffer,n)||!0===(null==(e=this.fragmentTracker.getAppendedFrag(n,vi))?void 0:e.gap))&&this.unblockAudio()},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn("Error executing block-audio operation",t)}};this.append(r,"audio",!0)}unblockAudio(){this.operationQueue&&this.operationQueue.unblockAudio()}onBufferAppending(t,e){const{tracks:i}=this,{data:n,type:r,parent:s,frag:a,part:o,chunkMeta:l,offset:h}=e,c=l.buffering[r],u=ki(a)&&!o&&!a.gap&&!l.partial&&!l.iframe;let d=null,f=!1;const{sn:g,cc:p}=a,m=self.performance.now();c.start=m;const v=a.stats.buffering,y=o?o.stats.buffering:null;0===v.start&&(v.start=m),0===(null==y?void 0:y.start)&&(y.start=m);const A=i.audio;let E=!1;"audio"===r&&"audio/mpeg"===(null==A?void 0:A.container)&&(E=!this.lastMpegAudioChunk||1===l.id||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const T=i.video,b=null==T?void 0:T.buffer;if(b&&"initSegment"!==g&&void 0!==h){const t=null==A?void 0:A.buffer,e=o||a;if("audio"===r&&"main"!==s&&!T.ending&&!T.ended&&t&&js.getBuffered(t).length){const t=e.start+.05*e.duration,i=js.getBuffered(b),n=this.currentOp("video");i.length||n?!js.isBuffered(b,t)&&this.lastVideoAppendEnd<t&&this.blockAudio(e):this.blockAudio(e)}else if("video"===r){const t=e.end,i=this.lastVideoAppendEnd-t;this.lastVideoAppendEnd=t,i<0||i>e.duration?this.unblockAudio():this.isAudioBlocked()&&this.executeNext("audio")}}const S=(o||a).start,k={label:`append-${r}`,execute:()=>{var t;c.executeStart=self.performance.now();const e=null==(t=this.tracks[r])?void 0:t.buffer;e&&(u&&(d=js.timeRangesToArray(js.getBuffered(e)),f=ch(hh(d,a),a)),E?this.updateTimestampOffset(e,S,.1,r,g,p):void 0!==h&&Qe(h)&&this.updateTimestampOffset(e,h,1e-6,r,g,p)),this.appendExecutor(n,r)},onStart:()=>{},onComplete:()=>{this.clearBufferAppendTimeoutId(this.tracks[r]);const t=self.performance.now();c.executeEnd=c.end=t,0===v.first&&(v.first=t),0===(null==y?void 0:y.first)&&(y.first=t);const e={};if(this.sourceBuffers.forEach(([t,i])=>{t&&(e[t]=js.getBuffered(i))}),u){const t=this.getFragmentAppendProgress(a),i=e[r];if(i&&d){const e=hh(js.timeRangesToArray(i),a);t.progressed||(t.progressed=e-hh(d,a)>.001);const n=f&&ch(e,a);t.fullyBuffered[r]=(void 0===t.fullyBuffered[r]||t.fullyBuffered[r])&&n}}this.hls.trigger(ii.BUFFER_APPENDED,{type:r,frag:a,part:o,chunkMeta:l,parent:s,timeRanges:e})},onError:t=>{var e;this.clearBufferAppendTimeoutId(this.tracks[r]);const i=t.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==t.name||"quota"in t;if(i&&!this._quotaEvictionPending[r]){const t=this.getBackBufferEvictionTarget(r,n.byteLength,a.type);if(t>0){this._quotaEvictionPending[r]=!0,this.log(`QuotaExceededError on "${r}" append sn: ${g} - evicting back buffer to ${t.toFixed(3)}s and retrying`);const e=this.getFlushOp(r,0,t),i=this.getClearEvictionPendingOp(r);return void this.insertNext([e,k,i],r)}this.warn(`QuotaExceededError on "${r}" sn: ${g} - no back buffer available to evict`)}u&&(this.getFragmentAppendProgress(a).errored=!0);const h={type:ti.MEDIA_ERROR,parent:s,details:ei.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:a,part:o,chunkMeta:l,error:t,err:t,fatal:!1},c=null==(e=this.media)?void 0:e.error;if(t.name!==nh||0!==this.sourceBufferCount||this.media&&0!==this.pendingTrackCount){var d;i&&(h.details=ei.BUFFER_FULL_ERROR);const e=++this.appendErrors[r],n=this.hls.config.appendErrorMaxRetry;this.warn(`Failed ${e}/${n+1} times to append segment in "${r}" sourceBuffer with error: ${t.message}`),e>=n&&(h.fatal=!i);const s=null==(d=this.mediaSource)?void 0:d.readyState;("ended"===s||"closed"===s||c)&&(this.warn(`MediaSource readyState "${s}" during SourceBuffer${oh(h.fatal,c)}`),h.details=ei.MEDIA_SOURCE_REQUIRES_RESET)}else h.errorAction=bs(!0);this.appendError=h,this.hls.trigger(ii.ERROR,h),i&&this.hls&&this.trimBuffers(a.start,1)}};this.log(`queuing "${r}" append sn: ${g}${o?" p: "+o.index:""} of ${s} playlist ${a.level} cc: ${p} offset: ${h} bytes: ${n.byteLength}`),this.append(k,r,this.isPending(this.tracks[r]))}getClearEvictionPendingOp(t){return{label:"clear",execute:()=>{this._quotaEvictionPending[t]=!1,this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:()=>{}}}getFlushOp(t,e,i){return this.log(`queuing "${t}" remove ${e}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(t,e,i)},onStart:()=>{},onComplete:()=>{var n;const r=null==(n=this.tracks[t])?void 0:n.buffer;this.log(`Remove request ${e}-${i} from ${t} Source Buffer complete > buffer: ${r?co(js.getBuffered(r)):"(detached)"}`),this.hls.trigger(ii.BUFFER_FLUSHED,{type:t,start:e,end:i})},onError:n=>{this.warn(`Failed to remove ${e}-${i} from "${t}" SourceBuffer`,n),this.hls.trigger(ii.BUFFER_FLUSHED,{type:t,start:0,end:0,error:n})}}}onBufferFlushing(t,e){const{type:i,startOffset:n,endOffset:r}=e;i&&"audio"!==i||this.unblockAudio(),i?this.append(this.getFlushOp(i,n,r),i):this.sourceBuffers.forEach(([t])=>{t&&this.append(this.getFlushOp(t,n,r),t)})}onFragParsed(t,e){const{frag:i,part:n,chunkMeta:r}=e,s=[],a=n?n.elementaryStreams:i.elementaryStreams;a[bi]?s.push("audiovideo"):(a[Ei]&&s.push("audio"),a[Ti]&&s.push("video"));0===s.length&&this.log(`Fragments must have at least one ElementaryStreamType set. ${i.type} ${i.level} ${n?`part: ${n.index} of `:""}sn: ${i.sn}`),this.blockBuffers(()=>{const t=self.performance.now();i.stats.buffering.end=t,n&&(n.stats.buffering.end=t);const e=n?n.stats:i.stats;this.checkAppendProgress(i,n,r,s),this.hls&&(this.hls.trigger(ii.FRAG_BUFFERED,{frag:i,part:n,stats:e,id:i.type,chunkMeta:r}),!n&&i.gap&&e.retry&&this.log(`Nothing buffered for ${i.type} level: ${i.level} sn: ${i.sn} retries ${e.retry}`))},s).catch(t=>{this.warn(`Fragment buffered callback ${t.message}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(t,e){var i,n;const r=null==(i=this.hls)?void 0:i.config;if(!r)return;const{backBufferLength:s,frontBufferFlushThreshold:a}=r;this.trimBuffers(a,s,e.frag,e.previousFrag);const o=e.frag.elementaryStreams,{appendErrors:l}=this,h=null==(n=this.appendError)?void 0:n.sourceBufferName;Object.keys(o).forEach(t=>{o[t]&&(l[t]=0,t===h&&(this.appendError=void 0),"audio"===t||"video"===t?(l.audiovideo=0,"audiovideo"===h&&(this.appendError=void 0)):(l.audio=0,l.video=0,"audiovideo"!==h&&(this.appendError=void 0)))})}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{if(t){const e=this.tracks[t];if(e)return!e.ended||e.ending}return!1})}onBufferEos(t,e){var i;this.sourceBuffers.forEach(([t])=>{if(t){const i=this.tracks[t];e.type&&e.type!==t||(i.ending=!0,i.ended||(i.ended=!0,this.log(`${t} buffer reached EOS`)))}});const n=!1!==(null==(i=this.overrides)?void 0:i.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{var e;return t&&!(null!=(e=this.tracks[t])&&e.ended)})?(this.unblockAudio(),n?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:t}=this;"open"===(null==t?void 0:t.readyState)?(this.log("Calling mediaSource.endOfStream()"),t.endOfStream(),this.hls.trigger(ii.BUFFERED_TO_END,void 0)):t&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${t.readyState}`)})):(this.tracksEnded(),this.hls.trigger(ii.BUFFERED_TO_END,void 0))):"video"===e.type&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([t])=>{if(null!==t){const e=this.tracks[t];e&&(e.ending=!1)}})}onLevelUpdated(t,{details:e}){e.fragments.length&&(this.details=e,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const t=this.getDurationAndRange();t&&this.updateMediaSource(t)})}onError(t,e){if(e.details===ei.BUFFER_APPEND_ERROR&&e.frag){var i;const t=null==(i=e.errorAction)?void 0:i.nextAutoLevel;Qe(t)&&t!==e.frag.level&&this.resetAppendErrors()}}getBackBufferEvictionTarget(t,e,i){const{media:n}=this;return n?this.fragmentTracker.getBackBufferEvictionEnd(n.currentTime,i,e):0}getFragmentAppendProgress(t){var e;const i=lh(t);let n=this.fragmentAppendProgress[i];return(null==(e=n)?void 0:e.stats)!==t.stats&&(n={stats:t.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[i]=n),n}checkAppendProgress(t,e,i,n){if(e||!ki(t)||t.gap||i.iframe||i.partial)return;const r=lh(t),s=this.fragmentAppendProgress[r];delete this.fragmentAppendProgress[r];const a=(null==s?void 0:s.stats)===t.stats?s:void 0;if(null!=a&&a.errored)return;const o=n.length>0&&n.every(t=>!0===(null==a?void 0:a.fullyBuffered[t]));if(null!=a&&a.progressed||o)return void delete this.appendsWithoutProgress[r];if(!a&&0===n.length)return;const l=(this.appendsWithoutProgress[r]||0)+1,h=this.hls;l>=h.config.appendErrorMaxRetry?delete this.appendsWithoutProgress[r]:this.appendsWithoutProgress[r]=l,this.warn(`Fragment ${t.sn} of ${t.type} playlist ${t.level} appended ${l} time${l>1?"s":""} without buffered range growth`),h.trigger(ii.ERROR,{type:ti.MEDIA_ERROR,details:ei.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:t,chunkMeta:i,parent:t.type,appendsWithoutProgress:l,error:new Error(`Fragment append did not increase buffered coverage (${l})`)})}resetAppendProgress(){this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null)}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0}trimBuffers(t,e,i,n){const{hls:r,details:s,media:a}=this;if(!a||null===s)return;if(!this.sourceBufferCount)return;const o=r.config,l=a.currentTime,h=s.levelTargetDuration;e=s.live&&null!==o.liveBackBufferLength?o.liveBackBufferLength:e;let c=-1/0;if(Qe(e)&&e>=0){const t=Math.max(e,h);c=Math.floor(l/h)*h-t}if(i){const t=this.getLoopBackBufferFlushEnd(i,null!=n?n:null);t>0&&(c=Math.max(c,t))}if(c>0&&this.flushBackBuffer(l,h,c),Qe(t)&&t>0){const e=Math.max(o.maxBufferLength,t),i=Math.max(e,h),n=Math.floor(l/h)*h+i;this.flushFrontBuffer(l,h,n)}}getLoopBackBufferFlushEnd(t,e){var i;const{media:n}=this;if(!1===(null==(i=this.hls)?void 0:i.config.loopBackBufferFlush)||null==n||!n.loop||!e||t.level<=e.level)return 0;const{video:r,audiovideo:s}=t.elementaryStreams;if(null!=r&&r.partial||null!=s&&s.partial)return 0;const a=this.getEarliestElementaryStreamStart(t)-.25;return a<=0?0:(this.log(`Flushing lower quality back buffer for loop: level ${t.level}, range [0-${a.toFixed(3)}]`),a)}getEarliestElementaryStreamStart(t){const{audio:e,video:i,audiovideo:n}=t.elementaryStreams;let r=t.start;return n?r=Math.min(r,n.startDTS):(e&&(r=Math.min(r,e.startDTS)),i&&(r=Math.min(r,i.startDTS))),r}flushBackBuffer(t,e,i){this.sourceBuffers.forEach(([t,e])=>{if(e){const a=js.getBuffered(e);if(a.length>0&&i>a.start(0)){var n,r,s;this.hls.trigger(ii.BACK_BUFFER_REACHED,{bufferEnd:i});const e=this.tracks[t];if(null!=(n=this.details)&&n.live)this.hls.trigger(ii.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(null!=e&&e.ended&&(null==(r=this.media)||!r.loop||!1===(null==(s=this.hls)?void 0:s.config.loopBackBufferFlush)))return void this.log(`Cannot flush ${t} back buffer while SourceBuffer is in ended state`);this.hls.trigger(ii.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:t})}}})}flushFrontBuffer(t,e,i){this.sourceBuffers.forEach(([e,n])=>{if(n){const r=js.getBuffered(n),s=r.length;if(s<2)return;const a=r.start(s-1),o=r.end(s-1);if(i>a||t>=a&&t<=o)return;this.hls.trigger(ii.BUFFER_FLUSHING,{startOffset:a,endOffset:1/0,type:e})}})}getDurationAndRange(){var t;const{details:e,mediaSource:i}=this;if(!e||!this.media||"open"!==(null==i?void 0:i.readyState))return null;const n=e.edge;if(e.live&&this.hls.config.liveDurationInfinity){if(e.fragments.length&&i.setLiveSeekableRange){const t=Math.max(0,e.fragmentStart);return{duration:1/0,start:t,end:Math.max(t,n)}}return{duration:1/0}}const r=null==(t=this.overrides)?void 0:t.duration;if(r)return Qe(r)?{duration:r}:null;const s=this.media.duration;return n>(Qe(i.duration)?i.duration:0)&&n>s||!Qe(s)?{duration:n}:null}updateMediaSource({duration:t,start:e,end:i}){const n=this.mediaSource;n&&this.media&&"open"===n.readyState&&(n.duration!==t&&(Qe(t)&&this.log(`Updating MediaSource duration to ${t.toFixed(3)}`),n.duration=t),void 0!==e&&void 0!==i&&(this.log(`MediaSource duration is set to ${n.duration}. Setting seekable range to ${e}-${i}.`),n.setLiveSeekableRange(e,i)))}get tracksReady(){const t=this.pendingTrackCount;return t>0&&(t>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:t,pendingTrackCount:e,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${e} codec events expected: ${t}) ${Wr(i)}`),this.tracksReady){var n;const t=null==(n=this.transferData)?void 0:n.tracks;t&&Object.keys(t).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const t={};this.sourceBuffers.forEach(([e,i])=>{if(e){const n=this.tracks[e];t[e]={buffer:i,container:n.container,codec:n.codec,supplemental:n.supplemental,levelCodec:n.levelCodec,id:n.id,metadata:n.metadata}}}),this.hls.trigger(ii.BUFFER_CREATED,{tracks:t}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(ii.ERROR,{type:ti.MEDIA_ERROR,details:ei.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}createSourceBuffers(){const{tracks:t,sourceBuffers:e,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in t){const s=r,a=t[s];if(this.isPending(a)){const t=this.getTrackCodec(a,s),r=`${a.container};codecs=${t}`;a.codec=t,this.log(`creating sourceBuffer(${r})${this.currentOp(s)?" Queued":""} ${Wr(a)}`);try{const t=i.addSourceBuffer(r),n=ah(s),o=[s,t];e[n]=o,a.buffer=t}catch(t){var n;return this.error(`error while trying to add sourceBuffer: ${t.message}`),this.shiftAndExecuteNext(s),null==(n=this.operationQueue)||n.removeBlockers(),delete this.tracks[s],void this.hls.trigger(ii.ERROR,{type:ti.MEDIA_ERROR,details:ei.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:s,mimeType:r,parent:a.id})}this.trackSourceBuffer(s,a)}}this.bufferCreated()}clearBufferAppendTimeoutId(t){t&&(self.clearTimeout(t.bufferAppendTimeoutId),t.bufferAppendTimeoutId=void 0)}getTrackCodec(t,e){const i=t.supplemental;let n=t.codec;i&&("video"===e||"audiovideo"===e)&&mr(i,"video")&&(n=function(t,e){const i=[];if(t){const e=t.split(",");for(let t=0;t<e.length;t++)pr(e[t],"video")||i.push(e[t])}return e&&i.push(e),i.join(",")}(n,i));const r=kr(n,t.levelCodec);return r?"audio"===e.slice(0,5)?Sr(r,this.appendSource):r:""}trackSourceBuffer(t,e){const i=e.buffer;if(!i)return;const n=this.getTrackCodec(e,t);this.tracks[t]={buffer:i,codec:n,container:e.container,levelCodec:e.levelCodec,supplemental:e.supplemental,metadata:e.metadata,id:e.id,listeners:[]},this.removeBufferListeners(t),this.addBufferListener(t,"updatestart",this.onSBUpdateStart),this.addBufferListener(t,"updateend",this.onSBUpdateEnd),this.addBufferListener(t,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(t,"bufferedchange",(t,e)=>{const i=e.removedRanges;null!=i&&i.length&&(this.log(`${t} buffer removed ${co(i)}`),this.hls.trigger(ii.BUFFER_FLUSHED,{type:t,start:i.start(0),end:i.end(i.length-1)}))})}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 e=this.currentOp(t);e&&e.onStart()}onSBUpdateEnd(t){var e,i;if("closed"===(null==(e=this.mediaSource)?void 0:e.readyState))return void this.resetBuffer(t);const n=this.currentOp(t);if(!n)return;n.onComplete();if(null==(i=this.tracks[t])||null==(i=i.buffer)?void 0:i.updating)return this.log(`${t} SourceBuffer updating on "updateend"`),void this.blockUntilOpen(()=>{this.shiftAndExecuteNext(t)});this.shiftAndExecuteNext(t)}onSBUpdateError(t,e){var i;const n=null==(i=this.mediaSource)?void 0:i.readyState,r=new Error(`${t} SourceBuffer error. MediaSource readyState: ${n}`);this.error(`${r.message}`,e),this.hls.trigger(ii.ERROR,{type:ti.MEDIA_ERROR,details:ei.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:r,fatal:!1});const s=this.currentOp(t);s&&s.onError(r)}updateTimestampOffset(t,e,i,n,r,s){const a=e-t.timestampOffset;Math.abs(a)>=i&&(this.log(`Updating ${n} SourceBuffer timestampOffset to ${e} (sn: ${r} cc: ${s})`),t.timestampOffset=e)}removeExecutor(t,e,i){const{media:n,mediaSource:r}=this,s=this.tracks[t],a=null==s?void 0:s.buffer;if(!n||!r||!a)throw new Error(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`);const o=Qe(n.duration)?n.duration:1/0,l=Qe(r.duration)?r.duration:1/0,h=Math.max(0,e);var c;if(h>=l)return null==(c=this.currentOp(t))||c.onComplete(),void this.shiftAndExecuteNext(t);const u=Math.min(i,o,l);if(!(u>h)||s.ending&&!s.ended)throw new Error(`Cannot remove ${u<=h?`invalid range (${h} >= ${u}) `:""}from the ${t} SourceBuffer${s.ending?" while track ending":""}`);s.ended=!1,this.log(`Removing [${h},${u}] from the ${t} SourceBuffer`),a.remove(h,u)}appendExecutor(t,e){const i=this.tracks[e],n=null==i?void 0:i.buffer;if(!n)throw new rh(`Attempting to append to the ${e} SourceBuffer, but it does not exist`);if(i.ending=!1,i.ended=!1,this.hls.config.appendTimeout!==1/0){const t=this.calculateAppendTimeoutTime(n);i.bufferAppendTimeoutId=self.setTimeout(()=>this.appendTimeoutHandler(e,n,t),t)}n.appendBuffer(t)}appendTimeoutHandler(t,e,i){this.log(`Received timeout after ${i}ms for append on ${t} source buffer. Aborting and triggering error.`);try{e.abort()}catch(e){this.log(`Failed to abort append on ${t} source buffer after timeout.`)}const n=this.currentOp(t);n&&n.onError(new Error(`${t}-append-timeout`))}calculateAppendTimeoutTime(t){let e=10;this.details&&(e=this.details.levelTargetDuration);let i=2*e*1e3;if(null===this.media)return i;const n=js.bufferInfo(t,this.media.currentTime,0);return n.len?(i=Math.max(1e3*n.len,i),Math.max(this.hls.config.appendTimeout,i)):i}blockUntilOpen(t){if(this.isUpdating()||this.isQueued())this.blockBuffers(t).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{t()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([t,e])=>t&&e.updating)}isQueued(){return this.sourceBuffers.some(([t])=>t&&!!this.currentOp(t))}isPending(t){return!!t&&!t.buffer}isAudioBlocked(){var t;return"block-audio"===(null==(t=this.currentOp("audio"))?void 0:t.label)}isAudioBlocking(){return!!this.operationQueue&&this.operationQueue.audioBlocking()}blockBuffers(t,e=this.sourceBufferTypes){if(!e.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);const{operationQueue:i}=this,n=2===e.length&&this.isAudioBlocking()?[this.appendBlocker("video")]:e.map(t=>this.appendBlocker(t));return Promise.all(n).then(e=>{i===this.operationQueue&&(t(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(t){t.forEach(t=>{var e;const i=null==(e=this.tracks[t])?void 0:e.buffer;!i||i.updating||"audio"===t&&this.isAudioBlocked()||this.shiftAndExecuteNext(t)})}append(t,e,i){this.operationQueue&&this.operationQueue.append(t,e,i)}insertNext(t,e){this.operationQueue&&this.operationQueue.insertNext(t,e)}appendBlocker(t){if(this.operationQueue)return this.operationQueue.appendBlocker(t)}currentOp(t){return this.operationQueue?this.operationQueue.current(t):null}executeNext(t){t&&this.operationQueue&&this.operationQueue.executeNext(t)}shiftAndExecuteNext(t){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(t)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((t,e)=>t+(this.isPending(this.tracks[e])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((t,[e])=>t+(e?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([t])=>t).filter(t=>!!t)}addBufferListener(t,e,i){const n=this.tracks[t];if(!n)return;const r=n.buffer;if(!r)return;const s=i.bind(this,t);n.listeners.push({event:e,listener:s}),lo(r,e,s)}removeBufferListeners(t){const e=this.tracks[t];if(!e)return;const i=e.buffer;i&&(e.listeners.forEach(t=>{ho(i,t.event,t.listener)}),e.listeners.length=0)}},capLevelController:uh,errorController:class extends ji{constructor(t){super("error-controller",t.logger),this.hls=void 0,this.playlistError=0,this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(ii.ERROR,this.onError,this),t.on(ii.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ii.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(ii.ERROR,this.onError,this),t.off(ii.ERROR,this.onErrorOut,this),t.off(ii.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ii.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){return(null==t?void 0:t.type)===vi?t.level:this.getVariantIndex()}getVariantIndex(){var t;const e=this.hls,i=e.currentLevel;return null!=(t=e.loadLevelObj)&&t.details||-1===i?e.loadLevel:i}variantHasKey(t,e){if(t){var i;if(null!=(i=t.details)&&i.hasKey(e))return!0;const n=t.audioGroups;if(n){return this.hls.allAudioTracks.filter(t=>n.indexOf(t.groupId)>=0).some(t=>{var i;return null==(i=t.details)?void 0:i.hasKey(e)})}}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(t,e){var i;if(e.fatal)return;const n=this.hls,r=e.context;switch(e.details){case ei.FRAG_LOAD_ERROR:case ei.FRAG_LOAD_TIMEOUT:case ei.KEY_LOAD_ERROR:case ei.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case ei.FRAG_PARSING_ERROR:if(null!=(i=e.frag)&&i.gap)return void(e.errorAction=bs());case ei.FRAG_GAP:case ei.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=us);case ei.PLAYLIST_UNCHANGED_ERROR:case ei.LEVEL_EMPTY_ERROR:case ei.LEVEL_PARSING_ERROR:{var s;const t=e.parent===vi?e.level:n.loadLevel;e.details===ei.LEVEL_EMPTY_ERROR&&null!=(s=e.context)&&null!=(s=s.levelDetails)&&s.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,t):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t))}return;case ei.LEVEL_LOAD_ERROR:case ei.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==r?void 0:r.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,r.level)));case ei.AUDIO_TRACK_LOAD_ERROR:case ei.AUDIO_TRACK_LOAD_TIMEOUT:case ei.SUBTITLE_LOAD_ERROR:case ei.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const t=n.loadLevelObj;if(t&&(r.type===ci&&t.hasAudioGroup(r.groupId)||r.type===ui&&t.hasSubtitleGroup(r.groupId)))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,n.loadLevel),e.errorAction.action=us,void(e.errorAction.flags=ps)}return;case ei.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(e.errorAction={action:us,flags:ms});case ei.KEY_SYSTEM_SESSION_UPDATE_FAILED:case ei.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case ei.KEY_SYSTEM_NO_SESSION:return void(e.errorAction={action:us,flags:vs});case ei.BUFFER_ADD_CODEC_ERROR:case ei.REMUX_ALLOC_ERROR:case ei.BUFFER_APPEND_ERROR:return void(e.errorAction||(e.errorAction=this.getLevelSwitchAction(e,e.level)));case ei.MEDIA_SOURCE_REQUIRES_RESET:return e.errorAction||(e.errorAction=this.getLevelSwitchAction(e,e.level)),void(e.errorAction.flags|=As|ys);case ei.INTERNAL_EXCEPTION:case ei.BUFFER_APPENDING_ERROR:case ei.BUFFER_APPEND_NO_PROGRESS:case ei.BUFFER_FULL_ERROR:case ei.LEVEL_SWITCH_ERROR:case ei.BUFFER_STALLED_ERROR:case ei.BUFFER_SEEK_OVER_HOLE:case ei.BUFFER_NUDGE_ON_STALL:return void(e.errorAction=bs())}e.type===ti.KEY_SYSTEM_ERROR&&(e.levelRetry=!1,e.errorAction=bs())}getPlaylistRetryOrSwitchAction(t,e){const i=Bi(this.hls.config.playlistLoadPolicy,t),n=this.playlistError++;if(Gi(i,n,Mi(t),t.response))return{action:fs,flags:gs,retryConfig:i,retryCount:n};const r=this.getLevelSwitchAction(t,e);return i&&(r.retryConfig=i,r.retryCount=n),r}getFragRetryOrSwitchAction(t){const e=this.hls,i=this.getVariantLevelIndex(t.frag),n=e.levels[i],{fragLoadPolicy:r,keyLoadPolicy:s}=e.config,a=Bi(Ni(t)?s:r,t),o=e.levels.reduce((t,e)=>t+e.fragmentError,0);if(n&&(t.details!==ei.FRAG_GAP&&n.fragmentError++,!Fi(t))){if(Gi(a,o,Mi(t),t.response))return{action:fs,flags:gs,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 n=this.hls.levels[e];if(n){var r,s;const e=t.details;n.loadError++,n.loadErrorTime=self.performance.now(),e===ei.BUFFER_APPEND_ERROR&&n.fragmentError++;let l=-1;const{levels:h,loadLevel:c,minAutoLevel:u,maxAutoLevel:d}=i;i.autoLevelEnabled||i.config.preserveManualLevelOnError||(i.loadLevel=-1);const f=null==(r=t.frag)?void 0:r.type,g=(f===yi&&e===ei.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&Es(t))&&h.some(({audioCodec:t})=>n.audioCodec!==t),p="video"===t.sourceBufferName&&Es(t)&&h.some(({codecSet:t,audioCodec:e})=>n.codecSet!==t&&n.audioCodec===e),{type:m,groupId:v}=null!=(s=t.context)?s:{};for(let r=h.length;r--;){const s=(r+c)%h.length;if(s!==c&&s>=u&&s<=d&&(0===h[s].loadError||Ki(h[s],i.config.errorPenaltyExpireMs))){var a,o;const i=h[s];if(e===ei.FRAG_GAP&&f===vi&&t.frag){const e=h[s].details;if(e){const i=ss(t.frag,e.fragments,t.frag.start);if(null!=i&&i.gap)continue}}else{if(m===ci&&i.hasAudioGroup(v)||m===ui&&i.hasSubtitleGroup(v))continue;if(f===yi&&null!=(a=n.audioGroups)&&a.some(t=>i.hasAudioGroup(t))||f===Ai&&null!=(o=n.subtitleGroups)&&o.some(t=>i.hasSubtitleGroup(t))||g&&n.audioCodec===i.audioCodec||p&&n.codecSet===i.codecSet||!g&&n.audioCodec!==i.audioCodec)continue}l=s;break}}if(l>-1&&i.loadLevel!==l)return t.levelRetry=!0,this.playlistError=0,{action:us,flags:gs,nextAutoLevel:l}}return{action:us,flags:ps}}onErrorOut(t,e){var i,n;switch(null==(i=e.errorAction)?void 0:i.action){case cs:break;case us:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===ei.FRAG_GAP||e.details===ei.PLAYLIST_UNCHANGED_ERROR||Ts(e)||(e.fatal=!0)}((null==(n=e.errorAction)?void 0:n.flags)||0)&As&&this.hls.recoverMediaError(),e.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(t){const e=this.hls,i=t.errorAction;if(!i)return;let n=i.nextAutoLevel;if(i.flags===gs)this.switchLevel(t,n);else if(i.flags&ys){const t=this.hls.levels;for(let e=t.length;e--;)"SDR"!==t[e].videoRange?(t[e].fragmentError++,t[e].loadError++):void 0===n&&(n=e)}else if(i.flags&ms){const n=this.getVariantLevelIndex(t.frag),r=e.levels[n],s=null==r?void 0:r.attrs["HDCP-LEVEL"];i.hdcpLevel=s;const a="NONE"===s;s&&!a?(e.maxHdcpLevel=Fr[Fr.indexOf(s)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`)):(a&&this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE"),i.flags|=vs)}if(i.flags&vs){const e=t.decryptdata;if(e){const n=this.hls.levels,a=n.length;for(let i=a;i--;){var r,s;if(this.variantHasKey(n[i],e))this.log(`Banned key found in level ${i} (${n[i].bitrate}bps) or audio group "${null==(r=n[i].audioGroups)?void 0:r.join(",")}" (${null==(s=t.frag)?void 0:s.type} fragment) ${bn(e.keyId||[])}`),n[i].fragmentError++,n[i].loadError++,this.log(`Removing level ${i} with key error (${t.error})`),this.hls.removeLevel(i)}const o=t.frag;if(this.hls.levels.length<a)i.resolved=!0;else if(o&&o.type!==vi){const t=o.decryptdata;t&&!e.matches(t)&&(i.resolved=!0)}}}i.resolved||this.switchLevel(t,n)}switchLevel(t,e){if(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,t.details===ei.BUFFER_ADD_CODEC_ERROR&&t.mimeType&&"audiovideo"!==t.sourceBufferName)){const e=Ir(t.mimeType),i=this.hls.levels;for(let n=i.length;n--;)i[n][`${t.sourceBufferName}Codec`]===e&&(this.log(`Removing level ${n} for ${t.details} ("${e}" not supported)`),this.hls.removeLevel(n))}}},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(ii.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(ii.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(ii.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(ii.MEDIA_DETACHING,this.onMediaDetaching,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)}}onMediaDetaching(){this.media=null}checkFPS(t,e,i){const n=performance.now();if(e){if(this.lastTime){const t=n-this.lastTime,r=i-this.lastDroppedFrames,s=e-this.lastDecodedFrames,a=1e3*r/t,o=this.hls;if(o.trigger(ii.FPS_DROP,{currentDropped:r,currentDecoded:s,totalDroppedFrames:i}),a>0&&r>o.config.fpsDroppedMonitoringThreshold*s){let t=o.currentLevel;o.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=t)&&(t-=1,o.trigger(ii.FPS_DROP_LEVEL_CAPPING,{level:t,droppedLevel:o.currentLevel}),o.autoLevelCapping=t,this.streamController.nextLevelSwitch())}}this.lastTime=n,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)}},id3TrackController:class{constructor(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(ii.EVENT_CUE_ENTER,{})},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:t}=this;t&&(t.on(ii.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(ii.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(ii.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(ii.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ii.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(ii.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(ii.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(ii.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(ii.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(ii.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(ii.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(ii.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ii.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(ii.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(ii.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(ii.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(t,e){this.media=e.media}onMediaAttached(){var t;const e=null==(t=this.hls)?void 0:t.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(t,e){this.media=null;!!e.transferMedia||(this.id3Track&&(this.id3Track.remove(),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){return Pu(t,"metadata","id3","","hidden")}onFragParsingMetadata(t,e){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:i,enableID3MetadataCues:n}=this.hls.config;if(!i&&!n)return;const{samples:r}=e;this.id3Track||(this.id3Track=this.createTrack(this.media));const s=Bu();if(s)for(let t=0;t<r.length;t++){const e=r[t].type;if(e===Vo.emsg&&!i||!n)continue;const a=yn(r[t].data),o=r[t].pts;let l=o+r[t].duration;l>Uu&&(l=Uu);l-o<=0&&(l=o+.25);for(let t=0;t<a.length;t++){const i=a[t];if(!An(i)){this.updateId3CueEnds(o,e);const t=$u(s,o,l,i,e);t&&this.id3Track.track.addCue(t)}}}}updateId3CueEnds(t,e){var i;const n=null==(i=this.id3Track)?void 0:i.track.cues;if(n)for(let i=n.length;i--;){const r=n[i];r.type===e&&r.startTime<t&&r.endTime===Uu&&(r.endTime=t)}}onBufferFlushing(t,{startOffset:e,endOffset:i,type:n}){const{id3Track:r,hls:s}=this;if(!s)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=s;if(r&&(a||o)){let t;t="audio"===n?t=>t.type===Vo.audioId3&&o:"video"===n?t=>t.type===Vo.emsg&&a:t=>t.type===Vo.audioId3&&o||t.type===Vo.emsg&&a,Ou(r.track,e,i,t)}}onLevelUpdated(t,{details:e}){this.updateDateRangeCues(e,!0)}onLevelPtsUpdated(t,e){Math.abs(e.drift)>.01&&this.updateDateRangeCues(e.details)}updateDateRangeCues(t,e){if(!this.hls||!this.media)return;const{assetPlayerId:i,timelineOffset:n,enableDateRangeMetadataCues:r,interstitialsController:s}=this.hls.config;if(!r)return;const a=Bu();if(i&&n&&!s){const{fragmentStart:e,fragmentEnd:n}=t;let r=this.assetCue;r?(r.startTime=e,r.endTime=n):a&&(r=this.assetCue=$u(a,e,n,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),r&&(r.id=i,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.track.addCue(r),r.addEventListener("enter",this.onEventCueEnter)))}if(!t.hasProgramDateTime)return;const{id3Track:o}=this,{dateRanges:l}=t,h=Object.keys(l);let c=this.dateRangeCuesAppended;var u;if(o&&e)if(null!=(u=o.track.cues)&&u.length){const t=Object.keys(c).filter(t=>-1===h.indexOf(t));for(let e=t.length;e--;){var d;const i=t[e],n=null==(d=c[i])?void 0:d.cues;delete c[i],n&&Object.keys(n).forEach(t=>{const e=n[t];if(e){e.removeEventListener("enter",this.onEventCueEnter);try{o.track.removeCue(e)}catch(t){}}})}}else c=this.dateRangeCuesAppended={};const f=t.fragments[t.fragments.length-1];if(0!==h.length&&Qe(null==f?void 0:f.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let t=0;t<h.length;t++){const e=h[t],i=l[e],n=i.startTime,r=c[e],o=(null==r?void 0:r.cues)||{};let u=(null==r?void 0:r.durationKnown)||!1,d=Uu;const{duration:f,endDate:g}=i;if(g&&null!==f)d=n+f,u=!0;else if(i.endOnNext&&!u){const t=h.reduce((t,e)=>{if(e!==i.id){const n=l[e];if(n.class===i.class&&n.startDate>i.startDate&&(!t||i.startDate<t.startDate))return n}return t},null);t&&(d=t.startTime,u=!0)}const p=Object.keys(i.attr);for(let t=0;t<p.length;t++){const l=p[t];if(!ea(l))continue;const h=o[l];if(h)!u||null!=r&&r.durationKnown?Math.abs(h.startTime-n)>.01&&(h.startTime=n,h.endTime=d):h.endTime=d;else if(a){let t=i.attr[l];ia(l)&&(t=Sn(t));const r=$u(a,n,d,{key:l,data:t},Vo.dateRange);r&&(r.id=e,this.id3Track.track.addCue(r),o[l]=r,s&&("X-ASSET-LIST"!==l&&"X-ASSET-URL"!==l||r.addEventListener("enter",this.onEventCueEnter)))}}c[e]={cues:o,dateRange:i,durationKnown:u}}}}},gapController:class extends Ks{constructor(t,e){super("gap-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.skipRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=void 0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var t;null!=(t=this.media)&&t.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var t;this.hls&&(this.ended=(null==(t=this.media)?void 0:t.currentTime)||1,this.hls.trigger(ii.MEDIA_ENDED,{stalled:!1}))},this.hls=t,this.fragmentTracker=e,this.lastCurrentTime=this.getCurrentTime(),this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(ii.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(ii.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(ii.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(ii.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(ii.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(ii.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(t,e){this.setInterval(100),this.mediaSource=e.mediaSource;const i=this.media=e.media;lo(i,"playing",this.onMediaPlaying),lo(i,"waiting",this.onMediaWaiting),lo(i,"ended",this.onMediaEnded)}onMediaDetaching(t,e){this.clearInterval();const{media:i}=this;i&&(ho(i,"playing",this.onMediaPlaying),ho(i,"waiting",this.onMediaWaiting),ho(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(t,e){this.buffered=e.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}getCurrentTime(){var t;const e=(null==(t=this.hls)?void 0:t.config.timelineOffset)||0;return this.media?Math.max(this.media.currentTime,e):e}tick(){var t;if(null==(t=this.media)||!t.readyState||!this.hasBuffered)return;const e=this.getCurrentTime();this.media.currentTime<e||(this.poll(e,this.lastCurrentTime),this.lastCurrentTime=e)}poll(t,e){var i,n;const r=null==(i=this.hls)?void 0:i.config;if(!r)return;const s=this.media;if(!s)return;const{seeking:a}=s,o=this.seeking&&!a,l=!this.seeking&&a,h=s.paused&&!a||s.ended||0===s.playbackRate;if(this.seeking=a,t!==e)return e&&(this.ended=0),this.moved=!0,a||(this.skipRetry=this.nudgeRetry=0,r.nudgeOnVideoHole&&!h&&t>e&&this.nudgeOnVideoHole(t,e)),void(0===this.waiting&&this.stallResolved(t));if(l||o)return void(o&&this.stallResolved(t));if(h)return this.skipRetry=this.nudgeRetry=0,this.stallResolved(t),void(!this.ended&&s.ended&&this.hls&&(this.ended=t||1,this.hls.trigger(ii.MEDIA_ENDED,{stalled:!1})));if(!js.getBuffered(s).length)return void(this.skipRetry=this.nudgeRetry=0);const c=js.bufferInfo(s,t,0),u=this.fragmentTracker;u&&this.hls&&Fu(c,t,u,this.hls);const d=c.nextStart||0;if(a&&u&&this.hls){const e=xu(this.hls.inFlightFragments,t),i=c.len>2,n=!d||e||d-t>2&&!u.getPartialFragment(t);if(i||n)return;this.moved=!1}const f=null==(n=this.hls)?void 0:n.latestLevelDetails;if(!this.moved&&null!==this.stalled&&u){if(!(c.len>0)&&!d)return;const e=Math.max(d,c.start||0)-t,i=!(null==f||!f.live)?2*f.targetduration:2,n=Nu(t,u);if(e>0&&(e<=i||n))return void(s.paused||this._trySkipBufferHole(n))}const g=r.detectStallWithCurrentTimeMs,p=self.performance.now(),m=this.waiting;let v=this.stalled;if(null===v){if(!(m>0&&p-m<g))return void(this.stalled=p);v=this.stalled=m}const y=p-v;if(!a&&(y>=g||m&&this.moved)&&this.hls){var A;if("ended"===(null==(A=this.mediaSource)?void 0:A.readyState)&&(null==f||!f.live)&&Math.abs(t-((null==f?void 0:f.edge)||0))<1){if(this.ended)return;return this.ended=t||1,void this.hls.trigger(ii.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(c),!this.media||!this.hls)return;if(s.currentTime!==t){const e=t;return t=s.currentTime,this.moved=!0,void this.log(`currentTime changed ${e} > ${t}`)}}const E=js.bufferInfo(s,t,r.maxBufferHole);this._tryFixBufferStall(E,y,t)}stallResolved(t){const e=this.stalled;if(e&&this.hls&&(this.stalled=null,this.stallReported)){const i=self.performance.now()-e;this.log(`playback not stuck anymore @${t}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(ii.STALL_RESOLVED,{})}}nudgeOnVideoHole(t,e){var i;const n=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(i=this.buffered.audio)&&i.length&&n&&n.length>1&&t>n.end(0)){const i=js.bufferedInfo(js.timeRangesToArray(this.buffered.audio),t,0);if(i.len>1&&e>=i.start){const i=js.timeRangesToArray(n),r=js.bufferedInfo(i,e,0).bufferedIndex;if(r>-1&&r<i.length-1){const e=js.bufferedInfo(i,t,0).bufferedIndex,n=i[r].end,s=i[r+1].start;if((-1===e||e>r)&&s-n<1&&t-n<2){const i=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${n} -> ${s} buffered index: ${e}`);this.warn(i.message),this.media.currentTime+=1e-6;let r=Nu(t,this.fragmentTracker);r&&"fragment"in r?r=r.fragment:r||(r=void 0);const a=js.bufferInfo(this.media,t,0);this.hls.trigger(ii.ERROR,{type:ti.MEDIA_ERROR,details:ei.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,frag:r,buffer:a.len,bufferInfo:a})}}}}}_tryFixBufferStall(t,e,i){var n,r;const{fragmentTracker:s,media:a}=this,o=null==(n=this.hls)?void 0:n.config;if(!a||!s||!o)return;const l=null==(r=this.hls)?void 0:r.latestLevelDetails,h=Nu(i,s);if(h||null!=l&&l.live&&i<l.fragmentStart){if(this._trySkipBufferHole(h)||!this.media)return}const c=t.buffered,u=this.adjacentTraversal(t,i);(c&&c.length>1&&t.len>o.maxBufferHole||t.nextStart&&(t.nextStart-i<o.maxBufferHole||u))&&(e>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}adjacentTraversal(t,e){const i=this.fragmentTracker,n=t.nextStart;if(i&&n){const t=i.getFragAtPos(e,vi),r=i.getFragAtPos(n,vi);if(t&&r)return r.sn-t.sn<2}return!1}_reportStall(t){const{hls:e,media:i,stallReported:n,stalled:r}=this;if(!n&&null!==r&&i&&e){this.stallReported=!0;const n=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${Wr(t)})`);this.warn(n.message),e.trigger(ii.ERROR,{type:ti.MEDIA_ERROR,details:ei.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:t.len,bufferInfo:t,stalled:{start:r}})}}_trySkipBufferHole(t){const{fragmentTracker:e,media:i,hls:n}=this,r=null==n?void 0:n.config;if(!i||!e||!r)return 0;const s=i.currentTime,a=js.bufferInfo(i,s,0);Fu(a,s,e,n);const o=s<a.start?a.start:a.nextStart;if(o){const h=a.len<=r.maxBufferHole,c=a.len>0&&a.len<1&&i.readyState<3,u=o-s;if(u>0&&(h||c)){if(u>r.maxBufferHole){let i=!1;if(0===s){const t=e.getAppendedFrag(0,vi);t&&o<t.end&&(i=!0)}if(!i&&t){var l;if(null==(l=n.loadLevelObj)||!l.details)return 0;if(xu(n.inFlightFragments,o))return 0;let i=!1,r=t.end;for(;r<o;){const t=Nu(r,e),n=t?t.duration:0;if(!(n>0)){i=!0;break}r+=n}if(i)return 0}}const{nudgeMaxRetry:h,skipBufferHolePadding:c}=r,d=++this.skipRetry>h,f=Math.max(o,s)+c;if(d||(this.warn(`skipping hole, adjusting currentTime from ${s} to ${f}`),this.moved=!0,i.currentTime=f),null==t||!t.gap||d){const e=new Error(d?`Playhead still not moving after seeking over buffer hole from ${s} to ${f} after ${r.nudgeMaxRetry} attempts.`:`fragment loaded with buffer holes, seeking from ${s} to ${f}`),i={type:ti.MEDIA_ERROR,details:ei.BUFFER_SEEK_OVER_HOLE,fatal:d,error:e,reason:e.message,buffer:a.len,bufferInfo:a};t&&("fragment"in t?i.part=t:i.frag=t),n.trigger(ii.ERROR,i)}return f}}return 0}_tryNudgeBuffer(t){const{hls:e,media:i,nudgeRetry:n}=this,r=null==e?void 0:e.config;if(!i||!r)return 0;const s=i.currentTime;if(this.nudgeRetry++,n<r.nudgeMaxRetry){const a=s+(n+1)*r.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${s} to ${a}`);this.warn(o.message),i.currentTime=a,e.trigger(ii.ERROR,{type:ti.MEDIA_ERROR,details:ei.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:t.len,bufferInfo:t})}else{const i=new Error(`Playhead still not moving while enough data buffered @${s} after ${r.nudgeMaxRetry} nudges`);this.error(i.message),e.trigger(ii.ERROR,{type:ti.MEDIA_ERROR,details:ei.BUFFER_STALLED_ERROR,error:i,fatal:!0,buffer:t.len,bufferInfo:t})}}},latencyController:class{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,e=this.levelDetails;if(!t||!e)return;this.currentTime=t.currentTime;const i=this.computeLatency();if(null===i)return;this._latency=i;const{lowLatencyMode:n,maxLiveSyncPlaybackRate:r}=this.config;if(!n||1===r||!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,r)),i=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20,n=Math.min(e,Math.max(1,i));this.changeMediaPlaybackRate(t,n)}else 1!==t.playbackRate&&0!==t.playbackRate&&this.changeMediaPlaybackRate(t,1)},this.hls=t,this.config=t.config,this.registerListeners()}get levelDetails(){var t;return(null==(t=this.hls)?void 0:t.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:t}=this;if(void 0!==t.liveMaxLatencyDuration)return t.liveMaxLatencyDuration;const e=this.levelDetails;return e?t.liveMaxLatencyDurationCount*e.targetduration:0}get targetLatency(){const t=this.levelDetails;if(null===t||null===this.hls)return null;const{holdBack:e,partHoldBack:i,targetduration:n}=t,{liveSyncDuration:r,liveSyncDurationCount:s,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&i||e;(this._targetLatencyUpdated||o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==r?r:s*n);const h=n;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,h)}set targetLatency(t){this.stallCount=0,this.config.liveSyncDuration=t,this._targetLatencyUpdated=!0}get liveSyncPosition(){const t=this.estimateLiveEdge(),e=this.targetLatency;if(null===t||null===e)return null;const i=this.levelDetails;if(null===i)return null;const n=i.edge,r=t-e-this.edgeStalled,s=n-i.totalduration,a=n-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(s,r),a)}get drift(){const t=this.levelDetails;return null===t?1:t.drift}get edgeStalled(){const t=this.levelDetails;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}=this,e=this.levelDetails;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.hls=null}registerListeners(){const{hls:t}=this;t&&(t.on(ii.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(ii.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(ii.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ii.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(ii.ERROR,this.onError,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(ii.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(ii.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(ii.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ii.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(ii.ERROR,this.onError,this))}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(t,{details:e}){e.advanced&&this.onTimeupdate(),!e.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(t,e){var i;e.details===ei.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(i=this.levelDetails)&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(t,e){var i,n;t.playbackRate!==e&&(null==(i=this.hls)||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(n=this.targetLatency)?void 0:n.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${t.playbackRate} to ${e}`),t.playbackRate=e)}estimateLiveEdge(){const t=this.levelDetails;return null===t?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return null===t?null:t-this.currentTime}}},{cueHandler:Bd,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 ko{constructor(t,e,i){super(t,e,i,"subtitle-stream-controller",Ai),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(ii.LEVEL_LOADED,this.onLevelLoaded,this),t.on(ii.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(ii.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(ii.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(ii.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(ii.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(ii.LEVEL_LOADED,this.onLevelLoaded,this),t.off(ii.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(ii.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(ii.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(ii.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(ii.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(t,e){this.stopLoad(),this.state=fo,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(t,e){this.tracksBuffered=[],super.onMediaDetaching(t,e)}onLevelLoaded(t,e){this.mainDetails=e.details}onSubtitleFragProcessed(t,e){const{frag:i,part:n,success:r}=e;if(!r)return;const s=this.tracksBuffered[this.currentTrackId];if(!s)return;let a;const o=(n||i).start;for(let t=0;t<s.length;t++)if(o>=s[t].start&&o<=s[t].end){a=s[t];break}const l=o+(n||i).duration;if(a?a.end=l:(a={start:o,end:l},s.push(a)),!n||l>=i.end){const t=this.fragmentTracker.fragBuffered(i);n&&t&&(t.range.subs={time:[{startPTS:i.start,endPTS:l}],partial:!0}),ki(i)&&!this.fragContextChanged(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,n),this.media&&this.tickImmediate()}}onBufferFlushing(t,e){const{startOffset:i,endOffset:n}=e;if(0===i&&n!==Number.POSITIVE_INFINITY){const t=n-1;if(t<=0)return;e.endOffsetSubtitles=Math.max(0,t),this.tracksBuffered.forEach(e=>{if(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,Ai)}}onError(t,e){const i=e.frag;(null==i?void 0:i.type)===Ai&&(e.details===ei.FRAG_GAP&&this.fragmentTracker.addAsGap(i),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==uo&&(this.state=fo))}onSubtitleTracksUpdated(t,{subtitleTracks:e}){this.levels&&Jl(this.levels,e)?this.levels=e.map(t=>new Hr(t)):(this.tracksBuffered=[],this.levels=e.map(t=>{const e=new Hr(t);return this.tracksBuffered[e.id]=[],e}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Ai),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 n=this.levels[this.currentTrackId];null!=n&&n.details?(this.mediaBuffer=this.mediaBufferTimeRanges,this.state!==uo&&this.setInterval(500)):this.mediaBuffer=null}onSubtitleTrackLoaded(t,e){var i;const{currentTrackId:n,levels:r}=this,{details:s,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 [${s.startSN},${s.endSN}]${s.lastPartSn?`[part-${s.lastPartSn}-${s.lastPartIndex}]`:""},duration:${s.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;const l=this.mainDetails;let h=0;if(s.live||null!=(i=o.details)&&i.live){if(s.deltaUpdateFailed)return;if(!l)return void(this.startFragRequested=!1);var c;if(o.details)h=this.alignPlaylists(s,o.details,null==(c=this.levelLastLoaded)?void 0:c.details);s.alignedSliding||(oo(l,s,this),h=s.fragmentStart)}o.details=s,this.levelLastLoaded=o,l&&!this.startFragRequested&&this.setStartPosition(l,h),a===n&&(this.hls.trigger(ii.SUBTITLE_TRACK_UPDATED,{details:s,id:a,groupId:e.groupId}),this.tickImmediate())}_handleFragmentLoadProgress(t){const{frag:e,part:i,payload:n}=t;i&&null!=n&&n.byteLength&&this.shouldDecrypt(e)&&this.decryptPayload(n,e,i)}_handleFragmentLoadComplete(t){const{frag:e,payload:i}=t;!this.fragContextChanged(e)&&null!=i&&i.byteLength&&this.shouldDecrypt(e)&&this.decryptPayload(i,e,null)}shouldDecrypt(t){const e=t.decryptdata;return!!(null!=e&&e.key&&e.iv&&oa(e.method))}decryptPayload(t,e,i){const n=e.decryptdata,r=performance.now();this.decrypter.decrypt(new Uint8Array(t),n.key.buffer,n.iv.buffer,la(n.method)).then(t=>{this.fragContextChanged(e)||this.hls.trigger(ii.FRAG_DECRYPTED,{frag:e,part:i,payload:t,stats:{tstart:r,tdecrypt:performance.now()}})}).catch(t=>{this.hls.trigger(ii.ERROR,{type:ti.MEDIA_ERROR,details:ei.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e,part:i}),i||(this.warn(`${t.name}: ${t.message}`),this.state=fo)})}doTick(){if(this.state===fo&&this.levels){var t;if(!this.media&&!this.primaryPrefetch&&(this.startFragRequested||!this.config.startFragPrefetch))return;const{currentTrackId:i,levels:n}=this,r=n[i],s=null==r?void 0:r.details;if(!s||this.waitForLive(r)||this.waitForCdnTuneIn(s))return void(this.startFragRequested=!1);const{config:a}=this,o=this.playhead,l=js.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],o,a.maxBufferHole),{end:h,len:c}=l;if(c>Math.max(this.hls.maxBufferLength+s.levelTargetDuration,(null==(t=this.hls.mainForwardBufferInfo)?void 0:t.len)||0)||c&&!this.buffering)return;let u=this.getNextFragment(h,s);if(!u)return;if(ki(u)){var e;const t=u.sn-s.startSN,i=s.fragments[t-1];u.cc!==(null==i?void 0:i.cc)||null!=(e=s.partList)&&e.length||this.fragmentTracker.getState(i)!==Ss||(u=i)}this.loadFragment(u,r,h)}}loadFragment(t,e,i){const n=this.fragmentTracker.getState(t);n!==Ss&&n!==_s||super.loadFragment(t,e,i)}get mediaBufferTimeRanges(){return new gd(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends Zl{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.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=-1,e=!1;if(this.currentTrack){var i;const n=null==(i=this.currentTrack.trackNode)?void 0:i.track.mode;"showing"===n?(t=this.trackId,e=!0):"hidden"===n&&(t=this.trackId)}if(!e)for(let e=0;e<this.tracksInGroup.length;e++){var n;const i=null==(n=this.tracksInGroup[e].trackNode)?void 0:n.track.mode;if("showing"===i){t=e;break}t<0&&"hidden"===i&&(t=e)}var r;t>-1&&(this._subtitleDisplay="showing"===(null==(r=this.tracksInGroup[t].trackNode)?void 0:r.track.mode));this.setSubtitleTrack(t,!0)},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(ii.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(ii.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(ii.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ii.MANIFEST_PARSED,this.onManifestParsed,this),t.on(ii.LEVEL_LOADING,this.onLevelLoading,this),t.on(ii.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(ii.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(ii.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(ii.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(ii.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(ii.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ii.MANIFEST_PARSED,this.onManifestParsed,this),t.off(ii.LEVEL_LOADING,this.onLevelLoading,this),t.off(ii.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(ii.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(ii.ERROR,this.onError,this)}createTracksInGroup(){var t;if(!this.media||!this.hls.config.renderTextTracksNatively)return;this.tracksInGroup.forEach(t=>{t.trackNode||(t.trackNode=Pu(this.media,Du(t),t.name,t.lang))});const e=null==(t=this.currentTrack)||null==(t=t.trackNode)?void 0:t.track;"disabled"===(null==e?void 0:e.mode)&&(e.mode=this._subtitleDisplay?"showing":"hidden")}onMediaAttached(t,e){const i=e.media;this.media=i;let n=this.trackId;this.queuedDefaultTrack>-1&&(n=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.setSubtitleTrack(n),this.createTracksInGroup(),this.useTextTrackPolling=!(i.textTracks&&"onchange"in i.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):i.textTracks.addEventListener("change",this.asyncPollTrackChange)}pollTrackChange(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,t)}onMediaDetaching(t,e){const i=this.media;if(!i)return;const n=!!e.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId,this.setSubtitleTrack(-1)),this.media=null,n||this.hls.config.renderTextTracksNatively&&this.tracksInGroup.forEach(t=>{const e=t.trackNode;e&&(e.track.mode="hidden",e.remove(),t.trackNode=void 0)})}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:n,details:r}=e,s=this.tracksInGroup[i];if(!s||s.groupId!==n)return void this.warn(`Subtitle track with id:${i} and group:${n} 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:${n} loaded [${r.startSN}-${r.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,n=this.groupIds;let r=this.currentTrack;if(!i||(null==n?void 0:n.length)!==(null==i?void 0:i.length)||null!=i&&i.some(t=>-1===(null==n?void 0:n.indexOf(t)))){this.groupIds=i;const t=[];if(this.tracks.forEach(e=>{(e.textCodec===Au?this.hls.config.enableIMSC1:this.hls.config.enableWebVTT)&&(!i||i.indexOf(e.groupId)>-1?(e.id=t.length,t.push(e)):e.trackNode&&(e.trackNode.remove(),e.trackNode=void 0))}),t.length===this.tracksInGroup.length){let e=!1;for(let i=0;i<t.length;i++)if(t[i]!==this.tracksInGroup[i]){e=!0;break}if(!e)return}t.length&&this.selectDefaultTrack&&!t.some(t=>t.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=t,this.trackId=-1,this.currentTrack=null;const e=this.hls.config.subtitlePreference;if(!r&&e){this.selectDefaultTrack=!1;const i=Qr(e,t);if(i>-1)r=t[i];else{const t=Qr(e,this.tracks);r=this.tracks[t]}}let n=this.findTrackId(r);-1===n&&r&&(n=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(ii.SUBTITLE_TRACKS_UPDATED,s),this.setSubtitleTrack(n),this.createTracksInGroup()}}findTrackId(t){const e=this.tracksInGroup,i=this.selectDefaultTrack;for(let n=0;n<e.length;n++){const r=e[n];if((!i||r.default)&&(i||t)&&(!t||Zr(r,t)))return n}if(t){for(let i=0;i<e.length;i++){const n=e[i];if(th(t.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<e.length;i++){const n=e[i];if(th(t.attrs,n.attrs,["LANGUAGE"]))return i}}return-1}onError(t,e){!e.fatal&&e.context&&e.context.type===ui&&e.context.id===this.trackId&&is(e.context.groupId,this.groupIds)&&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,!0)}setSubtitleOption(t){if(this.hls.config.subtitlePreference=t,t){if(-1===t.id)return this.setSubtitleTrack(-1,!0),null;const e=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,e.length){const i=this.currentTrack;if(i&&Zr(t,i))return i;const n=Qr(t,this.tracksInGroup);if(n>-1){const t=this.tracksInGroup[n];return this.setSubtitleTrack(n,!0),t}if(i)return null;{const i=Qr(t,e);if(i>-1)return e[i]}}}return null}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const i=t.id,n=t.groupId,r=this.getUrlWithDirectives(t.url,e),s=t.details,a=null==s?void 0:s.age;this.log(`Loading subtitle ${i} "${t.name}" lang:${t.lang} group:${n}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${a&&s.live?" age "+a.toFixed(1)+(s.type&&" "+s.type||""):""} ${r}`),this.hls.trigger(ii.SUBTITLE_TRACK_LOADING,{url:r,id:i,groupId:n,deliveryDirectives:e||null,track:t})}toggleTrackModes(){if(!this.media||!this.hls.config.renderTextTracksNatively)return;const t=this.currentTrack;this.tracksInGroup.forEach(e=>{if(e.trackNode){const i=e===t?this._subtitleDisplay?"showing":"hidden":"disabled",n=e.trackNode.track;n.mode!==i&&(n.mode=i)}})}setSubtitleTrack(t,e=!1){const i=this.tracksInGroup;if(this.media||(this.queuedDefaultTrack=t),t<-1||t>=i.length||!Qe(t))return void this.warn(`Invalid subtitle track id: ${t}`);const n=this.currentTrack,r=i[t]||null;if(this.trackId=t,this.currentTrack=r,e&&this.toggleTrackModes(),!r)return void(n&&this.hls.trigger(ii.SUBTITLE_TRACK_SWITCH,{id:t}));const s=!!r.details&&!r.details.live;if(r===n&&s)return;this.log(`Switching to subtitle-track ${t}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));const{id:a,groupId:o="",name:l,type:h,url:c}=r;this.hls.trigger(ii.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:h,url:c});const u=this.switchParams(r.url,null==n?void 0:n.details,r.details);this.loadPlaylist(u)}},timelineController:class{constructor(t){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.cueCache={},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.cueCache={},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(ii.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(ii.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(ii.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ii.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(ii.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(ii.FRAG_LOADING,this.onFragLoading,this),t.on(ii.FRAG_LOADED,this.onFragLoaded,this),t.on(ii.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(ii.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(ii.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(ii.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(ii.BUFFER_APPENDED,this.onBufferAppended,this),t.on(ii.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(ii.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(ii.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(ii.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ii.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(ii.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(ii.FRAG_LOADING,this.onFragLoading,this),t.off(ii.FRAG_LOADED,this.onFragLoaded,this),t.off(ii.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(ii.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(ii.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(ii.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(ii.BUFFER_APPENDED,this.onBufferAppended,this),t.off(ii.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const t=new Md(this,"textTrack1"),e=new Md(this,"textTrack2"),i=new Md(this,"textTrack3"),n=new Md(this,"textTrack4");this.cea608Parser1=new wd(1,t,e),this.cea608Parser2=new wd(3,i,n)}addCues(t,e,i,n,r){let s=!1;for(let t=r.length;t--;){const n=r[t],a=Nd(n[0],n[1],e,i);if(a>=0&&(n[0]=Math.min(n[0],e),n[1]=Math.max(n[1],i),s=!0,a/(i-e)>.5))return}if(s||r.push([e,i]),this.config.renderTextTracksNatively){const r=this.cueCache[t];if(r){const t=this.Cues.newCue(null,e,i,n);t.length&&r.push.apply(r,t)}else{const r=this.captionsTracks[t].track;this.Cues.newCue(r,e,i,n)}}else{var a;const r=this.Cues.newCue(null,e,i,n),s=null==(a=this.captionsProperties[t])?void 0:a.media;this.hls.trigger(ii.CUES_PARSED,{type:"captions",cues:r,track:t,closedCaptions:s})}}onInitPtsFound(t,{id:e,timestampOffsets:i}){const{unparsedVttFrags:n}=this;e===vi&&(this.initPTS=i),n.length&&(this.unparsedVttFrags=[],n.forEach(t=>{this.initPTS[t.frag.cc]?this.onFragLoaded(ii.FRAG_LOADED,t):this.hls.trigger(ii.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t.frag,part:null,error:new Error("Subtitle discontinuity domain does not match main")})}))}createCaptionsTrack(t){this.config.renderTextTracksNatively?this.createNativeTrack(t):this.createNonNativeTrack(t)}createNativeTrack(t){if(this.captionsTracks[t])return;const{captionsProperties:e,captionsTracks:i,cueCache:n,media:r}=this,{label:s,languageCode:a}=e[t];r&&(n[t]=[],i[t]=Pu(r,"captions",s,a,"hidden"))}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(ii.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}onMediaAttaching(t,e){this.media=e.media}onMediaDetaching(t,e){const i=!!e.transferMedia;if(this.media=null,!i){if(this.config.renderTextTracksNatively){const{captionsTracks:t,cueCache:e}=this;for(const i in t)t[i].remove(),delete e[i]}this.cueCache={},this.captionsTracks={},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.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}onSubtitleTracksUpdated(t,e){const i=e.subtitleTracks||[];if(i.length&&!this.config.renderTextTracksNatively&&!Jl(this.tracks,i)){const t=i.map(t=>({label:t.name,kind:t.type.toLowerCase(),default:t.default,subtitleTrack:t}));this.hls.trigger(ii.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:t})}this.tracks=i}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]}`,n=this.captionsProperties[i];n&&(n.label=t.name,t.lang&&(n.languageCode=t.lang),n.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===vi){var i,n;const{cea608Parser1:t,cea608Parser2:r,lastSn:s}=this,{cc:a,sn:o}=e.frag,l=null!=(i=null==(n=e.part)?void 0:n.index)?i:-1;t&&r&&(o!==s+1||o===s&&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:i,payload:n}=e;if(i.level<this.tracks.length&&i.type===Ai)if(n.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),(null==t?void 0:t.textCodec)===Au?this._parseIMSC1(e):this._parseVTTs(e)}}else{const t="part"in e?e.part:null;this.hls.trigger(ii.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,part:t,error:new Error("Empty subtitle payload")})}}_parseIMSC1(t){const{frag:e,payload:i}=t,n="part"in t?t.part:null,r=this.hls;Su(i,this.initPTS[e.cc],t=>{this._appendCues(t,e.level),r.trigger(ii.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e,part:n})},t=>{r.logger.log(`Cannot parse IMSC1 (sn: ${e.sn} @${e.start}): ${t}`),r.trigger(ii.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,part:n,error:t})})}_parseVTTs(t){var e;const{frag:i,payload:n}=t,r="part"in t?t.part:null,{initPTS:s,unparsedVttFrags:a}=this,o=s.length-1;if(!s[i.cc]&&-1===o)return void a.push(t);const l=this.hls,h=null==(e=i.initSegment)?void 0:e.data;yu(h?Zn(h,new Uint8Array(n)).buffer:n,this.initPTS[i.cc],this.vttCCs,i.cc,(r&&!h?r:i).start,t=>{this._appendCues(t,i.level),l.trigger(ii.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i,part:r})},e=>{const n=e.message.startsWith("Missing initPTS");l.logger.log(`${n?"Deferred parsing of":"Cannot parse"} VTT cue (sn: ${i.sn} @${i.start}): ${e}`),n?a.push(t):(this.config.enableIMSC1&&this._fallbackToIMSC1(t),l.trigger(ii.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,part:r,error:e}))})}_fallbackToIMSC1(t){const{frag:e,payload:i}=t,n=this.tracks[e.level];n.textCodec||Su(i,this.initPTS[e.cc],()=>{n.textCodec=Au,this._parseIMSC1(t)},()=>{n.textCodec="wvtt"})}_appendCues(t,e){const i=this.hls;if(this.config.renderTextTracksNatively){var n;const i=null==(n=this.tracks[e].trackNode)?void 0:n.track;if(!i||"disabled"===i.mode)return;t.forEach(t=>wu(i,t))}else{const n=this.tracks[e];if(!n)return;const r=n.default?"default":"subtitles"+e;i.trigger(ii.CUES_PARSED,{type:"subtitles",cues:t,track:r,subtitleTrack:n})}}onFragDecrypted(t,e){const{frag:i}=e;i.type===Ai&&this.onFragLoaded(ii.FRAG_LOADED,e)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,e){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:i,samples:n}=e;if(i.type!==vi||"NONE"!==this.closedCaptionsForLevel(i))for(let t=0;t<n.length;t++){const e=n[t].bytes;if(e){this.cea608Parser1||this.initCea608Parsers();const i=this.extractCea608Data(e);this.cea608Parser1.addData(n[t].pts,i[0]),this.cea608Parser2.addData(n[t].pts,i[1])}}}onBufferAppended(t,e){if(this.config.renderTextTracksNatively){var i;const{type:t,timeRanges:n}=e;if("video"===t&&null!=(i=n[t])&&i.length){const{captionsTracks:t,cueCache:e}=this;Object.keys(e).forEach(i=>{var n;const r=null==(n=t[i])?void 0:n.track;if(r){const t=e[i];for(let e=0;e<t.length;e++)wu(r,t[e])}delete e[i]})}}}onBufferFlushing(t,e){const{startOffset:i,endOffset:n,endOffsetSubtitles:r,type:s}=e,{media:a}=this;if(a&&!(a.currentTime<n)){if(!s||"video"===s){const{captionsTracks:t,cueCache:e}=this;Object.keys(t).forEach(e=>Ou(t[e].track,i,n)),Object.keys(e).forEach(t=>{const r=e[t];for(let t=r.length;t--;){const e=r[t];e.startTime>=i&&e.endTime<=n&&r.splice(t,1)}})}this.config.renderTextTracksNatively&&0===i&&void 0!==r&&this.tracks.forEach(t=>{var e;const n=null==(e=t.trackNode)?void 0:e.track;n&&Ou(n,i,r)})}}extractCea608Data(t){const e=[[],[]],i=31&t[0];let n=2;for(let r=0;r<i;r++){const i=t[n++],r=127&t[n++],s=127&t[n++];if(0===r&&0===s)continue;if(!!(4&i)){const t=3&i;0!==t&&1!==t||(e[t].push(r),e[t].push(s))}}return e}},audioStreamController:class extends ko{constructor(t,e,i){super(t,e,i,"audio-stream-controller",yi),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.nextTrackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(ii.LEVEL_LOADED,this.onLevelLoaded,this),t.on(ii.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(ii.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(ii.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(ii.BUFFER_RESET,this.onBufferReset,this),t.on(ii.BUFFER_CREATED,this.onBufferCreated,this),t.on(ii.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(ii.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(ii.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(ii.FRAG_LOADING,this.onFragLoading,this),t.on(ii.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:t}=this;t&&(super.unregisterListeners(),t.off(ii.LEVEL_LOADED,this.onLevelLoaded,this),t.off(ii.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(ii.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(ii.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(ii.BUFFER_RESET,this.onBufferReset,this),t.off(ii.BUFFER_CREATED,this.onBufferCreated,this),t.off(ii.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(ii.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(ii.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(ii.FRAG_LOADING,this.onFragLoading,this),t.off(ii.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(t,e){const{frag:i,id:n,initPTS:r,timescale:s,trackId:a,timestampOffsets:o}=e;if(n===vi){const t=i.cc,e=this.fragCurrent;if(this.initPTS=o,this.log(`InitPTS for cc: ${t} found from main: ${r/s} (${r}/${s}) trackId: ${a}`),this.mainAnchor=i,this.state===bo){const e=this.waitingData;(!e&&!this.loadingParts||e&&e.frag.cc!==t)&&this.syncWithAnchor(i,null==e?void 0:e.frag)}else!this.hls.hasEnoughToStart&&e&&e.cc!==t?(e.abortRequests(),this.syncWithAnchor(i,e)):this.state===fo&&this.tick()}}getLoadPosition(){var t;return!this.startFragRequested&&this.nextLoadPosition>=0&&!1!==(null==(t=this.switchingTrack)?void 0:t.flushImmediate)?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(t,e){var i;const n=(null==(i=this.mainFragLoading)?void 0:i.frag)||null;if(e&&(null==n?void 0:n.cc)===e.cc)return;const r=(n||t).cc,s=ls(this.getLevelDetails(),r,this.getLoadPosition());s&&(this.log(`Syncing with main frag at ${s.start} cc ${s.cc}`),this.startFragRequested=!1,this.nextLoadPosition=s.start,this.resetLoadingState(),this.state===fo&&this.doTickIdle())}startLoad(t,e){if(!this.levels)return this.startPosition=t,void(this.state=uo);const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),i>0&&-1===t&&!e&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),t=i),this.state=fo,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,e||this.fragmentTracker.hasFragments(this.playlistType)||(this.startFragRequested=!1),this.tick()}doTick(){switch(this.state){case fo:this.doTickIdle();break;case vo:{const{levels:t,trackId:e}=this,i=null==t?void 0:t[e],n=null==i?void 0:i.details;if(n&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(n))break;this.state=bo}break}case mo:this.checkRetryDate();break;case bo:{const t=this.waitingData;if(t){const{frag:e,part:i,cache:n,complete:r}=t,s=this.mainAnchor;if(void 0!==this.initPTS[e.cc]){this.waitingData=null,this.state=po;const t={frag:e,part:i,payload:n.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(t),r&&super._handleFragmentLoadComplete(t)}else s&&s.cc!==t.frag.cc&&this.syncWithAnchor(s,t.frag)}else this.state=fo}}this.onTickEnd()}resetLoadingState(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:t}=this;null!=t&&t.readyState&&(this.lastCurrentTime=t.currentTime,this.checkFragmentChanged())}doTickIdle(){var t;const{hls:e,levels:i,media:n,trackId:r}=this,s=e.config;if(!this.buffering||!n&&!this.primaryPrefetch&&(this.startFragRequested||!s.startFragPrefetch)||null==i||!i[r])return;const a=i[r],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o))return this.state=vo,void(this.startFragRequested=!1);const l=this.getBufferOutput();this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,Ei));const h=this.getFwdBufferInfo();if(null===h)return;if(!this.switchingTrack&&this._streamEnded(h,o))return e.trigger(ii.BUFFER_EOS,{type:"audio"}),void(this.state=Eo);const c=h.len,u=e.maxBufferLength,d=o.fragments,f=d[0].start,g=this.getLoadPosition(),p=this.flushing||this.switchingTrack&&!this.switchingTrack.flushImmediate?g:h.end;if(this.switchingTrack&&n){const t=g;o.PTSKnown&&t<f&&t>=this.timelineOffset&&(h.end>f||h.nextStart)&&(this.log(`Alt audio track ahead of main track, seek to start of alt audio track ${t} -> ${f} + 0.05`),n.currentTime=f+.05)}if(c>=u&&!this.switchingTrack&&p<d[d.length-1].start)return;let m=this.getNextFragment(p,o);if(m&&this.isLoopLoading(m,p)&&(m=this.getNextFragmentLoopLoading(m,o,h,vi,u)),!m)return void(this.bufferFlushed=!0);if(this.exceedsMaxBuffer(h,u,m))return;let v=(null==(t=this.mainFragLoading)?void 0:t.frag)||null;if(!this.audioOnly&&this.startFragRequested&&v&&ki(m)&&!m.endList&&(!o.live||!this.loadingParts&&p<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(v)===Ls&&(this.mainFragLoading=v=null),v&&ki(v))){if(m.start>v.end){const t=this.fragmentTracker.getFragAtPos(p,vi);t&&t.end>v.end&&(v=t,this.mainFragLoading={frag:t,targetBufferTime:null})}if(m.start>v.end)return}this.loadFragment(m,a,p)}onMediaDetaching(t,e){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(t,e)}onAudioTracksUpdated(t,{audioTracks:e}){this.resetTransmuxer(),this.levels=e.map(t=>new Hr(t))}onAudioTrackSwitching(t,e){const i=!!e.url;this.trackId=e.id;const{fragCurrent:n}=this;n&&(n.abortRequests(),this.removeUnbufferedFrags(n.start)),this.resetLoadingState(),i?(this.switchingTrack=e,e.flushImmediate||(this.nextTrackId=e.id,this.nextLevelSwitch()),this.flushAudioIfNeeded(e),this.state!==uo&&(this.setInterval(100),this.state=fo,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=e,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(t,e){this.mainDetails=e.details;const i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(ii.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(t,e){var i;const{levels:n}=this,{details:r,id:s,groupId:a,track:o}=e;if(!n)return void this.warn(`Audio tracks reset while loading track ${s} "${o.name}" of "${a}"`);const l=this.mainDetails;if(!l||r.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=e,void(this.state!==uo&&(this.state=vo));this.cachedTrackLoadedData=null,this.log(`Audio track ${s} "${o.name}" of "${a}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const h=n[s];let c=0;if(r.live||null!=(i=h.details)&&i.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;var u;if(h.details)c=this.alignPlaylists(r,h.details,null==(u=this.levelLastLoaded)?void 0:u.details);r.alignedSliding||(oo(l,r,this),c=r.fragmentStart)}h.details=r,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(l,c),this.hls.trigger(ii.AUDIO_TRACK_UPDATED,{details:r,id:s,groupId:e.groupId}),this.state!==vo||this.waitForCdnTuneIn(r)||(this.state=fo),this.tick()}_handleFragmentLoadProgress(t){var e;const i=t.frag,{part:n,payload:r}=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 h=l.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(i.start);const c=s.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let u=this.transmuxer;u||(u=this.transmuxer=new Ql(this.hls,yi,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=n?n.index:-1,s=-1!==e,a=new Hs(i.level,i.sn,i.stats.chunkCount,r.byteLength,e,s,i.duration);u.push(r,f,c,"",i,n,h.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 [${h.startSN} ,${h.endSN}],track ${a}`);const{cache:t}=this.waitingData=this.waitingData||{frag:i,part:n,cache:new Ro,complete:!1};t.push(new Uint8Array(r)),this.state!==uo&&(this.state=bo)}}_handleFragmentLoadComplete(t){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(t,e){this.bufferFlushed=this.flushing=!1;const i=e.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(t,e){!this.audioOnly&&e.frag.type===vi&&ki(e.frag)&&(this.mainFragLoading=e,this.state===fo&&this.tick())}onFragBuffered(t,e){const{frag:i,part:n}=e;if(i.type===yi)if(this.fragContextChanged(i))this.warn(`Fragment ${i.sn}${n?" p: "+n.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if(ki(i)){const t=this.switchingTrack;t&&(this.bufferedTrack=t)}this.fragBufferedComplete(i,n),this.media&&this.tick()}else this.audioOnly||i.type!==vi||i.elementaryStreams.video||i.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}getFwdBufferInfo(){const t=this.getBufferOutput();return super.getFwdBufferInfo(t,yi)}getBufferOutput(){return this.mediaBuffer?this.mediaBuffer:this.media}checkFragmentChanged(){const t=this.fragPlaying;if(!this.checkFragPlaying())return!1;const e=this.fragPlaying,i=null==t?void 0:t.level;return e&&e.level===i||(t&&this.cleanupBackBuffer(),this.switchingTrack&&this.completeAudioSwitch(this.switchingTrack)),!0}onError(t,e){var i;if(e.fatal)this.state=To;else switch(e.details){case ei.FRAG_GAP:case ei.FRAG_PARSING_ERROR:case ei.FRAG_DECRYPT_ERROR:case ei.FRAG_LOAD_ERROR:case ei.FRAG_LOAD_TIMEOUT:case ei.KEY_LOAD_ERROR:case ei.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(yi,e);break;case ei.AUDIO_TRACK_LOAD_ERROR:case ei.AUDIO_TRACK_LOAD_TIMEOUT:case ei.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==vo||(null==(i=e.context)?void 0:i.type)!==ci||(this.state=fo);break;case ei.BUFFER_APPEND_NO_PROGRESS:if("audio"!==e.parent)return;e.frag&&(e.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${e.frag.sn} of track ${e.frag.level} as a gap after ${e.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(e.frag));break;case ei.BUFFER_ADD_CODEC_ERROR:case ei.BUFFER_APPEND_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)||this.resetLoadingState();break;case ei.BUFFER_FULL_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case ei.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onBufferFlushing(t,{type:e}){e!==Ti&&(this.flushing=!0)}onBufferFlushed(t,{type:e}){if(e!==Ti){this.flushing=!1,this.bufferFlushed=!0,this.state===Eo&&(this.state=fo);const t=this.getBufferOutput();t&&(this.afterBufferFlushed(t,e),this.tick())}}_handleTransmuxComplete(t){var e;const i="audio",{hls:n}=this,{remuxResult:r,chunkMeta:s}=t,a=this.getCurrentContext(s);if(!a)return void this.resetWhenMissingContext(s);const{frag:o,part:l,level:h}=a,{details:c}=h,{audio:u,text:d,id3:f,initSegment:g}=r;if(this.fragContextChanged(o)||!c)return this.fragmentTracker.removeFragment(o),void(null!=g&&g.tracks&&this.resetTransmuxer());if(this.state=yo,u&&this.switchingTrack&&!this.switchingTrack.flushImmediate){const{config:t}=this,e=t.nextAudioTrackBufferFlushForwardOffset,i=Math.max(this.getLoadPosition()+e,o.start);super.flushMainBuffer(i,Number.POSITIVE_INFINITY,yi)}if(null!=g&&g.tracks){const t=o.initSegment||o;if(this.unhandledEncryptionError(g,o))return;this._bufferInitSegment(h,g.tracks,t,s),n.trigger(ii.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:i,tracks:g.tracks})}if(u){const{startPTS:t,endPTS:e,startDTS:i,endDTS:n}=u;l&&(l.elementaryStreams[Ei]={startPTS:t,endPTS:e,startDTS:i,endDTS:n}),o.setElementaryStreamInfo(Ei,t,e,i,n),this.bufferFragmentData(u,o,l,s)}if(null!=f&&null!=(e=f.samples)&&e.length){const t=Di({id:i,frag:o,details:c},f);n.trigger(ii.FRAG_PARSING_METADATA,t)}if(d){const t=Di({id:i,frag:o,details:c},d);n.trigger(ii.FRAG_PARSING_USERDATA,t)}}_bufferInitSegment(t,e,i,n){if(this.state!==yo)return;if(e.video&&delete e.video,e.audiovideo&&delete e.audiovideo,!e.audio)return;const r=e.audio;r.id=yi;const s=t.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${s}/${r.codec}]`),1===(null==s?void 0:s.split(",").length)&&(r.levelCodec=s),this.hls.trigger(ii.BUFFER_CODECS,e);const a=r.initSegment;if(null!=a&&a.byteLength){const t={type:"audio",frag:i,part:null,chunkMeta:n,parent:i.type,data:a};this.hls.trigger(ii.BUFFER_APPENDING,t)}this.tickImmediate()}loadFragment(t,e,i){const n=this.fragmentTracker.getState(t);var r;if(this.switchingTrack||n===Ss||n===_s)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=bo;const i=this.mainDetails;i&&i.fragmentStart!==e.details.fragmentStart&&oo(i,e.details,this)}else super.loadFragment(t,e,i);else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){if(this.media&&this.bufferedTrack&&t.flushImmediate){const{name:e,lang:i,assocLang:n,characteristics:r,audioCodec:s,channels:a}=this.bufferedTrack;Zr({name:e,lang:i,assocLang:n,characteristics:r,audioCodec:s,channels:a},t,Jr)||(es(t.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=t)}}completeAudioSwitch(t){const{hls:e}=this;this.bufferedTrack=t,this.switchingTrack=null,e.trigger(ii.AUDIO_TRACK_SWITCHED,Oi({},t))}get nextAudioTrack(){return this.nextTrackId}},audioTrackController:class extends Zl{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(ii.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ii.MANIFEST_PARSED,this.onManifestParsed,this),t.on(ii.LEVEL_LOADING,this.onLevelLoading,this),t.on(ii.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(ii.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(ii.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(ii.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ii.MANIFEST_PARSED,this.onManifestParsed,this),t.off(ii.LEVEL_LOADING,this.onLevelLoading,this),t.off(ii.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(ii.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(ii.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:n,details:r}=e,s=this.tracksInGroup[i];if(!s||s.groupId!==n)return void this.warn(`Audio track with id:${i} and group:${n} 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:${n} loaded [${r.startSN}-${r.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,n=this.groupIds;let r=this.currentTrack;if(!i||(null==n?void 0:n.length)!==(null==i?void 0:i.length)||null!=i&&i.some(t=>-1===(null==n?void 0:n.indexOf(t)))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter(t=>is(t.groupId,i));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 i=Qr(e,t,Jr);if(i>-1)r=t[i];else{const t=Qr(e,this.tracks);r=this.tracks[t]}}let n=this.findTrackId(r);-1===n&&r&&(n=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(ii.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==n&&-1===o)this.setAudioTrack(n);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(ii.ERROR,{type:ti.MEDIA_ERROR,details:ei.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:e})}}}onError(t,e){!e.fatal&&e.context&&e.context.type===ci&&e.context.id===this.trackId&&is(e.context.groupId,this.groupIds)&&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)}get nextAudioTrack(){return this.trackId}set nextAudioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t,!1)}setAudioOption(t){const e=this.hls;if(e.config.audioPreference=t,t){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const n=this.currentTrack;if(n&&Zr(t,n,Jr))return n;const r=Qr(t,this.tracksInGroup,Jr);if(r>-1){const e=this.tracksInGroup[r];return this.setAudioTrack(r,"flushImmediate"in t&&t.flushImmediate),e}if(n){let n=e.loadLevel;-1===n&&(n=e.firstAutoLevel);const r=function(t,e,i,n,r){const s=e[n],a=e.reduce((t,e,i)=>{const n=e.uri;return(t[n]||(t[n]=[])).push(i),t},{}),o=a[s.uri];o.length>1&&(n=Math.max.apply(Math,o));const l=s.videoRange,h=s.frameRate,c=s.codecSet.substring(0,4),u=ts(e,n,e=>{if(e.videoRange!==l||e.frameRate!==h||e.codecSet.substring(0,4)!==c)return!1;const n=e.audioGroups,s=i.filter(t=>is(t.groupId,n));return Qr(t,s,r)>-1});return u>-1?u:ts(e,n,e=>{const n=e.audioGroups,s=i.filter(t=>is(t.groupId,n));return Qr(t,s,r)>-1})}(t,e.levels,i,n,Jr);if(-1===r)return null;e.nextLoadLevel=r}if(t.channels||t.audioCodec){const e=Qr(t,i);if(e>-1)return i[e]}}}return null}setAudioTrack(t,e=!0){const i=this.tracksInGroup;if(t<0||t>=i.length)return void this.warn(`Invalid audio track id: ${t}`);this.selectDefaultTrack=!1;const n=this.currentTrack,r=i[t],s=r.details&&!r.details.live;if(t===this.trackId&&r===n&&s)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(ii.AUDIO_TRACK_SWITCHING,Oi(Oi({},r),{},{flushImmediate:e})),s)return;const a=this.switchParams(r.url,null==n?void 0:n.details,r.details);this.loadPlaylist(a)}findTrackId(t){const e=this.tracksInGroup;for(let i=0;i<e.length;i++){const n=e[i];if((!this.selectDefaultTrack||n.default)&&(!t||Zr(t,n,Jr)))return i}if(t){const{name:i,lang:n,assocLang:r,characteristics:s,audioCodec:a,channels:o}=t;for(let t=0;t<e.length;t++){if(Zr({name:i,lang:n,assocLang:r,characteristics:s,audioCodec:a,channels:o},e[t],Jr))return t}for(let i=0;i<e.length;i++){const n=e[i];if(th(t.attrs,n.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<e.length;i++){const n=e[i];if(th(t.attrs,n.attrs,["LANGUAGE"]))return i}}return-1}loadPlaylist(t){super.loadPlaylist();const e=this.currentTrack;this.shouldLoadPlaylist(e)&&es(e.url,this.hls)&&this.scheduleLoading(e,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const i=t.id,n=t.groupId,r=this.getUrlWithDirectives(t.url,e),s=t.details,a=null==s?void 0:s.age;this.log(`Loading audio-track ${i} "${t.name}" lang:${t.lang} group:${n}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${a&&s.live?" age "+a.toFixed(1)+(s.type&&" "+s.type||""):""} ${r}`),this.hls.trigger(ii.AUDIO_TRACK_LOADING,{url:r,id:i,groupId:n,deliveryDirectives:e||null,track:t})}},emeController:tu,cmcdController:class{constructor(t){this.hls=void 0,this.config=void 0,this.media=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.playerState=void 0,this.reporter=void 0,this.playheadLevel=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0,this.setPlayerState(Dc)),this.buffering=!0},this.onPlay=()=>{this.initialized||this.setPlayerState(Ic)},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1,this.setPlayerState(Cc)},this.onPause=()=>{this.media&&!this.media.ended&&this.setPlayerState(wc)},this.onSeeking=()=>{this.initialized&&this.setPlayerState(Pc)},this.onSeeked=()=>{var t;this.initialized&&null!=(t=this.media)&&t.paused&&this.setPlayerState(wc)},this.onRateChange=()=>{this.reporter&&this.media&&this.reporter.update({pr:this.media.playbackRate})},this.applyPlaylistData=t=>{try{this.apply(t,{ot:bc,su:!this.initialized})}catch(t){this.hls.logger.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=t=>{try{const{frag:s,part:a}=t,o=this.hls.levels[s.level],l=this.getObjectType(s,o),h={d:1e3*(a||s).duration,ot:l};if(l===kc||l===Sc||l===_c||null==l&&("main"===s.type||"audio"===s.type)){var e;const t=o.bitrate/1e3;h.br=[t];const{cmcd:n}=this.config,r=null!=(e=null==n?void 0:n.rtpSafetyFactor)?e:5;if(h.rtp=100*Math.round(t*r/100),l===_c||null==l&&"main"===s.type){const t=this.getTopBandwidth()/1e3;Qe(t)&&(h.tb=[t]);const e=this.getLowestBandwidth()/1e3;Qe(e)&&(h.lb=[e])}const a=this.getBufferLength(s);if(Qe(a)){var i;h.bl=[a];const t=(null==(i=this.media)?void 0:i.playbackRate)||1;h.dl=100*Math.round(a/t/100)}this.playheadLevel&&(h.pb=[this.playheadLevel.bitrate/1e3]);const c=this.hls.maxAutoLevel;if(c>=0){const t=this.hls.levels[c];t&&(h.tpb=[t.bitrate/1e3])}}const c=a?this.getNextPart(a):this.getNextFrag(s);null!=c&&c.url&&c.url!==s.url&&(c.byteRange.length>0?h.nor=[(n=c.url,r={r:`${c.byteRange[0]}-${c.byteRange[1]}`},new dh(n,r))]:h.nor=[c.url]),this.apply(t,h)}catch(t){this.hls.logger.warn("Could not generate segment CMCD data.",t)}var n,r},this.recordFragmentResponse=(t,e,i)=>{var n;const{cmcd:r}=this.config,s=null==r||null==(n=r.eventTargets)?void 0:n.some(t=>{var e;return null==(e=t.events)?void 0:e.includes(Gh)});if(this.reporter&&i.loading.first>0&&s)try{this.reporter.recordResponseReceived({request:{url:t},status:e.code,resourceTiming:{startTime:i.loading.start,responseStart:i.loading.first,duration:i.loading.end-i.loading.start,encodedBodySize:i.total}})}catch(t){this.hls.logger.warn("Could not record fragment response 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.registerListeners())}createReporter(){var t,e;const{cmcd:i}=this.config;if(null==i)return;const n=i.version||1;if(this.reporter=new Hc({sid:i.sessionId||this.hls.sessionId,cid:i.contentId,version:n,transmissionMode:!0===i.useHeaders?Fc:Nc,enabledKeys:null!=(t=i.includeKeys)?t:[...n>=Fh?Tc:nc],eventTargets:(null!=(e=i.eventTargets)?e:[]).map(t=>{let{includeKeys:e}=t;return Oi(Oi({},xi(t,qc)),{},{enabledKeys:null!=e?e:Tc})})},i.loader),this.reporter.update({sf:Yc,sta:this.playerState}),i.reporterCallback){const t=this.reporter,e={updateCustomData:e=>{Xc(e)&&t.update(e)},recordCustomEvent:(e,i={})=>{Xc(i)&&t.recordEvent(Vh,Oi({cen:e},i))}};i.reporterCallback(e)}this.reporter.start()}registerListeners(){const t=this.hls;t.on(ii.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ii.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(ii.MEDIA_DETACHED,this.onMediaDetached,this),t.on(ii.MEDIA_ENDED,this.onMediaEnded,this),t.on(ii.ERROR,this.onError,this),t.on(ii.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(ii.LEVEL_SWITCHED,this.onLevelSwitched,this),t.on(ii.BUFFER_APPENDED,this.onBufferInfoChange,this),t.on(ii.BUFFER_FLUSHED,this.onBufferInfoChange,this)}unregisterListeners(){const t=this.hls;t.off(ii.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ii.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(ii.MEDIA_DETACHED,this.onMediaDetached,this),t.off(ii.MEDIA_ENDED,this.onMediaEnded,this),t.off(ii.ERROR,this.onError,this),t.off(ii.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(ii.LEVEL_SWITCHED,this.onLevelSwitched,this),t.off(ii.BUFFER_APPENDED,this.onBufferInfoChange,this),t.off(ii.BUFFER_FLUSHED,this.onBufferInfoChange,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.hls=this.config=null,this.onWaiting=this.onPlay=this.onPlaying=this.onPause=null,this.onSeeking=this.onSeeked=this.onRateChange=this.media=null}onMediaAttaching(t,e){const i=this.media=e.media;this.setPlayerState(this.media.autoplay?Ic:Mc),lo(i,"waiting",this.onWaiting),lo(i,"play",this.onPlay),lo(i,"playing",this.onPlaying),lo(i,"pause",this.onPause),lo(i,"seeking",this.onSeeking),lo(i,"seeked",this.onSeeked),lo(i,"ratechange",this.onRateChange)}onMediaDetached(){const t=this.media;t&&(ho(t,"waiting",this.onWaiting),ho(t,"play",this.onPlay),ho(t,"playing",this.onPlaying),ho(t,"pause",this.onPause),ho(t,"seeking",this.onSeeking),ho(t,"seeked",this.onSeeked),ho(t,"ratechange",this.onRateChange),this.media=null)}onMediaEnded(t,e){this.setPlayerState(Oc)}onManifestLoading(t,e){this.initialized=!1,this.starved=!1,this.buffering=!0,this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.createReporter(),this.media||this.setPlayerState(Mc)}onError(t,e){e.fatal&&(this.setPlayerState(xc),this.reporter&&this.reporter.recordEvent(Uh,{ec:[e.details]}))}onLevelSwitching(t,e){var i;if(!this.reporter)return;const n={br:[e.bitrate/1e3]},r=null==(i=e.details)?void 0:i.fragments[0];r&&(n.ot=this.getObjectType(r,e)),this.reporter.recordEvent($h,n)}onLevelSwitched(t,e){const i=this.hls.levels[e.level];i&&(this.playheadLevel=i)}setPlayerState(t){this.playerState=t,this.reporter&&this.reporter.update({sta:t})}getStreamType(){const t=this.hls.latestLevelDetails;if(t)return t.live?t.partList&&t.canBlockReload?zc:Wc:jc}apply(t,e={}){var i;if(!this.reporter)return;this.reporter.update({mtp:[this.hls.bandwidthEstimate/1e3],pr:null==(i=this.media)?void 0:i.playbackRate,st:this.getStreamType()});const n=e.ot===Lc||e.ot===kc||e.ot===_c;this.starved&&n&&(e.bs=!0,e.su=!0,this.starved=!1),null==e.su&&(e.su=this.buffering);const r=this.reporter.createRequestReport({url:t.url,headers:t.headers},e);t.url=r.url,t.headers=r.headers}getNextFrag(t){var e;const i=null==(e=this.hls.levels[t.level])?void 0:e.details;if(i){const e=t.sn-i.startSN;return i.fragments[e+1]}}getNextPart(t){var e;const{index:i,fragment:n}=t,r=null==(e=this.hls.levels[n.level])||null==(e=e.details)?void 0:e.partList;if(r){const{sn:t}=n;for(let e=r.length-1;e>=0;e--){const n=r[e];if(n.index===i&&n.fragment.sn===t)return r[e+1]}}}getObjectType(t,e){const{type:i}=t;if("subtitle"===i)return Rc;if("initSegment"===t.sn)return Lc;if("audio"===i)return Sc;if("main"===i){if(t.hasStreams){const e=t.elementaryStreams;if(e.audiovideo)return _c;if(e.video)return kc;if(e.audio)return Sc}if(e){const{audioCodec:t,videoCodec:i}=e;if(!this.hls.audioTracks.length){if(t&&i)return _c;if(t)return Sc}if(i)return kc}}}getTopBandwidth(){let t=0;const e=this.hls,i=e.maxAutoLevel,n=i>-1?i+1:e.levels.length;return e.levels.slice(0,n).forEach(e=>{e.bitrate>t&&(t=e.bitrate)}),t>0?t:NaN}getLowestBandwidth(){let t=1/0;const e=this.hls,i=e.maxAutoLevel,n=i>-1?i+1:e.levels.length;return e.levels.slice(0,n).forEach(e=>{e.bitrate<t&&(t=e.bitrate)}),Qe(t)?t:NaN}getBufferLength(t){if(!this.media)return NaN;const e="audio"===t.type?this.hls.audioForwardBufferInfo:this.hls.mainForwardBufferInfo;return e?1e3*e.len:NaN}getEventBufferLength(){if(!this.media)return NaN;const t=this.hls.mainForwardBufferInfo,e=this.hls.audioForwardBufferInfo;if(t&&e)return 1e3*Math.min(t.len,e.len);const i=t||e;return i?1e3*i.len:NaN}onBufferInfoChange(t,e){if(!this.reporter)return;const i=this.getEventBufferLength();Qe(i)&&this.reporter.update({bl:[i]})}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,n){e(t),this.loader.load(t,i,n)}}}createFragmentLoader(){const{fLoader:t}=this.config,e=this.applyFragmentData,i=this.recordFragmentResponse,n=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new n(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,n,r){e(t);const{onSuccess:s}=r;this.loader.load(t,n,Oi(Oi({},r),{},{onSuccess:(e,n,r,a)=>{s(e,n,r,a),i(t.url,e,n)}}))}}}},contentSteeringController:class extends ji{constructor(t){super("content-steering",t.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(ii.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ii.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(ii.MANIFEST_PARSED,this.onManifestParsed,this),t.on(ii.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(ii.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ii.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(ii.MANIFEST_PARSED,this.onManifestParsed,this),t.off(ii.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((t,e)=>(-1===t.indexOf(e.pathwayId)&&t.push(e.pathwayId),t),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(t){this.updatePathwayPriority(t)}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)===us&&i.flags&ps){const t=this.levels;let n=this._pathwayPriority,r=this.pathwayId;if(e.context){const{groupId:i,pathwayId:n,type:s}=e.context;i&&t?r=this.getPathwayForGroupId(i,s,r):n&&(r=n)}r in this.penalizedPathways||(this.penalizedPathways[r]=performance.now()),!n&&t&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),i.resolved=this.pathwayId!==r,i.resolved||e.details===ei.BUFFER_APPEND_ERROR&&!e.fatal||this.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${r} levels: ${t?t.length:t} priorities: ${Wr(n)} penalized: ${Wr(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}getLevelsForPathway(t){return null===this.levels?[]:this.levels.filter(e=>t===e.pathwayId)}updatePathwayPriority(t){let e;this._pathwayPriority=t;const i=this.penalizedPathways,n=performance.now();Object.keys(i).forEach(t=>{n-i[t]>3e5&&delete i[t]});for(let n=0;n<t.length;n++){const r=t[n];if(r in i)continue;if(r===this.pathwayId)return;const s=this.hls.nextLoadLevel,a=this.hls.levels[s];if(e=this.getLevelsForPathway(r),e.length>0){this.log(`Setting Pathway to "${r}"`),this.pathwayId=r,eo(e),this.hls.trigger(ii.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 n=this.getLevelsForPathway(i).concat(this.levels||[]);for(let i=0;i<n.length;i++)if(e===ci&&n[i].hasAudioGroup(t)||e===ui&&n[i].hasSubtitleGroup(t))return n[i].pathwayId;return i}clonePathways(t){const e=this.levels;if(!e)return;const i={},n={};t.forEach(t=>{const{ID:r,"BASE-ID":s,"URI-REPLACEMENT":a}=t;if(e.some(t=>t.pathwayId===r))return;const o=this.getLevelsForPathway(s).map(t=>{const e=new ta(t.attrs);e["PATHWAY-ID"]=r;const s=e.AUDIO&&`${e.AUDIO}_clone_${r}`,o=e.SUBTITLES&&`${e.SUBTITLES}_clone_${r}`;s&&(i[e.AUDIO]=s,e.AUDIO=s),o&&(n[e.SUBTITLES]=o,e.SUBTITLES=o);const l=Zc(t.uri,e["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),h=new Hr({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),Qc(this.audioTracks,i,a,r),Qc(this.subtitleTracks,n,a,r)})}loadSteeringManifest(t){const e=this.hls.config,i=e.loader;let n;this.loader&&this.loader.destroy(),this.loader=new i(e);try{n=new self.URL(t)}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${t}`)}if("data:"!==n.protocol){const t=0|(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate);Nr(n,"_HLS_pathway",this.pathwayId),Nr(n,"_HLS_throughput",""+t)}const r={type:gi,responseType:"json",url:n.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,r)=>{this.log(`Loaded steering manifest: "${n}"`);const s=t.data;if(1!==(null==s?void 0: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,n).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 h={steeringManifest:s,url:n.toString()};this.hls.trigger(ii.STEERING_MANIFEST_LOADED,h),l&&this.updatePathwayPriority(l)},onError:(t,e,i,n)=>{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){const t=this.loader;if("function"==typeof(null==t?void 0:t.getResponseHeader)){const e=t.getResponseHeader("Retry-After");e&&(r=1e3*parseFloat(e))}return void this.log(`Steering manifest ${e.url} rate limited`)}this.scheduleRefresh(this.uri||e.url,r)},onTimeout:(t,e,i)=>{this.log(`Timeout loading steering manifest (${e.url})`),this.scheduleRefresh(this.uri||e.url)}};this.log(`Requesting steering manifest: ${n}`),this.loader.load(r,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)}},iframeController:class extends ji{constructor(t,e){var i;super("iframes",t.logger),this.hls=void 0,this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances=void 0,this.instanceCounter=0,Qu||(i=e,Qu=class extends i{constructor(t,e,i,n){t.streamController||(t.streamController=Wu),super(t),this._url=e,this.streamController.setInitPts(i),this.streamController.initDetails=n}loadSource(){}loadMediaAt(t,e=Xu){if(t<0)return;const i=Oi(Oi({},Xu),e);this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t,i)}}),Zu||(Zu=function(t){return class extends t{constructor(t,e,i,n){t.cmcdController=void 0,t.emeController=void 0,t.streamController||(t.streamController=zu),t.capLevelController=void 0,t.bufferController=void 0,super(t,e,i,n)}attachImage(t){this.streamController.image=t}detachImage(){this.streamController.image=void 0}loadSource(){}attachMedia(){throw new Error(qu)}detachMedia(){}recoverMediaError(){}transferMedia(){return null}loadMediaAt(t){if(t<0)return null;this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t)}}}(Qu)),this.hls=t,this.iframeInstances=[],this.registerListeners()}registerListeners(){const t=this.hls;t&&(t.on(ii.MANIFEST_LOADING,this.clearAsset,this),t.on(ii.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(ii.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(ii.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(ii.FRAG_BUFFERED,this.onFragBuffered,this),t.on(ii.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off(ii.MANIFEST_LOADING,this.clearAsset,this),t.off(ii.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(ii.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(ii.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(ii.FRAG_BUFFERED,this.onFragBuffered,this),t.off(ii.DESTROYING,this.onDestroying,this))}clearAsset(){this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances.forEach(t=>t.destroy()),this.iframeInstances.length=0}onDestroying(){this.unregisterListeners(),this.clearAsset(),this.hls=void 0}onManifestLoaded(t,e){this.stats=e.stats,this.variableList=e.variableList}onLevelsUpdated(t,{levels:e}){var i;const n=null==(i=this.hls)?void 0:i.pathwayPriority;e.length&&n&&this.iframeInstances.forEach(t=>{t.pathwayPriority=n})}onInitPtsFound(t,{id:e,timestampOffsets:i}){e===vi&&(this.initPTS=i)}onFragBuffered(t,e){var i;const n=this.hls;n&&n.hasEnoughToStart&&((null==(i=n.mainForwardBufferInfo)?void 0:i.len)||0)>10&&this.iframeInstances.forEach(t=>{var e;t.loadingEnabled||t.startLoad((null==(e=this.hls)||null==(e=e.media)?void 0:e.currentTime)||0)})}createIFramePlayer(t){var e;return this.createInstance(Qu,null==(e=this.hls)?void 0:e.iframeVariants,t)}createImageIFramePlayer(t){var e;const i=null==(e=this.hls)?void 0:e.iframeVariants.filter(t=>t.imageCodec);return this.createInstance(Zu,i,t,"image-")}createInstance(t,e,i,n){const{hls:r}=this;if(!r)return null;const{url:s,userConfig:a,latestLevelDetails:o,loadLevelObj:l,loadLevel:h,bandwidthEstimate:c,sessionId:u}=r,{stats:d,variableList:f}=this;if(null==e||!e.length||!d||!s)return null;const g=`${n||""}iframe-player-${this.instanceCounter++}`,p=r.levels,m=l||p[h],v=ns(m,a.videoPreference),y=(null==m?void 0:m.pathwayId)||".",A=new t(Oi(Oi({},a),{},{loggerId:g,primarySessionId:u,videoPreference:v,abrEwmaDefaultEstimate:c,streamController:void 0,audioStreamController:void 0,audioTrackController:void 0,subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,id3TrackController:void 0,fpsController:void 0,gapController:void 0,iframeController:void 0,cmcd:void 0,interstitialsController:void 0,backBufferLength:1/0,maxMaxBufferLength:1,capLevelToPlayerSize:!0,enableWorker:!1,autoStartLoad:!1,startFragPrefetch:!1,testBandwidth:!1,progressive:!1},i),s,this.initPTS,o);return this.iframeInstances=this.iframeInstances.filter(t=>!t.url),this.iframeInstances.push(A),A.trigger(ii.MANIFEST_LOADED,{levels:e,contentSteering:{uri:"",pathwayId:y},sessionKeys:null,audioTracks:[],iframeVariants:[],sessionData:null,startTimeOffset:null,stats:d,networkDetails:null,url:s,variableList:f}),A}},interstitialsController:class extends ji{constructor(t,e){super("interstitials",t.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.bufferPastEdge=!1,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const t=this.currentTime;if(void 0===t||this.playbackDisabled||!this.schedule)return;const e=t-this.timelinePos;if(Math.abs(e)<1/7056e5)return;const i=e<=-.01;-1!==this.timelinePos||this.effectivePlayingItem||this.checkStart(),this.timelinePos=t,this.bufferedPos=t;const n=this.playingItem;if(!n)return void this.checkBuffer();if(i){this.schedule.resetErrorsInRange(t,t-e)&&this.updateSchedule(!0)}if(this.checkBuffer(),i&&t<n.start||t>=n.end){var r;const e=this.findItemIndex(n);let s=this.schedule.findItemIndexAtTime(t);if(-1===s&&(s=e+(i?-1:1),this.log(`seeked ${i?"back ":""}to position not covered by schedule ${t} (resolving from ${e} to ${s})`)),!this.isInterstitial(n)&&null!=(r=this.media)&&r.paused&&(this.shouldPlay=!1),!i&&s>e){const t=this.schedule.findJumpRestrictedIndex(e+1,s);if(t>e)return void this.setSchedulePosition(t)}return void this.setSchedulePosition(s)}const s=this.playingAsset;if(!s){if(this.playingLastItem&&this.isInterstitial(n)){const e=n.event.assetList[0];e&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(t,e))}return}const a=s.timelineStart,o=s.duration||0;var l;(i&&t<a||t>=a+o)&&(null!=(l=n.event)&&l.appendInPlace&&(this.clearAssetPlayers(n.event,n),this.flushFrontBuffer(t)),this.setScheduleToAssetAtTime(t,s))},this.onTimeupdate=()=>{const t=this.currentTime;if(void 0===t||this.playbackDisabled)return;if(-1!==this.timelinePos||this.effectivePlayingItem||this.checkStart(),!(t>this.timelinePos))return;this.timelinePos=t,t>this.bufferedPos&&this.checkBuffer();const e=this.playingItem;if(!e||this.playingLastItem)return;if(t>=e.end){this.timelinePos=e.end;const t=this.findItemIndex(e);this.setSchedulePosition(t+1)}const i=this.playingAsset;if(!i)return;t>=i.timelineStart+(i.duration||0)&&this.setScheduleToAssetAtTime(t,i)},this.onScheduleUpdate=(t,e)=>{const i=this.schedule;if(!i)return;const n=this.playingItem,r=i.events||[],s=i.items||[],a=i.durations,o=t.map(t=>t.identifier),l=!(!r.length&&!o.length);(l||e)&&this.log(`INTERSTITIALS_UPDATED (${r.length}): ${r}\nSchedule: ${s.map(t=>cd(t))} pos: ${this.timelinePos}`),o.length&&this.log(`Removed events ${o}`);let h=null,c=null;n&&(h=this.updateItem(n,this.timelinePos),this.itemsMatch(n,h)?this.playingItem=h:this.waitingItem=null),this.waitingItem=this.updateItem(this.waitingItem);const u=this.bufferingItem;if(u&&(c=this.updateItem(u,this.bufferedPos),this.itemsMatch(u,c)?this.bufferingItem=c:u.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(u.event,null))),t.forEach(t=>{t.assetList.forEach(t=>{this.clearAssetPlayer(t.identifier,null)})}),this.playerQueue.forEach(t=>{if(t.interstitial.appendInPlace){const e=t.assetItem.timelineStart,i=t.timelineOffset-e;if(i)try{t.timelineOffset=e}catch(n){Math.abs(i)>Ju&&this.warn(`${n} ("${t.assetId}" ${t.timelineOffset}->${e})`)}}}),l||e){if(this.hls.trigger(ii.INTERSTITIALS_UPDATED,{events:r.slice(0),schedule:s.slice(0),durations:a,removedIds:o}),this.isInterstitial(n)&&o.indexOf(n.event.identifier)>-1)return this.warn(`Interstitial "${n.event.identifier}" removed while playing`),void this.primaryFallback(n.event);n&&this.trimInPlace(h,n),u&&c!==h&&this.trimInPlace(c,u),this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=e,this.assetListLoader=new ud(t),this.schedule=new hd(this.onScheduleUpdate,t.logger),this.registerListeners()}registerListeners(){const t=this.hls;t&&(t.on(ii.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(ii.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(ii.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(ii.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ii.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(ii.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(ii.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on(ii.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(ii.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on(ii.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on(ii.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on(ii.BUFFER_APPENDED,this.onBufferAppended,this),t.on(ii.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(ii.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on(ii.MEDIA_ENDED,this.onMediaEnded,this),t.on(ii.ERROR,this.onError,this),t.on(ii.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off(ii.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(ii.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(ii.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(ii.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ii.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(ii.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(ii.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off(ii.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(ii.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off(ii.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off(ii.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off(ii.BUFFER_CODECS,this.onBufferCodecs,this),t.off(ii.BUFFER_APPENDED,this.onBufferAppended,this),t.off(ii.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(ii.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off(ii.MEDIA_ENDED,this.onMediaEnded,this),t.off(ii.ERROR,this.onError,this),t.off(ii.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var t;null==(t=this.getBufferingPlayer())||t.resumeBuffering()}pauseBuffering(){var t;null==(t=this.getBufferingPlayer())||t.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const t=this.primaryMedia||this.media;t&&this.removeMediaListeners(t)}removeMediaListeners(t){ho(t,"play",this.onPlay),ho(t,"pause",this.onPause),ho(t,"seeking",this.onSeeking),ho(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,e){const i=this.media=e.media;lo(i,"seeking",this.onSeeking),lo(i,"timeupdate",this.onTimeupdate),lo(i,"play",this.onPlay),lo(i,"pause",this.onPause)}onMediaAttached(t,e){const i=this.effectivePlayingItem,n=this.detachedData;if(this.detachedData=null,null===i)this.checkStart();else if(!n){this.clearScheduleState();const t=this.findItemIndex(i);this.setSchedulePosition(t)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(t,e){const i=!!e.transferMedia,n=this.media;if(this.media=null,!i&&(n&&this.removeMediaListeners(n),this.detachedData)){const t=this.getBufferingPlayer();t&&(this.log(`Removing schedule state for detachedData and ${t}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,t.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const t=this,e=()=>t.bufferingItem||t.waitingItem,i=e=>e?t.getAssetPlayer(e.identifier):e,n=(e,n,s,a,o)=>{if(e){let l=e[n].start;const h=e.event;if(h){if("playout"===n||h.timelineOccupancy!==td.Point){const t=i(s);(null==t?void 0:t.interstitial)===h&&(l+=t.assetItem.startOffset+t[o])}}else{l+=("bufferedPos"===a?r():t[a])-e.start}return l}return 0},r=()=>{const e=t.bufferedPos;return e===Number.MAX_VALUE?s("primary"):Math.max(e,0)},s=e=>{var i,n;return null!=(i=t.primaryDetails)&&i.live?t.primaryDetails.edge:(null==(n=t.schedule)?void 0:n.durations[e])||0},a=(e,r)=>{var s,a;const o=t.effectivePlayingItem;if(null!=o&&null!=(s=o.event)&&s.restrictions.skip||!t.schedule)return;t.log(`seek to ${e} "${r}"`);const l=t.effectivePlayingItem,h=t.schedule.findItemIndexAtTime(e,r),c=null==(a=t.schedule.items)?void 0:a[h],u=t.getBufferingPlayer(),d=null==u?void 0:u.interstitial,f=null==d?void 0:d.appendInPlace,g=l&&t.itemsMatch(l,c);if(l&&(f||g)){const s=i(t.playingAsset),a=(null==s?void 0:s.media)||t.primaryMedia;if(a){const i="primary"===r?a.currentTime:n(l,r,t.playingAsset,"timelinePos","currentTime"),o=e-i,h=(f?i:a.currentTime)+o;if(h>=0&&(!s||f||h<=s.duration))return void(a.currentTime=h)}}if(c){let i=e;if("primary"!==r){const t=e-c[r].start;i=c.start+t}const n=!t.isInterstitial(c);if(t.isInterstitial(l)&&!l.event.appendInPlace||!n&&!c.event.appendInPlace){if(l){const s=t.findItemIndex(l);if(h>s){const e=t.schedule.findJumpRestrictedIndex(s+1,h);if(e>s)return void t.setSchedulePosition(e)}let a=0;if(n)t.timelinePos=i,t.checkBuffer();else{const t=c.event.assetList,i=e-(c[r]||c).start;for(let e=t.length;e--;){const n=t[e];if(n.duration&&i>=n.startOffset&&i<n.startOffset+n.duration){a=e;break}}}t.setSchedulePosition(h,a)}}else{const e=t.media||(f?null==u?void 0:u.media:null);e&&(e.currentTime=i)}}},o=()=>{const i=t.effectivePlayingItem;if(t.isInterstitial(i))return i;const n=e();return t.isInterstitial(n)?n:null},l={get bufferedEnd(){const i=e(),r=t.bufferingItem;var s;return r&&r===i&&(n(r,"playout",t.bufferingAsset,"bufferedPos","bufferedEnd")-r.playout.start||(null==(s=t.bufferingAsset)?void 0:s.startOffset))||0},get currentTime(){const e=o(),i=t.effectivePlayingItem;return i&&i===e?n(i,"playout",t.effectivePlayingAsset,"timelinePos","currentTime")-i.playout.start:0},set currentTime(e){const i=o(),n=t.effectivePlayingItem;n&&n===i&&a(e+n.playout.start,"playout")},get duration(){const t=o();return t?t.playout.end-t.playout.start:0},get assetPlayers(){var e;const i=null==(e=o())?void 0:e.event.assetList;return i?i.map(e=>t.getAssetPlayer(e.identifier)):[]},get playingIndex(){var e;const i=null==(e=o())?void 0:e.event;return i&&t.effectivePlayingAsset?i.findAssetIndex(t.effectivePlayingAsset):-1},get scheduleItem(){return o()}};return this.manager={get events(){var e;return(null==(e=t.schedule)||null==(e=e.events)?void 0:e.slice(0))||[]},get schedule(){var e;return(null==(e=t.schedule)||null==(e=e.items)?void 0:e.slice(0))||[]},get interstitialPlayer(){return o()?l:null},get playerQueue(){return t.playerQueue.slice(0)},get bufferingAsset(){return t.bufferingAsset},get bufferingItem(){return e()},get bufferingIndex(){const i=e();return t.findItemIndex(i)},get playingAsset(){return t.effectivePlayingAsset},get playingItem(){return t.effectivePlayingItem},get playingIndex(){const e=t.effectivePlayingItem;return t.findItemIndex(e)},primary:{get bufferedEnd(){return r()},get currentTime(){const e=t.timelinePos;return e>0?e:0},set currentTime(t){a(t,"primary")},get duration(){return s("primary")},get seekableStart(){return t.seekableStart}},integrated:{get bufferedEnd(){return n(e(),"integrated",t.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return n(t.effectivePlayingItem,"integrated",t.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(t){a(t,"integrated")},get duration(){return s("integrated")},get seekableStart(){return((e,i)=>{var n;if(0!==e&&"primary"!==i&&null!=(n=t.schedule)&&n.length){var r;const n=t.schedule.findItemIndexAtTime(e),s=null==(r=t.schedule.items)?void 0:r[n];if(s)return e+(s[i].start-s.start)}return e})(t.seekableStart,"integrated")}},skip:()=>{const e=t.effectivePlayingItem,i=null==e?void 0:e.event;if(i&&!i.restrictions.skip){const n=t.findItemIndex(e);if(i.appendInPlace){const t=e.playout.start+e.event.duration;a(t+.001,"playout")}else t.advanceAfterAssetEnded(i,n,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var t;const e=this.playingItem,i=null==(t=this.schedule)?void 0:t.items;return!!(this.playbackStarted&&e&&i)&&this.findItemIndex(e)===i.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var t,e;if(null===this.mediaSelection)return;const i=this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&!i.event.appendInPlace)return;let n=this.media;!n&&null!=(t=this.bufferingItem)&&null!=(t=t.event)&&t.appendInPlace&&(n=this.primaryMedia);const r=null==(e=n)?void 0:e.currentTime;return void 0!==r&&Qe(r)?r:void 0}get primaryMedia(){var t;return this.media||(null==(t=this.detachedData)?void 0:t.media)||null}isInterstitial(t){return!(null==t||!t.event)}retreiveMediaSource(t,e){const i=this.getAssetPlayer(t);i&&this.transferMediaFromPlayer(i,e)}transferMediaFromPlayer(t,e){const i=t.interstitial.appendInPlace,n=t.media;if(i&&n===this.primaryMedia){if(this.bufferingAsset=null,(!e||this.isInterstitial(e)&&!e.event.appendInPlace)&&e&&n)return void(this.detachedData={media:n});const i=t.transferMedia();this.log(`transfer MediaSource from ${t} ${Wr(i)}`),this.detachedData=i}else e&&n&&(this.shouldPlay||(this.shouldPlay=!n.paused))}transferMediaTo(t,e){var i,n;if(t.media===e)return;let r=null;const s=this.hls,a=t!==s,o=a&&t.interstitial.appendInPlace,l=null==(i=this.detachedData)?void 0:i.mediaSource;let h;if(s.media)o&&(r=s.transferMedia(),this.detachedData=r),h="Primary";else{const t=this.getBufferingPlayer();t?(r=t.transferMedia(),this.detachedData=r,h=`${t}`):h=l?"detached MediaSource":"detached media"}if(!r)if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${Wr(r)}`);else if(!this.detachedData||s.media===e){const t=this.playerQueue;t.length>1&&t.forEach(t=>{if(a&&t.interstitial.appendInPlace!==o){const e=t.interstitial;this.clearInterstitial(t.interstitial,null),e.appendInPlace=!1,e.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${e}`)}}),this.hls.detachMedia(),this.detachedData={media:e}}const c=r&&"mediaSource"in r&&"closed"!==(null==(n=r.mediaSource)?void 0:n.readyState);if(this.log(`${c?"transfering MediaSource":"attaching media"} to ${a?t:"Primary"} from ${h} (media.currentTime: ${e.currentTime})`),!c&&!a)return void t.attachMedia(e);const u=c&&r?r:{media:e},d=this.schedule;if(d){const e=a&&t.assetId===d.assetIdAtEnd;u.overrides={duration:d.duration,endOfStream:!a||e||!1===t.appendInPlace}}if(!c&&o){const e=t,i=e.assetItem.timelineStart;if(i){const t=e.hls,n=Math.max(this.timelinePos-i,Number.EPSILON);t.startPosition!==n&&(this.log(`Set ${e} startPosition: ${n}`),t.config.startPosition=n,t.loadingEnabled&&t.startLoad(n))}}t.attachMedia(u)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const t=this.schedule,e=null==t?void 0:t.events,i=this.hls;if(!e||this.playbackDisabled||!this.media||!i)return;-1===this.bufferedPos&&(this.bufferedPos=0);const n=this.timelinePos,r=this.effectivePlayingItem;if(-1===n){if(!i.loadingEnabled)return void this.log("waiting for startLoad( <startPosition> )");const n=i.startPosition;if(this.timelinePos=n,0===e.length)this.setSchedulePosition(0);else if(e[0].cue.pre){this.log(fd("checkStart (preroll)",n));const i=t.findEventIndex(e[0].identifier);this.setSchedulePosition(i)}else if(n>=0||!this.primaryLive){this.log(fd("checkStart",n));const e=this.timelinePos=n>0?n:0,i=t.findItemIndexAtTime(e);this.setSchedulePosition(i)}else 0===i.liveSyncPosition?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(r&&!this.playingItem){this.log(fd("checkStart (playing item)",r.start));const e=t.findItemIndex(r);this.setSchedulePosition(e)}}advanceAssetBuffering(t,e){const i=t.event,n=i.findAssetIndex(e),r=sd(i,n);if(i.isAssetPastPlayoutLimit(r)){if(this.schedule){var s;const e=this.getNextItemIndex(t,!0),i=null==(s=this.schedule.items)?void 0:s[e];i&&this.bufferedToItem(i)}}else this.bufferedToEvent(t,r)}livePrerollResumption(t,e){if(t.cue.pre&&this.primaryLive&&!Qe(t.resumeOffset)&&this.hls){const t=this.getLiveStartPos();if(e){const e=this.getBufferingPlayer();return t+(null!=e&&e.interstitial.cue.pre?e.remaining:0)}return t}}getNextItemIndex(t,e){if(this.schedule){const i=this.livePrerollResumption(t.event,e);if(void 0!==i)return this.log(`find next item index @${i}`),this.schedule.findItemIndexAtTime(i)}return this.findItemIndex(t)+1}advanceAfterAssetEnded(t,e,i){const n=sd(t,i);if(t.isAssetPastPlayoutLimit(n)){if(this.schedule){const i=this.schedule.items;if(i){const n=i[e],r=n.event?this.getNextItemIndex(n):e+1;if(r>=i.length)return void this.setSchedulePosition(-1);const s=t.resumeTime;this.timelinePos<s&&(this.log(fd("advanceAfterAssetEnded",s)),this.timelinePos=s,t.appendInPlace&&!i[r].event&&this.hls.startLoad(s+.01),this.checkBuffer(this.bufferedPos<s)),this.setSchedulePosition(r)}}}else{if(t.appendInPlace){const e=t.assetList[n];e&&this.advanceInPlace(e.timelineStart)}this.setSchedulePosition(e,n)}}setScheduleToAssetAtTime(t,e){const i=this.schedule;if(!i)return;const n=e.parentIdentifier,r=i.getEvent(n);if(r){const e=i.findEventIndex(n),s=i.findAssetIndex(r,t);this.advanceAfterAssetEnded(r,e,s-1)}}setSchedulePosition(t,e){var i;const n=null==(i=this.schedule)?void 0:i.items;if(!n||this.playbackDisabled)return;const r=t>=0?n[t]:null;this.log(`setSchedulePosition ${t}, ${e} (${r?cd(r):r}) pos: ${this.timelinePos}`);const s=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(s)){const i=s.event,c=this.playingAsset,u=null==c?void 0:c.identifier,d=u?this.getAssetPlayer(u):null;if(d&&u&&(!this.eventItemsMatch(s,r)||void 0!==e&&u!==i.assetList[e].identifier)){var o;const e=i.findAssetIndex(c);if(this.log(`INTERSTITIAL_ASSET_ENDED ${e+1}/${i.assetList.length} ${ad(c)}`),this.endedAsset=c,this.playingAsset=null,this.hls.trigger(ii.INTERSTITIAL_ASSET_ENDED,{asset:c,assetListIndex:e,event:i,schedule:n.slice(0),scheduleIndex:t,player:d}),s!==this.playingItem)return void(this.itemsMatch(s,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(i,this.findItemIndex(this.playingItem),e));this.retreiveMediaSource(u,r),!d.media||null!=(o=this.detachedData)&&o.mediaSource||d.detachMedia()}if(!this.eventItemsMatch(s,r)&&(this.endedItem=s,this.playingItem=this.waitingItem=null,this.log(`INTERSTITIAL_ENDED ${i} ${cd(s)}`),i.hasPlayed=!0,this.hls.trigger(ii.INTERSTITIAL_ENDED,{event:i,schedule:n.slice(0),scheduleIndex:t}),i.cue.once&&this.hls)){var l;this.updateSchedule();const t=null==(l=this.schedule)?void 0:l.items;if(r&&t){const o=this.findItemIndex(r),l=this.livePrerollResumption(i);if(void 0!==l){let e=l;const r=this.getNextItemIndex(s);if(!this.isInterstitial(n[r])){var h;const t=null==(h=this.primaryDetails)?void 0:h.fragments;if(i.snapOptions.in&&t){const i=ss(null,t,l);i&&(e=Math.min(Math.max(n[r].start,nd(e,i)),n[r].end))}}if(this.log(fd("live join (preroll)",e)),this.timelinePos=e,r!==o&&(r||0===r))return void this.advanceSchedule(r,t,void 0,s,a)}this.advanceSchedule(o,t,e,s,a)}return}}this.advanceSchedule(t,n,e,s,a)}advanceSchedule(t,e,i,n,r){const s=this.schedule;if(!s)return;const a=e[t]||null,o=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(e=>{const i=e.interstitial,n=s.findEventIndex(i.identifier);(n<t||n>t+1)&&this.clearInterstitial(i,a)}),this.isInterstitial(a)){this.timelinePos=Math.min(Math.max(this.timelinePos,a.start),a.end);const r=a.event;if(void 0===i){const e=sd(r,(i=r.cue.pre?0:s.findAssetIndex(r,this.timelinePos))-1);if(r.isAssetPastPlayoutLimit(e)||r.appendInPlace&&this.timelinePos===a.end)return void this.advanceAfterAssetEnded(r,t,i);i=e}const l=this.waitingItem;this.assetsBuffered(a,o)||this.setBufferingItem(a);let h=this.preloadAssets(r,i);if(this.eventItemsMatch(a,l||n)||(this.waitingItem=a,this.log(`INTERSTITIAL_STARTED ${cd(a)} ${r.appendInPlace?"append in place":""}`),r.hasPlayed=!1,this.hls.trigger(ii.INTERSTITIAL_STARTED,{event:r,schedule:e.slice(0),scheduleIndex:t})),!r.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${r}`);if(r.assetListLoader&&(r.assetListLoader.destroy(),r.assetListLoader=void 0),!o)return void this.log(`Waiting for attachMedia to start Interstitial ${r}`);this.waitingItem=this.endedItem=null,this.playingItem=a;const c=r.assetList[i];if(!c)return void this.advanceAfterAssetEnded(r,t,i||0);if(h||(h=this.getAssetPlayer(c.identifier)),null===h||h.destroyed){const t=r.assetList.length;this.warn(`asset ${i+1}/${t} player destroyed ${r}`),h=this.createAssetPlayer(r,c,i),h.loadSource()}if(!this.eventItemsMatch(a,this.bufferingItem)&&r.appendInPlace&&this.isAssetBuffered(c))return;this.startAssetPlayer(h,i,e,t,o),this.shouldPlay&&dd(h.media)}else a?(this.resumePrimary(a,t,n),this.shouldPlay&&dd(this.hls.media)):r&&this.isInterstitial(n)&&(this.endedItem=null,this.playingItem=n,n.event.appendInPlace||this.attachPrimary(s.durations.primary,null))}get playbackDisabled(){return!1===this.hls.config.enableInterstitialPlayback}get primaryDetails(){var t;return null==(t=this.mediaSelection)?void 0:t.main.details}get primaryLive(){var t;return!(null==(t=this.primaryDetails)||!t.live)}resumePrimary(t,e,i){var n,r;this.playingItem=t,this.playingAsset=this.endedAsset=null,this.waitingItem=null,this.bufferedToItem(t),this.endedItem=null,this.log(`resuming ${cd(t)}`);let s=this.timelinePos;if(null!=(n=this.detachedData)&&n.mediaSource?this.primaryLive&&this.startLoadingPrimaryAt(s):((s<t.start||s>=t.end||s<this.seekableStart)&&(s=this.getPrimaryResumption(t,e),this.log(fd("resumePrimary",s)),this.timelinePos=s),this.attachPrimary(s,t)),!i)return;const a=null==(r=this.schedule)?void 0:r.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${cd(t)}`),this.hls.trigger(ii.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:e}),this.checkBuffer())}get seekableStart(){var t;return this.primaryLive&&(null==(t=this.primaryDetails)?void 0:t.fragmentStart)||0}getPrimaryResumption(t,e,i){const n=t.start;if(this.primaryLive){if(0===e)return this.hls.startPosition;const t=this.endedItem||this.playingItem,r=null!=t&&t.event?this.livePrerollResumption(t.event,i):void 0;if(void 0!==r)return r;const s=this.primaryDetails;if(s){const{fragmentStart:t,edge:e}=s;if(n<t||n>e&&!i){const i=this.hls.liveSyncPosition;return this.log(`primary resumption out of bounds (${n} [${t}-${e}]) snapping to liveSync ${i}`),i||t}}}return this.log(`primary resumption itemStart: ${n}`),n}getLiveStartPos(){var t;const e=this.hls.startPosition,i=this.hls.liveSyncPosition||0,n=3*((null==(t=this.primaryDetails)?void 0:t.targetduration)||10);return-1===e||i&&i-e<n?i||0:e}isAssetBuffered(t){const e=this.getAssetPlayer(t.identifier);if(null!=e&&e.hls)return e.hls.bufferedToEnd;return js.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=t.timelineStart+(t.duration||0)}attachPrimary(t,e,i){e?this.setBufferingItem(e):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const n=this.primaryMedia;if(!n)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,n),i&&this.startLoadingPrimaryAt(t,i)),i||(this.log(fd("attachPrimary",t)),this.timelinePos=t,this.startLoadingPrimaryAt(t,i))}startLoadingPrimaryAt(t,e){const i=this.hls,{loadingEnabled:n,bufferingEnabled:r,startPosition:s}=i,a=!e&&i.hasEnoughToStart;if(this.log(`Start loading primary @${t} bufferedPos: ${this.bufferedPos} instructToSeek: ${a} startPosition: ${s} loadingEnabled: ${n} bufferingEnabled: ${r}`),a||!n||Math.abs(s-t)>.1){const n=this.primaryDetails;if(null!=n&&n.live&&t>=n.edge){const e=this.bufferingItem;return this.log(`Resume primary loading when live reaches ${t} buffering item: ${e?cd(e):null}`),i.pauseBuffering(),void(this.bufferPastEdge=!0)}i.startLoad(t,e)}else r||i.resumeBuffering()}onManifestLoading(){var t;this.stopLoad(),null==(t=this.schedule)||t.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(ii.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(ii.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(t,e){if(-1===e.level||!this.schedule)return;const i=this.hls.levels[e.level];if(!i.details)return;const n=Oi(Oi({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=n;const r=this.hls.startPosition;this.schedule.parseInterstitialDateRanges(n,this.hls.config.interstitialAppendInPlace,-1===r?0:r);if(this.schedule.items)if(this.effectivePlayingItem){if(this.bufferPastEdge){const t=this.primaryDetails,e=this.bufferedPos;if(null!=t&&t.live&&e<t.edge){this.bufferPastEdge=!1;const i=this.bufferingItem;this.log(`Live edge ${t.edge} reached buffer: ${e} buffering item: ${i?cd(i):null}`);if((null==i?void 0:i.end)===1/0)this.startLoadingPrimaryAt(Math.max(e,i.start));else{const t=this.getBufferingPlayer();if(t){t.bufferedInPlaceToEnd(this.primaryMedia,t.currentTime)&&t.hls&&t.hls.trigger(ii.BUFFERED_TO_END,void 0)}}}}}else this.checkStart()}onAudioTrackUpdated(t,e){const i=this.hls.audioTracks[e.id],n=this.mediaSelection;if(!n)return void(this.altSelection=Oi(Oi({},this.altSelection),{},{audio:i}));const r=Oi(Oi({},n),{},{audio:i});this.mediaSelection=r}onSubtitleTrackUpdated(t,e){const i=this.hls.subtitleTracks[e.id],n=this.mediaSelection;if(!n)return void(this.altSelection=Oi(Oi({},this.altSelection),{},{subtitles:i}));const r=Oi(Oi({},n),{},{subtitles:i});this.mediaSelection=r}onAudioTrackSwitching(t,e){const i=Xr(e);this.playerQueue.forEach(({hls:t})=>t&&(t.setAudioOption(e)||t.setAudioOption(i)))}onSubtitleTrackSwitch(t,e){const i=Xr(e);this.playerQueue.forEach(({hls:t})=>t&&(t.setSubtitleOption(e)||-1!==e.id&&t.setSubtitleOption(i)))}onBufferCodecs(t,e){const i=e.tracks;i&&(this.requiredTracks=i)}onBufferAppended(t,e){this.checkBuffer()}onBufferFlushed(t,e){const i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){const t=this.timelinePos;this.bufferedPos=t,this.checkBuffer()}}onBufferedToEnd(t){if(!this.schedule)return;const e=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&e){for(let t=0;t<e.length;t++){const i=e[t];if(i.cue.post){const t=this.getEventItem(i.identifier);t&&this.eventItemsMatch(t,this.bufferingItem)&&this.bufferedToItem(t,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(t){const e=this.playingItem;if(!this.playingLastItem&&e){const t=this.findItemIndex(e);this.setSchedulePosition(t+1)}else this.shouldPlay=!1}updateItem(t,e){var i;const n=null==(i=this.schedule)?void 0:i.items;if(t&&n){return n[this.findItemIndex(t,e)]||null}return null}trimInPlace(t,e){if(this.isInterstitial(t)&&t.event.appendInPlace&&e.end-t.end>.25){t.event.assetList.forEach((e,i)=>{t.event.isAssetPastPlayoutLimit(i)&&this.clearAssetPlayer(e.identifier,null)});const i=t.end+.25,n=js.bufferInfo(this.primaryMedia,i,0);if(n.end>i||(n.nextStart||0)>i){this.log(`trim buffered interstitial ${cd(t)} (was ${cd(e)})`);const n=!0;this.attachPrimary(i,null,n),this.flushFrontBuffer(i)}}}itemsMatch(t,e){return!!e&&(t===e||t.event&&e.event&&this.eventItemsMatch(t,e)||!t.event&&!e.event&&this.findItemIndex(t)===this.findItemIndex(e))}eventItemsMatch(t,e){var i;return!!e&&(t===e||t.event.identifier===(null==(i=e.event)?void 0:i.identifier))}findEventIndex(t){return this.schedule?this.schedule.findEventIndex(t):-1}getEventItem(t){if(this.schedule){var e;const i=null==(e=this.schedule.items)?void 0:e[this.findEventIndex(t)];if(this.isInterstitial(i)&&i.event.identifier===t)return i}}findItemIndex(t,e){return t&&this.schedule?this.schedule.findItemIndex(t,e):-1}updateSchedule(t=!1){var e,i;const n=this.mediaSelection;if(!n)return;const r=(null==(e=this.hls)?void 0:e.liveSyncPosition)||0;null==(i=this.schedule)||i.updateSchedule(n,[],r,t)}checkBuffer(t){var e;const i=null==(e=this.schedule)?void 0:e.items;if(!i)return;const n=js.bufferInfo(this.primaryMedia,this.timelinePos,0);t&&(this.bufferedPos=this.timelinePos),t||(t=n.len<1),this.updateBufferedPos(n.end,i,t)}updateBufferedPos(t,e,i){const n=this.schedule,r=this.bufferingItem;if(this.bufferedPos>t||!n)return;if(1===e.length&&this.itemsMatch(e[0],r))return void(this.bufferedPos=t);const s=this.playingItem,a=this.findItemIndex(s);let o=n.findItemIndexAtTime(t);if(this.bufferedPos<t){var l;const i=this.findItemIndex(r),n=Math.min(i+1,e.length-1),s=e[n];if((-1===o&&r&&t>=r.end||null!=(l=s.event)&&l.appendInPlace&&t+.01>=s.start)&&(o=n),this.isInterstitial(r)){const t=r.event;if(n-a>1&&!1===t.appendInPlace)return;if(0===t.assetList.length&&t.assetListLoader)return}if(this.bufferedPos=t,o>i&&o>a)this.bufferedToItem(s);else{const e=this.primaryDetails;this.primaryLive&&e&&t>e.edge-e.targetduration&&s.start<e.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(s)&&this.preloadAssets(s.event,0)}}else i&&s&&!this.itemsMatch(s,r)&&(o===a?this.bufferedToItem(s):o===a+1&&this.bufferedToItem(e[o]))}assetsBuffered(t,e){return 0!==t.event.assetList.length&&!t.event.assetList.some(t=>{const i=this.getAssetPlayer(t.identifier);return!(null!=i&&i.bufferedInPlaceToEnd(e))})}setBufferingItem(t){const e=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(t,e)&&i){const{items:n,events:r}=i;if(!n||!r)return e;const s=this.isInterstitial(t),a=this.getBufferingPlayer();this.bufferingItem=t,this.bufferedPos=Math.max(t.start,Math.min(t.end,this.timelinePos));const o=a?a.remaining:e?e.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${cd(t)}`+(e?` (${o.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(s){const e=i.findAssetIndex(t.event,this.bufferedPos);t.event.assetList.forEach((t,i)=>{const n=this.getAssetPlayer(t.identifier);n&&(i===e&&n.loadSource(),n.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(t=>t.pauseBuffering());this.hls.trigger(ii.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:n.slice(0),bufferingIndex:this.findItemIndex(t),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==t&&(this.bufferingItem=t);return e}bufferedToItem(t,e=0){const i=this.setBufferingItem(t);if(!this.playbackDisabled)if(this.isInterstitial(t))this.bufferedToEvent(t,e);else if(null!==i){this.bufferingAsset=null;const e=this.getPrimaryResumption(t,this.findItemIndex(t),!0),i=this.bufferedPos=Math.max(e,Math.min(this.bufferedPos,t.end),this.timelinePos,t.start),n=this.detachedData;if(n)if(n.mediaSource){const e=!0;this.attachPrimary(i,t,e)}else this.startLoadingPrimaryAt(i);else this.startLoadingPrimaryAt(i)}}bufferedToEvent(t,e){const i=t.event,n=0===i.assetList.length&&!i.assetListLoader,r=i.cue.once;if(n||!r){const t=this.preloadAssets(i,e);if(null!=t&&t.interstitial.appendInPlace){const e=this.primaryMedia;e&&this.bufferAssetPlayer(t,e)}}}preloadAssets(t,e){const i=t.assetUrl,n=t.assetList.length,r=0===n&&!t.assetListLoader,s=t.cue.once;if(r){const r=t.timelineStart,s=this.playingItem,o=this.getBufferingPlayer();var a;if(t.appendInPlace)this.isInterstitial(s)||(null==s||null==(a=s.nextEvent)?void 0:a.identifier)!==t.identifier||this.flushFrontBuffer(r+.25);let l,h=0;if(o&&!o.interstitial.cue.pre||!this.primaryLive||(h=this.getLiveStartPos(),o&&(h+=o.remaining)),h&&!t.cue.pre&&!t.cue.post){const t=h-r;t>0&&(l=Math.round(1e3*t)/1e3)}if(this.log(`Load interstitial asset ${e+1}/${i?1:n} ${t}${h?` live-start: ${h} start-offset: ${l} (timeline-start: ${r})`:""}`),i)return this.createAsset(t,0,0,r,t.duration,i);const c=this.assetListLoader.loadAssetList(t,l);c&&(t.assetListLoader=c)}else if(!s&&n){for(let i=e;i<n;i++){const e=t.assetList[i],n=this.getAssetPlayerQueueIndex(e.identifier);-1!==n&&!this.playerQueue[n].destroyed||e.error||this.createAssetPlayer(t,e,i)}const i=t.assetList[e];if(i){const t=this.getAssetPlayer(i.identifier);return t&&t.loadSource(),t}}return null}flushFrontBuffer(t){const e=this.requiredTracks;if(!e)return;const i=this.primaryDetails;if(i&&t>=i.edge)return;this.log(`Removing front buffer starting at ${t}`);Object.keys(e).forEach(e=>{this.hls.trigger(ii.BUFFER_FLUSHING,{startOffset:t,endOffset:1/0,type:e})})}getAssetPlayerQueueIndex(t){const e=this.playerQueue;for(let i=0;i<e.length;i++)if(t===e[i].assetId)return i;return-1}getAssetPlayer(t){const e=this.getAssetPlayerQueueIndex(t);return this.playerQueue[e]||null}getBufferingPlayer(){const{playerQueue:t,primaryMedia:e}=this;if(e)for(let i=0;i<t.length;i++)if(t[i].media===e)return t[i];return null}createAsset(t,e,i,n,r,s){const a={parentIdentifier:t.identifier,identifier:ed(t,s,e),duration:r,startOffset:i,timelineStart:n,uri:s};return this.createAssetPlayer(t,a,e)}createAssetPlayer(t,e,i){const n=this.hls,r=n.userConfig,s=ns(n.loadLevelObj||n.levels[n.currentLevel],r.videoPreference),a=n.audioTracks[n.audioTrack],o=n.subtitleTracks[n.subtitleTrack];let l=0;if(this.primaryLive||t.appendInPlace){const t=this.timelinePos-e.timelineStart;if(t>=0){const i=e.duration;i&&t<i&&(l=t)}}const h=e.identifier,c=Oi(Oi({},r),{},{maxMaxBufferLength:Math.min(15,n.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:n.sessionId,assetPlayerId:h,abrEwmaDefaultEstimate:n.bandwidthEstimate,interstitialsController:void 0,startPosition:l,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:s,audioPreference:a||r.audioPreference,subtitlePreference:o||r.subtitlePreference});t.appendInPlace&&(t.appendInPlaceStarted=!0,e.timelineStart&&(c.timelineOffset=e.timelineStart));const u=c.cmcd;null!=u&&u.sessionId&&u.contentId&&(c.cmcd=Di({},u,{contentId:gu(e.uri)})),this.getAssetPlayer(h)&&this.warn(`Duplicate date range identifier ${t} and asset ${h}`);const d=new od(this.HlsPlayerClass,c,t,e);this.playerQueue.push(d),t.assetList[i]=e;let f=!0;const g=n=>{if(n.live){const e=new Error(`Interstitials MUST be VOD assets ${t}`),n={fatal:!0,type:ti.OTHER_ERROR,details:ei.INTERSTITIAL_ASSET_ITEM_ERROR,error:e},r=this.findEventIndex(t.identifier);return void this.handleAssetItemError(n,t,r,i,e.message)}const r=n.edge-n.fragmentStart,s=e.duration;(f||null===s||r>s)&&(f=!1,this.log(`Interstitial asset "${h}" duration change ${s} > ${r}`),e.duration=r,this.updateSchedule())};d.on(ii.LEVEL_UPDATED,(t,{details:e})=>g(e)),d.on(ii.LEVEL_PTS_UPDATED,(t,{details:e})=>g(e)),d.on(ii.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const p=(t,e)=>{const i=this.getAssetPlayer(h);if(i&&e.tracks){i.off(ii.BUFFER_CODECS,p),i.tracks=e.tracks;const t=this.primaryMedia;this.bufferingAsset===i.assetItem&&t&&!i.media&&this.bufferAssetPlayer(i,t)}};d.on(ii.BUFFER_CODECS,p);d.on(ii.BUFFERED_TO_END,()=>{const e=this.getAssetPlayer(h);if(this.log(`buffered to end of asset ${e}`),!e||!this.schedule)return;const i=this.getEventItem(t.identifier);i&&this.advanceAssetBuffering(i,e.assetItem)});const m=e=>()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;this.shouldPlay=!0;const i=this.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,i,e)};return d.once(ii.MEDIA_ENDED,m(i)),d.once(ii.PLAYOUT_LIMIT_REACHED,m(1/0)),d.on(ii.ERROR,(e,n)=>{if(!this.schedule)return;const r=this.getAssetPlayer(h);if(n.details===ei.BUFFER_STALLED_ERROR)return null!=r&&r.appendInPlace?void this.handleInPlaceStall(t):(this.onTimeupdate(),void this.checkBuffer(!0));n.details!==ei.BUFFER_SEEK_OVER_HOLE&&this.handleAssetItemError(n,t,this.findEventIndex(t.identifier),i,`Asset player error ${n.error} ${t}`)}),d.on(ii.DESTROYING,()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;const e=new Error(`Asset player destroyed unexpectedly ${h}`),n={fatal:!0,type:ti.OTHER_ERROR,details:ei.INTERSTITIAL_ASSET_ITEM_ERROR,error:e};this.handleAssetItemError(n,t,this.findEventIndex(t.identifier),i,e.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${ad(e)}`),this.hls.trigger(ii.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:e,assetListIndex:i,event:t,player:d}),d}clearInterstitial(t,e){this.clearAssetPlayers(t,e),t.reset()}clearAssetPlayers(t,e){t.assetList.forEach(t=>{this.clearAssetPlayer(t.identifier,e)})}resetAssetPlayer(t){const e=this.getAssetPlayerQueueIndex(t);if(-1!==e){this.log(`reset asset player "${t}" after error`);const i=this.playerQueue[e];this.transferMediaFromPlayer(i,null),i.resetDetails()}}clearAssetPlayer(t,e){const i=this.getAssetPlayerQueueIndex(t);if(-1!==i){const t=this.playerQueue[i];this.log(`clear ${t} toSegment: ${e?cd(e):e}`),this.transferMediaFromPlayer(t,e),this.playerQueue.splice(i,1),t.destroy()}}emptyPlayerQueue(){let t;for(;t=this.playerQueue.pop();)t.destroy();this.playerQueue=[]}startAssetPlayer(t,e,i,n,r){const{interstitial:s,assetItem:a,assetId:o}=t,l=s.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=a,(null==h?void 0:h.identifier)!==o&&(h&&(this.clearAssetPlayer(h.identifier,i[n]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${e+1}/${l} ${ad(a)}`),this.hls.trigger(ii.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:e,event:s,schedule:i.slice(0),scheduleIndex:n,player:t})),this.bufferAssetPlayer(t,r)}bufferAssetPlayer(t,e){var i;if(!this.schedule)return;const{interstitial:n,assetItem:r}=t,s=this.getEventItem(n.identifier);if(!s)return;if(t.loadSource(),this.setBufferingItem(s),this.bufferingAsset=r,t.bufferedInPlaceToEnd(this.primaryMedia,t.currentTime))return void this.advanceAssetBuffering(s,r);const a=this.getBufferingPlayer();if(a===t)return;const o=n.appendInPlace;if(o&&!1===(null==a?void 0:a.interstitial.appendInPlace))return;const l=(null==a?void 0:a.tracks)||(null==(i=this.detachedData)?void 0:i.tracks)||this.requiredTracks;if(o&&r!==this.playingAsset){if(!t.tracks)return void this.log(`Waiting for track info before buffering ${t}`);if(l&&!tn(l,t.tracks)){const e=new Error(`Asset ${ad(r)} SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(l)}')`),i={fatal:!0,type:ti.OTHER_ERROR,details:ei.INTERSTITIAL_ASSET_ITEM_ERROR,error:e},s=n.findAssetIndex(r);return void this.handleAssetItemError(i,n,this.findEventIndex(n.identifier),s,e.message)}}this.transferMediaTo(t,e)}handleInPlaceStall(t){const e=this.schedule,i=this.primaryMedia;if(!e||!i)return;const n=i.currentTime,r=e.findAssetIndex(t,n),s=t.assetList[r];if(s){const a=this.getAssetPlayer(s.identifier);if(a){const o=a.currentTime||n-s.timelineStart,l=a.duration-o;if(this.warn(`Stalled at ${o} of ${o+l} in ${a} ${t} (media.currentTime: ${n})`),o&&(l/i.playbackRate<.5||a.bufferedInPlaceToEnd(i,a.currentTime))&&a.hls){const i=e.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,i,r)}}}}advanceInPlace(t){const e=this.primaryMedia;if(e&&e.currentTime<t){const i=`advance currentTime to ${t}, duration: ${e.duration}`;e.duration>t?(this.log(i),e.currentTime=t):this.log(`Cannot ${i}`)}}handleAssetItemError(t,e,i,n,r){if(t.details===ei.BUFFER_STALLED_ERROR)return;const s=e.assetList[n]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${s?ad(s):s} ${t.error}`),!this.schedule)return;const a=(null==s?void 0:s.identifier)||"",o=this.getAssetPlayerQueueIndex(a),l=this.playerQueue[o]||null,h=this.schedule.items,c=Di({},t,{fatal:!1,errorAction:bs(!0),asset:s,assetListIndex:n,event:e,schedule:h,scheduleIndex:i,player:l});if(this.hls.trigger(ii.INTERSTITIAL_ASSET_ERROR,c),!t.fatal)return;const u=this.playingAsset,d=this.bufferingAsset,f=new Error(r);if(s&&(this.clearAssetPlayer(a,null),s.error=f),e.assetList.some(t=>!t.error))for(let t=n;t<e.assetList.length;t++)this.resetAssetPlayer(e.assetList[t].identifier);else e.error=f;this.updateSchedule(!0),e.error?this.primaryFallback(e):(null==u?void 0:u.identifier)===a?this.advanceAfterAssetEnded(e,i,n):(null==d?void 0:d.identifier)===a&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,d)}primaryFallback(t){const e=t.timelineStart,i=this.effectivePlayingItem,n=this.playingItem,r=this.seekableStart,s=this.hls.startPosition;let a=this.timelinePos;if(this.isInterstitial(i)){this.log(`Fallback to primary from event "${t.identifier}" start: ${e} pos: ${a} playing: ${cd(i)} startPosition: ${s} seekableStart: ${r} error: ${t.error}`),-1===a&&(a=s),a=Math.max(a,r);const n=this.updateItem(i,a);this.itemsMatch(i,n)&&this.clearInterstitial(t,null),t.appendInPlace&&(this.attachPrimary(e,null),this.flushFrontBuffer(e))}else if(-1===a)return void this.checkStart();if(!this.schedule)return;if(!this.isInterstitial(n))return;const o=this.schedule.findItemIndexAtTime(a);this.setSchedulePosition(o)}onAssetListLoaded(t,e){var i,n;const r=e.event,s=r.identifier,a=e.assetListResponse.ASSETS;if(null==(i=this.schedule)||!i.hasEvent(s))return;const o=r.timelineStart,l=r.duration;let h=0;a.forEach((t,e)=>{const i=parseFloat(t.DURATION);this.createAsset(r,e,h,o+h,i,t.URI),h+=i}),r.duration=h,this.log(`Loaded asset-list with duration: ${h} (was: ${l}) ${r}`);const c=this.waitingItem,u=(null==c?void 0:c.event.identifier)===s;this.updateSchedule();const d=null==(n=this.bufferingItem)?void 0:n.event;if(u){const t=this.findEventIndex(s),e=this.getEventItem(s);if(e){if(!this.playingItem&&this.timelinePos>e.end){if(this.schedule.findItemIndexAtTime(this.timelinePos)!==t)return r.error=new Error(`Interstitial ${a.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),void this.primaryFallback(r)}this.setBufferingItem(e)}this.setSchedulePosition(t)}else if((null==d?void 0:d.identifier)===s){const t=r.assetList[0];if(t){const e=this.getAssetPlayer(t.identifier);if(d.appendInPlace){const t=this.primaryMedia;e&&t&&this.bufferAssetPlayer(e,t)}else e&&e.loadSource()}}}onError(t,e){if(this.schedule)switch(e.details){case ei.ASSET_LIST_PARSING_ERROR:case ei.ASSET_LIST_LOAD_ERROR:case ei.ASSET_LIST_LOAD_TIMEOUT:{const t=e.interstitial;t&&(this.updateSchedule(!0),this.primaryFallback(t));break}case ei.BUFFER_STALLED_ERROR:{const t=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(t)&&t.event.appendInPlace)return void this.handleInPlaceStall(t.event);const e=this.primaryMedia;this.log(`Primary player stall @${this.timelinePos} currentTime: ${null==e?void 0:e.currentTime} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}});function Wd(t,e,i){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"');if(void 0!==e.liveMaxUnchangedPlaylistRefresh){const t=e.liveMaxUnchangedPlaylistRefresh,a=(n=t,r=2,s=1/0,Math.max(r,Math.min(n,s)));a!==t&&i.warn(`hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from ${t} to ${a}.`),e.liveMaxUnchangedPlaylistRefresh=a}var n,r,s;const a=zd(t),o=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(t=>{const n=`${"level"===t?"playlist":t}LoadPolicy`,r=void 0===e[n],s=[];o.forEach(i=>{const o=`${t}Loading${i}`,l=e[o];if(void 0!==l&&r){s.push(o);const t=a[n].default;switch(e[n]={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}}}),s.length&&i.warn(`hls.js config: "${s.join('", "')}" setting(s) are deprecated, use "${n}": ${Wr(e[n])}`)}),Oi(Oi({},a),e)}function zd(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(zd):Object.keys(t).reduce((e,i)=>(e[i]=zd(t[i]),e),{}):t}function qd(t,e){const i=t.loader;if(i!==Gd&&i!==Yd)e.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=Gd,t.progressive=!0,t.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class Xd extends Zl{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.lastABRSwitchTime=-1,this._iframeVariants=[],this.onParsedComplete=void 0,this.steering=e,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(ii.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ii.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(ii.LEVEL_LOADED,this.onLevelLoaded,this),t.on(ii.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(ii.FRAG_BUFFERED,this.onFragBuffered,this),t.on(ii.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(ii.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ii.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(ii.LEVEL_LOADED,this.onLevelLoaded,this),t.off(ii.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(ii.FRAG_BUFFERED,this.onFragBuffered,this),t.off(ii.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,this._iframeVariants=[]}onManifestLoading(t,e){this.resetLevels()}onManifestLoaded(t,e){const i=this.hls.config.preferManagedMediaSource,n=[],r={},s={};let a=!1,o=!1,l=!1,h=!1;e.levels.forEach(t=>{const e=t.attrs,c=Jd(t,i),{audioCodec:u,videoCodec:d,imageCodec:f,width:g,height:p}=t;if(!c)return void this.log(`Some or all CODECS not supported "${e.CODECS}"`);a||(a=!(!g||!p)),o||(o=!!d),l||(l=!!u),h||(h=!!f);const{CODECS:m,"FRAME-RATE":v,"HDCP-LEVEL":y,"PATHWAY-ID":A,RESOLUTION:E,"VIDEO-RANGE":T}=e,b=`${`${A||"."}-`}${t.bitrate}-${E}-${v}-${m}-${T}-${y}`;if(r[b])if(r[b].uri===t.url||t.attrs["PATHWAY-ID"])t.iframes||(r[b].addGroupId("audio",e.AUDIO),r[b].addGroupId("text",e.SUBTITLES));else{const e=s[b]+=1;t.attrs["PATHWAY-ID"]=new Array(e+1).join(".");const i=this.createLevel(t);r[b]=i,n.push(i)}else{const e=this.createLevel(t);r[b]=e,s[b]=1,n.push(e)}}),this.filterAndSortMediaOptions(n,e,a,o,l,h)}createLevel(t){const e=new Hr(t),i=t.supplemental;if(null!=i&&i.videoCodec&&!Zd(i.videoCodec,this.hls.config.preferManagedMediaSource)){const t=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(t.message),e.supportedResult=Dr(t,[])}return e}filterAndSortMediaOptions(t,e,i,n,r,s){var a;let o=[],l=[],h=t;const c=(null==(a=e.stats)?void 0:a.parsing)||{},u=this.hls.config.preferManagedMediaSource;if((i||n)&&r&&(h=h.filter(({videoCodec:t,videoRange:e,width:i,height:n})=>{return(!!t||!(!i||!n))&&(!!(r=e)&&Br.indexOf(r)>-1);var r})),n&&s&&(h=h.filter(t=>!t.imageCodec)),0===h.length)return Promise.resolve().then(()=>{if(this.hls){let t="no level with compatible codecs found in manifest",i=t;e.levels.length&&(i=`one or more CODECS in variant not supported: ${Wr(e.levels.map(t=>t.attrs.CODECS).filter((t,e,i)=>i.indexOf(t)===e))}`,this.warn(i),t+=` (${i})`);const n=new Error(t);this.hls.trigger(ii.ERROR,{type:ti.MEDIA_ERROR,details:ei.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:n,reason:i})}}),void(c.end=performance.now());e.audioTracks&&(o=e.audioTracks.filter(t=>!t.audioCodec||Qd(t.audioCodec,u)),tf(o)),e.subtitles&&(l=e.subtitles,tf(l));const d=h.slice(0);h.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 Br.indexOf(t.videoRange)-Br.indexOf(e.videoRange);if(t.videoCodec!==e.videoCodec){const i=Ar(t.videoCodec),n=Ar(e.videoCodec);if(i!==n)return n-i}if(t.uri===e.uri&&t.codecSet!==e.codecSet){const i=Er(t.codecSet),n=Er(e.codecSet);if(i!==n)return n-i}return t.averageBitrate!==e.averageBitrate?t.averageBitrate-e.averageBitrate:0});let f=d[0];if(this.steering&&(h=this.steering.filterParsedLevels(h),h.length!==d.length))for(let t=0;t<d.length;t++)if(d[t].pathwayId===h[0].pathwayId){f=d[t];break}this._levels=h;for(let t=0;t<h.length;t++)if(h[t]===f){var g;this._firstLevel=t;const e=f.bitrate,i=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${h.length} level(s) found, first bitrate: ${e}`),void 0===(null==(g=this.hls.userConfig)?void 0:g.abrEwmaDefaultEstimate)){const t=Math.min(e,this.hls.config.abrEwmaDefaultEstimateMax);t>i&&i===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=t)}break}const p=e.iframeVariants.filter(t=>Jd(t,u));this._iframeVariants=p;const m=r&&!n,v=this.hls.config,y=!(!v.audioStreamController||!v.audioTrackController),A={levels:h,audioTracks:o,subtitleTracks:l,iframeVariants:p,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:r,video:n,altAudio:y&&!m&&o.some(t=>!!t.url)};c.end=performance.now(),this.hls.trigger(ii.MANIFEST_PARSED,A)}get iframeVariants(){return 0===this._iframeVariants.length?null:this._iframeVariants}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}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"),n=t<0;if(this.hls.trigger(ii.ERROR,{type:ti.OTHER_ERROR,details:ei.LEVEL_SWITCH_ERROR,level:t,fatal:n,error:i,reason:i.message}),n)return;t=Math.min(t,e.length-1)}const i=this.currentLevelIndex,n=this.currentLevel,r=n?n.attrs["PATHWAY-ID"]:void 0,s=e[t],a=s.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=s,i===t&&n&&r===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}${r?" with Pathway "+r:""}`);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(ii.LEVEL_SWITCHING,o);const l=s.details;if(!l||l.live){const t=this.switchParams(s.uri,null==n?void 0:n.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}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(t){if(this.steering){const e=this.steering.pathways(),i=t.filter(t=>-1!==e.indexOf(t));if(t.length<1)return void this.warn(`pathwayPriority ${t} should contain at least one pathway from list: ${e}`);this.steering.pathwayPriority=i}}onError(t,e){!e.fatal&&e.context&&e.context.type===hi&&e.context.level===this.level&&this.checkRetry(e)}onFragBuffered(t,{frag:e}){if(e.type===vi){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:n,details:r}=e,s=e.levelInfo;var a;if(!s)return this.warn(`Invalid level index ${n}`),void(null!=(a=e.deliveryDirectives)&&a.skip&&(r.deltaUpdateFailed=!0));if(s===this.currentLevel||e.withoutMultiVariant){0===s.fragmentError&&(s.loadError=0);let t=s.details;t===e.details&&t.advanced&&(t=void 0),this.playlistLoaded(n,e,t)}else null!=(i=e.deliveryDirectives)&&i.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const i=this.getUrlWithDirectives(t.uri,e),n=this.currentLevelIndex,r=t.attrs["PATHWAY-ID"],s=t.details,a=null==s?void 0:s.age;this.log(`Loading level index ${n}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${r?" Pathway "+r:""}${a&&s.live?" age "+a.toFixed(1)+(s.type&&" "+s.type||""):""} ${i}`),this.hls.trigger(ii.LEVEL_LOADING,{url:i,level:n,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){const e=this.currentLevelIndex;if(-1===this.manualLevelIndex&&t!==e&&-1!==t){const i=this.hls.config.abrSwitchInterval;if(i>0){const n=performance.now(),r=n-this.lastABRSwitchTime,s=1e3*i;if(this.lastABRSwitchTime>-1&&r<s)return void this.warn(`Preventing ABR level switch: ${e} -> ${t} (${Math.round(r)}ms < ${s}ms / ${i}s)`);this.lastABRSwitchTime=n,this.log(`Allowing ABR level switch: ${e} -> ${t} (${Math.round(r)}ms >= ${s}ms / ${i}s)`)}}this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}removeLevel(t){var e;if(1===this._levels.length)return;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));eo(i),this._levels=i,this.currentLevelIndex>-1&&null!=(e=this.currentLevel)&&e.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const n=i.length-1;this._firstLevel=Math.min(this._firstLevel,n),this._startLevel&&(this._startLevel=Math.min(this._startLevel,n)),this.hls.trigger(ii.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(ii.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function Qd(t,e){return mr(t,"audio",e)}function Zd(t,e){return mr(t,"video",e)}function Jd(t,e){let{audioCodec:i,videoCodec:n}=t;i&&(t.audioCodec=i=Sr(i,e)||void 0),n&&(n=t.videoCodec=function(t){const e=t.split(",");for(let t=0;t<e.length;t++){const i=e[t].split(".");i.length>2&&"avc1"===i[0]&&(e[t]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`)}return e.join(",")}(n));const{unknownCodecs:r}=t;return!((null==r?void 0:r.length)||0||i&&!Qd(i,e)||n&&!Zd(n,e))}function tf(t){const e={};t.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}class ef extends ji{constructor(t,e){super("key-loader",e),this.config=void 0,this.keyLoaderInfo={},this.emeController=null,this.config=t}abort(t){for(const i in this.keyLoaderInfo){const n=this.keyLoaderInfo[i].loader;if(n){var e;if(t&&t!==(null==(e=n.context)?void 0:e.frag.type))return;n.abort()}}}destroy(){for(const t in this.keyLoaderInfo){const e=this.keyLoaderInfo[t].loader;e&&e.destroy()}this.emeController=null,this.keyLoaderInfo={}}loadClear(t,e,i){return this.emeController?this.emeController.loadClear(t,e,i):null}load(t,e){return!t.decryptdata&&t.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(t).then(i=>this.loadInternal(t,e,i)):this.loadInternal(t,e)}loadInternal(t,e,i){i&&t.setKeyFormat(i);const n=t.decryptdata;if(!n){const e=new Error(i?`Expected frag.decryptdata to be defined after setting format ${i}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(nf(t,ei.KEY_LOAD_ERROR,e))}const r=t;switch(n.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===n.keyFormat?this.loadKeyHTTP(r):e?e.then(()=>this.loadKeyEME(r)):this.loadKeyEME(r);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(r);default:return Promise.reject(nf(t,ei.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(t){if(this.emeController&&this.config.emeEnabled){var e;if(!t.decryptdata.keyId&&null!=(e=t.initSegment)&&e.data){const e=function(t){const e=[];return Wn(t,t=>e.push(t.subarray(8,24))),e}(t.initSegment.data);if(e.length){let i=e[0];const n=t.decryptdata.uri;if(i.some(t=>0!==t))this.log(`Using keyId found in init segment ${bn(i)} keyUri: ${n}`),La.setKeyIdForUri(n,i);else{const t=La.addKeyIdForUri(n);this.log(`Patching empty keyId with ${bn(t)} keyUri: ${n}`),i=t}t.decryptdata.keyId=i}}return this.emeController.loadKey(t).then(()=>({frag:t,keyInfo:{decryptdata:t.decryptdata}}))}return Promise.reject(nf(t,ei.KEY_LOAD_ERROR,new Error(`emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`)))}loadKeyHTTP(t){const e=t.decryptdata,i=e.uri;if(!i)return Promise.reject(nf(t,ei.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${i}"`)));const n=this.keyLoaderInfo[i];if(n){if(n.decryptdata.key)return e.key=n.decryptdata.key,n.keyLoadPromise=null,Promise.resolve({frag:t,keyInfo:n});if(n.keyLoadPromise)return n.keyLoadPromise.then(i=>(e.key=n.decryptdata.key,Oi(Oi({},i),{},{frag:t})))}this.log(`Loading${e.keyId?" keyId: "+bn(e.keyId):""} URI: ${e.uri} from ${t.type} ${t.level}`);const r=this.config,s=new(0,r.loader)(r);t.keyLoader=s;const a=this.keyLoaderInfo[i]={decryptdata:e,keyLoadPromise:null,loader:s};return a.keyLoadPromise=new Promise((e,n)=>{const o={type:fi,keyInfo:a,frag:t,responseType:"arraybuffer",url:i},l=r.keyLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(t,i,r,s)=>{const{frag:a,keyInfo:o,url:l}=r;if(!a.decryptdata||o!==this.keyLoaderInfo[l])return n(nf(a,ei.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),s));o.decryptdata.key=a.decryptdata.key=new Uint8Array(t.data),a.keyLoader=o.loader=o.keyLoadPromise=null,e({frag:a,keyInfo:o})},onError:(e,r,s,a)=>{this.resetLoader(r),n(nf(t,ei.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),s,Oi({url:i,data:void 0},e)))},onTimeout:(e,i,r)=>{this.resetLoader(i),n(nf(t,ei.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),r))},onAbort:(e,i,r)=>{this.resetLoader(i),n(nf(t,ei.INTERNAL_ABORTED,new Error("key loading aborted"),r))}};s.load(o,h,c)})}resetLoader(t){const{frag:e,keyInfo:i,url:n}=t,r=i.loader;e.keyLoader===r&&(e.keyLoader=i.loader=i.keyLoadPromise=null),delete this.keyLoaderInfo[n],r&&r.destroy()}}function nf(t,e=ei.KEY_LOAD_ERROR,i,n,r){return new Vs({type:ti.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:r,error:i,networkDetails:n||null})}function rf(t){const{type:e}=t;switch(e){case ci:return yi;case ui:return Ai;default:return vi}}function sf(t,e){let i=t.url;return void 0!==i&&0!==i.indexOf("data:")||(i=e.url),i}class af{constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=t,this.registerListeners()}startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:t}=this;t.on(ii.MANIFEST_LOADING,this.onManifestLoading,this),t.on(ii.LEVEL_LOADING,this.onLevelLoading,this),t.on(ii.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(ii.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(ii.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(ii.MANIFEST_LOADING,this.onManifestLoading,this),t.off(ii.LEVEL_LOADING,this.onLevelLoading,this),t.off(ii.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(ii.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(ii.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(t){const e=this.hls.config,i=e.pLoader,n=e.loader,r=new(i||n)(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:i}=e;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:li,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(t,e){const{id:i,level:n,pathwayId:r,url:s,deliveryDirectives:a,levelInfo:o}=e;this.load({id:i,level:n,pathwayId:r,responseType:"text",type:hi,url:s,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(t,e){const{id:i,groupId:n,url:r,deliveryDirectives:s,track:a}=e;this.load({id:i,groupId:n,level:null,responseType:"text",type:ci,url:r,deliveryDirectives:s,levelOrTrack:a})}onSubtitleTrackLoading(t,e){const{id:i,groupId:n,url:r,deliveryDirectives:s,track:a}=e;this.load({id:i,groupId:n,level:null,responseType:"text",type:ui,url:r,deliveryDirectives:s,levelOrTrack:a})}onLevelsUpdated(t,e){const i=this.loaders[hi];if(i){const t=i.context;t&&!e.levels.some(e=>e===t.levelOrTrack)&&(i.abort(),delete this.loaders[hi])}}load(t){var e;const i=this.hls.config;let n,r=this.getInternalLoader(t);if(r){const e=this.hls.logger,i=r.context;if((null==i?void 0:i.levelOrTrack)===t.levelOrTrack&&(i.url===t.url||i.deliveryDirectives&&!t.deliveryDirectives))return void(i.url===t.url?e.log(`[playlist-loader]: ignore ${t.url} ongoing request`):e.log(`[playlist-loader]: ignore ${t.url} in favor of ${i.url}`));e.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),r.abort()}if(n=t.type===li?i.manifestLoadPolicy.default:Di({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(t),Qe(null==(e=t.deliveryDirectives)?void 0:e.part)){let e;if(t.type===hi&&null!==t.level?e=this.hls.levels[t.level].details:t.type===ci&&null!==t.id?e=this.hls.audioTracks[t.id].details:t.type===ui&&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);n=Di({},n,{maxTimeToFirstByteMs:Math.min(e,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(e,n.maxTimeToFirstByteMs)})}}}const s=n.errorRetry||n.timeoutRetry||{},a={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:s.maxNumRetry||0,retryDelay:s.retryDelayMs||0,maxRetryDelay:s.maxRetryDelayMs||0},o={onSuccess:(t,e,i,n)=>{const r=this.getInternalLoader(i);this.resetInternalLoader(i.type);const s=t.data;e.parsing.start=performance.now(),Oa.isMediaPlaylist(s)||i.type!==li?this.handleTrackOrLevelPlaylist(t,e,i,n||null,r):this.handleMasterPlaylist(t,e,i,n)},onError:(t,e,i,n)=>{this.handleNetworkError(e,i,!1,t,n)},onTimeout:(t,e,i)=>{this.handleNetworkError(e,i,!0,void 0,t)}};r.load(t,a,o)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:t,startPosition:e},forceStartLoad:i}=this.hls;(t||i)&&(this.hls.logger.log(`${t?"auto":"force"} startLoad with configured startPosition ${e}`),this.hls.startLoad(e))}handleMasterPlaylist(t,e,i,n){const r=this.hls,s=t.data,a=sf(t,i),o=Oa.parseMasterPlaylist(s,a);if(o.playlistParsingError)return e.parsing.end=performance.now(),void this.handleManifestParsingError(t,i,o.playlistParsingError,n,e);const{contentSteering:l,levels:h,iframeVariants:c,sessionData:u,sessionKeys:d,startTimeOffset:f,variableList:g}=o;this.variableList=g,h.forEach(t=>{const{unknownCodecs:e}=t;if(e){const{preferManagedMediaSource:i}=this.hls.config;let{audioCodec:n,videoCodec:r}=t;for(let s=e.length;s--;){const a=e[s];mr(a,"audio",i)?(t.audioCodec=n=n?`${n},${a}`:a,gr.audio[n.substring(0,4)]=2,e.splice(s,1)):mr(a,"video",i)&&(t.videoCodec=r=r?`${r},${a}`:a,gr.video[r.substring(0,4)]=2,e.splice(s,1))}}});const{AUDIO:p=[],SUBTITLES:m,"CLOSED-CAPTIONS":v}=Oa.parseMasterPlaylistMedia(s,a,o);if(p.length){p.some(t=>!t.url)||!h[0].audioCodec||h[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ta({}),bitrate:0,url:""}))}r.trigger(ii.MANIFEST_LOADED,{levels:h,audioTracks:p,subtitles:m,iframeVariants:c,captions:v,contentSteering:l,url:a,stats:e,networkDetails:n,sessionData:u,sessionKeys:d,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(t,e,i,n,r){const s=this.hls,{id:a,level:o,type:l}=i,h=sf(t,i),c=Qe(o)?o:Qe(a)?a:0,u=rf(i),d=Oa.parseLevelPlaylist(t.data,h,c,u,0,this.variableList);if(l===li){const t={attrs:new ta({}),bitrate:0,details:d,name:"",url:h};d.requestScheduled=e.loading.start+Qa(d,0),s.trigger(ii.MANIFEST_LOADED,{levels:[t],audioTracks:[],iframeVariants:[],url:h,stats:e,networkDetails:n,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),i.levelDetails=d,this.handlePlaylistLoaded(d,t,e,i,n,r)}handleManifestParsingError(t,e,i,n,r){this.hls.trigger(ii.ERROR,{type:ti.NETWORK_ERROR,details:ei.MANIFEST_PARSING_ERROR,fatal:e.type===li,url:t.url,err:i,error:i,reason:i.message,response:t,context:e,networkDetails:n,stats:r})}handleNetworkError(t,e,i=!1,n,r){let s=`A network ${i?"timeout":"error"+(n?" (status "+n.code+")":"")} occurred while loading ${t.type}`;t.type===hi?s+=`: ${t.level} id: ${t.id}`:t.type!==ci&&t.type!==ui||(s+=` id: ${t.id} group-id: "${t.groupId}"`);const a=new Error(s);this.hls.logger.warn(`[playlist-loader]: ${s}`);let o=ei.UNKNOWN,l=!1;const h=this.getInternalLoader(t);switch(t.type){case li:o=i?ei.MANIFEST_LOAD_TIMEOUT:ei.MANIFEST_LOAD_ERROR,l=!0;break;case hi:o=i?ei.LEVEL_LOAD_TIMEOUT:ei.LEVEL_LOAD_ERROR,l=!1;break;case ci:o=i?ei.AUDIO_TRACK_LOAD_TIMEOUT:ei.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case ui:o=i?ei.SUBTITLE_TRACK_LOAD_TIMEOUT:ei.SUBTITLE_LOAD_ERROR,l=!1}h&&this.resetInternalLoader(t.type);const c={type:ti.NETWORK_ERROR,details:o,fatal:l,url:t.url,loader:h,context:t,error:a,networkDetails:e,stats:r};if(n){let i=t.url;e&&"url"in e&&(i=e.url),c.response=Oi({url:i,data:void 0},n)}this.hls.trigger(ii.ERROR,c)}handlePlaylistLoaded(t,e,i,n,r,s){const a=this.hls,{type:o,level:l,levelOrTrack:h,id:c,groupId:u,deliveryDirectives:d}=n,f=sf(e,n),g=rf(n);let p="number"==typeof n.level&&g===vi?l:void 0;h&&"iframes"in h&&h.iframes&&!t.iframesOnly&&(t.playlistParsingError=new Error("EXT-X-I-FRAME-STREAM-INF media playlist MUST contain an EXT-X-I-FRAMES-ONLY tag"),t.iframesOnly=!0);const m=t.playlistParsingError;if(m){if(this.hls.logger.warn(`${m} ${t.url}`),!a.config.ignorePlaylistParsingErrors)return void a.trigger(ii.ERROR,{type:ti.NETWORK_ERROR,details:ei.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:m,reason:m.message,response:e,context:n,level:p,parent:g,networkDetails:r,stats:i});t.playlistParsingError=null}if(!t.fragments.length){const s=t.playlistParsingError=new Error("No Segments found in Playlist");return void a.trigger(ii.ERROR,{type:ti.NETWORK_ERROR,details:ei.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:s,reason:s.message,response:e,context:n,level:p,parent:g,networkDetails:r,stats:i})}switch(t.live&&s&&(s.getCacheAge&&(t.ageHeader=s.getCacheAge()||0),s.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),o){case li:case hi:if(p)if(h){if(h!==a.levels[p]){const t=a.levels.indexOf(h);t>-1&&(p=t)}}else p=0;a.trigger(ii.LEVEL_LOADED,{details:t,levelInfo:h||a.levels[0],level:p||0,id:c||0,stats:i,networkDetails:r,deliveryDirectives:d,withoutMultiVariant:o===li,context:n});break;case ci:a.trigger(ii.AUDIO_TRACK_LOADED,{details:t,track:h,id:c||0,groupId:u||"",stats:i,networkDetails:r,deliveryDirectives:d,context:n});break;case ui:a.trigger(ii.SUBTITLE_TRACK_LOADED,{details:t,track:h,id:c||0,groupId:u||"",stats:i,networkDetails:r,deliveryDirectives:d,context:n})}}}class of{static get version(){return wo}static isMSESupported(){return Vu()}static isSupported(){return function(){if(!Vu())return!1;const t=Ji();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(yr(e,"video")))||["mp4a.40.2","fLaC"].some(e=>t.isTypeSupported(yr(e,"audio"))))}()}static getMediaSource(){return Ji()}static get Events(){return ii}static get MetadataSchema(){return Vo}static get ErrorTypes(){return ti}static get ErrorDetails(){return ei}static get DefaultConfig(){return of.defaultConfig?of.defaultConfig:jd}static set DefaultConfig(t){of.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this._url=null,this.streamController=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Do,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.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.iframeController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const e=this.logger=function(t,e,i){const n=qi();if("object"==typeof console&&!0===t||"object"==typeof t){const r=["debug","log","info","warn","error"];r.forEach(e=>{n[e]=Xi(e,t,i)});try{n.log(`Debug logs enabled for "${e}" in hls.js version 1.7.0`)}catch(t){return qi()}r.forEach(e=>{Qi[e]=Xi(e,t)})}else Di(Qi,n);return n}(t.debug||!1,"Hls instance",t.loggerId||t.assetPlayerId),i=this.config=Wd(of.DefaultConfig,t,e);this.userConfig=t,i.progressive&&qd(i,e);const{streamController:n,abrController:r,bufferController:s,capLevelController:a,errorController:o,fpsController:l,id3TrackController:h,iframeController:c,gapController:u}=i,d=new o(this),f=this.abrController=new r(this),g=new Rs(this),p=i.interstitialsController,m=p?this.interstitialsController=new p(this,of):null,v=s?this.bufferController=new s(this,g):null,y=a?this.capLevelController=new a(this):null,A=l?new l(this):null,E=i.cmcdController,T=E?this.cmcdController=new E(this):null,b=new af(this),S=i.contentSteeringController,k=S?new S(this):null,_=this.levelController=new Xd(this,k),L=h?new h(this):void 0,R=new ef(this.config,this.logger),I=this.streamController=new n(this,g,R),C=this.gapController=u?new u(this,g):void 0;y&&y.setStreamController(I);const P=[b,_,I];m&&P.splice(1,0,m),k&&P.splice(1,0,k),this.networkControllers=P;const D=[f];v&&D.push(v),C&&D.push(C),y&&D.push(y),A&&(A.setStreamController(I),D.push(A)),L&&D.push(L),D.push(g),this.audioTrackController=this.createController(i.audioTrackController,P);const w=i.audioStreamController;w&&P.push(this.audioStreamController=new w(this,g,R)),this.subtitleTrackController=this.createController(i.subtitleTrackController,P);const O=i.subtitleStreamController;O&&P.push(this.subtititleStreamController=new O(this,g,R)),this.createController(i.timelineController,D),R.emeController=this.emeController=this.createController(i.emeController,D),T&&D.push(T),this.latencyController=this.createController(i.latencyController,D),this.coreComponents=D,this.iframeController=c?new c(this,of):void 0,P.push(d);const x=d.onErrorOut;"function"==typeof x&&this.on(ii.ERROR,x,d),this.on(ii.MANIFEST_LOADED,b.onManifestLoaded,b)}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,n){this._emitter.off(t,e,i,n)}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(this.logger.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===ii.ERROR;this.trigger(ii.ERROR,{type:ti.OTHER_ERROR,details:ei.INTERNAL_EXCEPTION,fatal:i,event:t,error:e}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger(ii.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,this.iframeController=void 0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){if(!t||"media"in t&&!t.media){const e=new Error(`attachMedia failed: invalid argument (${t})`);return void this.trigger(ii.ERROR,{type:ti.OTHER_ERROR,details:ei.ATTACH_MEDIA_ERROR,fatal:!0,error:e})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const e="media"in t,i=e?t.media:t,n=e?t:{media:i};this._media=i,this.trigger(ii.MEDIA_ATTACHING,n)}detachMedia(){this.logger.log("detachMedia");const t={};this.trigger(ii.MEDIA_DETACHING,t),this._media=null,this.trigger(ii.MEDIA_DETACHED,t)}transferMedia(){var t;this._media=null;const e=(null==(t=this.bufferController)?void 0:t.transferMedia())||null,i={transferMedia:e};return this.trigger(ii.MEDIA_DETACHING,i),this.trigger(ii.MEDIA_DETACHED,i),e}loadSource(t){var e;this.stopLoad();const i=this.media,n=this._url,r=this._url=ai.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),i&&n&&(n!==r||null!=(e=this.bufferController)&&e.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(i)),this.trigger(ii.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(t=-1,e){this.logger.log(`startLoad(${t+(e?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(t,e),this.started&&this.networkControllers);i++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let t=0;t<this.networkControllers.length&&(this.networkControllers[t].stopLoad(),!this.started&&this.networkControllers);t++);}get loadingEnabled(){return this.started&&this.streamController.state!==uo}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(t=>{t.resumeBuffering&&t.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(t=>{t.pauseBuffering&&t.pauseBuffering()}))}get inFlightFragments(){const t={[vi]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[yi]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[Ai]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const t=this._media,e=this.started,i=null==t?void 0:t.currentTime;this.detachMedia(),t&&(this.attachMedia(t),e&&(i?this.startLoad(i):this.config.autoStartLoad||this.startLoad()))}removeLevel(t){this.levelController.removeLevel(t)}get sessionId(){let t=this._sessionId;return t||(t=this._sessionId=on()),t}get levels(){const t=this.levelController.levels;return t||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){this.logger.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){this.logger.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){this.logger.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){this.logger.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){this.logger.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=this.capLevelController,i=!!t;e&&i!==this.config.capLevelToPlayerSize&&(i?e.startCapping():(e.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=i)}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 abrEwmaDefaultEstimate(){const{bwEstimator:t}=this.abrController;return t?t.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(this.logger.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){(function(t){return Fr.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 n=0;n<i;n++)if(t[n].maxBitrate>=e)return n;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:i}=this;let n;if(n=-1===e&&null!=t&&t.length?t.length-1:e,i)for(let e=n;e--;){const n=t[e].attrs["HDCP-LEVEL"];if(n&&n<=i)return e}return n}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()}get audioForwardBufferInfo(){var t;return(null==(t=this.audioStreamController)?void 0:t.getFwdBufferInfo())||null}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(t){var e;return(null==(e=this.audioTrackController)?void 0:e.setAudioOption(t))||null}setSubtitleOption(t){var e;return(null==(e=this.subtitleTrackController)?void 0: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 nextAudioTrack(){var t,e;return null!=(t=null==(e=this.audioStreamController)?void 0:e.nextAudioTrack)?t:-1}set nextAudioTrack(t){const{audioTrackController:e}=this;e&&(e.nextAudioTrack=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(){var t,e;return null!=(t=null==(e=this.latencyController)?void 0:e.liveSyncPosition)?t:null}get latency(){var t;return(null==(t=this.latencyController)?void 0:t.latency)||0}get maxLatency(){var t;return(null==(t=this.latencyController)?void 0:t.maxLatency)||0}get targetLatency(){var t;return(null==(t=this.latencyController)?void 0:t.targetLatency)||null}set targetLatency(t){this.latencyController&&(this.latencyController.targetLatency=t)}get drift(){var t;return(null==(t=this.latencyController)?void 0:t.drift)||null}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(t){this.levelController.pathwayPriority=t}get bufferedToEnd(){var t;return!(null==(t=this.bufferController)||!t.bufferedToEnd)}get interstitialsManager(){return this.interstitialsController?this.interstitialsController.interstitialsManager:null}get iframeVariants(){const t=this.levelController.iframeVariants;return t||[]}createIFramePlayer(t){return this._url&&this.iframeController?this.iframeController.createIFramePlayer(t):null}createImageIFramePlayer(t){return this._url&&this.iframeController?this.iframeController.createImageIFramePlayer(t):null}getMediaDecodingInfo(t,e=this.allAudioTracks){return Or(t,qr(e),navigator.mediaCapabilities)}}function lf(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,n=Array(e);i<e;i++)n[i]=t[i];return n}function hf(t,e,i){return e=ff(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,gf()?Reflect.construct(e,i||[],ff(t).constructor):e.apply(t,i))}function cf(t,e){for(var i=0;i<e.length;i++){var n=e[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,Ef(n.key),n)}}function uf(t,e,i){return(e=Ef(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function df(){return df="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(t,e,i){var n=function(t,e){for(;!{}.hasOwnProperty.call(t,e)&&null!==(t=ff(t)););return t}(t,e);if(n){var r=Object.getOwnPropertyDescriptor(n,e);return r.get?r.get.call(arguments.length<3?t:i):r.value}},df.apply(null,arguments)}function ff(t){return ff=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},ff(t)}function gf(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(gf=function(){return!!t})()}function pf(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),i.push.apply(i,n)}return i}function mf(t){for(var e=1;e<arguments.length;e++){var i=null!=arguments[e]?arguments[e]:{};e%2?pf(Object(i),!0).forEach(function(e){uf(t,e,i[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):pf(Object(i)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))})}return t}function vf(t,e){return vf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},vf(t,e)}function yf(t,e,i,n){var r=df(ff(t.prototype),e,i);return 2&n&&"function"==typeof r?function(t){return r.apply(i,t)}:r}function Af(t){return function(t){if(Array.isArray(t))return lf(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||function(t,e){if(t){if("string"==typeof t)return lf(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)?lf(t,e):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 Ef(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var n=i.call(t,e);if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}(t,"string");return"symbol"==typeof e?e:e+""}if(of.defaultConfig=void 0,!of)throw new Error("@clappr/hlsjs-playback requires hls.js (^1) to be loaded before it");var Tf=X.now,bf=X.listContainsIgnoreCase;ot.register("PLAYBACK_FRAGMENT_CHANGED"),ot.register("PLAYBACK_FRAGMENT_PARSING_METADATA");var Sf=function(t){function e(){var t;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e);for(var i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];return(t=hf(this,e,[].concat(n))).options.hlsPlayback=mf(mf({},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&&vf(t,e)}(e,t),i=e,n=[{key:"name",get:function(){return"hls"}},{key:"supportedVersion",get:function(){return{min:"0.16.3"}}},{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(ot.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.LIVE&&"EVENT"!==this._playlistType?this._extrapolatedStartTime:this._playableRegionStartTime}},{key:"_now",get:function(){return Tf()}},{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,n=(e.remote+i)/1e3;return Math.max(t-this._extrapolatedWindowDuration,Math.min(n,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(){var t;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.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=null!==(t=this.options.hlsRecoverAttempts)&&void 0!==t?t: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=mf({},this.options.playback.hlsjsConfig);this._hls=new of(t)}},{key:"_attachHLSMedia",value:function(){this._hls&&this._hls.attachMedia(this.el)}},{key:"_listenHLSEvents",value:function(){var t=this;this._hls&&(this._hls.once(of.Events.MEDIA_ATTACHED,function(){t.options.hlsPlayback.preload&&t._hls.loadSource(t.options.src)}),this._hls.on(of.Events.MANIFEST_LOADING,function(){t._manifestLoading=!0}),this._hls.on(of.Events.LEVEL_LOADED,function(e,i){return t._updatePlaybackType(e,i)}),this._hls.on(of.Events.LEVEL_UPDATED,function(e,i){return t._onLevelUpdated(e,i)}),this._hls.on(of.Events.LEVEL_SWITCHED,function(e,i){return t._onLevelSwitch(e,i)}),this._hls.on(of.Events.FRAG_CHANGED,function(e,i){return t._onFragmentChanged(e,i)}),this._hls.on(of.Events.FRAG_LOADED,function(e,i){return t._onFragmentLoaded(e,i)}),this._hls.on(of.Events.FRAG_BUFFERED,function(e,i){return t._onFragmentBuffered(e,i)}),this._hls.on(of.Events.FRAG_PARSING_METADATA,function(e,i){return t._onFragmentParsingMetadata(e,i)}),this._hls.on(of.Events.ERROR,function(e,i){return t._onHLSJSError(e,i)}),this._hls.on(of.Events.SUBTITLE_TRACK_LOADED,function(e,i){return t._onSubtitleLoaded(e,i)}),this._hls.on(of.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,n=e.once?"once":"on";i&&t._hls["".concat(n)](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(ot.Custom.PLAYBACK_FRAGMENT_PARSING_METADATA,{evt:t,data:e})}},{key:"render",value:function(){return this._ready(),yf(e,"render",this,3)([])}},{key:"_ready",value:function(){this._isReadyState||(!this._hls&&this._setup(),this._isReadyState=!0,this.trigger(ot.PLAYBACK_READY,this.name))}},{key:"_recover",value:function(t,e,i){if(this._recoveredDecodingError)if(this._recoveredAudioCodecError){it.error("hlsjs: failed to recover",{evt:t,data:e}),i.level=Tt.Levels.FATAL;var n=this.createError(i);this.trigger(ot.PLAYBACK_ERROR,n),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:"getFrameRate",value:function(){if(this._hls&&this._hls.levels&&this._hls.currentLevel>=0){var t=this._hls.levels[this._hls.currentLevel];return t&&t.frameRate?t.frameRate:null}return null}},{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){this.seek(this._duration*(t/100))}},{key:"seek",value:function(t){t<0&&(it.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===_t.VOD?this.settings.left=["playpause","position","duration"]:this.dvrEnabled?this.settings.left=["playpause"]:this.settings.left=["playstop"],this.settings.seekEnabled=this.isSeekEnabled(),this.trigger(ot.PLAYBACK_SETTINGSUPDATE)}},{key:"_onHLSJSError",value:function(t,e){var i,n={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&&(n.description+=", response: ".concat(JSON.stringify(e.response))),e.fatal)if(this._recoverAttemptsRemaining>0)switch(this._recoverAttemptsRemaining-=1,e.type){case of.ErrorTypes.NETWORK_ERROR:switch(e.details){case of.ErrorDetails.MANIFEST_LOAD_ERROR:case of.ErrorDetails.MANIFEST_LOAD_TIMEOUT:case of.ErrorDetails.MANIFEST_PARSING_ERROR:case of.ErrorDetails.LEVEL_LOAD_ERROR:case of.ErrorDetails.LEVEL_LOAD_TIMEOUT:it.error("hlsjs: unrecoverable network fatal error.",{evt:t,data:e}),i=this.createError(n),this.trigger(ot.PLAYBACK_ERROR,i),this.stop();break;default:it.warn("hlsjs: trying to recover from network error.",{evt:t,data:e}),n.level=Tt.Levels.WARN,this._hls.startLoad()}break;case of.ErrorTypes.MEDIA_ERROR:it.warn("hlsjs: trying to recover from media error.",{evt:t,data:e}),n.level=Tt.Levels.WARN,this._recover(t,e,n);break;default:it.error("hlsjs: could not recover from error.",{evt:t,data:e}),i=this.createError(n),this.trigger(ot.PLAYBACK_ERROR,i),this.stop()}else it.error("hlsjs: could not recover from error after maximum number of attempts.",{evt:t,data:e}),i=this.createError(n),this.trigger(ot.PLAYBACK_ERROR,i),this.stop();else{if(this.options.playback.triggerFatalErrorOnResourceDenied&&this._keyIsDenied(e))return it.error("hlsjs: could not load decrypt key.",{evt:t,data:e}),i=this.createError(n),this.trigger(ot.PLAYBACK_ERROR,i),void this.stop();n.level=Tt.Levels.WARN,it.warn("hlsjs: non-fatal error occurred",{evt:t,data:e})}}},{key:"_keyIsDenied",value:function(t){return t.type===of.ErrorTypes.NETWORK_ERROR&&t.details===of.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(ot.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,n=t.firstFragDateTime===this._lastTimeUpdate.firstFragDateTime,r=e&&i&&n,s=this._now-this._lastTimeUpdateFiredTime<this._timeUpdateThrottleDelay;return r&&s}},{key:"_onDurationChange",value:function(){var t=this.getDuration();Math.abs(this._lastDuration-t)<this._durationChangeMinOffset||(this._lastDuration=t,yf(e,"_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(Af(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 n={start:t[e].start,current:t[e].end,total:this.getDuration()};this.trigger(ot.PLAYBACK_PROGRESS,n,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),yf(e,"play",this,3)([]),this._startTimeUpdateTimer()}},{key:"pause",value:function(){this._hls&&this.el.pause()}},{key:"stop",value:function(){this._stopTimeUpdateTimer(),this._hls&&yf(e,"stop",this,3)([]),this._destroyHLSInstance()}},{key:"destroy",value:function(){this._stopTimeUpdateTimer(),this._destroyHLSInstance(),yf(e,"destroy",this,3)([])}},{key:"_updatePlaybackType",value:function(t,e){this._playbackType=e.details.live?_t.LIVE:_t.VOD,this._onLevelUpdated(t,e),this._ccTracksUpdated&&this._playbackType===_t.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(ot.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,n=!1,r=e.details.fragments,s=this._playableRegionStartTime,a=this._playableRegionDuration;if(0!==r.length){if(r[0].rawProgramDateTime&&(this._programDateTime=r[0].rawProgramDateTime),this._playableRegionStartTime!==r[0].start&&(i=!0,this._playableRegionStartTime=r[0].start),i)if(this._localStartTimeCorrelation){var o=this._localStartTimeCorrelation,l=this._now-o.local,h=(o.remote+l)/1e3;h<r[0].start?this._localStartTimeCorrelation={local:this._now,remote:1e3*r[0].start}:h>s+this._extrapolatedWindowDuration&&(this._localStartTimeCorrelation={local:this._now,remote:1e3*Math.max(r[0].start,s+this._extrapolatedWindowDuration)})}else this._localStartTimeCorrelation={local:this._now,remote:1e3*(r[0].start+this._extrapolatedWindowDuration/2)};var c=e.details.totalduration;if(this._playbackType===_t.LIVE){var u=e.details.targetduration*((this.options.playback.hlsjsConfig||{}).liveSyncDurationCount||of.DefaultConfig.liveSyncDurationCount);u<=c?(c-=u,this._durationExcludesAfterLiveSyncPoint=!0):this._durationExcludesAfterLiveSyncPoint=!1}c!==this._playableRegionDuration&&(n=!0,this._playableRegionDuration=c);var d=r[0].start+c,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};n&&this._onDurationChange(),i&&this._onProgress()}}},{key:"_onFragmentChanged",value:function(t,e){this._currentFragment=e.frag,this.trigger(ot.Custom.PLAYBACK_FRAGMENT_CHANGED,e)}},{key:"_onFragmentLoaded",value:function(t,e){this.trigger(ot.PLAYBACK_FRAGMENT_LOADED,e)}},{key:"_onFragmentBuffered",value:function(t,e){this.trigger(ot.PLAYBACK_FRAGMENT_BUFFERED,e)}},{key:"_onSubtitleLoaded",value:function(){if(!this._ccIsSetup){this.trigger(ot.PLAYBACK_SUBTITLE_AVAILABLE);var t=this._playbackType===_t.LIVE?-1:this.closedCaptionsTrackId;this.closedCaptionsTrackId=t,this._ccIsSetup=!0}}},{key:"_onLevelSwitch",value:function(t,e){this.levels.length||this._fillLevels(),this.trigger(ot.PLAYBACK_LEVEL_SWITCH_END),this.trigger(ot.PLAYBACK_LEVEL_SWITCH,e);var i=this._hls.levels[e.level];i&&(this.highDefinition=i.height>=720||i.bitrate/1e3>=2e3,this.trigger(ot.PLAYBACK_HIGHDEFINITIONUPDATE,this.highDefinition),this.trigger(ot.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()===_t.LIVE}},{key:"getPlaybackType",value:function(){return this._playbackType}},{key:"isSeekEnabled",value:function(){return this._playbackType===_t.VOD||this.dvrEnabled}}],r=[{key:"HLSJS",get:function(){return of}}],n&&cf(i.prototype,n),r&&cf(i,r),Object.defineProperty(i,"prototype",{writable:!1}),i;var i,n,r}(Ht);return Sf.canPlay=function(t,e){var i=t.split("?")[0].match(/.*\.(.*)$/)||[],n=i.length>1&&"m3u8"===i[1].toLowerCase()||bf(e,["application/vnd.apple.mpegurl","application/x-mpegURL"]);return!(!of.isSupported()||!n)},Xe.Loader.registerPlayback(Sf),i(i({},Xe),{},{HLS:Sf})});
|
|
2
2
|
//# sourceMappingURL=clappr.min.js.map
|