@byteplus/veplayer 1.18.0 → 1.19.0-rc.1
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/index.d.ts +1141 -266
- package/index.min.css +1 -1
- package/index.min.js +2 -2
- package/lite.cjs +2 -2
- package/lite.cjs.css +1 -1
- package/lite.d.ts +637 -0
- package/lite.esm.css +1 -1
- package/lite.esm.mjs +2 -2
- package/lite.min.css +1 -1
- package/lite.min.js +2 -2
- package/package.json +1 -1
- package/plugin/hlsEncrypt.js +2 -2
- package/plugin/hlsjs.js +1 -1
- package/plugin/hlsjsPro.js +2 -2
- package/plugin/modules/DashAbralgo.mjs +1 -1
- package/plugin/modules/XGVideo.mjs +1 -1
- package/plugin/modules/danmuMask.mjs +1 -1
- package/plugin/modules/danmujs.mjs +1 -1
- package/plugin/modules/dash.mjs +1 -1
- package/plugin/modules/flv.mjs +1 -1
- package/plugin/modules/hls.mjs +1 -1
- package/plugin/modules/hlsEncrypt.mjs +2 -2
- package/plugin/modules/hlsjs.mjs +2 -2
- package/plugin/modules/hlsjsPro.mjs +2 -2
- package/plugin/modules/mp4Encrypt.mjs +1 -1
- package/plugin/modules/preloader.mjs +1 -1
- package/plugin/modules/streamprobe.mjs +1 -1
- package/plugin/modules/vestrategy.mjs +1 -1
- package/plugin/modules/vestrategy_adapt_range.mjs +1 -1
- package/plugin/modules/vestrategy_h265.mjs +1 -1
- package/plugin/modules/vestrategy_preload.mjs +1 -1
- package/plugin/xgHls.js +1 -1
package/plugin/modules/hlsjs.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
// @byteplus/veplayer@1.
|
|
2
|
-
function ownKeys$1(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,r)}return s}function _objectSpread2$1(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$1(Object(s),!0).forEach((function(t){_defineProperty$1(e,t,s[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):ownKeys$1(Object(s)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))}))}return e}function _typeof(e){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var s=0;s<t.length;s++){var r=t[s];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,_toPropertyKey$1(r.key),r)}}function _createClass(e,t,s){return t&&_defineProperties(e.prototype,t),s&&_defineProperties(e,s),Object.defineProperty(e,"prototype",{writable:!1}),e}function _defineProperty$1(e,t,s){return(t=_toPropertyKey$1(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function _toConsumableArray(e){return _arrayWithoutHoles(e)||_iterableToArray(e)||_unsupportedIterableToArray(e)||_nonIterableSpread()}function _arrayWithoutHoles(e){if(Array.isArray(e))return _arrayLikeToArray(e)}function _iterableToArray(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function _unsupportedIterableToArray(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray(e,t);var s=Object.prototype.toString.call(e).slice(8,-1);return"Object"===s&&e.constructor&&(s=e.constructor.name),"Map"===s||"Set"===s?Array.from(e):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?_arrayLikeToArray(e,t):void 0}}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var s=0,r=new Array(t);s<t;s++)r[s]=e[s];return r}function _nonIterableSpread(){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 _toPrimitive$1(e,t){if("object"!=typeof e||null===e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var r=s.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}function _toPropertyKey$1(e){var t=_toPrimitive$1(e,"string");return"symbol"==typeof t?t:String(t)}var XG_DEBUG_OPEN="undefined"!=typeof window&&window.location&&window.location.href.indexOf("xgplayerdebugger=1")>-1,STYLE={info:"color: #525252; background-color: #90ee90;",error:"color: #525252; background-color: red;",warn:"color: #525252; background-color: yellow; "},XGTAG="%c[xgplayer]",XG_DEBUG={config:{debug:XG_DEBUG_OPEN?3:0},logInfo:function(e){for(var t,s=arguments.length,r=new Array(s>1?s-1:0),i=1;i<s;i++)r[i-1]=arguments[i];this.config.debug>=3&&(t=console).log.apply(t,[XGTAG,STYLE.info,e].concat(r))},logWarn:function(e){for(var t,s=arguments.length,r=new Array(s>1?s-1:0),i=1;i<s;i++)r[i-1]=arguments[i];this.config.debug>=1&&(t=console).warn.apply(t,[XGTAG,STYLE.warn,e].concat(r))},logError:function(e){var t;if(!(this.config.debug<1)){for(var s=this.config.debug>=2?"trace":"error",r=arguments.length,i=new Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];(t=console)[s].apply(t,[XGTAG,STYLE.error,e].concat(i))}}},XgplayerTimeRange=function(){function e(t){_classCallCheck(this,e),this.bufferedList=t}return _createClass(e,[{key:"start",value:function(e){return this.bufferedList[e].start}},{key:"end",value:function(e){return this.bufferedList[e].end}},{key:"length",get:function(){return this.bufferedList.length}}]),e}(),util={};function checkIsIn(e,t){for(var s=0,r=t.length;s<r;s++)if(e.indexOf(t[s])>-1)return!0;return!1}util.createDom=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"div",t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",i=document.createElement(e);return i.className=r,i.innerHTML=t,Object.keys(s).forEach((function(t){var r=t,n=s[t];"video"===e||"audio"===e||"live-video"===e?n&&i.setAttribute(r,n):i.setAttribute(r,n)})),i},util.createDomFromHtml=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";try{var r=document.createElement("div");r.innerHTML=e;var i=r.children;return r=null,i.length>0?(i=i[0],s&&util.addClass(i,s),t&&Object.keys(t).forEach((function(e){i.setAttribute(e,t[e])})),i):null}catch(e){return XG_DEBUG.logError("util.createDomFromHtml",e),null}},util.hasClass=function(e,t){if(!e||!t)return!1;try{return Array.prototype.some.call(e.classList,(function(e){return e===t}))}catch(r){var s=e.className&&"object"===_typeof(e.className)?e.getAttribute("class"):e.className;return s&&!!s.match(new RegExp("(\\s|^)"+t+"(\\s|$)"))}},util.addClass=function(e,t){if(e&&t)try{t.replace(/(^\s+|\s+$)/g,"").split(/\s+/g).forEach((function(t){t&&e.classList.add(t)}))}catch(s){util.hasClass(e,t)||(e.className&&"object"===_typeof(e.className)?e.setAttribute("class",e.getAttribute("class")+" "+t):e.className+=" "+t)}},util.removeClass=function(e,t){if(e&&t)try{t.replace(/(^\s+|\s+$)/g,"").split(/\s+/g).forEach((function(t){t&&e.classList.remove(t)}))}catch(s){util.hasClass(e,t)&&t.split(/\s+/g).forEach((function(t){var s=new RegExp("(\\s|^)"+t+"(\\s|$)");e.className&&"object"===_typeof(e.className)?e.setAttribute("class",e.getAttribute("class").replace(s," ")):e.className=e.className.replace(s," ")}))}},util.toggleClass=function(e,t){e&&t.split(/\s+/g).forEach((function(t){util.hasClass(e,t)?util.removeClass(e,t):util.addClass(e,t)}))},util.classNames=function(){for(var e=arguments,t=[],s=function(s){"String"===util.typeOf(e[s])?t.push(e[s]):"Object"===util.typeOf(e[s])&&Object.keys(e[s]).map((function(r){e[s][r]&&t.push(r)}))},r=0;r<arguments.length;r++)s(r);return t.join(" ")},util.findDom=function(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:document,s=arguments.length>1?arguments[1]:void 0;try{e=t.querySelector(s)}catch(r){XG_DEBUG.logError("util.findDom",r),0===s.indexOf("#")&&(e=t.getElementById(s.slice(1)))}return e},util.getCss=function(e,t){return e.currentStyle?e.currentStyle[t]:document.defaultView.getComputedStyle(e,!1)[t]},util.padStart=function(e,t,s){for(var r=String(s),i=t>>0,n=Math.ceil(i/r.length),a=[],o=String(e);n--;)a.push(r);return a.join("").substring(0,i-o.length)+o},util.format=function(e){if(window.isNaN(e))return"";e=Math.round(e);var t=util.padStart(Math.floor(e/3600),2,0),s=util.padStart(Math.floor((e-3600*t)/60),2,0),r=util.padStart(Math.floor(e-3600*t-60*s),2,0);return("00"===t?[s,r]:[t,s,r]).join(":")},util.event=function(e){if(e.touches){var t=e.touches[0]||e.changedTouches[0];e.clientX=t.clientX||0,e.clientY=t.clientY||0,e.offsetX=t.pageX-t.target.offsetLeft,e.offsetY=t.pageY-t.target.offsetTop}e._target=e.target||e.srcElement},util.typeOf=function(e){return Object.prototype.toString.call(e).match(/([^\s.*]+)(?=]$)/g)[0]},util.deepCopy=function(e,t){if("Object"===util.typeOf(t)&&"Object"===util.typeOf(e))return Object.keys(t).forEach((function(s){"Object"!==util.typeOf(t[s])||t[s]instanceof Node?"Array"===util.typeOf(t[s])?e[s]="Array"===util.typeOf(e[s])?e[s].concat(t[s]):t[s]:e[s]=t[s]:void 0===e[s]||void 0===e[s]?e[s]=t[s]:util.deepCopy(e[s],t[s])})),e},util.deepMerge=function(e,t){return Object.keys(t).map((function(s){var r;"Array"===util.typeOf(t[s])&&"Array"===util.typeOf(e[s])?"Array"===util.typeOf(e[s])&&(r=e[s]).push.apply(r,_toConsumableArray(t[s])):util.typeOf(e[s])!==util.typeOf(t[s])||null===e[s]||"Object"!==util.typeOf(e[s])||t[s]instanceof window.Node?null!==t[s]&&(e[s]=t[s]):util.deepMerge(e[s],t[s])})),e},util.getBgImage=function(e){var t=(e.currentStyle||window.getComputedStyle(e,null)).backgroundImage;if(!t||"none"===t)return"";var s=document.createElement("a");return s.href=t.replace(/url\("|"\)/g,""),s.href},util.copyDom=function(e){if(e&&1===e.nodeType){var t=document.createElement(e.tagName);return Array.prototype.forEach.call(e.attributes,(function(e){t.setAttribute(e.name,e.value)})),e.innerHTML&&(t.innerHTML=e.innerHTML),t}return""},util.setInterval=function(e,t,s,r){e._interval[t]||(e._interval[t]=window.setInterval(s.bind(e),r))},util.clearInterval=function(e,t){clearInterval(e._interval[t]),e._interval[t]=null},util.setTimeout=function(e,t,s){e._timers||(e._timers=[]);var r=setTimeout((function(){t(),util.clearTimeout(e,r)}),s);return e._timers.push(r),r},util.clearTimeout=function(e,t){var s=e._timers;if("Array"===util.typeOf(s)){for(var r=0;r<s.length;r++)if(s[r]===t){s.splice(r,1),clearTimeout(t);break}}else clearTimeout(t)},util.clearAllTimers=function(e){var t=e._timers;"Array"===util.typeOf(t)&&(t.map((function(e){clearTimeout(e)})),e._timerIds=[])},util.createImgBtn=function(e,t,s,r){var i,n,a,o=util.createDom("xg-".concat(e),"",{},"xgplayer-".concat(e,"-img"));(o.style.backgroundImage='url("'.concat(t,'")'),s&&r)&&(["px","rem","em","pt","dp","vw","vh","vm","%"].every((function(e){return!(s.indexOf(e)>-1&&r.indexOf(e)>-1)||(i=parseFloat(s.slice(0,s.indexOf(e)).trim()),n=parseFloat(r.slice(0,r.indexOf(e)).trim()),a=e,!1)})),o.style.width="".concat(i).concat(a),o.style.height="".concat(n).concat(a),o.style.backgroundSize="".concat(i).concat(a," ").concat(n).concat(a),o.style.margin="start"===e?"-".concat(n/2).concat(a," auto auto -").concat(i/2).concat(a):"auto 5px auto 5px");return o},util.Hex2RGBA=function(e,t){var s=[];if(/^\#[0-9A-F]{3}$/i.test(e)){var r="#";e.replace(/[0-9A-F]/gi,(function(e){r+=e+e})),e=r}return/^#[0-9A-F]{6}$/i.test(e)?(e.replace(/[0-9A-F]{2}/gi,(function(e){s.push(parseInt(e,16))})),"rgba(".concat(s.join(","),", ").concat(t,")")):"rgba(255, 255, 255, 0.1)"},util.getFullScreenEl=function(){return document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement},util.checkIsFunction=function(e){return e&&"function"==typeof e},util.checkIsObject=function(e){return null!==e&&"object"===_typeof(e)},util.hide=function(e){e.style.display="none"},util.show=function(e,t){e.style.display=t||"block"},util.isUndefined=function(e){if(null==e)return!0},util.isNotNull=function(e){return!(null==e)},util.setStyleFromCsstext=function(e,t){t&&("String"===util.typeOf(t)?t.replace(/\s+/g,"").split(";").map((function(t){if(t){var s=t.split(":");s.length>1&&(e.style[s[0]]=s[1])}})):Object.keys(t).map((function(s){e.style[s]=t[s]})))},util.filterStyleFromText=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:["width","height","top","left","bottom","right","position","z-index","padding","margin","transform"],s=e.style.cssText;if(!s)return{};var r=s.replace(/\s+/g,"").split(";"),i={},n={};return r.map((function(e){if(e){var s=e.split(":");s.length>1&&(checkIsIn(s[0],t)?i[s[0]]=s[1]:n[s[0]]=s[1])}})),e.setAttribute("style",""),Object.keys(n).map((function(t){e.style[t]=n[t]})),i},util.getStyleFromCsstext=function(e){var t=e.style.cssText;if(!t)return{};var s=t.replace(/\s+/g,"").split(";"),r={};return s.map((function(e){if(e){var t=e.split(":");t.length>1&&(r[t[0]]=t[1])}})),r},util.preloadImg=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(){},s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){};if(e){var r=new window.Image;r.onload=function(e){r=null,t&&t(e)},r.onerror=function(e){r=null,s&&s(e)},r.src=e}},util.stopPropagation=function(e){e&&e.stopPropagation()},util.scrollTop=function(){return window.pageYOffset||document.documentElement.scrollTop||document.body.scrollTop||0},util.scrollLeft=function(){return window.pageXOffset||document.documentElement.scrollLeft||document.body.scrollLeft||0},util.checkTouchSupport=function(){return"ontouchstart"in window},util.getBuffered2=function(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:.5,s=[],r=0;r<e.length;r++)s.push({start:e.start(r)<.5?0:e.start(r),end:e.end(r)});s.sort((function(e,t){var s=e.start-t.start;return s||t.end-e.end}));var i=[];if(t)for(var n=0;n<s.length;n++){var a=i.length;if(a){var o=i[a-1].end;s[n].start-o<t?s[n].end>o&&(i[a-1].end=s[n].end):i.push(s[n])}else i.push(s[n])}else i=s;return new XgplayerTimeRange(i)},util.getEventPos=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return e.touches&&e.touches.length>0&&(e=e.touches[0]),{x:e.x/t,y:e.y/t,clientX:e.clientX/t,clientY:e.clientY/t,offsetX:e.offsetX/t,offsetY:e.offsetY/t,pageX:e.pageX/t,pageY:e.pageY/t}},util.requestAnimationFrame=function(e){var t=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame;if(t)return t(e)},util.getHostFromUrl=function(e){if("String"!==util.typeOf(e))return"";var t=e.split("/"),s="";return t.length>3&&t[2]&&(s=t[2]),s},util.cancelAnimationFrame=function(e){var t=window.cancelAnimationFrame||window.mozCancelAnimationFrame||window.cancelRequestAnimationFrame;t&&t(e)},util.isMSE=function(e){return e.media&&(e=e.media),!!(e&&e instanceof HTMLMediaElement)&&(/^blob/.test(e.currentSrc)||/^blob/.test(e.src))},util.isBlob=function(e){return"string"==typeof e&&/^blob/.test(e)},util.generateSessionId=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=(new Date).getTime();try{e=parseInt(e)}catch(t){e=0}return t+=e,window.performance&&"function"==typeof window.performance.now&&(t+=parseInt(window.performance.now())),"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var s=(t+16*Math.random())%16|0;return t=Math.floor(t/16),("x"===e?s:3&s|8).toString(16)}))},util.createEvent=function(e){var t;return"function"==typeof window.Event?t=new Event(e):(t=document.createEvent("Event")).initEvent(e,!0,!0),t},util.adjustTimeByDuration=function(e,t,s){return t&&e&&(e>t||s&&e<t)?t:e},util.createPositionBar=function(e,t){var s=util.createDom("xg-bar","",{"data-index":-1},e);return t.appendChild(s),s},util.getTransformStyle=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{x:0,y:0,scale:1,rotate:0},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",s={scale:"".concat(e.scale||1),translate:"".concat(e.x||0,"%, ").concat(e.y||0,"%"),rotate:"".concat(e.rotate||0,"deg")};return Object.keys(s).forEach((function(e){var r=new RegExp("".concat(e,"\\([^\\(]+\\)"),"g"),i="".concat(e,"(").concat(s[e],")");r.test(t)?(r.lastIndex=-1,t=t.replace(r,i)):t+="".concat(i," ")})),t},util.convertDeg=function(e){return Math.abs(e)<=1?360*e:e%360},util.getIndexByTime=function(e,t){var s=t.length,r=-1;if(s<1)return r;if(e<=t[0].end||s<2)r=0;else if(e>t[s-1].end)r=s-1;else for(var i=1;i<s;i++)if(e>t[i-1].end&&e<=t[i].end){r=i;break}return r},util.getOffsetCurrentTime=function(e,t){var s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:-1,r=-1;if((r=s>=0&&s<t.length?s:util.getIndexByTime(e,t))<0)return-1;var i=t.length,n=t[r],a=n.start,o=n.end,l=n.cTime,d=n.offset;return e<a?l:e>=a&&e<=o?e-d:e>o&&r>=i-1?o:-1},util.getCurrentTimeByOffset=function(e,t){var s=-1;if(!t||t.length<0)return e;for(var r=0;r<t.length;r++)if(e<=t[r].duration){s=r;break}if(-1!==s){var i=t[s].start;return s-1<0?i+e:i+(e-t[s-1].duration)}return e};var URL_CHANGE="urlchange";function callHandler(e,t,s){for(var r=arguments.length,i=new Array(r>3?r-3:0),n=3;n<r;n++)i[n-3]=arguments[n];var a=t.call.apply(t,[e].concat(i));s&&"function"==typeof s&&(a&&a.then?a.then((function(){for(var t=arguments.length,r=new Array(t),i=0;i<t;i++)r[i]=arguments[i];s.call.apply(s,[e].concat(r))})):s.call.apply(s,[e].concat(i)))}function hook(e,t){var s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{pre:null,next:null};return this.__hooks||(this.__hooks={}),!this.__hooks[e]&&(this.__hooks[e]=null),function(){var r=arguments,i=this;if(s.pre)try{var n;(n=s.pre).call.apply(n,[this].concat(Array.prototype.slice.call(arguments)))}catch(t){throw t.message="[pluginName: ".concat(this.pluginName,":").concat(e,":pre error] >> ").concat(t.message),t}if(this.__hooks&&this.__hooks[e])try{var a=runHooks.apply(void 0,[this,e,t].concat(Array.prototype.slice.call(arguments)));a?a.then?a.then((function(e){!1!==e&&callHandler.apply(void 0,[i,t,s.next].concat(_toConsumableArray(r)))})).catch((function(e){throw e})):callHandler.apply(void 0,[this,t,s.next].concat(Array.prototype.slice.call(arguments))):void 0===a&&callHandler.apply(void 0,[this,t,s.next].concat(Array.prototype.slice.call(arguments)))}catch(t){throw t.message="[pluginName: ".concat(this.pluginName,":").concat(e,"] >> ").concat(t.message),t}else callHandler.apply(void 0,[this,t,s.next].concat(Array.prototype.slice.call(arguments)))}.bind(this)}function findHookIndex(e,t){var s=this.__hooks;if(!s||!Array.isArray(s[e]))return-1;for(var r=s[e],i=0;i<r.length;i++)if(r[i]===t)return i;return-1}function useHooks(e,t){var s=this.__hooks;if(s)return s.hasOwnProperty(e)?(Array.isArray(s[e])||(s[e]=[]),-1===findHookIndex.call(this,e,t)&&s[e].push(t),!0):(console.warn("has no supported hook which name [".concat(e,"]")),!1)}function removeHooks(e,t){var s=this.__hooks;if(s)if(Array.isArray(s[e])){var r=s[e],i=findHookIndex.call(this,e,t);-1!==i&&r.splice(i,1)}else s[e]&&(s[e]=null)}function hooksDescriptor(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];e.__hooks={},t&&t.map((function(t){e.__hooks[t]=null})),Object.defineProperty(e,"hooks",{get:function(){return e.__hooks&&Object.keys(e.__hooks).map((function(t){if(e.__hooks[t])return t}))}})}function delHooksDescriptor(e){e.__hooks=null}function runHooks(e,t,s){for(var r=arguments.length,i=new Array(r>3?r-3:0),n=3;n<r;n++)i[n-3]=arguments[n];if(e.__hooks&&Array.isArray(e.__hooks[t])){var a=e.__hooks[t],o=-1;return function e(t,s,r){for(var i=arguments.length,n=new Array(i>3?i-3:0),l=3;l<i;l++)n[l-3]=arguments[l];if(o++,0===a.length||o===a.length)return r.call.apply(r,[t,t].concat(n));var d=a[o],h=d.call.apply(d,[t,t].concat(n));return h&&h.then?h.then((function(i){return!1===i?null:e.apply(void 0,[t,s,r].concat(n))})).catch((function(e){console.warn("[runHooks]".concat(s," reject"),e.message)})):!1!==h?e.apply(void 0,[t,s,r].concat(n)):void 0}.apply(void 0,[e,t,s].concat(i))}return s.call.apply(s,[e,e].concat(i))}function showErrorMsg(e,t){XG_DEBUG.logError("[".concat(e,"] event or callback cant be undefined or null when call ").concat(t))}var BasePlugin=function(){function e(t){_classCallCheck(this,e),util.checkIsFunction(this.beforeCreate)&&this.beforeCreate(t),hooksDescriptor(this),this.__args=t,this.__events={},this.__onceEvents={},this.config=t.config||{},this.player=null,this.playerConfig={},this.pluginName="",this.__init(t)}return _createClass(e,[{key:"beforeCreate",value:function(e){}},{key:"afterCreate",value:function(){}},{key:"beforePlayerInit",value:function(){}},{key:"onPluginsReady",value:function(){}},{key:"afterPlayerInit",value:function(){}},{key:"destroy",value:function(){}},{key:"__init",value:function(e){this.player=e.player,this.playerConfig=e.player&&e.player.config,this.pluginName=e.pluginName?e.pluginName.toLowerCase():this.constructor.pluginName.toLowerCase(),this.logger=e.player&&e.player.logger}},{key:"updateLang",value:function(e){e||(e=this.lang)}},{key:"lang",get:function(){return this.player.lang}},{key:"i18n",get:function(){return this.player.i18n}},{key:"i18nKeys",get:function(){return this.player.i18nKeys}},{key:"domEventType",get:function(){var e=util.checkTouchSupport()?"touch":"mouse";return!this.playerConfig||"touch"!==this.playerConfig.domEventType&&"mouse"!==this.playerConfig.domEventType||(e=this.playerConfig.domEventType),e}},{key:"on",value:function(e,t){var s=this;e&&t&&this.player?"string"==typeof e?(this.__events[e]=t,this.player.on(e,t)):Array.isArray(e)&&e.forEach((function(e){s.__events[e]=t,s.player.on(e,t)})):showErrorMsg(this.pluginName,"plugin.on(event, callback)")}},{key:"once",value:function(e,t){var s=this;e&&t&&this.player?"string"==typeof e?(this.__onceEvents[e]=t,this.player.once(e,t)):Array.isArray(e)&&e.forEach((function(r){s.__onceEvents[r]=t,s.player.once(e,t)})):showErrorMsg(this.pluginName,"plugin.once(event, callback)")}},{key:"off",value:function(e,t){var s=this;e&&t&&this.player?"string"==typeof e?(delete this.__events[e],this.player.off(e,t)):Array.isArray(e)&&e.forEach((function(r){delete s.__events[e],s.player.off(r,t)})):showErrorMsg(this.pluginName,"plugin.off(event, callback)")}},{key:"offAll",value:function(){var e=this;["__events","__onceEvents"].forEach((function(t){Object.keys(e[t]).forEach((function(s){e[t][s]&&e.off(s,e[t][s]),s&&delete e[t][s]}))})),this.__events={},this.__onceEvents={}}},{key:"emit",value:function(e){var t;if(this.player){for(var s=arguments.length,r=new Array(s>1?s-1:0),i=1;i<s;i++)r[i-1]=arguments[i];(t=this.player).emit.apply(t,[e].concat(r))}}},{key:"emitUserAction",value:function(e,t){var s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(this.player){var r=_objectSpread2$1(_objectSpread2$1({},s),{},{pluginName:this.pluginName});this.player.emitUserAction(e,t,r)}}},{key:"hook",value:function(e,t){return hook.call.apply(hook,[this].concat(Array.prototype.slice.call(arguments)))}},{key:"useHooks",value:function(e,t){for(var s=arguments.length,r=new Array(s>2?s-2:0),i=2;i<s;i++)r[i-2]=arguments[i];return useHooks.call.apply(useHooks,[this].concat(Array.prototype.slice.call(arguments)))}},{key:"removeHooks",value:function(e,t){for(var s=arguments.length,r=new Array(s>2?s-2:0),i=2;i<s;i++)r[i-2]=arguments[i];return removeHooks.call.apply(removeHooks,[this].concat(Array.prototype.slice.call(arguments)))}},{key:"registerPlugin",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";if(this.player)return s&&(t.pluginName=s),this.player.registerPlugin({plugin:e,options:t})}},{key:"getPlugin",value:function(e){return this.player?this.player.getPlugin(e):null}},{key:"__destroy",value:function(){var e=this,t=this.player,s=this.pluginName;this.offAll(),util.clearAllTimers(this),util.checkIsFunction(this.destroy)&&this.destroy(),["player","playerConfig","pluginName","logger","__args","__hooks"].map((function(t){e[t]=null})),t.unRegisterPlugin(s),delHooksDescriptor(this)}}],[{key:"defineGetterOrSetter",value:function(e,t){for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&Object.defineProperty(e,s,t[s])}},{key:"defineMethod",value:function(e,t){for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&"function"==typeof t[s]&&Object.defineProperty(e,s,{configurable:!0,value:t[s]})}},{key:"defaultConfig",get:function(){return{}}},{key:"pluginName",get:function(){return"pluginName"}}]),e}();const isFiniteNumber=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},isSafeInteger=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=MAX_SAFE_INTEGER},MAX_SAFE_INTEGER=Number.MAX_SAFE_INTEGER||9007199254740991;let ErrorTypes=function(e){return e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError",e}({}),ErrorDetails=function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",e.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",e.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.ASSET_LIST_LOAD_ERROR="assetListLoadError",e.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",e.ASSET_LIST_PARSING_ERROR="assetListParsingError",e.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.ATTACH_MEDIA_ERROR="attachMediaError",e.UNKNOWN="unknown",e}({}),Events=function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.MEDIA_ENDED="hlsMediaEnded",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFERED_TO_END="hlsBufferedToEnd",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",e.ASSET_LIST_LOADING="hlsAssetListLoading",e.ASSET_LIST_LOADED="hlsAssetListLoaded",e.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",e.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",e.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",e.INTERSTITIAL_STARTED="hlsInterstitialStarted",e.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",e.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",e.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",e.INTERSTITIAL_ENDED="hlsInterstitialEnded",e.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",e.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",e.EVENT_CUE_ENTER="hlsEventCueEnter",e}({});var PlaylistContextType={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},PlaylistLevelType={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class EWMA{constructor(e,t=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=s}sample(e,t){const s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class EwmaBandWidthEstimator{constructor(e,t,s,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new EWMA(e),this.fast_=new EWMA(t),this.defaultTTFB_=r,this.ttfb_=new EWMA(e)}update(e,t){const{slow_:s,fast_:r,ttfb_:i}=this;s.halfLife!==e&&(this.slow_=new EWMA(e,s.getEstimate(),s.getTotalWeight())),r.halfLife!==t&&(this.fast_=new EWMA(t,r.getEstimate(),r.getTotalWeight())),i.halfLife!==e&&(this.ttfb_=new EWMA(e,i.getEstimate(),i.getTotalWeight()))}sample(e,t){const s=(e=Math.max(e,this.minDelayMs_))/1e3,r=8*t/s;this.fast_.sample(s,r),this.slow_.sample(s,r)}sampleTTFB(e){const t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function _defineProperty(e,t,s){return(t=_toPropertyKey(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function _extends(){return _extends=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var s=arguments[t];for(var r in s)({}).hasOwnProperty.call(s,r)&&(e[r]=s[r])}return e},_extends.apply(null,arguments)}function ownKeys(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,r)}return s}function _objectSpread2(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?ownKeys(Object(s),!0).forEach((function(t){_defineProperty(e,t,s[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):ownKeys(Object(s)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))}))}return e}function _toPrimitive(e,t){if("object"!=typeof e||!e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var r=s.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}function _toPropertyKey(e){var t=_toPrimitive(e,"string");return"symbol"==typeof t?t:t+""}class Logger{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const s=`[${e}]:`;this.trace=noop,this.debug=t.debug.bind(null,s),this.log=t.log.bind(null,s),this.warn=t.warn.bind(null,s),this.info=t.info.bind(null,s),this.error=t.error.bind(null,s)}}const noop=function(){},fakeLogger={trace:noop,debug:noop,log:noop,warn:noop,info:noop,error:noop};function createLogger(){return _extends({},fakeLogger)}function consolePrintFn(e,t){const s=self.console[e];return s?s.bind(self.console,`${t?"["+t+"] ":""}[${e}] >`):noop}function getLoggerFn(e,t,s){return t[e]?t[e].bind(t):consolePrintFn(e,s)}const exportedLogger=createLogger();function enableLogs(e,t,s){const r=createLogger();if("object"==typeof console&&!0===e||"object"==typeof e){const i=["debug","log","info","warn","error"];i.forEach((t=>{r[t]=getLoggerFn(t,e,s)}));try{r.log(`Debug logs enabled for "${t}" in hls.js version 1.6.0-beta.2`)}catch(e){return createLogger()}i.forEach((t=>{exportedLogger[t]=getLoggerFn(t,e)}))}else _extends(exportedLogger,r);return r}const logger=exportedLogger;function getMediaSource(e=!0){if("undefined"==typeof self)return;return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function isManagedMediaSource(e){return"undefined"!=typeof self&&e===self.ManagedMediaSource}function isCompatibleTrackChange(e,t){const s=Object.keys(e),r=Object.keys(t),i=s.length,n=r.length;return!i||!n||i===n&&!s.some((e=>-1===r.indexOf(e)))}const sampleEntryCodesISO={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function isCodecType(e,t){const s=sampleEntryCodesISO[t];return!!s&&!!s[e.slice(0,4)]}function areCodecsMediaSourceSupported(e,t,s=!0){return!e.split(",").some((e=>!isCodecMediaSourceSupported(e,t,s)))}function isCodecMediaSourceSupported(e,t,s=!0){var r;const i=getMediaSource(s);return null!=(r=null==i?void 0:i.isTypeSupported(mimeTypeForCodec(e,t)))&&r}function mimeTypeForCodec(e,t){return`${t}/mp4;codecs=${e}`}function videoCodecPreferenceValue(e){if(e){const t=e.substring(0,4);return sampleEntryCodesISO.video[t]}return 2}function codecsSetSelectionPreferenceValue(e){return e.split(",").reduce(((e,t)=>{const s=sampleEntryCodesISO.video[t];return s?(2*s+e)/(e?3:2):(sampleEntryCodesISO.audio[t]+e)/(e?2:1)}),0)}const CODEC_COMPATIBLE_NAMES={};function getCodecCompatibleNameLower(e,t=!0){if(CODEC_COMPATIBLE_NAMES[e])return CODEC_COMPATIBLE_NAMES[e];const s={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e];for(let i=0;i<s.length;i++){var r;if(isCodecMediaSourceSupported(s[i],"audio",t))return CODEC_COMPATIBLE_NAMES[e]=s[i],s[i];if("mp3"===s[i]&&null!=(r=getMediaSource(t))&&r.isTypeSupported("audio/mpeg"))return""}return e}const AUDIO_CODEC_REGEXP=/flac|opus|mp4a\.40\.34/i;function getCodecCompatibleName(e,t=!0){return e.replace(AUDIO_CODEC_REGEXP,(e=>getCodecCompatibleNameLower(e.toLowerCase(),t)))}function pickMostCompleteCodecName(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e)))return e;if(t){const s=t.split(",");if(s.length>1){if(e)for(let t=s.length;t--;)if(s[t].substring(0,4)===e.substring(0,4))return s[t];return s[0]}}return t||e}function convertAVC1ToAVCOTI(e){const t=e.split(",");for(let e=0;e<t.length;e++){const s=t[e].split(".");if(s.length>2){let r=s.shift()+".";r+=parseInt(s.shift()).toString(16),r+=("000"+parseInt(s.shift()).toString(16)).slice(-4),t[e]=r}}return t.join(",")}function fillInMissingAV01Params(e){if(e.startsWith("av01.")){const t=e.split("."),s=["0","111","01","01","01","0"];for(let e=t.length;e>4&&e<10;e++)t[e]=s[e-4];return t.join(".")}return e}function getM2TSSupportedAudioTypes(e){const t=getMediaSource(e)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}const SUPPORTED_INFO_DEFAULT={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},SUPPORTED_INFO_CACHE={};function requiresMediaCapabilitiesDecodingInfo(e,t,s,r,i,n){const a=e.audioCodec?e.audioGroups:null,o=null==n?void 0:n.audioCodec,l=null==n?void 0:n.channels,d=l?parseInt(l):o?1/0:2;let h=null;if(null!=a&&a.length)try{h=1===a.length&&a[0]?t.groups[a[0]].channels:a.reduce(((e,s)=>{if(s){const r=t.groups[s];if(!r)throw new Error(`Audio track group ${s} not found`);Object.keys(r.channels).forEach((t=>{e[t]=(e[t]||0)+r.channels[t]}))}return e}),{2:0})}catch(e){return!0}return void 0!==e.videoCodec&&(e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(r,30)||"SDR"!==e.videoRange&&e.videoRange!==s||e.bitrate>Math.max(i,8e6))||!!h&&isFiniteNumber(d)&&Object.keys(h).some((e=>parseInt(e)>d))}function getMediaDecodingInfoPromise(e,t,s){const r=e.videoCodec,i=e.audioCodec;if(!r&&!i||!s)return Promise.resolve(SUPPORTED_INFO_DEFAULT);const n=[];if(r){const t={width:e.width,height:e.height,bitrate:Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)),framerate:e.frameRate||30},s=e.videoRange;"SDR"!==s&&(t.transferFunction=s.toLowerCase()),n.push.apply(n,r.split(",").map((e=>({type:"media-source",video:_objectSpread2(_objectSpread2({},t),{},{contentType:mimeTypeForCodec(fillInMissingAV01Params(e),"video")})}))))}return i&&e.audioGroups&&e.audioGroups.forEach((e=>{var s;e&&(null==(s=t.groups[e])||s.tracks.forEach((t=>{if(t.groupId===e){const e=t.channels||"",s=parseFloat(e);isFiniteNumber(s)&&s>2&&n.push.apply(n,i.split(",").map((e=>({type:"media-source",audio:{contentType:mimeTypeForCodec(e,"audio"),channels:""+s}}))))}})))})),Promise.all(n.map((e=>{const t=getMediaDecodingInfoKey(e);return SUPPORTED_INFO_CACHE[t]||(SUPPORTED_INFO_CACHE[t]=s.decodingInfo(e))}))).then((e=>({supported:!e.some((e=>!e.supported)),configurations:n,decodingInfoResults:e}))).catch((e=>({supported:!1,configurations:n,decodingInfoResults:[],error:e})))}function getMediaDecodingInfoKey(e){const{audio:t,video:s}=e,r=s||t;if(r){const e=r.contentType.split('"')[1];if(s)return`r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${e}_${Math.ceil(s.bitrate/1e5)}`;if(t)return`c${t.channels}${t.spatialRendering?"s":"n"}_${e}`}return""}const HdcpLevels=["NONE","TYPE-0","TYPE-1",null];function isHdcpLevel(e){return HdcpLevels.indexOf(e)>-1}const VideoRangeValues=["SDR","PQ","HLG"];function isVideoRange(e){return!!e&&VideoRangeValues.indexOf(e)>-1}var HlsSkip={No:"",Yes:"YES",v2:"v2"};function getSkipValue(e){const{canSkipUntil:t,canSkipDateRanges:s,age:r}=e;return t&&r<t/2?s?HlsSkip.v2:HlsSkip.Yes:HlsSkip.No}class HlsUrlParameters{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){const t=new self.URL(e);return void 0!==this.msn&&t.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class Level{constructor(e){this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter((e=>!!e)).map((e=>e.substring(0,4))).join(","),this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return hasGroup(this._audioGroups,e)}hasSubtitleGroup(e){return hasGroup(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t)if("audio"===e){let e=this._audioGroups;e||(e=this._audioGroups=[]),-1===e.indexOf(t)&&e.push(t)}else if("text"===e){let e=this._subtitleGroups;e||(e=this._subtitleGroups=[]),-1===e.indexOf(t)&&e.push(t)}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return null==(e=this.audioGroups)?void 0:e[0]}get textGroupId(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}addFallback(){}}function hasGroup(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}function isHdrSupported(){if("function"==typeof matchMedia){const e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}function getVideoSelectionOptions(e,t){let s=!1,r=[];if(e&&(s="SDR"!==e,r=[e]),t){r=t.allowedVideoRanges||VideoRangeValues.slice(0);const e="SDR"!==r.join("")&&!t.videoCodec;s=void 0!==t.preferHDR?t.preferHDR:e&&isHdrSupported(),s||(r=["SDR"])}return{preferHDR:s,allowedVideoRanges:r}}function getStartCodecTier(e,t,s,r,i){const n=Object.keys(e),a=null==r?void 0:r.channels,o=null==r?void 0:r.audioCodec,l=null==i?void 0:i.videoCodec,d=a&&2===parseInt(a);let h=!1,c=!1,u=1/0,f=1/0,g=1/0,m=1/0,p=0,E=[];const{preferHDR:y,allowedVideoRanges:v}=getVideoSelectionOptions(t,i);for(let t=n.length;t--;){const s=e[n[t]];h||(h=s.channels[2]>0),u=Math.min(u,s.minHeight),f=Math.min(f,s.minFramerate),g=Math.min(g,s.minBitrate);v.filter((e=>s.videoRanges[e]>0)).length>0&&(c=!0)}u=isFiniteNumber(u)?u:0,f=isFiniteNumber(f)?f:0;const T=Math.max(1080,u),S=Math.max(30,f);g=isFiniteNumber(g)?g:s,s=Math.max(g,s),c||(t=void 0);const A=n.length>1;return{codecSet:n.reduce(((t,r)=>{const i=e[r];if(r===t)return t;if(E=c?v.filter((e=>i.videoRanges[e]>0)):[],A){if(i.minBitrate>s)return logStartCodecCandidateIgnored(r,`min bitrate of ${i.minBitrate} > current estimate of ${s}`),t;if(!i.hasDefaultAudio)return logStartCodecCandidateIgnored(r,"no renditions with default or auto-select sound found"),t;if(o&&r.indexOf(o.substring(0,4))%5!=0)return logStartCodecCandidateIgnored(r,`audio codec preference "${o}" not found`),t;if(a&&!d){if(!i.channels[a])return logStartCodecCandidateIgnored(r,`no renditions with ${a} channel sound found (channels options: ${Object.keys(i.channels)})`),t}else if((!o||d)&&h&&0===i.channels[2])return logStartCodecCandidateIgnored(r,"no renditions with stereo sound found"),t;if(i.minHeight>T)return logStartCodecCandidateIgnored(r,`min resolution of ${i.minHeight} > maximum of ${T}`),t;if(i.minFramerate>S)return logStartCodecCandidateIgnored(r,`min framerate of ${i.minFramerate} > maximum of ${S}`),t;if(!E.some((e=>i.videoRanges[e]>0)))return logStartCodecCandidateIgnored(r,`no variants with VIDEO-RANGE of ${JSON.stringify(E)} found`),t;if(l&&r.indexOf(l.substring(0,4))%5!=0)return logStartCodecCandidateIgnored(r,`video codec preference "${l}" not found`),t;if(i.maxScore<p)return logStartCodecCandidateIgnored(r,`max score of ${i.maxScore} < selected max of ${p}`),t}return t&&(codecsSetSelectionPreferenceValue(r)>=codecsSetSelectionPreferenceValue(t)||i.fragmentError>e[t].fragmentError)?t:(m=i.minIndex,p=i.maxScore,r)}),void 0),videoRanges:E,preferHDR:y,minFramerate:f,minBitrate:g,minIndex:m}}function logStartCodecCandidateIgnored(e,t){logger.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function getAudioTracksByGroup(e){return e.reduce(((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);const r=t.channels||"2";return s.channels[r]=(s.channels[r]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function getCodecTiers(e,t,s,r){return e.slice(s,r+1).reduce(((e,s,r)=>{if(!s.codecSet)return e;const i=s.audioGroups;let n=e[s.codecSet];n||(e[s.codecSet]=n={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:r,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!i,fragmentError:0}),n.minBitrate=Math.min(n.minBitrate,s.bitrate);const a=Math.min(s.height,s.width);return n.minHeight=Math.min(n.minHeight,a),n.minFramerate=Math.min(n.minFramerate,s.frameRate),n.minIndex=Math.min(n.minIndex,r),n.maxScore=Math.max(n.maxScore,s.score),n.fragmentError+=s.fragmentError,n.videoRanges[s.videoRange]=(n.videoRanges[s.videoRange]||0)+1,i&&i.forEach((e=>{if(!e)return;const s=t.groups[e];s&&(n.hasDefaultAudio=n.hasDefaultAudio||t.hasDefaultAudio?s.hasDefault:s.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(s.channels).forEach((e=>{n.channels[e]=(n.channels[e]||0)+s.channels[e]})))})),e}),{})}function getBasicSelectionOption(e){if(!e)return e;const{lang:t,assocLang:s,characteristics:r,channels:i,audioCodec:n}=e;return{lang:t,assocLang:s,characteristics:r,channels:i,audioCodec:n}}function findMatchingOption(e,t,s){if("attrs"in e){const s=t.indexOf(e);if(-1!==s)return s}for(let r=0;r<t.length;r++){if(matchesOption(e,t[r],s))return r}return-1}function matchesOption(e,t,s){const{groupId:r,name:i,lang:n,assocLang:a,characteristics:o,default:l}=e,d=e.forced;return(void 0===r||t.groupId===r)&&(void 0===i||t.name===i)&&(void 0===n||languagesMatch(n,t.lang))&&(void 0===n||t.assocLang===a)&&(void 0===l||t.default===l)&&(void 0===d||t.forced===d)&&(void 0===o||characteristicsMatch(o,t.characteristics))&&(void 0===s||s(e,t))}function languagesMatch(e,t="--"){return e.length===t.length?e===t:e.startsWith(t)||t.startsWith(e)}function characteristicsMatch(e,t=""){const s=e.split(","),r=t.split(",");return s.length===r.length&&!s.some((e=>-1===r.indexOf(e)))}function audioMatchPredicate(e,t){const{audioCodec:s,channels:r}=e;return!(void 0!==s&&(t.audioCodec||"").substring(0,4)!==s.substring(0,4)||void 0!==r&&r!==(t.channels||"2"))}function findClosestLevelWithAudioGroup(e,t,s,r,i){const n=t[r],a=t.reduce(((e,t,s)=>{const r=t.uri;return(e[r]||(e[r]=[])).push(s),e}),{})[n.uri];a.length>1&&(r=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,d=n.codecSet.substring(0,4),h=searchDownAndUpList(t,r,(t=>{if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==d)return!1;const r=t.audioGroups,n=s.filter((e=>!r||-1!==r.indexOf(e.groupId)));return findMatchingOption(e,n,i)>-1}));return h>-1?h:searchDownAndUpList(t,r,(t=>{const r=t.audioGroups,n=s.filter((e=>!r||-1!==r.indexOf(e.groupId)));return findMatchingOption(e,n,i)>-1}))}function searchDownAndUpList(e,t,s){for(let r=t;r>-1;r--)if(s(e[r]))return r;for(let r=t+1;r<e.length;r++)if(s(e[r]))return r;return-1}function useAlternateAudio(e,t){var s;return!!e&&e!==(null==(s=t.levels[t.loadLevel])?void 0:s.uri)}class AbrController extends Logger{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this._abandonRulesCheck=()=>{var e;const{fragCurrent:t,partCurrent:s,hls:r}=this,{autoLevelEnabled:i,media:n}=r;if(!t||!n)return;const a=performance.now(),o=s?s.stats:t.stats,l=s?s.duration:t.duration,d=a-o.loading.start,h=r.minAutoLevel;if(o.aborted||o.loaded&&o.loaded===o.total||t.level<=h)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!i||n.paused||!n.playbackRate||!n.readyState)return;const c=r.mainForwardBufferInfo;if(null===c)return;const u=this.bwEstimator.getEstimateTTFB(),f=Math.abs(n.playbackRate);if(d<=Math.max(u,l/(2*f)*1e3))return;const g=c.len/f,m=o.loading.first?o.loading.first-o.loading.start:-1,p=o.loaded&&m>-1,E=this.getBwEstimate(),y=r.levels,v=y[t.level],T=Math.max(o.loaded,Math.round(l*(t.bitrate||v.averageBitrate)/8));let S=p?d-m:d;S<1&&p&&(S=Math.min(d,8*o.loaded/E));const A=p?1e3*o.loaded/S:0,L=u/1e3,I=A?(T-o.loaded)/A:8*T/E+L;if(I<=g)return;const R=A?8*A:E,D=!0===(null==(e=this.hls.latestLevelDetails)?void 0:e.live),b=this.hls.config.abrBandWidthUpFactor;let _,P=Number.POSITIVE_INFINITY;for(_=t.level-1;_>h;_--){const e=y[_].maxBitrate,t=!y[_].details||D;if(P=this.getTimeToLoadFrag(L,R,l*e,t),P<Math.min(g,l+L))break}if(P>=I)return;if(P>10*l)return;p?this.bwEstimator.sample(d-Math.min(u,m),o.loaded):this.bwEstimator.sampleTTFB(d);const C=y[_].maxBitrate;this.getBwEstimate()*b>C&&this.resetEstimator(C);const k=this.findBestLevel(C,h,_,0,g,1,1);k>-1&&(_=k),this.warn(`Fragment ${t.sn}${s?" part "+s.index:""} of level ${t.level} is loading too slowly;\n Fragment duration: ${t.duration.toFixed(3)}\n Time to underbuffer: ${g.toFixed(3)} s\n Estimated load time for current fragment: ${I.toFixed(3)} s\n Estimated load time for down switch fragment: ${P.toFixed(3)} s\n TTFB estimate: ${0|m} ms\n Current BW estimate: ${isFiniteNumber(E)?0|E:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${_} @ ${0|C} bps`),r.nextLoadLevel=r.nextAutoLevel=_,this.clearTimer(),this.timer=self.setInterval((()=>{if(this.clearTimer(),this.fragCurrent===t&&this.hls.loadLevel===_&&_>0){const e=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${_>0?"and switching down":""}\n Fragment duration: ${t.duration.toFixed(3)} s\n Time to underbuffer: ${e.toFixed(3)} s`),t.abortRequests(),this.fragCurrent=this.partCurrent=null,_>h){let t=this.findBestLevel(this.hls.levels[h].bitrate,h,_,0,e,1,1);-1===t&&(t=h),this.hls.nextLoadLevel=this.hls.nextAutoLevel=t,this.resetEstimator(this.hls.levels[t].bitrate)}}}),1e3*P),r.trigger(Events.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:s,stats:o})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new EwmaBandWidthEstimator(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.FRAG_LOADING,this.onFragLoading,this),e.on(Events.FRAG_LOADED,this.onFragLoaded,this),e.on(Events.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Events.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Events.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(Events.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.FRAG_LOADING,this.onFragLoading,this),e.off(Events.FRAG_LOADED,this.onFragLoaded,this),e.off(Events.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Events.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Events.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(Events.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const s=t.frag;if(!this.ignoreFragment(s)){var r;if(!s.bitrateTest)this.fragCurrent=s,this.partCurrent=null!=(r=t.part)?r:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case ErrorDetails.BUFFER_ADD_CODEC_ERROR:case ErrorDetails.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case ErrorDetails.FRAG_LOAD_TIMEOUT:{const e=t.frag,{fragCurrent:s,partCurrent:r}=this;if(e&&s&&e.sn===s.sn&&e.level===s.level){const t=performance.now(),s=r?r.stats:e.stats,i=t-s.loading.start,n=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&n>-1){const e=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(i-Math.min(e,n),s.loaded)}else this.bwEstimator.sampleTTFB(i)}break}}}getTimeToLoadFrag(e,t,s,r){return e+s/t+(r?this.lastLevelLoadSec:0)}onLevelLoaded(e,t){const s=this.hls.config,{loading:r}=t.stats,i=r.end-r.start;isFiniteNumber(i)&&(this.lastLevelLoadSec=i/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD)}onFragLoaded(e,{frag:t,part:s}){const r=s?s.stats:t.stats;if(t.type===PlaylistLevelType.MAIN&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const e=s?s.duration:t.duration,i=this.hls.levels[t.level],n=(i.loaded?i.loaded.bytes:0)+r.loaded,a=(i.loaded?i.loaded.duration:0)+e;i.loaded={bytes:n,duration:a},i.realBitrate=Math.round(8*n/a)}if(t.bitrateTest){const e={stats:r,frag:t,part:s,id:t.type};this.onFragBuffered(Events.FRAG_BUFFERED,e),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:s,part:r}=t,i=null!=r&&r.stats.loaded?r.stats:s.stats;if(i.aborted)return;if(this.ignoreFragment(s))return;const n=i.parsing.end-i.loading.start-Math.min(i.loading.first-i.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,i.loaded),i.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==PlaylistLevelType.MAIN||"initSegment"===e.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,s=this.getBwEstimate(),r=this.hls.config.maxStarvationDelay,i=this.findBestLevel(s,t,e,0,r,1,1);if(i>-1)return i;const n=this.hls.firstLevel,a=Math.min(Math.max(n,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&s&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;const r=t&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){const t=this.hls.levels;if(t.length>Math.max(e,r)&&t[e].loadError<=t[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:s}=this;if(s.levels.length<=1)return s.loadLevel;const{maxAutoLevel:r,config:i,minAutoLevel:n}=s,a=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let d=i.abrBandWidthFactor,h=i.abrBandWidthUpFactor;if(l){const e=this.findBestLevel(o,n,r,l,0,d,h);if(e>=0)return e}let c=a?Math.min(a,i.maxStarvationDelay):i.maxStarvationDelay;if(!l){const e=this.bitrateTestDelay;if(e){c=(a?Math.min(a,i.maxLoadingDelay):i.maxLoadingDelay)-e,this.info(`bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*c)} ms`),d=h=1}}const u=this.findBestLevel(o,n,r,l,c,d,h);if(this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${u}`),u>-1)return u;const f=s.levels[n],g=s.levels[s.loadLevel];return(null==f?void 0:f.bitrate)<(null==g?void 0:g.bitrate)?n:s.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const s=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,r=e.mainForwardBufferInfo;return(r?r.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,s,r,i,n,a){var o;const l=r+i,d=this.lastLoadedFragLevel,h=-1===d?this.hls.firstLevel:d,{fragCurrent:c,partCurrent:u}=this,{levels:f,allAudioTracks:g,loadLevel:m,config:p}=this.hls;if(1===f.length)return 0;const E=f[h],y=!(null==(o=this.hls.latestLevelDetails)||!o.live),v=-1===m||-1===d;let T,S="SDR",A=(null==E?void 0:E.frameRate)||0;const{audioPreference:L,videoPreference:I}=p,R=this.audioTracksByGroup||(this.audioTracksByGroup=getAudioTracksByGroup(g));let D=-1;if(v){if(-1!==this.firstSelection)return this.firstSelection;const r=getStartCodecTier(this.codecTiers||(this.codecTiers=getCodecTiers(f,R,t,s)),S,e,L,I),{codecSet:i,videoRanges:n,minFramerate:a,minBitrate:o,minIndex:l,preferHDR:d}=r;D=l,T=i,S=d?n[n.length-1]:n[0],A=a,e=Math.max(e,o),this.log(`picked start tier ${JSON.stringify(r)}`)}else T=null==E?void 0:E.codecSet,S=null==E?void 0:E.videoRange;const b=u?u.duration:c?c.duration:0,_=this.bwEstimator.getEstimateTTFB()/1e3,P=[];for(let o=s;o>=t;o--){var C;const t=f[o],c=o>h;if(!t)continue;if(p.useMediaCapabilities&&!t.supportedResult&&!t.supportedPromise){var k;const s=navigator.mediaCapabilities;"function"!=typeof(null==s?void 0:s.decodingInfo)||!requiresMediaCapabilitiesDecodingInfo(t,R,S,A,e,L)&&"hvc1"!==(null==(k=t.videoCodec)?void 0:k.substring(0,4))?t.supportedResult=SUPPORTED_INFO_DEFAULT:(t.supportedPromise=getMediaDecodingInfoPromise(t,R,s),t.supportedPromise.then((e=>{if(!this.hls)return;t.supportedResult=e;const s=this.hls.levels,r=s.indexOf(t);e.error?this.warn(`MediaCapabilities decodingInfo error: "${e.error}" for level ${r} ${JSON.stringify(e)}`):e.supported||(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${r} ${JSON.stringify(e)}`),r>-1&&s.length>1&&(this.log(`Removing unsupported level ${r}`),this.hls.removeLevel(r),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))})))}if((T&&t.codecSet!==T||S&&t.videoRange!==S||c&&A>t.frameRate||!c&&A>0&&A<t.frameRate||t.supportedResult&&(null==(C=t.supportedResult.decodingInfoResults)||!C[0].smooth))&&(!v||o!==D)){P.push(o);continue}const g=t.details,E=(u?null==g?void 0:g.partTarget:null==g?void 0:g.averagetargetduration)||b;let I;I=c?a*e:n*e;const M=b&&r>=2*b&&0===i?t.averageBitrate:t.maxBitrate,w=this.getTimeToLoadFrag(_,I,M*E,void 0===g);if(I>=M&&(o===d||0===t.loadError&&0===t.fragmentError)&&(w<=_||!isFiniteNumber(w)||y&&!this.bitrateTestDelay||w<l)){const e=this.forcedAutoLevel;return o===m||-1!==e&&e===m||(P.length&&this.trace(`Skipped level(s) ${P.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${f[P[0]].codecs}" ${f[P[0]].videoRange}; not compatible with "${T}" ${S}`),this.info(`switch candidate:${h}->${o} adjustedbw(${Math.round(I)})-bitrate=${Math.round(I-M)} ttfb:${_.toFixed(1)} avgDuration:${E.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${w.toFixed(1)} firstSelection:${v} codecSet:${t.codecSet} videoRange:${t.videoRange} hls.loadLevel:${m}`)),v&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:s}=this.hls,r=Math.min(Math.max(e,s),t);this._nextAutoLevel!==r&&(this.nextAutoLevelKey="",this._nextAutoLevel=r)}}const BinarySearch={search:function(e,t){let s=0,r=e.length-1,i=null,n=null;for(;s<=r;){i=(s+r)/2|0,n=e[i];const a=t(n);if(a>0)s=i+1;else{if(!(a<0))return n;r=i-1}}return null}};function findFragmentByPDT(e,t,s){if(null===t||!Array.isArray(e)||!e.length||!isFiniteNumber(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;s=s||0;for(let r=0;r<e.length;++r){const i=e[r];if(pdtWithinToleranceTest(t,s,i))return i}return null}function findFragmentByPTS(e,t,s=0,r=0,i=.005){let n=null;if(e){n=t[1+e.sn-t[0].sn]||null;const r=e.endDTS-s;r>0&&r<15e-7&&(s+=15e-7),n&&e.level!==n.level&&n.end<=e.end&&(n=t[2+e.sn-t[0].sn]||null)}else 0===s&&0===t[0].start&&(n=t[0]);if(n&&((!e||e.level===n.level)&&0===fragmentWithinToleranceTest(s,r,n)||fragmentWithinFastStartSwitch(n,e,Math.min(i,r))))return n;const a=BinarySearch.search(t,fragmentWithinToleranceTest.bind(null,s,r));return!a||a===e&&n?n:a}function fragmentWithinFastStartSwitch(e,t,s){if(t&&0===t.start&&t.level<e.level&&(t.endPTS||0)>0){const r=t.tagList.reduce(((e,t)=>("INF"===t[0]&&(e+=parseFloat(t[1])),e)),s);return e.start<=r}return!1}function fragmentWithinToleranceTest(e=0,t=0,s){if(s.start<=e&&s.start+s.duration>e)return 0;const r=Math.min(t,s.duration+(s.deltaPTS?s.deltaPTS:0));return s.start+s.duration-r<=e?1:s.start-r>e&&s.start?-1:0}function pdtWithinToleranceTest(e,t,s){const r=1e3*Math.min(t,s.duration+(s.deltaPTS?s.deltaPTS:0));return(s.endProgramDateTime||0)-r>e}function findFragWithCC(e,t){return BinarySearch.search(e,(e=>e.cc<t?1:e.cc>t?-1:0))}function findNearestWithCC(e,t,s){if(e&&e.startCC<=t&&e.endCC>=t){const r=s.start,i=s.end;let n=e.fragments;if(!s.relurl){const{fragmentHint:t}=e;t&&(n=n.concat(t))}return BinarySearch.search(n,(e=>e.cc<t||e.end<=r?1:e.cc>t||e.start>=i?-1:0))}return null}function isTimeoutError(e){switch(e.details){case ErrorDetails.FRAG_LOAD_TIMEOUT:case ErrorDetails.KEY_LOAD_TIMEOUT:case ErrorDetails.LEVEL_LOAD_TIMEOUT:case ErrorDetails.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function getRetryConfig(e,t){const s=isTimeoutError(t);return e.default[(s?"timeout":"error")+"Retry"]}function getRetryDelay(e,t){const s="linear"===e.backoff?1:Math.pow(2,t);return Math.min(s*e.retryDelayMs,e.maxRetryDelayMs)}function getLoaderConfigWithoutReties(e){return _objectSpread2(_objectSpread2({},e),{errorRetry:null,timeoutRetry:null})}function shouldRetry(e,t,s,r){if(!e)return!1;const i=null==r?void 0:r.code,n=t<e.maxNumRetry&&(retryForHttpStatus(i)||!!s);return e.shouldRetry?e.shouldRetry(e,t,s,r,n):n}function retryForHttpStatus(e){return 0===e&&!1===navigator.onLine||!!e&&(e<400||e>499)}var NetworkErrorAction={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},ErrorActionFlags={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,SwitchToSDR:4};class ErrorController extends Logger{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(Events.ERROR,this.onError,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(Events.ERROR,this.onError,this),e.off(Events.ERROR,this.onErrorOut,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(null==e?void 0:e.type)===PlaylistLevelType.MAIN?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var s;if(t.fatal)return;const r=this.hls,i=t.context;switch(t.details){case ErrorDetails.FRAG_LOAD_ERROR:case ErrorDetails.FRAG_LOAD_TIMEOUT:case ErrorDetails.KEY_LOAD_ERROR:case ErrorDetails.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case ErrorDetails.FRAG_PARSING_ERROR:if(null!=(s=t.frag)&&s.gap)return void(t.errorAction=createDoNothingErrorAction());case ErrorDetails.FRAG_GAP:case ErrorDetails.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=NetworkErrorAction.SendAlternateToPenaltyBox);case ErrorDetails.LEVEL_EMPTY_ERROR:case ErrorDetails.LEVEL_PARSING_ERROR:{var n,a;const e=t.parent===PlaylistLevelType.MAIN?t.level:r.loadLevel;t.details===ErrorDetails.LEVEL_EMPTY_ERROR&&null!=(n=t.context)&&null!=(a=n.levelDetails)&&a.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case ErrorDetails.LEVEL_LOAD_ERROR:case ErrorDetails.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==i?void 0:i.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.level)));case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:case ErrorDetails.SUBTITLE_LOAD_ERROR:case ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){const e=r.levels[r.loadLevel];if(e&&(i.type===PlaylistContextType.AUDIO_TRACK&&e.hasAudioGroup(i.groupId)||i.type===PlaylistContextType.SUBTITLE_TRACK&&e.hasSubtitleGroup(i.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=NetworkErrorAction.SendAlternateToPenaltyBox,void(t.errorAction.flags=ErrorActionFlags.MoveAllAlternatesMatchingHost)}return;case ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const e=r.levels[r.loadLevel],s=null==e?void 0:e.attrs["HDCP-LEVEL"];s?t.errorAction={action:NetworkErrorAction.SendAlternateToPenaltyBox,flags:ErrorActionFlags.MoveAllAlternatesMatchingHDCP,hdcpLevel:s}:this.keySystemError(t)}return;case ErrorDetails.BUFFER_ADD_CODEC_ERROR:case ErrorDetails.REMUX_ALLOC_ERROR:case ErrorDetails.BUFFER_APPEND_ERROR:var o;if(!t.errorAction)t.errorAction=this.getLevelSwitchAction(t,null!=(o=t.level)?o:r.loadLevel);return;case ErrorDetails.INTERNAL_EXCEPTION:case ErrorDetails.BUFFER_APPENDING_ERROR:case ErrorDetails.BUFFER_FULL_ERROR:case ErrorDetails.LEVEL_SWITCH_ERROR:case ErrorDetails.BUFFER_STALLED_ERROR:case ErrorDetails.BUFFER_SEEK_OVER_HOLE:case ErrorDetails.BUFFER_NUDGE_ON_STALL:return void(t.errorAction=createDoNothingErrorAction())}t.type===ErrorTypes.KEY_SYSTEM_ERROR&&this.keySystemError(t)}keySystemError(e){const t=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t)}getPlaylistRetryOrSwitchAction(e,t){const s=getRetryConfig(this.hls.config.playlistLoadPolicy,e),r=this.playlistError++;if(shouldRetry(s,r,isTimeoutError(e),e.response))return{action:NetworkErrorAction.RetryRequest,flags:ErrorActionFlags.None,retryConfig:s,retryCount:r};const i=this.getLevelSwitchAction(e,t);return s&&(i.retryConfig=s,i.retryCount=r),i}getFragRetryOrSwitchAction(e){const t=this.hls,s=this.getVariantLevelIndex(e.frag),r=t.levels[s],{fragLoadPolicy:i,keyLoadPolicy:n}=t.config,a=getRetryConfig(e.details.startsWith("key")?n:i,e),o=t.levels.reduce(((e,t)=>e+t.fragmentError),0);if(r){e.details!==ErrorDetails.FRAG_GAP&&r.fragmentError++;if(shouldRetry(a,o,isTimeoutError(e),e.response))return{action:NetworkErrorAction.RetryRequest,flags:ErrorActionFlags.None,retryConfig:a,retryCount:o}}const l=this.getLevelSwitchAction(e,s);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(e,t){const s=this.hls;null==t&&(t=s.loadLevel);const r=this.hls.levels[t];if(r){var i,n;const t=e.details;r.loadError++,t===ErrorDetails.BUFFER_APPEND_ERROR&&r.fragmentError++;let l=-1;const{levels:d,loadLevel:h,minAutoLevel:c,maxAutoLevel:u}=s;s.autoLevelEnabled||(s.loadLevel=-1);const f=null==(i=e.frag)?void 0:i.type,g=(f===PlaylistLevelType.AUDIO&&t===ErrorDetails.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(t===ErrorDetails.BUFFER_ADD_CODEC_ERROR||t===ErrorDetails.BUFFER_APPEND_ERROR))&&d.some((({audioCodec:e})=>r.audioCodec!==e)),m="video"===e.sourceBufferName&&(t===ErrorDetails.BUFFER_ADD_CODEC_ERROR||t===ErrorDetails.BUFFER_APPEND_ERROR)&&d.some((({codecSet:e,audioCodec:t})=>r.codecSet!==e&&r.audioCodec===t)),{type:p,groupId:E}=null!=(n=e.context)?n:{};for(let s=d.length;s--;){const i=(s+h)%d.length;if(i!==h&&i>=c&&i<=u&&0===d[i].loadError){var a,o;const s=d[i];if(t===ErrorDetails.FRAG_GAP&&f===PlaylistLevelType.MAIN&&e.frag){const t=d[i].details;if(t){const s=findFragmentByPTS(e.frag,t.fragments,e.frag.start);if(null!=s&&s.gap)continue}}else{if(p===PlaylistContextType.AUDIO_TRACK&&s.hasAudioGroup(E)||p===PlaylistContextType.SUBTITLE_TRACK&&s.hasSubtitleGroup(E))continue;if(f===PlaylistLevelType.AUDIO&&null!=(a=r.audioGroups)&&a.some((e=>s.hasAudioGroup(e)))||f===PlaylistLevelType.SUBTITLE&&null!=(o=r.subtitleGroups)&&o.some((e=>s.hasSubtitleGroup(e)))||g&&r.audioCodec===s.audioCodec||!g&&r.audioCodec!==s.audioCodec||m&&r.codecSet===s.codecSet)continue}l=i;break}}if(l>-1&&s.loadLevel!==l)return e.levelRetry=!0,this.playlistError=0,{action:NetworkErrorAction.SendAlternateToPenaltyBox,flags:ErrorActionFlags.None,nextAutoLevel:l}}return{action:NetworkErrorAction.SendAlternateToPenaltyBox,flags:ErrorActionFlags.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s;switch(null==(s=t.errorAction)?void 0:s.action){case NetworkErrorAction.DoNothing:break;case NetworkErrorAction.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===ErrorDetails.FRAG_GAP?/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):t.fatal=!0}t.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(e){const t=this.hls,s=e.errorAction;if(!s)return;const{flags:r,hdcpLevel:i,nextAutoLevel:n}=s;switch(r){case ErrorActionFlags.None:this.switchLevel(e,n);break;case ErrorActionFlags.MoveAllAlternatesMatchingHDCP:i&&(t.maxHdcpLevel=HdcpLevels[HdcpLevels.indexOf(i)-1],s.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`)}s.resolved||this.switchLevel(e,n)}switchLevel(e,t){void 0!==t&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}}function createDoNothingErrorAction(e){const t={action:NetworkErrorAction.DoNothing,flags:ErrorActionFlags.None};return e&&(t.resolved=!0),t}var FragmentState={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class FragmentTracker{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.BUFFER_APPENDED,this.onBufferAppended,this),e.on(Events.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Events.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.BUFFER_APPENDED,this.onBufferAppended,this),e.off(Events.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Events.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const s=this.activePartLists[t];if(s)for(let t=s.length;t--;){const r=s[t];if(!r)break;const i=r.end;if(r.start<=e&&null!==i&&e<=i)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,s){const{fragments:r}=this,i=Object.keys(r);for(let n=i.length;n--;){const a=r[i[n]];if((null==a?void 0:a.body.type)===t&&(!s||a.buffered)){const t=a.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,s,r,i){this.timeRanges&&(this.timeRanges[e]=t);const n=(null==r?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach((r=>{const a=this.fragments[r];if(!a)return;if(n>=a.body.sn)return;if(!a.buffered&&(!a.loaded||i))return void(a.body.type===s&&this.removeFragment(a.body));const o=a.range[e];o&&(0!==o.time.length?o.time.some((e=>{const s=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return s&&this.removeFragment(a.body),s})):this.removeFragment(a.body))}))}detectPartialFragments(e){const t=this.timeRanges;if(!t||"initSegment"===e.frag.sn)return;const s=e.frag,r=getFragmentKey(s),i=this.fragments[r];if(!i||i.buffered&&s.gap)return;const n=!s.relurl;if(Object.keys(t).forEach((r=>{const a=s.elementaryStreams[r];if(!a)return;const o=t[r],l=n||!0===a.partial;i.range[r]=this.getBufferedTimes(s,e.part,l,o)})),i.loaded=null,Object.keys(i.range).length){i.buffered=!0;(i.body.endList=s.endList||i.body.endList)&&(this.endListFragments[i.body.type]=i),isPartial(i)||this.removeParts(s.sn-1,s.type)}else this.removeFragment(i.body)}removeParts(e,t){const s=this.activePartLists[t];s&&(this.activePartLists[t]=s.filter((t=>t.fragment.sn>=e)))}fragBuffered(e,t){const s=getFragmentKey(e);let r=this.fragments[s];!r&&t&&(r=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,r.buffered=!0)}getBufferedTimes(e,t,s,r){const i={time:[],partial:s},n=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||n;for(let e=0;e<r.length;e++){const t=r.start(e)-this.bufferPadding,s=r.end(e)+this.bufferPadding;if(l>=t&&o<=s){i.time.push({startPTS:Math.max(n,r.start(e)),endPTS:Math.min(a,r.end(e))});break}if(n<s&&a>t){const t=Math.max(n,r.start(e)),s=Math.min(a,r.end(e));s>t&&(i.partial=!0,i.time.push({startPTS:t,endPTS:s}))}else if(a<=t)break}return i}getPartialFragment(e){let t,s,r,i=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach((l=>{const d=o[l];d&&isPartial(d)&&(s=d.body.start-a,r=d.body.end+a,e>=s&&e<=r&&(t=Math.min(e-s,r-e),n<=t&&(i=d.body,n=t)))})),i}isEndListAppended(e){const t=this.endListFragments[e];return void 0!==t&&(t.buffered||isPartial(t))}getState(e){const t=getFragmentKey(e),s=this.fragments[t];return s?s.buffered?isPartial(s)?FragmentState.PARTIAL:FragmentState.OK:FragmentState.APPENDING:FragmentState.NOT_LOADED}isTimeBuffered(e,t,s){let r,i;for(let n=0;n<s.length;n++){if(r=s.start(n)-this.bufferPadding,i=s.end(n)+this.bufferPadding,e>=r&&t<=i)return!0;if(t<=r)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if("initSegment"===t.frag.sn||t.frag.bitrateTest)return;const s=t.frag,r=t.part?null:t,i=getFragmentKey(s);this.fragments[i]={body:s,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:s,part:r,timeRanges:i,type:n}=t;if("initSegment"===s.sn)return;const a=s.type;if(r){let e=this.activePartLists[a];e||(this.activePartLists[a]=e=[]),e.push(r)}this.timeRanges=i;const o=i[n];this.detectEvictedFragments(n,o,a,r)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=getFragmentKey(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let r=s.length;r--;){const i=t[s[r]];if((null==i?void 0:i.body.type)===e)return!0}return!1}hasParts(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}removeFragmentsInRange(e,t,s,r,i){r&&!this.hasGaps||Object.keys(this.fragments).forEach((n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==s||r&&!o.gap||o.start<t&&o.end>e&&(a.buffered||i)&&this.removeFragment(o)}))}removeFragment(e){const t=getFragmentKey(e);e.stats.loaded=0,e.clearElementaryStreamInfo();const s=this.activePartLists[e.type];if(s){const t=e.sn;this.activePartLists[e.type]=s.filter((e=>e.fragment.sn!==t))}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e,t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const s=null==(e=this.hls)||null==(t=e.latestLevelDetails)?void 0:t.partList;s&&s.forEach((e=>e.clearElementaryStreamInfo()))}}function isPartial(e){var t,s,r;return e.buffered&&(e.body.gap||(null==(t=e.range.video)?void 0:t.partial)||(null==(s=e.range.audio)?void 0:s.partial)||(null==(r=e.range.audiovideo)?void 0:r.partial))}function getFragmentKey(e){return`${e.type}_${e.level}_${e.sn}`}var DecrypterAesMode={cbc:0,ctr:1};class AESCrypto{constructor(e,t,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=s}decrypt(e,t){switch(this.aesMode){case DecrypterAesMode.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case DecrypterAesMode.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function sliceUint8(e,t,s){return Uint8Array.prototype.slice?e.slice(t,s):new Uint8Array(Array.prototype.slice.call(e,t,s))}function removePadding(e){const t=e.byteLength,s=t&&new DataView(e.buffer).getUint8(t-1);return s?sliceUint8(e,0,t-s):e}class AESDecryptor{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),s=new Uint32Array(4);for(let e=0;e<4;e++)s[e]=t.getUint32(4*e);return s}initTable(){const e=this.sBox,t=this.invSBox,s=this.subMix,r=s[0],i=s[1],n=s[2],a=s[3],o=this.invSubMix,l=o[0],d=o[1],h=o[2],c=o[3],u=new Uint32Array(256);let f=0,g=0,m=0;for(m=0;m<256;m++)u[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){let s=g^g<<1^g<<2^g<<3^g<<4;s=s>>>8^255&s^99,e[f]=s,t[s]=f;const o=u[f],m=u[o],p=u[m];let E=257*u[s]^16843008*s;r[f]=E<<24|E>>>8,i[f]=E<<16|E>>>16,n[f]=E<<8|E>>>24,a[f]=E,E=16843009*p^65537*m^257*o^16843008*f,l[s]=E<<24|E>>>8,d[s]=E<<16|E>>>16,h[s]=E<<8|E>>>24,c[s]=E,f?(f=o^u[u[u[p^o]]],g^=u[u[g]]):f=g=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let s=!0,r=0;for(;r<t.length&&s;)s=t[r]===this.key[r],r++;if(s)return;this.key=t;const i=this.keySize=t.length;if(4!==i&&6!==i&&8!==i)throw new Error("Invalid aes key size="+i);const n=this.ksRows=4*(i+6+1);let a,o;const l=this.keySchedule=new Uint32Array(n),d=this.invKeySchedule=new Uint32Array(n),h=this.sBox,c=this.rcon,u=this.invSubMix,f=u[0],g=u[1],m=u[2],p=u[3];let E,y;for(a=0;a<n;a++)a<i?E=l[a]=t[a]:(y=E,a%i==0?(y=y<<8|y>>>24,y=h[y>>>24]<<24|h[y>>>16&255]<<16|h[y>>>8&255]<<8|h[255&y],y^=c[a/i|0]<<24):i>6&&a%i==4&&(y=h[y>>>24]<<24|h[y>>>16&255]<<16|h[y>>>8&255]<<8|h[255&y]),l[a]=E=(l[a-i]^y)>>>0);for(o=0;o<n;o++)a=n-o,y=3&o?l[a]:l[a-4],d[o]=o<4||a<=4?y:f[h[y>>>24]]^g[h[y>>>16&255]]^m[h[y>>>8&255]]^p[h[255&y]],d[o]=d[o]>>>0}networkToHostOrderSwap(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24}decrypt(e,t,s){const r=this.keySize+6,i=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],d=a[2],h=a[3],c=this.uint8ArrayToUint32Array_(s);let u=c[0],f=c[1],g=c[2],m=c[3];const p=new Int32Array(e),E=new Int32Array(p.length);let y,v,T,S,A,L,I,R,D,b,_,P,C,k;const M=this.networkToHostOrderSwap;for(;t<p.length;){for(D=M(p[t]),b=M(p[t+1]),_=M(p[t+2]),P=M(p[t+3]),A=D^i[0],L=P^i[1],I=_^i[2],R=b^i[3],C=4,k=1;k<r;k++)y=o[A>>>24]^l[L>>16&255]^d[I>>8&255]^h[255&R]^i[C],v=o[L>>>24]^l[I>>16&255]^d[R>>8&255]^h[255&A]^i[C+1],T=o[I>>>24]^l[R>>16&255]^d[A>>8&255]^h[255&L]^i[C+2],S=o[R>>>24]^l[A>>16&255]^d[L>>8&255]^h[255&I]^i[C+3],A=y,L=v,I=T,R=S,C+=4;y=n[A>>>24]<<24^n[L>>16&255]<<16^n[I>>8&255]<<8^n[255&R]^i[C],v=n[L>>>24]<<24^n[I>>16&255]<<16^n[R>>8&255]<<8^n[255&A]^i[C+1],T=n[I>>>24]<<24^n[R>>16&255]<<16^n[A>>8&255]<<8^n[255&L]^i[C+2],S=n[R>>>24]<<24^n[A>>16&255]<<16^n[L>>8&255]<<8^n[255&I]^i[C+3],E[t]=M(y^u),E[t+1]=M(S^f),E[t+2]=M(T^g),E[t+3]=M(v^m),u=D,f=b,g=_,m=P,t+=4}return E.buffer}}class FastAESKey{constructor(e,t,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=s}expandKey(){const e=getSubtleAlgoName(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function getSubtleAlgoName(e){switch(e){case DecrypterAesMode.cbc:return"AES-CBC";case DecrypterAesMode.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${e}`)}}function utf8ArrayToStr(e,t=!1){if("undefined"!=typeof TextDecoder){const s=new TextDecoder("utf-8").decode(e);if(t){const e=s.indexOf("\0");return-1!==e?s.substring(0,e):s}return s.replace(/\0/g,"")}const s=e.length;let r,i,n,a="",o=0;for(;o<s;){if(r=e[o++],0===r&&t)return a;if(0!==r&&3!==r)switch(r>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(r);break;case 12:case 13:i=e[o++],a+=String.fromCharCode((31&r)<<6|63&i);break;case 14:i=e[o++],n=e[o++],a+=String.fromCharCode((15&r)<<12|(63&i)<<6|(63&n)<<0)}}return a}const Hex={hexDump:function(e){let t="";for(let s=0;s<e.length;s++){let r=e[s].toString(16);r.length<2&&(r="0"+r),t+=r}return t}};function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var urlToolkit={exports:{}};!function(e,t){var s,r,i,n,a;s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,i=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(e,t,s){if(s=s||{},e=e.trim(),!(t=t.trim())){if(!s.alwaysNormalize)return e;var i=a.parseURL(e);if(!i)throw new Error("Error trying to parse base URL.");return i.path=a.normalizePath(i.path),a.buildURLFromParts(i)}var n=a.parseURL(t);if(!n)throw new Error("Error trying to parse relative URL.");if(n.scheme)return s.alwaysNormalize?(n.path=a.normalizePath(n.path),a.buildURLFromParts(n)):t;var o=a.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=r.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var d={scheme:o.scheme,netLoc:n.netLoc,path:null,params:n.params,query:n.query,fragment:n.fragment};if(!n.netLoc&&(d.netLoc=o.netLoc,"/"!==n.path[0]))if(n.path){var h=o.path,c=h.substring(0,h.lastIndexOf("/")+1)+n.path;d.path=a.normalizePath(c)}else d.path=o.path,n.params||(d.params=o.params,n.query||(d.query=o.query));return null===d.path&&(d.path=s.alwaysNormalize?a.normalizePath(n.path):n.path),a.buildURLFromParts(d)},parseURL:function(e){var t=s.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(i,"");e.length!==(e=e.replace(n,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},urlToolkit.exports=a}();var urlToolkitExports=urlToolkit.exports;class LoadStats{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 ElementaryStreamTypes={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class BaseSegment{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof e&&(e={url:e}),this.base=e}setByteRange(e,t){const s=e.split("@",2);let r;r=1===s.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(s[1]),this._byteRange=[r,parseInt(s[0])+r]}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={[ElementaryStreamTypes.AUDIO]:null,[ElementaryStreamTypes.VIDEO]:null,[ElementaryStreamTypes.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new LoadStats),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=urlToolkitExports.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[ElementaryStreamTypes.AUDIO]=null,e[ElementaryStreamTypes.VIDEO]=null,e[ElementaryStreamTypes.AUDIOVIDEO]=null}}function isMediaFragment(e){return"initSegment"!==e.sn}class Fragment extends BaseSegment{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange){const e=this.byteRange[0],t=this.byteRange[1];if(isFiniteNumber(e)&&isFiniteNumber(t))return t-e}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){const{levelkeys:e}=this;if(!e&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const e=this.levelkeys.identity;if(e)this._decryptdata=e.getDecryptData(this.sn);else{const e=Object.keys(this.levelkeys);if(1===e.length)return this._decryptdata=this.levelkeys[e[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;const e=isFiniteNumber(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){const e=Object.keys(this.levelkeys),t=e.length;if(t>1||1===t&&this.levelkeys[e[0]].encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){isFiniteNumber(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}get ref(){return isMediaFragment(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){if(this.levelkeys){const t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}}abortRequests(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}setElementaryStreamInfo(e,t,s,r,i,n=!1){const{elementaryStreams:a}=this,o=a[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,s),o.startDTS=Math.min(o.startDTS,r),o.endDTS=Math.max(o.endDTS,i)):a[e]={startPTS:t,endPTS:s,startDTS:r,endDTS:i,partial:n}}}class Part extends BaseSegment{constructor(e,t,s,r,i){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=r;const n=e.enumeratedString("BYTERANGE");n&&this.setByteRange(n,i),i&&(this.fragOffset=i.fragOffset+i.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}const UINT32_MAX$1=Math.pow(2,32)-1,push=[].push,RemuxerTrackIdConfig={video:1,audio:2,id3:3,text:4};function bin2str(e){return String.fromCharCode.apply(null,e)}function readUint16(e,t){const s=e[t]<<8|e[t+1];return s<0?65536+s:s}function readUint32(e,t){const s=readSint32(e,t);return s<0?4294967296+s:s}function readUint64(e,t){let s=readUint32(e,t);return s*=Math.pow(2,32),s+=readUint32(e,t+4),s}function readSint32(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function writeUint32(e,t,s){e[t]=s>>24,e[t+1]=s>>16&255,e[t+2]=s>>8&255,e[t+3]=255&s}function hasMoofData(e){const t=e.byteLength;for(let s=0;s<t;){const r=readUint32(e,s);if(r>8&&109===e[s+4]&&111===e[s+5]&&111===e[s+6]&&102===e[s+7])return!0;s=r>1?s+r:t}return!1}function findBox(e,t){const s=[];if(!t.length)return s;const r=e.byteLength;for(let i=0;i<r;){const n=readUint32(e,i),a=n>1?i+n:r;if(bin2str(e.subarray(i+4,i+8))===t[0])if(1===t.length)s.push(e.subarray(i+8,a));else{const r=findBox(e.subarray(i+8,a),t.slice(1));r.length&&push.apply(s,r)}i=a}return s}function parseSegmentIndex(e){const t=[],s=e[0];let r=8;const i=readUint32(e,r);r+=4;let n=0,a=0;0===s?(n=readUint32(e,r),a=readUint32(e,r+4),r+=8):(n=readUint64(e,r),a=readUint64(e,r+8),r+=16),r+=2;let o=e.length+a;const l=readUint16(e,r);r+=2;for(let s=0;s<l;s++){let s=r;const n=readUint32(e,s);s+=4;const a=2147483647&n;if(1===(2147483648&n)>>>31)return logger.warn("SIDX has hierarchical references (not supported)"),null;const l=readUint32(e,s);s+=4,t.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/i,start:o,end:o+a-1}}),o+=a,s+=4,r=s}return{earliestPresentationTime:n,timescale:i,version:s,referencesCount:l,references:t}}function parseInitSegment(e){const t=[],s=findBox(e,["moov","trak"]);for(let e=0;e<s.length;e++){const r=s[e],i=findBox(r,["tkhd"])[0];if(i){let e=i[0];const s=readUint32(i,0===e?12:20),n=findBox(r,["mdia","mdhd"])[0];if(n){e=n[0];const i=readUint32(n,0===e?12:20),a=findBox(r,["mdia","hdlr"])[0];if(a){const e=bin2str(a.subarray(8,12)),n={soun:ElementaryStreamTypes.AUDIO,vide:ElementaryStreamTypes.VIDEO}[e];if(n){const e=parseStsd(findBox(r,["mdia","minf","stbl","stsd"])[0]);t[s]={timescale:i,type:n},t[n]=_objectSpread2({timescale:i,id:s},e)}}}}}return findBox(e,["moov","mvex","trex"]).forEach((e=>{const s=readUint32(e,4),r=t[s];r&&(r.default={duration:readUint32(e,12),flags:readUint32(e,20)})})),t}function parseStsd(e){const t=e.subarray(8),s=t.subarray(86),r=bin2str(t.subarray(4,8));let i=r;const n="enca"===r||"encv"===r;if(n){const e=findBox(t,[r])[0];findBox(e.subarray("enca"===r?28:78),["sinf"]).forEach((e=>{const t=findBox(e,["schm"])[0];if(t){const s=bin2str(t.subarray(4,8));if("cbcs"===s||"cenc"===s){const t=findBox(e,["frma"])[0];t&&(i=bin2str(t))}}}))}switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{const e=findBox(s,["avcC"])[0];i+="."+toHex(e[1])+toHex(e[2])+toHex(e[3]);break}case"mp4a":{const e=findBox(t,[r])[0],s=findBox(e.subarray(28),["esds"])[0];if(s&&s.length>7){let e=4;if(3!==s[e++])break;e=skipBERInteger(s,e),e+=2;const t=s[e++];if(128&t&&(e+=2),64&t&&(e+=s[e++]),4!==s[e++])break;e=skipBERInteger(s,e);const r=s[e++];if(64!==r)break;if(i+="."+toHex(r),e+=12,5!==s[e++])break;e=skipBERInteger(s,e);const n=s[e++];let a=(248&n)>>3;31===a&&(a+=1+((7&n)<<3)+((224&s[e])>>5)),i+="."+a}break}case"hvc1":case"hev1":{const e=findBox(s,["hvcC"])[0],t=e[1],r=["","A","B","C"][t>>6],n=31&t,a=readUint32(e,2),o=(32&t)>>5?"H":"L",l=e[12],d=e.subarray(6,12);i+="."+r+n,i+="."+a.toString(16).toUpperCase(),i+="."+o+l;let h="";for(let e=d.length;e--;){const t=d[e];if(t||h){h="."+t.toString(16).toUpperCase()+h}}i+=h;break}case"dvh1":case"dvhe":{const e=findBox(s,["dvcC"])[0],t=e[2]>>1&127,r=e[2]<<5&32|e[3]>>3&31;i+="."+addLeadingZero(t)+"."+addLeadingZero(r);break}case"vp09":{const e=findBox(s,["vpcC"])[0],t=e[4],r=e[5],n=e[6]>>4&15;i+="."+addLeadingZero(t)+"."+addLeadingZero(r)+"."+addLeadingZero(n);break}case"av01":{const e=findBox(s,["av1C"])[0],t=e[1]>>>5,r=31&e[1],n=e[2]>>>7?"H":"M",a=(64&e[2])>>6,o=(32&e[2])>>5,l=2===t&&a?o?12:10:a?10:8,d=(16&e[2])>>4,h=(8&e[2])>>3,c=(4&e[2])>>2,u=3&e[2],f=1,g=1,m=1,p=0;i+="."+t+"."+addLeadingZero(r)+n+"."+addLeadingZero(l)+"."+d+"."+h+c+u+"."+addLeadingZero(f)+"."+addLeadingZero(g)+"."+addLeadingZero(m)+"."+p;break}}return{codec:i,encrypted:n}}function skipBERInteger(e,t){const s=t+5;for(;128&e[t++]&&t<s;);return t}function toHex(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function addLeadingZero(e){return(e<10?"0":"")+e}function patchEncyptionData(e,t){if(!e||!t)return e;const s=t.keyId;if(s&&t.isCommonEncryption){findBox(e,["moov","trak"]).forEach((e=>{const t=findBox(e,["mdia","minf","stbl","stsd"])[0].subarray(8);let r=findBox(t,["enca"]);const i=r.length>0;i||(r=findBox(t,["encv"])),r.forEach((e=>{findBox(i?e.subarray(28):e.subarray(78),["sinf"]).forEach((e=>{const t=parseSinf(e);if(t){const e=t.subarray(8,24);e.some((e=>0!==e))||(logger.log(`[eme] Patching keyId in 'enc${i?"a":"v"}>sinf>>tenc' box: ${Hex.hexDump(e)} -> ${Hex.hexDump(s)}`),t.set(s,8))}}))}))}))}return e}function parseSinf(e){const t=findBox(e,["schm"])[0];if(t){const s=bin2str(t.subarray(4,8));if("cbcs"===s||"cenc"===s)return findBox(e,["schi","tenc"])[0]}return null}function getStartDTS(e,t){return findBox(t,["moof","traf"]).reduce(((t,s)=>{const r=findBox(s,["tfdt"])[0],i=r[0],n=findBox(s,["tfhd"]).reduce(((t,s)=>{const n=readUint32(s,4),a=e[n];if(a){let e=readUint32(r,4);if(1===i){if(e===UINT32_MAX$1)return logger.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),t;e*=UINT32_MAX$1+1,e+=readUint32(r,8)}const s=e/(a.timescale||9e4);if(isFiniteNumber(s)&&(null===t||s<t))return s}return t}),null);return null!==n&&isFiniteNumber(n)&&(null===t||n<t)?n:t}),null)}function getDuration(e,t){let s=0,r=0,i=0;const n=findBox(e,["moof","traf"]);for(let e=0;e<n.length;e++){const a=n[e],o=findBox(a,["tfhd"])[0],l=t[readUint32(o,4)];if(!l)continue;const d=l.default,h=readUint32(o,0)|(null==d?void 0:d.flags);let c=null==d?void 0:d.duration;8&h&&(c=readUint32(o,2&h?12:8));const u=l.timescale||9e4,f=findBox(a,["trun"]);for(let e=0;e<f.length;e++){if(s=computeRawDurationFromSamples(f[e]),!s&&c){s=c*readUint32(f[e],4)}l.type===ElementaryStreamTypes.VIDEO?r+=s/u:l.type===ElementaryStreamTypes.AUDIO&&(i+=s/u)}}if(0===r&&0===i){let t=1/0,s=0,r=0;const i=findBox(e,["sidx"]);for(let e=0;e<i.length;e++){const n=parseSegmentIndex(i[e]);if(null!=n&&n.references){t=Math.min(t,n.earliestPresentationTime/n.timescale);const e=n.references.reduce(((e,t)=>e+t.info.duration||0),0);s=Math.max(s,e+n.earliestPresentationTime/n.timescale),r=s-t}}if(r&&isFiniteNumber(r))return r}return r||i}function computeRawDurationFromSamples(e){const t=readUint32(e,0);let s=8;1&t&&(s+=4),4&t&&(s+=4);let r=0;const i=readUint32(e,4);for(let n=0;n<i;n++){if(256&t){r+=readUint32(e,s),s+=4}512&t&&(s+=4),1024&t&&(s+=4),2048&t&&(s+=4)}return r}function offsetStartDTS(e,t,s){findBox(t,["moof","traf"]).forEach((t=>{findBox(t,["tfhd"]).forEach((r=>{const i=readUint32(r,4),n=e[i];if(!n)return;const a=n.timescale||9e4;findBox(t,["tfdt"]).forEach((e=>{const t=e[0],r=s*a;if(r){let s=readUint32(e,4);if(0===t)s-=r,s=Math.max(s,0),writeUint32(e,4,s);else{s*=Math.pow(2,32),s+=readUint32(e,8),s-=r,s=Math.max(s,0);const t=Math.floor(s/(UINT32_MAX$1+1)),i=Math.floor(s%(UINT32_MAX$1+1));writeUint32(e,4,t),writeUint32(e,8,i)}}}))}))}))}function segmentValidRange(e){const t={valid:null,remainder:null},s=findBox(e,["moof"]);if(s.length<2)return t.remainder=e,t;const r=s[s.length-1];return t.valid=sliceUint8(e,0,r.byteOffset-8),t.remainder=sliceUint8(e,r.byteOffset-8),t}function appendUint8Array(e,t){const s=new Uint8Array(e.length+t.length);return s.set(e),s.set(t,e.length),s}function parseSamples(e,t){const s=[],r=t.samples,i=t.timescale,n=t.id;let a=!1;return findBox(r,["moof"]).map((o=>{const l=o.byteOffset-8;findBox(o,["traf"]).map((o=>{const d=findBox(o,["tfdt"]).map((e=>{const t=e[0];let s=readUint32(e,4);return 1===t&&(s*=Math.pow(2,32),s+=readUint32(e,8)),s/i}))[0];return void 0!==d&&(e=d),findBox(o,["tfhd"]).map((d=>{const h=readUint32(d,4),c=16777215&readUint32(d,0);let u=0;const f=0!=(16&c);let g=0;const m=0!=(32&c);let p=8;h===n&&(0!=(1&c)&&(p+=8),0!=(2&c)&&(p+=4),0!=(8&c)&&(u=readUint32(d,p),p+=4),f&&(g=readUint32(d,p),p+=4),m&&(p+=4),"video"===t.type&&(a=isHEVC(t.codec)),findBox(o,["trun"]).map((n=>{const o=n[0],d=16777215&readUint32(n,0),h=0!=(1&d);let c=0;const f=0!=(4&d),m=0!=(256&d);let p=0;const E=0!=(512&d);let y=0;const v=0!=(1024&d),T=0!=(2048&d);let S=0;const A=readUint32(n,4);let L=8;h&&(c=readUint32(n,L),L+=4),f&&(L+=4);let I=c+l;for(let l=0;l<A;l++){if(m?(p=readUint32(n,L),L+=4):p=u,E?(y=readUint32(n,L),L+=4):y=g,v&&(L+=4),T&&(S=0===o?readUint32(n,L):readSint32(n,L),L+=4),t.type===ElementaryStreamTypes.VIDEO){let t=0;for(;t<y;){const n=readUint32(r,I);if(I+=4,isSEIMessage(a,r[I])){parseSEIMessageFromNALu(r.subarray(I,I+n),a?2:1,e+S/i,s)}I+=n,t+=n+4}}e+=p/i}})))}))}))})),s}function isHEVC(e){if(!e)return!1;const t=e.indexOf("."),s=t<0?e:e.substring(0,t);return"hvc1"===s||"hev1"===s||"dvh1"===s||"dvhe"===s}function isSEIMessage(e,t){if(e){const e=t>>1&63;return 39===e||40===e}return 6===(31&t)}function parseSEIMessageFromNALu(e,t,s,r){const i=discardEPB(e);let n=0;n+=t;let a=0,o=0,l=0;for(;n<i.length;){a=0;do{if(n>=i.length)break;l=i[n++],a+=l}while(255===l);o=0;do{if(n>=i.length)break;l=i[n++],o+=l}while(255===l);const e=i.length-n;let t=n;if(o<e)n+=o;else if(o>e){logger.error(`Malformed SEI payload. ${o} is too small, only ${e} bytes left to parse.`);break}if(4===a){if(181===i[t++]){const e=readUint16(i,t);if(t+=2,49===e){const e=readUint32(i,t);if(t+=4,1195456820===e){const e=i[t++];if(3===e){const n=i[t++],o=64&n,l=o?2+3*(31&n):0,d=new Uint8Array(l);if(o){d[0]=n;for(let e=1;e<l;e++)d[e]=i[t++]}r.push({type:e,payloadType:a,pts:s,bytes:d})}}}}}else if(5===a&&o>16){const e=[];for(let s=0;s<16;s++){const r=i[t++].toString(16);e.push(1==r.length?"0"+r:r),3!==s&&5!==s&&7!==s&&9!==s||e.push("-")}const n=o-16,l=new Uint8Array(n);for(let e=0;e<n;e++)l[e]=i[t++];r.push({payloadType:a,pts:s,uuid:e.join(""),userData:utf8ArrayToStr(l),userDataBytes:l})}}}function discardEPB(e){const t=e.byteLength,s=[];let r=1;for(;r<t-2;)0===e[r]&&0===e[r+1]&&3===e[r+2]?(s.push(r+2),r+=2):r++;if(0===s.length)return e;const i=t-s.length,n=new Uint8Array(i);let a=0;for(r=0;r<i;a++,r++)a===s[0]&&(a++,s.shift()),n[r]=e[a];return n}function parseEmsg(e){const t=e[0];let s="",r="",i=0,n=0,a=0,o=0,l=0,d=0;if(0===t){for(;"\0"!==bin2str(e.subarray(d,d+1));)s+=bin2str(e.subarray(d,d+1)),d+=1;for(s+=bin2str(e.subarray(d,d+1)),d+=1;"\0"!==bin2str(e.subarray(d,d+1));)r+=bin2str(e.subarray(d,d+1)),d+=1;r+=bin2str(e.subarray(d,d+1)),d+=1,i=readUint32(e,12),n=readUint32(e,16),o=readUint32(e,20),l=readUint32(e,24),d=28}else if(1===t){d+=4,i=readUint32(e,d),d+=4;const t=readUint32(e,d);d+=4;const n=readUint32(e,d);for(d+=4,a=2**32*t+n,isSafeInteger(a)||(a=Number.MAX_SAFE_INTEGER,logger.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=readUint32(e,d),d+=4,l=readUint32(e,d),d+=4;"\0"!==bin2str(e.subarray(d,d+1));)s+=bin2str(e.subarray(d,d+1)),d+=1;for(s+=bin2str(e.subarray(d,d+1)),d+=1;"\0"!==bin2str(e.subarray(d,d+1));)r+=bin2str(e.subarray(d,d+1)),d+=1;r+=bin2str(e.subarray(d,d+1)),d+=1}return{schemeIdUri:s,value:r,timeScale:i,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:e.subarray(d,e.byteLength)}}function mp4Box(e,...t){const s=t.length;let r=8,i=s;for(;i--;)r+=t[i].byteLength;const n=new Uint8Array(r);for(n[0]=r>>24&255,n[1]=r>>16&255,n[2]=r>>8&255,n[3]=255&r,n.set(e,4),i=0,r=8;i<s;i++)n.set(t[i],r),r+=t[i].byteLength;return n}function mp4pssh(e,t,s){if(16!==e.byteLength)throw new RangeError("Invalid system id");let r,i,n;r=0,i=new Uint8Array,n=new Uint8Array;const a=new Uint8Array(4);return s&&s.byteLength>0&&new DataView(a.buffer).setUint32(0,s.byteLength,!1),mp4Box([112,115,115,104],new Uint8Array([0,0,0,0]),e,n,i,a,s||new Uint8Array)}function parseMultiPssh(e){const t=[];if(e instanceof ArrayBuffer){const s=e.byteLength;let r=0;for(;r+32<s;){const s=parsePssh(new DataView(e,r));t.push(s),r+=s.size}}return t}function parsePssh(e){const t=e.getUint32(0),s=e.byteOffset,r=e.byteLength;if(r<t)return{offset:s,size:r};if(1886614376!==e.getUint32(4))return{offset:s,size:t};const i=e.getUint32(8)>>>24;if(0!==i&&1!==i)return{offset:s,size:t};const n=e.buffer,a=Hex.hexDump(new Uint8Array(n,s+12,16)),o=e.getUint32(28);let l=null,d=null;if(0===i){if(t-32<o||o<22)return{offset:s,size:t};d=new Uint8Array(n,s+32,o)}else if(1===i){if(!o||r<s+32+16*o+16)return{offset:s,size:t};l=[];for(let e=0;e<o;e++)l.push(new Uint8Array(n,s+32+16*e,16))}return{version:i,systemId:a,kids:l,data:d,offset:s,size:t}}const CHUNK_SIZE=16;class Decrypter{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const e=self.crypto;e&&(this.subtle=e.subtle||e.webkitSubtle)}catch(e){}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:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const s=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?removePadding(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,r){return this.useSoftware?new Promise(((i,n)=>{const a=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(a,t,s,r);const o=this.flush();o?i(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(e),t,s,r)}softwareDecrypt(e,t,s,r){const{currentIV:i,currentResult:n,remainderData:a}=this;if(r!==DecrypterAesMode.cbc||16!==t.byteLength)return logger.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=appendUint8Array(a,e),this.remainderData=null);const o=this.getValidChunk(e);if(!o.length)return null;i&&(s=i);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new AESDecryptor),l.expandKey(t);const d=n;return this.currentResult=l.decrypt(o.buffer,0,s),this.currentIV=sliceUint8(o,-16).buffer,d||null}webCryptoDecrypt(e,t,s,r){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,r));this.key=t,this.fastAesKey=new FastAESKey(this.subtle,t,r)}return this.fastAesKey.expandKey().then((t=>{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new AESCrypto(this.subtle,new Uint8Array(s),r).decrypt(e.buffer,t)})).catch((i=>(logger.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${i.name}: ${i.message}`),this.onWebCryptoError(e,t,s,r))))}onWebCryptoError(e,t,s,r){const i=this.enableSoftwareAES;if(i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,r);const i=this.flush();if(i)return i.buffer}throw new Error("WebCrypto"+(i?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const s=e.length-e.length%16;return s!==e.length&&(t=sliceUint8(e,0,s),this.remainderData=sliceUint8(e,s)),t}logOnce(e){this.logEnabled&&(logger.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const MIN_CHUNK_SIZE=Math.pow(2,17);class FragmentLoader{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const s=e.url;if(!s)return Promise.reject(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(s?"part list":"url")),networkDetails:null}));this.abort();const r=this.config,i=r.fLoader,n=r.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some((e=>"GAP"===e[0])))return void o(createGapLoadError(e));e.gap=!1}const l=this.loader=i?new i(r):new n(r),d=createLoaderContext(e);e.loader=l;const h=getLoaderConfigWithoutReties(r.fragLoadPolicy.default),c={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:MIN_CHUNK_SIZE};e.stats=l.stats;const u={onSuccess:(t,s,r,i)=>{this.resetLoader(e,l);let n=t.data;r.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),a({frag:e,part:null,payload:n,networkDetails:i})},onError:(t,r,i,n)=>{this.resetLoader(e,l),o(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:_objectSpread2({url:s,data:void 0},t),error:new Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:i,stats:n}))},onAbort:(t,s,r)=>{this.resetLoader(e,l),o(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:r,stats:t}))},onTimeout:(t,s,r)=>{this.resetLoader(e,l),o(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:r,stats:t}))}};t&&(u.onProgress=(s,r,i,n)=>t({frag:e,part:null,payload:i,networkDetails:n})),l.load(d,c,u)}))}loadPart(e,t,s){this.abort();const r=this.config,i=r.fLoader,n=r.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void o(createGapLoadError(e,t));const l=this.loader=i?new i(r):new n(r),d=createLoaderContext(e,t);e.loader=l;const h=getLoaderConfigWithoutReties(r.fragLoadPolicy.default),c={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:MIN_CHUNK_SIZE};t.stats=l.stats,l.load(d,c,{onSuccess:(r,i,n,o)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const d={frag:e,part:t,payload:r.data,networkDetails:o};s(d),a(d)},onError:(s,r,i,n)=>{this.resetLoader(e,l),o(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:_objectSpread2({url:d.url,data:void 0},s),error:new Error(`HTTP Error ${s.code} ${s.text}`),networkDetails:i,stats:n}))},onAbort:(s,r,i)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),o(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:i,stats:s}))},onTimeout:(s,r,i)=>{this.resetLoader(e,l),o(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:i,stats:s}))}})}))}updateStatsFromPart(e,t){const s=e.stats,r=t.stats,i=r.total;if(s.loaded+=r.loaded,i){const r=Math.round(e.duration/t.duration),n=Math.min(Math.round(s.loaded/i),r),a=(r-n)*Math.round(s.loaded/n);s.total=s.loaded+a}else s.total=Math.max(s.loaded,s.total);const n=s.loading,a=r.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function createLoaderContext(e,t=null){const s=t||e,r={frag:e,part:t,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},i=s.byteRangeStartOffset,n=s.byteRangeEndOffset;if(isFiniteNumber(i)&&isFiniteNumber(n)){var a;let t=i,s=n;if("initSegment"===e.sn&&isMethodFullSegmentAesCbc(null==(a=e.decryptdata)?void 0:a.method)){const e=n-i;e%16&&(s=n+(16-e%16)),0!==i&&(r.resetIV=!0,t=i-16)}r.rangeStart=t,r.rangeEnd=s}return r}function createGapLoadError(e,t){const s=new Error(`GAP ${e.gap?"tag":"attribute"} found`),r={type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_GAP,fatal:!1,frag:e,error:s,networkDetails:null};return t&&(r.part=t),(t||e).stats.aborted=!0,new LoadError(r)}function isMethodFullSegmentAesCbc(e){return"AES-128"===e||"AES-256"===e}class LoadError extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class TaskLoop extends Logger{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class ChunkMetadata{constructor(e,t,s,r=0,i=-1,n=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=getNewPerformanceTiming(),this.buffering={audio:getNewPerformanceTiming(),video:getNewPerformanceTiming(),audiovideo:getNewPerformanceTiming()},this.level=e,this.sn=t,this.id=s,this.size=r,this.part=i,this.partial=n}}function getNewPerformanceTiming(){return{start:0,executeStart:0,executeEnd:0,end:0}}const noopBuffered={length:0,start:()=>0,end:()=>0};class BufferHelper{static isBuffered(e,t){if(e){const s=BufferHelper.getBuffered(e);for(let e=s.length;e--;)if(t>=s.start(e)&&t<=s.end(e))return!0}return!1}static bufferInfo(e,t,s){if(e){const r=BufferHelper.getBuffered(e);if(r.length){const e=[];for(let t=0;t<r.length;t++)e.push({start:r.start(t),end:r.end(t)});return BufferHelper.bufferedInfo(e,t,s)}}return{len:0,start:t,end:t,nextStart:void 0}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.sort(((e,t)=>e.start-t.start||t.end-e.end));let r=[];if(s)for(let t=0;t<e.length;t++){const i=r.length;if(i){const n=r[i-1].end;e[t].start-n<s?e[t].end>n&&(r[i-1].end=e[t].end):r.push(e[t])}else r.push(e[t])}else r=e;let i,n=0,a=t,o=t;for(let e=0;e<r.length;e++){const l=r[e].start,d=r[e].end;if(t+s>=l&&t<d)a=l,o=d,n=o-t;else if(t+s<l){i=l;break}}return{len:n,start:a||0,end:o||0,nextStart:i}}static getBuffered(e){try{return e.buffered||noopBuffered}catch(e){return logger.log("failed to get media.buffered",e),noopBuffered}}}const VARIABLE_REPLACEMENT_REGEX=/\{\$([a-zA-Z0-9-_]+)\}/g;function hasVariableReferences(e){return VARIABLE_REPLACEMENT_REGEX.test(e)}function substituteVariables(e,t){if(null!==e.variableList||e.hasVariableRefs){const s=e.variableList;return t.replace(VARIABLE_REPLACEMENT_REGEX,(t=>{const r=t.substring(2,t.length-1),i=null==s?void 0:s[r];return void 0===i?(e.playlistParsingError||(e.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),t):i}))}return t}function addVariableDefinition(e,t,s){let r,i,n=e.variableList;if(n||(e.variableList=n={}),"QUERYPARAM"in t){r=t.QUERYPARAM;try{const e=new self.URL(s).searchParams;if(!e.has(r))throw new Error(`"${r}" does not match any query parameter in URI: "${s}"`);i=e.get(r)}catch(t){e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${t.message}`))}}else r=t.NAME,i=t.VALUE;r in n?e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):n[r]=i||""}function importVariableDefinition(e,t,s){const r=t.IMPORT;if(s&&r in s){let t=e.variableList;t||(e.variableList=t={}),t[r]=s[r]}else e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`))}const DECIMAL_RESOLUTION_REGEX=/^(\d+)x(\d+)$/,ATTR_LIST_REGEX=/(.+?)=(".*?"|.*?)(?:,|$)/g;class AttrList{constructor(e,t){"string"==typeof e&&(e=AttrList.parseAttrList(e,t)),_extends(this,e)}get clientAttrs(){return Object.keys(this).filter((e=>"X-"===e.substring(0,2)))}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;const s=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)s[e]=parseInt(t.slice(2*e,2*e+2),16);return s}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const s=this[e];return(s?s.split(/[ ,]+/):[]).reduce(((e,t)=>(e[t.toLowerCase()]=!0,e)),t)}bool(e){return"YES"===this[e]}decimalResolution(e){const t=DECIMAL_RESOLUTION_REGEX.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let s;const r={};for(ATTR_LIST_REGEX.lastIndex=0;null!==(s=ATTR_LIST_REGEX.exec(e));){const i=s[1].trim();let n=s[2];const a=0===n.indexOf('"')&&n.lastIndexOf('"')===n.length-1;let o=!1;if(a)n=n.slice(1,-1);else switch(i){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(t&&(a||o))n=substituteVariables(t,n);else if(!o&&!a)switch(i){case"CLOSED-CAPTIONS":if("NONE"===n)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":logger.warn(`${e}: attribute ${i} is missing quotes`)}r[i]=n}return r}}const CLASS_INTERSTITIAL="com.apple.hls.interstitial";function isDateRangeCueAttribute(e){return"ID"!==e&&"CLASS"!==e&&"CUE"!==e&&"START-DATE"!==e&&"DURATION"!==e&&"END-DATE"!==e&&"END-ON-NEXT"!==e}function isSCTE35Attribute(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}class DateRange{constructor(e,t,s=0){var r;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==t?void 0:t.tagAnchor)||null,this.tagOrder=null!=(r=null==t?void 0:t.tagOrder)?r:s,t){const s=t.attr;for(const t in s)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==s[t]){logger.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=_extends(new AttrList({}),s,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const e=(null==t?void 0:t.endDate)||new Date(this.attr["END-DATE"]);isFiniteNumber(e.getTime())&&(this._endDate=e)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return void 0===e?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return null===e||null===e.programDateTime?(logger.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return null!==t?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*t):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(isFiniteNumber(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===CLASS_INTERSTITIAL}get isValid(){return!!this.id&&!this._badValueForSameId&&isFiniteNumber(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)}}const DEFAULT_TARGET_DURATION=10;class LevelDetails{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e)return this.advanced=!0,void(this.updated=!0);const t=this.lastPartSn-e.lastPartSn,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&s>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1,this.availabilityDelay=e.availabilityDelay}get hasProgramDateTime(){return!!this.fragments.length&&isFiniteNumber(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const e=this.driftEndTime-this.driftStartTime;if(e>0){return 1e3*(this.driftEnd-this.driftStart)/e}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var e;return null!=(e=this.fragments)&&e.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){var e;return null!=(e=this.fragments)&&e.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(-1!==t){for(let s=e.length;s--;)if(e[s].index>t)return e[s].index;return t}}return 0}get lastPartSn(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function isFullSegmentEncryption(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function getAesModeFromFullSegmentMethod(e){switch(e){case"AES-128":case"AES-256":return DecrypterAesMode.cbc;case"AES-256-CTR":return DecrypterAesMode.ctr;default:throw new Error(`invalid full segment method ${e}`)}}function base64Decode(e){return Uint8Array.from(atob(e),(e=>e.charCodeAt(0)))}function strToUtf8array(e){return Uint8Array.from(unescape(encodeURIComponent(e)),(e=>e.charCodeAt(0)))}function getKeyIdBytes(e){const t=strToUtf8array(e).subarray(0,16),s=new Uint8Array(16);return s.set(t,16-t.length),s}function changeEndianness(e){const t=function(e,t,s){const r=e[t];e[t]=e[s],e[s]=r};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function convertDataUriToArrayBytes(e){const t=e.split(":");let s=null;if("data"===t[0]&&2===t.length){const e=t[1].split(";"),r=e[e.length-1].split(",");if(2===r.length){const t="base64"===r[0],i=r[1];t?(e.splice(-1,1),s=base64Decode(i)):s=getKeyIdBytes(i)}}return s}const optionalSelf="undefined"!=typeof self?self:void 0;var KeySystems={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},KeySystemFormats={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function keySystemFormatToKeySystemDomain(e){switch(e){case KeySystemFormats.FAIRPLAY:return KeySystems.FAIRPLAY;case KeySystemFormats.PLAYREADY:return KeySystems.PLAYREADY;case KeySystemFormats.WIDEVINE:return KeySystems.WIDEVINE;case KeySystemFormats.CLEARKEY:return KeySystems.CLEARKEY}}var KeySystemIds={CENC:"1077efecc0b24d02ace33c1e52e2fb4b",CLEARKEY:"e2719d58a985b3c9781ab030af78d30e",FAIRPLAY:"94ce86fb07ff4f43adb893d2fa968ca2",PLAYREADY:"9a04f07998404286ab92e65be0885f95",WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function keySystemIdToKeySystemDomain(e){return e===KeySystemIds.WIDEVINE?KeySystems.WIDEVINE:e===KeySystemIds.PLAYREADY?KeySystems.PLAYREADY:e===KeySystemIds.CENC||e===KeySystemIds.CLEARKEY?KeySystems.CLEARKEY:void 0}function keySystemDomainToKeySystemFormat(e){switch(e){case KeySystems.FAIRPLAY:return KeySystemFormats.FAIRPLAY;case KeySystems.PLAYREADY:return KeySystemFormats.PLAYREADY;case KeySystems.WIDEVINE:return KeySystemFormats.WIDEVINE;case KeySystems.CLEARKEY:return KeySystemFormats.CLEARKEY}}function getKeySystemsForConfig(e){const{drmSystems:t,widevineLicenseUrl:s}=e,r=t?[KeySystems.FAIRPLAY,KeySystems.WIDEVINE,KeySystems.PLAYREADY,KeySystems.CLEARKEY].filter((e=>!!t[e])):[];return!r[KeySystems.WIDEVINE]&&s&&r.push(KeySystems.WIDEVINE),r}const requestMediaKeySystemAccess=function(e){return null!=optionalSelf&&null!=(e=optionalSelf.navigator)&&e.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function getSupportedMediaKeySystemConfigurations(e,t,s,r){let i;switch(e){case KeySystems.FAIRPLAY:i=["cenc","sinf"];break;case KeySystems.WIDEVINE:case KeySystems.PLAYREADY:i=["cenc"];break;case KeySystems.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${e}`)}return createMediaKeySystemConfigurations(i,t,s,r)}function createMediaKeySystemConfigurations(e,t,s,r){return[{initDataTypes:e,persistentState:r.persistentState||"optional",distinctiveIdentifier:r.distinctiveIdentifier||"optional",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:t.map((e=>({contentType:`audio/mp4; codecs=${e}`,robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null}))),videoCapabilities:s.map((e=>({contentType:`video/mp4; codecs=${e}`,robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null})))}]}function parsePlayReadyWRM(e){const t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),s=String.fromCharCode.apply(null,Array.from(t)),r=s.substring(s.indexOf("<"),s.length),i=(new DOMParser).parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(i){const e=i.childNodes[0]?i.childNodes[0].nodeValue:i.getAttribute("VALUE");if(e){const t=base64Decode(e).subarray(0,16);return changeEndianness(t),t}}return null}let keyUriToKeyIdMap={};class LevelKey{static clearKeyUriToKeyIdMap(){keyUriToKeyIdMap={}}constructor(e,t,s,r=[1],i=null){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=s,this.keyFormatVersions=r,this.iv=i,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&!isFullSegmentEncryption(e)}isSupported(){if(this.method){if(isFullSegmentEncryption(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case KeySystemFormats.FAIRPLAY:case KeySystemFormats.WIDEVINE:case KeySystemFormats.PLAYREADY:case KeySystemFormats.CLEARKEY:return-1!==["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(e){if(!this.encrypted||!this.uri)return null;if(isFullSegmentEncryption(this.method)&&this.uri&&!this.iv){"number"!=typeof e&&(logger.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0);const t=createInitializationVector(e);return new LevelKey(this.method,this.uri,"identity",this.keyFormatVersions,t)}const t=convertDataUriToArrayBytes(this.uri);if(t)switch(this.keyFormat){case KeySystemFormats.WIDEVINE:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case KeySystemFormats.PLAYREADY:{const e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=mp4pssh(e,null,t),this.keyId=parsePlayReadyWRM(t);break}default:{let e=t.subarray(0,16);if(16!==e.length){const t=new Uint8Array(16);t.set(e,16-e.length),e=t}this.keyId=e;break}}if(!this.keyId||16!==this.keyId.byteLength){let e=keyUriToKeyIdMap[this.uri];if(!e){const t=Object.keys(keyUriToKeyIdMap).length%Number.MAX_SAFE_INTEGER;e=new Uint8Array(16);new DataView(e.buffer,12,4).setUint32(0,t),keyUriToKeyIdMap[this.uri]=e}this.keyId=e}return this}}function createInitializationVector(e){const t=new Uint8Array(16);for(let s=12;s<16;s++)t[s]=e>>8*(15-s)&255;return t}const MASTER_PLAYLIST_REGEX=/#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,MASTER_PLAYLIST_MEDIA_REGEX=/#EXT-X-MEDIA:(.*)/g,IS_MEDIA_PLAYLIST=/^#EXT(?:INF|-X-TARGETDURATION):/m,LEVEL_PLAYLIST_REGEX_FAST=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),LEVEL_PLAYLIST_REGEX_SLOW=new RegExp([/#(EXTM3U)/.source,/#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 M3U8Parser{static findGroup(e,t){for(let s=0;s<e.length;s++){const r=e[s];if(r.id===t)return r}}static resolve(e,t){return urlToolkitExports.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return IS_MEDIA_PLAYLIST.test(e)}static parseMasterPlaylist(e,t){const s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:hasVariableReferences(e)},r=[];let i;for(MASTER_PLAYLIST_REGEX.lastIndex=0;null!=(i=MASTER_PLAYLIST_REGEX.exec(e));)if(i[1]){var n;const e=new AttrList(i[1],s),a=substituteVariables(s,i[2]),o={attrs:e,bitrate:e.decimalInteger("BANDWIDTH")||e.decimalInteger("AVERAGE-BANDWIDTH"),name:e.NAME,url:M3U8Parser.resolve(a,t)},l=e.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),setCodecs(e.CODECS,o),null!=(n=o.unknownCodecs)&&n.length||r.push(o),s.levels.push(o)}else if(i[3]){const e=i[3],r=i[4];switch(e){case"SESSION-DATA":{const e=new AttrList(r,s),t=e["DATA-ID"];t&&(null===s.sessionData&&(s.sessionData={}),s.sessionData[t]=e);break}case"SESSION-KEY":{const e=parseKey(r,t,s);e.encrypted&&e.isSupported()?(null===s.sessionKeys&&(s.sessionKeys=[]),s.sessionKeys.push(e)):logger.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${r}"`);break}case"DEFINE":addVariableDefinition(s,new AttrList(r,s),t);break;case"CONTENT-STEERING":{const e=new AttrList(r,s);s.contentSteering={uri:M3U8Parser.resolve(e["SERVER-URI"],t),pathwayId:e["PATHWAY-ID"]||"."};break}case"START":s.startTimeOffset=parseStartTimeOffset(r)}}const a=r.length>0&&r.length<s.levels.length;return s.levels=a?r:s.levels,0===s.levels.length&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(e,t,s){let r;const i={},n=s.levels,a={AUDIO:n.map((e=>({id:e.attrs.AUDIO,audioCodec:e.audioCodec}))),SUBTITLES:n.map((e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec}))),"CLOSED-CAPTIONS":[]};let o=0;for(MASTER_PLAYLIST_MEDIA_REGEX.lastIndex=0;null!==(r=MASTER_PLAYLIST_MEDIA_REGEX.exec(e));){const e=new AttrList(r[1],s),n=e.TYPE;if(n){const s=a[n],r=i[n]||[];i[n]=r;const l=e.LANGUAGE,d=e["ASSOC-LANGUAGE"],h=e.CHANNELS,c=e.CHARACTERISTICS,u=e["INSTREAM-ID"],f={attrs:e,bitrate:0,id:o++,groupId:e["GROUP-ID"]||"",name:e.NAME||l||"",type:n,default:e.bool("DEFAULT"),autoselect:e.bool("AUTOSELECT"),forced:e.bool("FORCED"),lang:l,url:e.URI?M3U8Parser.resolve(e.URI,t):""};if(d&&(f.assocLang=d),h&&(f.channels=h),c&&(f.characteristics=c),u&&(f.instreamId=u),null!=s&&s.length){const e=M3U8Parser.findGroup(s,f.groupId)||s[0];assignCodec(f,e,"audioCodec"),assignCodec(f,e,"textCodec")}r.push(f)}}return i}static parseLevelPlaylist(e,t,s,r,i,n){const a={url:t},o=new LevelDetails(t),l=o.fragments,d=[];let h,c,u,f=null,g=0,m=0,p=0,E=0,y=0,v=null,T=new Fragment(r,a),S=-1,A=!1,L=null;for(LEVEL_PLAYLIST_REGEX_FAST.lastIndex=0,o.m3u8=e,o.hasVariableRefs=hasVariableReferences(e);null!==(h=LEVEL_PLAYLIST_REGEX_FAST.exec(e));){A&&(A=!1,T=new Fragment(r,a),T.playlistOffset=p,T.start=p,T.sn=g,T.cc=E,y&&(T.bitrate=y),T.level=s,f&&(T.initSegment=f,f.rawProgramDateTime&&(T.rawProgramDateTime=f.rawProgramDateTime,f.rawProgramDateTime=null),L&&(T.setByteRange(L),L=null)));const e=h[1];if(e){T.duration=parseFloat(e);const t=(" "+h[2]).slice(1);T.title=t||null,T.tagList.push(t?["INF",e,t]:["INF",e])}else if(h[3]){if(isFiniteNumber(T.duration)){T.playlistOffset=p,T.start=p,u&&setFragLevelKeys(T,u,o),T.sn=g,T.level=s,T.cc=E,l.push(T);const e=(" "+h[3]).slice(1);T.relurl=substituteVariables(o,e),assignProgramDateTime(T,v,d),v=T,p+=T.duration,g++,m=0,A=!0}}else{if(h=h[0].match(LEVEL_PLAYLIST_REGEX_SLOW),!h){logger.warn("No matches on slow regex match for level playlist!");continue}for(c=1;c<h.length&&void 0===h[c];c++);const e=(" "+h[c]).slice(1),i=(" "+h[c+1]).slice(1),d=h[c+2]?(" "+h[c+2]).slice(1):null;switch(e){case"BYTERANGE":v?T.setByteRange(i,v):T.setByteRange(i);break;case"PROGRAM-DATE-TIME":T.rawProgramDateTime=i,T.tagList.push(["PROGRAM-DATE-TIME",i]),-1===S&&(S=l.length);break;case"PLAYLIST-TYPE":o.type=i.toUpperCase();break;case"MEDIA-SEQUENCE":g=o.startSN=parseInt(i);break;case"SKIP":{o.skippedSegments&&(o.playlistParsingError=new Error("#EXT-X-SKIP MUST NOT appear more than once in a Playlist"));const e=new AttrList(i,o),t=e.decimalInteger("SKIPPED-SEGMENTS");if(isFiniteNumber(t)){o.skippedSegments+=t;for(let e=t;e--;)l.push(null);g+=t}const s=e.enumeratedString("RECENTLY-REMOVED-DATERANGES");s&&(o.recentlyRemovedDateranges=(o.recentlyRemovedDateranges||[]).concat(s.split("\t")));break}case"TARGETDURATION":o.targetduration=Math.max(parseInt(i),1);break;case"VERSION":o.version=parseInt(i);break;case"INDEPENDENT-SEGMENTS":case"EXTM3U":break;case"ENDLIST":o.live=!1;break;case"#":(i||d)&&T.tagList.push(d?[i,d]:[i]);break;case"DISCONTINUITY":E++,T.tagList.push(["DIS"]);break;case"GAP":T.gap=!0,T.tagList.push([e]);break;case"BITRATE":T.tagList.push([e,i]),y=1e3*parseInt(i),isFiniteNumber(y)?T.bitrate=y:y=0;break;case"DATERANGE":{const e=new AttrList(i,o),t=new DateRange(e,o.dateRanges[e.ID],o.dateRangeTagCount);o.dateRangeTagCount++,t.isValid||o.skippedSegments?o.dateRanges[t.id]=t:logger.warn(`Ignoring invalid DATERANGE tag: "${i}"`),T.tagList.push(["EXT-X-DATERANGE",i]);break}case"DEFINE":{const e=new AttrList(i,o);"IMPORT"in e?importVariableDefinition(o,e,n):addVariableDefinition(o,e,t)}break;case"DISCONTINUITY-SEQUENCE":o.startCC=E=parseInt(i);break;case"KEY":{const e=parseKey(i,t,o);if(e.isSupported()){if("NONE"===e.method){u=void 0;break}u||(u={}),u[e.keyFormat]&&(u=_extends({},u)),u[e.keyFormat]=e}else logger.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${i}"`);break}case"START":o.startTimeOffset=parseStartTimeOffset(i);break;case"MAP":{const e=new AttrList(i,o);if(T.duration){const t=new Fragment(r,a);setInitSegment(t,e,s,u),f=t,T.initSegment=f,f.rawProgramDateTime&&!T.rawProgramDateTime&&(T.rawProgramDateTime=f.rawProgramDateTime)}else{const t=T.byteRangeEndOffset;if(t){const e=T.byteRangeStartOffset;L=`${t-e}@${e}`}else L=null;setInitSegment(T,e,s,u),f=T,A=!0}f.cc=E;break}case"SERVER-CONTROL":{const e=new AttrList(i);o.canBlockReload=e.bool("CAN-BLOCK-RELOAD"),o.canSkipUntil=e.optionalFloat("CAN-SKIP-UNTIL",0),o.canSkipDateRanges=o.canSkipUntil>0&&e.bool("CAN-SKIP-DATERANGES"),o.partHoldBack=e.optionalFloat("PART-HOLD-BACK",0),o.holdBack=e.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const e=new AttrList(i);o.partTarget=e.decimalFloatingPoint("PART-TARGET");break}case"PART":{let e=o.partList;e||(e=o.partList=[]);const t=m>0?e[e.length-1]:void 0,s=m++,r=new AttrList(i,o),n=new Part(r,T,a,s,t);e.push(n),T.duration+=n.duration;break}case"PRELOAD-HINT":{const e=new AttrList(i,o);o.preloadHint=e;break}case"RENDITION-REPORT":{const e=new AttrList(i,o);o.renditionReports=o.renditionReports||[],o.renditionReports.push(e);break}default:logger.warn(`line parsed but not handled: ${h}`)}}}v&&!v.relurl?(l.pop(),p-=v.duration,o.partList&&(o.fragmentHint=v)):o.partList&&(assignProgramDateTime(T,v,d),T.cc=E,o.fragmentHint=T,u&&setFragLevelKeys(T,u,o));const I=l.length,R=l[0],D=l[I-1];if(p+=o.skippedSegments*o.targetduration,p>0&&I&&D){o.averagetargetduration=p/I;const e=D.sn;o.endSN="initSegment"!==e?e:0,o.live||(D.endList=!0),R&&!o.startCC&&(o.startCC=R.cc),S>0&&(backfillProgramDateTimes(l,S),R&&d.unshift(R))}else o.endSN=0,o.startCC=0;return o.fragmentHint&&(p+=o.fragmentHint.duration),o.totalduration=p,d.length&&o.dateRangeTagCount&&R&&mapDateRanges(d,o),o.endCC=E,o}}function mapDateRanges(e,t){const s=e.length,r=e[s-1],i=t.live?1/0:t.totalduration,n=Object.keys(t.dateRanges);for(let a=n.length;a--;){const o=t.dateRanges[n[a]],l=o.startDate.getTime();o.tagAnchor=r.ref;for(let r=s;r--;){const s=findFragmentWithStartDate(t,l,e,r,i);if(-1!==s){o.tagAnchor=t.fragments[s].ref;break}}}}function findFragmentWithStartDate(e,t,s,r,i){const n=s[r];if(n){const o=n.programDateTime;if(t>=o||0===r){var a;if(t<=o+1e3*(((null==(a=s[r+1])?void 0:a.start)||i)-n.start)){const i=s[r].sn-e.startSN,n=e.fragments;if(n.length>s.length){for(let a=(s[r+1]||n[n.length-1]).sn-e.startSN;a>i;a--){const e=n[a].programDateTime;if(t>=e&&t<e+1e3*n[a].duration)return a}}return i}}}return-1}function parseKey(e,t,s){var r,i;const n=new AttrList(e,s),a=null!=(r=n.METHOD)?r:"",o=n.URI,l=n.hexadecimalInteger("IV"),d=n.KEYFORMATVERSIONS,h=null!=(i=n.KEYFORMAT)?i:"identity";o&&n.IV&&!l&&logger.error(`Invalid IV: ${n.IV}`);const c=o?M3U8Parser.resolve(o,t):"",u=(d||"1").split("/").map(Number).filter(Number.isFinite);return new LevelKey(a,c,h,u,l)}function parseStartTimeOffset(e){const t=new AttrList(e).decimalFloatingPoint("TIME-OFFSET");return isFiniteNumber(t)?t:null}function setCodecs(e,t){let s=(e||"").split(/[ ,]+/).filter((e=>e));["video","audio","text"].forEach((e=>{const r=s.filter((t=>isCodecType(t,e)));r.length&&(t[`${e}Codec`]=r.join(","),s=s.filter((e=>-1===r.indexOf(e))))})),t.unknownCodecs=s}function assignCodec(e,t,s){const r=t[s];r&&(e[s]=r)}function backfillProgramDateTimes(e,t){let s=e[t];for(let r=t;r--;){const t=e[r];if(!t)return;t.programDateTime=s.programDateTime-1e3*t.duration,s=t}}function assignProgramDateTime(e,t,s){e.rawProgramDateTime?s.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function setInitSegment(e,t,s,r){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=s,e.sn="initSegment",r&&(e.levelkeys=r),e.initSegment=null}function setFragLevelKeys(e,t,s){e.levelkeys=t;const{encryptedFragments:r}=s;r.length&&r[r.length-1].levelkeys===t||!Object.keys(t).some((e=>t[e].isCommonEncryption))||r.push(e)}function updateFromToPTS(e,t){const s=t.startPTS;if(isFiniteNumber(s)){let r,i=0;t.sn>e.sn?(i=s-e.start,r=e):(i=e.start-s,r=t),r.duration!==i&&r.setDuration(i)}else if(t.sn>e.sn){e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration)}else t.setStart(Math.max(e.start-t.duration,0))}function updateFragPTSDTS(e,t,s,r,i,n){r-s<=0&&(logger.warn("Fragment should have a positive duration",t),r=s+t.duration,n=i+t.duration);let a=s,o=r;const l=t.startPTS,d=t.endPTS;if(isFiniteNumber(l)){const e=Math.abs(l-s);isFiniteNumber(t.deltaPTS)?t.deltaPTS=Math.max(e,t.deltaPTS):t.deltaPTS=e,a=Math.max(s,l),s=Math.min(s,l),i=Math.min(i,t.startDTS),o=Math.min(r,d),r=Math.max(r,d),n=Math.max(n,t.endDTS)}const h=s-t.start;0!==t.start&&t.setStart(s),t.setDuration(r-t.start),t.startPTS=s,t.maxStartPTS=a,t.startDTS=i,t.endPTS=r,t.minEndPTS=o,t.endDTS=n;const c=t.sn;if(!e||c<e.startSN||c>e.endSN)return 0;let u;const f=c-e.startSN,g=e.fragments;for(g[f]=t,u=f;u>0;u--)updateFromToPTS(g[u],g[u-1]);for(u=f;u<g.length-1;u++)updateFromToPTS(g[u],g[u+1]);return e.fragmentHint&&updateFromToPTS(g[g.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,h}function mergeDetails(e,t){let s=null;const r=e.fragments;for(let e=r.length-1;e>=0;e--){const t=r[e].initSegment;if(t){s=t;break}}e.fragmentHint&&delete e.fragmentHint.endPTS;let i,n=0;mapFragmentIntersection(e,t,((e,r)=>{e.relurl&&(n=e.cc-r.cc),isFiniteNumber(e.startPTS)&&isFiniteNumber(e.endPTS)&&(r.setStart(r.startPTS=e.startPTS),r.startDTS=e.startDTS,r.maxStartPTS=e.maxStartPTS,r.endPTS=e.endPTS,r.endDTS=e.endDTS,r.minEndPTS=e.minEndPTS,r.setDuration(e.endPTS-e.startPTS),r.duration&&(i=r),t.PTSKnown=t.alignedSliding=!0),e.hasStreams&&(r.elementaryStreams=e.elementaryStreams),r.loader=e.loader,e.hasStats&&(r.stats=e.stats),e.initSegment&&(r.initSegment=e.initSegment,s=e.initSegment)}));const a=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments;if(s&&a.forEach((e=>{var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=s)?void 0:t.relurl)||(e.initSegment=s)})),t.skippedSegments)if(t.deltaUpdateFailed=t.fragments.some((e=>!e)),t.deltaUpdateFailed){logger.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let e=t.skippedSegments;e--;)t.fragments.shift();t.startSN=t.fragments[0].sn,t.startCC||(t.startCC=t.fragments[0].cc)}else{t.canSkipDateRanges&&(t.dateRanges=mergeDateRanges(e.dateRanges,t));const s=e.fragments.filter((e=>e.rawProgramDateTime));if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(let e=1;e<a.length;e++)null===a[e].programDateTime&&assignProgramDateTime(a[e],a[e-1],s);mapDateRanges(s,t)}const o=t.fragments;if(n){logger.warn("discontinuity sliding from playlist, take drift into account");for(let e=0;e<o.length;e++)o[e].cc+=n}t.skippedSegments&&(t.startCC=t.fragments[0].cc),mapPartIntersection(e.partList,t.partList,((e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats})),i?updateFragPTSDTS(t,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS):adjustSliding(e,t),o.length&&(t.totalduration=t.edge-o[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;const l=t.advancedDateTime;if(t.advanced&&l){const e=t.edge;t.driftStart||(t.driftStartTime=l,t.driftStart=e),t.driftEndTime=l,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}function mergeDateRanges(e,t){const{dateRanges:s,recentlyRemovedDateranges:r}=t,i=_extends({},e);r&&r.forEach((e=>{delete i[e]}));const n=Object.keys(i).length;return n&&Object.keys(s).forEach((e=>{const t=i[e],r=new DateRange(s[e].attr,t);r.isValid?(i[e]=r,t||(r.tagOrder+=n)):logger.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(s[e].attr)}"`)})),i}function mapPartIntersection(e,t,s){if(e&&t){let r=0;for(let i=0,n=e.length;i<=n;i++){const n=e[i],a=t[i+r];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?s(n,a):r--}}}function mapFragmentIntersection(e,t,s){const r=t.skippedSegments,i=Math.max(e.startSN,t.startSN)-t.startSN,n=(e.fragmentHint?1:0)+(r?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,a=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let e=i;e<=n;e++){const i=l[a+e];let n=o[e];r&&!n&&i&&(n=t.fragments[e]=i),i&&n&&s(i,n)}}function adjustSliding(e,t,s=!0){const r=t.startSN+t.skippedSegments-e.startSN,i=e.fragments,n=r>=0;let a=0;if(n&&r<i.length)a=i[r].start;else if(n&&t.startSN===e.endSN+1)a=e.fragmentEnd;else if(n&&s)a=e.fragmentStart+r*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return;a=e.fragmentStart}addSliding(t,a)}function addSliding(e,t){if(t){const s=e.fragments;for(let r=e.skippedSegments;r<s.length;r++)s[r].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}function computeReloadInterval(e,t=1/0){let s=1e3*e.targetduration;if(e.updated){const r=e.fragments,i=4;if(r.length&&s*i>t){const e=1e3*r[r.length-1].duration;e<s&&(s=e)}}else s/=2;return Math.round(s)}function getFragmentWithSN(e,t,s){if(!e)return null;let r=e.fragments[t-e.startSN];return r||(r=e.fragmentHint,r&&r.sn===t?r:t<e.startSN&&s&&s.sn===t?s:null)}function getPartWith(e,t,s){return e?findPart(e.partList,t,s):null}function findPart(e,t,s){if(e)for(let r=e.length;r--;){const i=e[r];if(i.index===s&&i.fragment.sn===t)return i}return null}function reassignFragmentLevelIndexes(e){e.forEach(((e,t)=>{var s;const r=null==(s=e.details)?void 0:s.fragments;r&&r.forEach((e=>{e.level=t,e.initSegment&&(e.initSegment.level=t)}))}))}function findFirstFragWithCC(e,t){for(let r=0,i=e.length;r<i;r++){var s;if((null==(s=e[r])?void 0:s.cc)===t)return e[r]}return null}function shouldAlignOnDiscontinuities(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}function adjustFragmentStart(e,t){if(e){const s=e.start+t;e.start=e.startPTS=s,e.endPTS=s+e.duration}}function adjustSlidingStart(e,t){const s=t.fragments;for(let t=0,r=s.length;t<r;t++)adjustFragmentStart(s[t],e);t.fragmentHint&&adjustFragmentStart(t.fragmentHint,e),t.alignedSliding=!0}function alignStream(e,t){e&&(alignDiscontinuities(t,e),!t.alignedSliding&&e&&alignMediaPlaylistByPDT(t,e),t.alignedSliding||!e||t.skippedSegments||adjustSliding(e,t,!1))}function alignDiscontinuities(e,t){if(!shouldAlignOnDiscontinuities(t,e))return;const s=Math.min(t.endCC,e.endCC),r=findFirstFragWithCC(t.fragments,s),i=findFirstFragWithCC(e.fragments,s);if(!r||!i)return;logger.log(`Aligning playlist at start of dicontinuity sequence ${s}`);adjustSlidingStart(r.start-i.start,e)}function alignMediaPlaylistByPDT(e,t){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;const s=e.fragments,r=t.fragments;if(!s.length||!r.length)return;let i,n;const a=Math.min(t.endCC,e.endCC);t.startCC<a&&e.startCC<a&&(i=findFirstFragWithCC(r,a),n=findFirstFragWithCC(s,a)),i&&n||(i=r[Math.floor(r.length/2)],n=findFirstFragWithCC(s,i.cc)||s[Math.floor(s.length/2)]);const o=i.programDateTime,l=n.programDateTime;if(!o||!l)return;adjustSlidingStart((l-o)/1e3-(n.start-i.start),e)}const TimeRanges={toString:function(e){let t="";const s=e.length;for(let r=0;r<s;r++)t+=`[${e.start(r).toFixed(3)}-${e.end(r).toFixed(3)}]`;return t}},State={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class BaseStreamController extends TaskLoop{constructor(e,t,s,r,i){super(r,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=State.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.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:e,fragCurrent:t,media:s,mediaBuffer:r,state:i}=this,n=s?s.currentTime:0,a=BufferHelper.bufferInfo(r||s,n,e.maxBufferHole);if(this.log(`media seeking to ${isFiniteNumber(n)?n.toFixed(3):n}, state: ${i}`),this.state===State.ENDED)this.resetLoadingState();else if(t){const s=e.maxFragLookUpTolerance,r=t.start-s,i=t.start+t.duration+s;if(!a.len||i<a.start||r>a.end){const e=n>i;(n<r||e)&&(e&&t.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(s){this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0);if(n>this.lastCurrentTime&&(this.lastCurrentTime=n),!this.loadingParts){const e=Math.max(a.end,n),t=this.shouldLoadParts(this.getLevelDetails(),e);t&&(this.log(`LL-Part loading ON after seeking to ${n.toFixed(2)} with buffer @${e.toFixed(2)}`),this.loadingParts=t)}}this.hls.hasEnoughToStart||a.len||(this.log(`setting startPosition to ${n} because of seek before start`),this.nextLoadPosition=this.startPosition=n),this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0,this.triggerEnded()},this.playlistType=i,this.hls=e,this.fragmentLoader=new FragmentLoader(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Decrypter(e.config)}registerListeners(){const{hls:e}=this;e.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Events.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Events.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===State.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=State.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return-1===t&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}_streamEnded(e,t){const s=void 0!==this.config.timelineOffset,r=e.nextStart,i=r&&(!s||r<t.edge);if(t.live||i||!e.end||!this.media)return!1;const n=t.partList;if(null!=n&&n.length){const e=n[n.length-1];return BufferHelper.isBuffered(this.media,e.start+e.duration/2)}const a=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(a)}getLevelDetails(){var e;if(this.levels&&null!==this.levelLastLoaded)return null==(e=this.levelLastLoaded)?void 0:e.details}onMediaAttached(e,t){const s=this.media=this.mediaBuffer=t.media;s.removeEventListener("seeking",this.onMediaSeeking),s.removeEventListener("ended",this.onMediaEnded),s.addEventListener("seeking",this.onMediaSeeking),s.addEventListener("ended",this.onMediaEnded);const r=this.config;this.levels&&r.autoStartLoad&&this.state===State.STOPPED&&this.startLoad(r.startPosition)}onMediaDetaching(e,t){const s=!!t.transferMedia,r=this.media;null!==r&&(r.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),r.removeEventListener("seeking",this.onMediaSeeking),r.removeEventListener("ended",this.onMediaEnded),this.keyLoader&&!s&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,s?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(e,t){}triggerEnded(){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=State.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,s){const r=this.hls.config;if(r.interstitialsController&&!1!==r.enableInterstitialPlayback&&e.type!==PlaylistLevelType.SUBTITLE){const s=this.hls.interstitialsManager,r=null==s?void 0:s.bufferingItem;if(r){const s=r.event;if(s){if(s.appendInPlace||Math.abs(e.start-r.start)>1||0===r.start)return}else{var i;if(e.end<=r.start&&!1===(null==(i=t.details)?void 0:i.live))return;if(e.start>r.end&&r.nextEvent)return}}}this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){this._doFragLoad(e,t,s,(e=>{const t=e.frag;if(this.fragContextChanged(t))return this.warn(`${t.type} sn: ${t.sn}${e.part?" part: "+e.part.index:""} of ${this.fragInfo(t,!1,e.part)}) was dropped during download.`),void this.fragmentTracker.removeFragment(t);t.stats.chunkCount++,this._handleFragmentLoadProgress(e)})).then((e=>{if(!e)return;const t=this.state,s=e.frag;this.fragContextChanged(s)?(t===State.FRAG_LOADING||!this.fragCurrent&&t===State.PARSING)&&(this.fragmentTracker.removeFragment(s),this.state=State.IDLE):("payload"in e&&(this.log(`Loaded ${s.type} sn: ${s.sn} of ${this.playlistLabel()} ${s.level}`),this.hls.trigger(Events.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e))})).catch((t=>{this.state!==State.STOPPED&&this.state!==State.ERROR&&(this.warn(`Frag error: ${(null==t?void 0:t.message)||t}`),this.resetFragmentLoading(e))}))}clearTrackerIfNeeded(e){var t;const{fragmentTracker:s}=this;if(s.getState(e)===FragmentState.APPENDING){const t=e.type,r=this.getFwdBufferInfo(this.mediaBuffer,t),i=Math.max(e.duration,r?r.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?e.sn-n.sn:0)||this.reduceMaxBufferLength(i,e.duration))&&s.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===FragmentState.PARTIAL&&s.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,s=null){if(!(e-t))return;const r={startOffset:e,endOffset:t,type:s};this.hls.trigger(Events.BUFFER_FLUSHING,r)}_loadInitSegment(e,t){this._doFragLoad(e,t).then((e=>{const t=null==e?void 0:e.frag;if(!t||this.fragContextChanged(t)||!this.levels)throw new Error("init load aborted");return e})).then((e=>{const{hls:t}=this,{frag:s,payload:r}=e,i=s.decryptdata;if(r&&r.byteLength>0&&null!=i&&i.key&&i.iv&&isFullSegmentEncryption(i.method)){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),i.key.buffer,i.iv.buffer,getAesModeFromFullSegmentMethod(i.method)).catch((e=>{throw t.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:s}),e})).then((r=>{const i=self.performance.now();return t.trigger(Events.FRAG_DECRYPTED,{frag:s,payload:r,stats:{tstart:n,tdecrypt:i}}),e.payload=r,this.completeInitSegmentLoad(e)}))}return this.completeInitSegmentLoad(e)})).catch((t=>{this.state!==State.STOPPED&&this.state!==State.ERROR&&(this.warn(t),this.resetFragmentLoading(e))}))}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const s=e.frag.stats;this.state!==State.STOPPED&&(this.state=State.IDLE),e.frag.data=new Uint8Array(e.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${s?TimeRanges.toString(BufferHelper.getBuffered(s)):"(detached)"})`),isMediaFragment(e)){var r;if(e.type!==PlaylistLevelType.SUBTITLE){const t=e.elementaryStreams;if(!Object.keys(t).some((e=>!!t[e])))return void(this.state=State.IDLE)}const t=null==(r=this.levels)?void 0:r[e.level];null!=t&&t.fragmentError&&(this.log(`Resetting level fragment error count of ${t.fragmentError} on frag buffered`),t.fragmentError=0)}this.state=State.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:s,part:r,partsLoaded:i}=e,n=!i||0===i.length||i.some((e=>!e)),a=new ChunkMetadata(s.level,s.sn,s.stats.chunkCount+1,0,r?r.index:-1,!n);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,s=null,r){var i;this.fragCurrent=e;const n=null==t?void 0:t.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=null;!e.encrypted||null!=(i=e.decryptdata)&&i.key?!e.encrypted&&n.encryptedFragments.length&&this.keyLoader.loadClear(e,n.encryptedFragments):(this.log(`Loading key for ${e.sn} of [${n.startSN}-${n.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=State.KEY_LOADING,this.fragCurrent=e,a=this.keyLoader.load(e).then((e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(Events.KEY_LOADED,e),this.state===State.KEY_LOADING&&(this.state=State.IDLE),e})),this.hls.trigger(Events.KEY_LOADING,{frag:e}),null===this.fragCurrent&&(a=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING"))));const o=this.fragPrevious;if(isMediaFragment(e)&&(!o||e.sn!==o.sn)){const s=this.shouldLoadParts(t.details,e.end);s!==this.loadingParts&&(this.log(`LL-Part loading ${s?"ON":"OFF"} loading sn ${null==o?void 0:o.sn}->${e.sn}`),this.loadingParts=s)}if(s=Math.max(e.start,s||0),this.loadingParts&&isMediaFragment(e)){const i=n.partList;if(i&&r){s>e.end&&n.fragmentHint&&(e=n.fragmentHint);const o=this.getNextPart(i,e,s);if(o>-1){const l=i[o];let d;return e=this.fragCurrent=l.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${l.index} (${o}/${i.length-1}) of ${this.fragInfo(e,!1,l)}) cc: ${e.cc} [${n.startSN}-${n.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=State.FRAG_LOADING,d=a?a.then((s=>!s||this.fragContextChanged(s.frag)?null:this.doFragPartsLoad(e,l,t,r))).catch((e=>this.handleFragLoadError(e))):this.doFragPartsLoad(e,l,t,r).catch((e=>this.handleFragLoadError(e))),this.hls.trigger(Events.FRAG_LOADING,{frag:e,part:l,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):d}if(!e.url||this.loadedEndOfParts(i,s))return Promise.resolve(null)}}if(isMediaFragment(e)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)}`),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${n?"["+n.startSN+"-"+n.endSN+"]":""}, target: ${parseFloat(s.toFixed(3))}`),isFiniteNumber(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=State.FRAG_LOADING;const l=this.config.progressive;let d;return d=l&&a?a.then((t=>!t||this.fragContextChanged(null==t?void 0:t.frag)?null:this.fragmentLoader.load(e,r))).catch((e=>this.handleFragLoadError(e))):Promise.all([this.fragmentLoader.load(e,l?r:void 0),a]).then((([e])=>(!l&&e&&r&&r(e),e))).catch((e=>this.handleFragLoadError(e))),this.hls.trigger(Events.FRAG_LOADING,{frag:e,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):d}doFragPartsLoad(e,t,s,r){return new Promise(((i,n)=>{var a;const o=[],l=null==(a=s.details)?void 0:a.partList,d=t=>{this.fragmentLoader.loadPart(e,t,r).then((r=>{o[t.index]=r;const n=r.part;this.hls.trigger(Events.FRAG_LOADED,r);const a=getPartWith(s.details,e.sn,t.index+1)||findPart(l,e.sn,t.index+1);if(!a)return i({frag:e,part:n,partsLoaded:o});d(a)})).catch(n)};d(t)}))}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===ErrorDetails.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(Events.ERROR,t)}else this.hls.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==State.PARSING)return void(this.fragCurrent||this.state===State.STOPPED||this.state===State.ERROR||(this.state=State.IDLE));const{frag:s,part:r,level:i}=t,n=self.performance.now();s.stats.parsing.end=n,r&&(r.stats.parsing.end=n);const a=this.getLevelDetails(),o=a&&s.sn>a.endSN||this.shouldLoadParts(a,s.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${s.end.toFixed(2)}`),this.loadingParts=o),this.updateLevelTiming(s,r,i,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(null!=e&&e.partList){var s;const i=e.partList[0];if(t>=i.end+((null==(s=e.fragmentHint)?void 0:s.duration)||0)){var r;if((this.hls.hasEnoughToStart?(null==(r=this.media)?void 0:r.currentTime)||this.lastCurrentTime:this.getLoadPosition())>i.start-i.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:s}=this,{level:r,sn:i,part:n}=e;if(null==t||!t[r])return this.warn(`Levels object was unset while buffering fragment ${i} of ${this.playlistLabel()} ${r}. The current chunk will not be buffered.`),null;const a=t[r],o=a.details,l=n>-1?getPartWith(o,i,n):null,d=l?l.fragment:getFragmentWithSN(o,i,s);return d?(s&&s!==d&&(d.stats=s.stats),{frag:d,part:l,level:a}):null}bufferFragmentData(e,t,s,r,i){var n;if(!e||this.state!==State.PARSING)return;const{data1:a,data2:o}=e;let l=a;if(a&&o&&(l=appendUint8Array(a,o)),null==(n=l)||!n.length)return;const d={type:e.type,frag:t,part:s,chunkMeta:r,parent:t.type,data:l};if(this.hls.trigger(Events.BUFFER_APPENDING,d),e.dropped&&e.independent&&!s){if(i)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!BufferHelper.isBuffered(t,t.currentTime))return void this.flushMainBuffer(0,e.start);const s=t.currentTime,r=BufferHelper.bufferInfo(t,s,0),i=e.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*i),a=Math.max(Math.min(e.start-n,r.end-n),s+n);e.start-a>n&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){var s;const r=this.getLoadPosition();if(!isFiniteNumber(r))return null;const i=this.lastCurrentTime>r||null!=(s=this.media)&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,r,t,i)}getFwdBufferInfoAtPos(e,t,s,r){const i=BufferHelper.bufferInfo(e,t,r);if(0===i.len&&void 0!==i.nextStart){const n=this.fragmentTracker.getBufferedFrag(t,s);if(n&&(i.nextStart<=n.end||n.gap))return BufferHelper.bufferInfo(e,t,Math.max(i.nextStart,r))}return i}getMaxBufferLength(e){const{config:t}=this;let s;return s=e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const s=this.config,r=Math.max(Math.min(e-t,s.maxBufferLength),t),i=Math.max(e-3*t,s.maxMaxBufferLength/2,r);return i>=r&&(s.maxMaxBufferLength=i,this.warn(`Reduce max buffer length to ${i}s`),!0)}getAppendedFrag(e,t=PlaylistLevelType.MAIN){var s;const r=null==(s=this.fragmentTracker)?void 0:s.getAppendedFrag(e,t);return r&&"fragment"in r?r.fragment:r}getNextFragment(e,t){const s=t.fragments,r=s.length;if(!r)return null;const{config:i}=this,n=s[0].start,a=i.lowLatencyMode&&!!t.partList;let o=null;if(t.live){const d=i.initialLiveManifestSize;if(r<d)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${d})`),null;if(!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<n){var l;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(t,s);const r=this.hls.startPosition,i=this.hls.liveSyncPosition,n=o?(-1!==r?r:i)||o.start:e;this.log(`Setting startPosition to ${n} to match initial live edge. mainStart: ${r} liveSyncPosition: ${i} frag.start: ${null==(l=o)?void 0:l.start}`),this.startPosition=this.nextLoadPosition=n}}else e<=n&&(o=s[0]);if(!o){const s=this.loadingParts?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,s,t)}return this.mapToInitFragWhenRequired(o)}isLoopLoading(e,t){const s=this.fragmentTracker.getState(e);return(s===FragmentState.OK||s===FragmentState.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,s,r,i){let n=null;if(e.gap&&(n=this.getNextFragment(this.nextLoadPosition,t),n&&!n.gap&&s.nextStart)){const e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,r,0);if(null!==e&&s.len+e.len>=i){const e=n.sn;return this.loopSn!==e&&(this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${e}`),this.loopSn=e),null}}return this.loopSn=void 0,n}mapToInitFragWhenRequired(e){return null==e||!e.initSegment||null!=e&&e.initSegment.data||this.bitrateTest?e:e.initSegment}getNextPart(e,t,s){let r=-1,i=!1,n=!0;for(let a=0,o=e.length;a<o;a++){const o=e[a];if(n=n&&!o.independent,r>-1&&s<o.start)break;const l=o.loaded;l?r=-1:(i||o.independent||n)&&o.fragment===t&&(r=a),i=l}return r}loadedEndOfParts(e,t){const s=e[e.length-1];return s&&t>s.start&&s.loaded}getInitialLiveFragment(e,t){const s=this.fragPrevious;let r=null;if(s){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),r=findFragmentByPDT(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){const i=s.sn+1;if(i>=e.startSN&&i<=e.endSN){const n=t[i-e.startSN];s.cc===n.cc&&(r=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=findFragWithCC(t,s.cc),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{const t=this.hls.liveSyncPosition;null!==t&&(r=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r}getFragmentAtPosition(e,t,s){const{config:r}=this;let{fragPrevious:i}=this,{fragments:n,endSN:a}=s;const{fragmentHint:o}=s,{maxFragLookUpTolerance:l}=r,d=s.partList,h=!!(this.loadingParts&&null!=d&&d.length&&o);let c;if(h&&o&&!this.bitrateTest&&d[d.length-1].fragment.sn===o.sn&&(n=n.concat(o),a=o.sn),e<t){var u;c=findFragmentByPTS(i,n,e,e<this.lastCurrentTime||e>t-l||null!=(u=this.media)&&u.paused||!this.startFragRequested?0:l)}else c=n[n.length-1];if(c){const e=c.sn-s.startSN,t=this.fragmentTracker.getState(c);if((t===FragmentState.OK||t===FragmentState.PARTIAL&&c.gap)&&(i=c),i&&c.sn===i.sn&&(!h||d[0].fragment.sn>c.sn||!s.live&&!h)){if(i&&c.level===i.level){const t=n[e+1];c=c.sn<a&&this.fragmentTracker.getState(t)!==FragmentState.OK?t:null}}}return c}alignPlaylists(e,t,s){const r=e.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;const i=e.fragmentStart,n=!t,a=e.alignedSliding&&isFiniteNumber(i);if(n||!a&&!i){alignStream(s,e);const i=e.fragmentStart;return this.log(`Live playlist sliding: ${i.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${r}`),i}return i}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}setStartPosition(e,t){let s=this.startPosition;if(s<t&&(s=-1),-1===s){const r=null!==this.startTimeOffset,i=r?this.startTimeOffset:e.startTimeOffset;null!==i&&isFiniteNumber(i)?(s=t+i,i<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${i} found in ${r?"multivariant":"media"} playlist`),this.startPosition=s):e.live?(s=this.hls.liveSyncPosition||t,this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s}this.nextLoadPosition=s}getLoadPosition(){var e;const{media:t}=this;let s=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t?s=t.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&isMediaFragment(e)&&e.stats.aborted&&(this.warn(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===State.FRAG_LOADING_WAITING_RETRY)||(this.state=State.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}const s=t.frag;if(!s||s.type!==e||!this.levels)return;var r;if(this.fragContextChanged(s))return void this.warn(`Frag load error must match current frag to retry ${s.url} > ${null==(r=this.fragCurrent)?void 0:r.url}`);const i=t.details===ErrorDetails.FRAG_GAP;i&&this.fragmentTracker.fragBuffered(s,!0);const n=t.errorAction,{action:a,flags:o,retryCount:l=0,retryConfig:d}=n||{},h=!!n&&!!d,c=h&&a===NetworkErrorAction.RetryRequest,u=h&&!n.resolved&&o===ErrorActionFlags.MoveAllAlternatesMatchingHost;if(!c&&u&&isMediaFragment(s)&&!s.endList)this.resetFragmentErrors(e),this.treatAsGap(s),n.resolved=!0;else if((c||u)&&l<d.maxNumRetry){this.resetStartWhenNotLoaded(this.levelLastLoaded);const r=getRetryDelay(d,l);this.warn(`Fragment ${s.sn} of ${e} ${s.level} errored with ${t.details}, retrying loading ${l+1}/${d.maxNumRetry} in ${r}ms`),n.resolved=!0,this.retryDate=self.performance.now()+r,this.state=State.FRAG_LOADING_WAITING_RETRY}else if(d&&n){if(this.resetFragmentErrors(e),!(l<d.maxNumRetry))return void this.warn(`${t.details} reached or exceeded max retry (${l})`);i||a===NetworkErrorAction.RemoveAlternatePermanently||(n.resolved=!0)}else a===NetworkErrorAction.SendAlternateToPenaltyBox?this.state=State.WAITING_LEVEL:this.state=State.ERROR;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===State.PARSING||this.state===State.PARSED){const t=e.frag,s=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,s),i=r&&r.len>.5;i&&this.reduceMaxBufferLength(r.len,(null==t?void 0:t.duration)||10);const n=!i;return n&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${s} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(e){e===PlaylistLevelType.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==State.STOPPED&&(this.state=State.IDLE)}afterBufferFlushed(e,t,s){if(!e)return;const r=BufferHelper.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,s),this.state===State.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==State.STOPPED&&(this.state=State.IDLE)}resetStartWhenNotLoaded(e){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=e?e.details:null;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(e){this.warn(`The loading context changed while buffering fragment ${e.sn} of ${this.playlistLabel()} ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,s,r){var i;const n=s.details;if(!n)return void this.warn("level.details undefined");if(!Object.keys(e.elementaryStreams).reduce(((t,i)=>{const a=e.elementaryStreams[i];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${e.sn} ${i} duration reliably (${o})`),t||!1;const l=r?0:updateFragPTSDTS(n,e,a.startPTS,a.endPTS,a.startDTS,a.endDTS);return this.hls.trigger(Events.LEVEL_PTS_UPDATED,{details:n,level:s,drift:l,type:i,frag:e,start:a.startPTS,end:a.endPTS}),!0}return t}),!1)&&null===(null==(i=this.transmuxer)?void 0:i.error)){const t=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(0===s.fragmentError&&this.treatAsGap(e,s),this.warn(t.message),this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,error:t,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=State.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(Events.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===PlaylistLevelType.MAIN?"level":"track"}fragInfo(e,t=!0,s){var r,i;return`${this.playlistLabel()} ${e.level} (${s?"part":"frag"}:[${(null!=(r=t&&!s?e.startPTS:(s||e).start)?r:NaN).toFixed(3)}-${(null!=(i=t&&!s?e.endPTS:(s||e).end)?i:NaN).toFixed(3)}]${s&&"main"===e.type?"INDEPENDENT="+(s.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;null==(e=this.transmuxer)||e.reset()}recoverWorkerError(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}class ChunkCache{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let s;return e.length?(s=1===e.length?e[0]:concatUint8Arrays(e,t),this.reset(),s):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}function concatUint8Arrays(e,t){const s=new Uint8Array(t);let r=0;for(let t=0;t<e.length;t++){const i=e[t];s.set(i,r),r+=i.length}return s}var eventemitter3={exports:{}};!function(e){var t=Object.prototype.hasOwnProperty,s="~";function r(){}function i(e,t,s){this.fn=e,this.context=t,this.once=s||!1}function n(e,t,r,n,a){if("function"!=typeof r)throw new TypeError("The listener must be a function");var o=new i(r,n||e,a),l=s?s+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function a(e,t){0==--e._eventsCount?e._events=new r:delete e._events[t]}function o(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(s=!1)),o.prototype.eventNames=function(){var e,r,i=[];if(0===this._eventsCount)return i;for(r in e=this._events)t.call(e,r)&&i.push(s?r.slice(1):r);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},o.prototype.listeners=function(e){var t=s?s+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var i=0,n=r.length,a=new Array(n);i<n;i++)a[i]=r[i].fn;return a},o.prototype.listenerCount=function(e){var t=s?s+e:e,r=this._events[t];return r?r.fn?1:r.length:0},o.prototype.emit=function(e,t,r,i,n,a){var o=s?s+e:e;if(!this._events[o])return!1;var l,d,h=this._events[o],c=arguments.length;if(h.fn){switch(h.once&&this.removeListener(e,h.fn,void 0,!0),c){case 1:return h.fn.call(h.context),!0;case 2:return h.fn.call(h.context,t),!0;case 3:return h.fn.call(h.context,t,r),!0;case 4:return h.fn.call(h.context,t,r,i),!0;case 5:return h.fn.call(h.context,t,r,i,n),!0;case 6:return h.fn.call(h.context,t,r,i,n,a),!0}for(d=1,l=new Array(c-1);d<c;d++)l[d-1]=arguments[d];h.fn.apply(h.context,l)}else{var u,f=h.length;for(d=0;d<f;d++)switch(h[d].once&&this.removeListener(e,h[d].fn,void 0,!0),c){case 1:h[d].fn.call(h[d].context);break;case 2:h[d].fn.call(h[d].context,t);break;case 3:h[d].fn.call(h[d].context,t,r);break;case 4:h[d].fn.call(h[d].context,t,r,i);break;default:if(!l)for(u=1,l=new Array(c-1);u<c;u++)l[u-1]=arguments[u];h[d].fn.apply(h[d].context,l)}}return!0},o.prototype.on=function(e,t,s){return n(this,e,t,s,!1)},o.prototype.once=function(e,t,s){return n(this,e,t,s,!0)},o.prototype.removeListener=function(e,t,r,i){var n=s?s+e:e;if(!this._events[n])return this;if(!t)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn!==t||i&&!o.once||r&&o.context!==r||a(this,n);else{for(var l=0,d=[],h=o.length;l<h;l++)(o[l].fn!==t||i&&!o[l].once||r&&o[l].context!==r)&&d.push(o[l]);d.length?this._events[n]=1===d.length?d[0]:d:a(this,n)}return this},o.prototype.removeAllListeners=function(e){var t;return e?(t=s?s+e:e,this._events[t]&&a(this,t)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=s,o.EventEmitter=o,e.exports=o}(eventemitter3);var eventemitter3Exports=eventemitter3.exports,EventEmitter=getDefaultExportFromCjs(eventemitter3Exports);const version="1.6.0-beta.2",workerStore={};function hasUMDWorker(){return"function"==typeof __HLS_WORKER_BUNDLE__}function injectWorker(){const e=workerStore[version];if(e)return e.clientCount++,e;const t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),s=self.URL.createObjectURL(t),r={worker:new self.Worker(s),objectURL:s,clientCount:1};return workerStore[version]=r,r}function loadWorker(e){const t=workerStore[e];if(t)return t.clientCount++,t;const s=new self.URL(e,self.location.href).href,r={worker:new self.Worker(s),scriptURL:s,clientCount:1};return workerStore[e]=r,r}function removeWorkerFromStore(e){const t=workerStore[e||version];if(t){if(1===t.clientCount--){const{worker:s,objectURL:r}=t;delete workerStore[e||version],r&&self.URL.revokeObjectURL(r),s.terminate()}}}function isId3Footer(e,t){return t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function isId3Header(e,t){return t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function readId3Size(e,t){let s=0;return s=(127&e[t])<<21,s|=(127&e[t+1])<<14,s|=(127&e[t+2])<<7,s|=127&e[t+3],s}function getId3Data(e,t){const s=t;let r=0;for(;isId3Header(e,t);){r+=10;r+=readId3Size(e,t+6),isId3Footer(e,t+10)&&(r+=10),t+=r}if(r>0)return e.subarray(s,s+r)}function getAudioConfig(e,t,s,r){const i=t[s+2],n=i>>2&15;if(n>12){const t=new Error(`invalid ADTS sampling index:${n}`);return void e.emit(Events.ERROR,Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,fatal:!0,error:t,reason:t.message})}const a=1+(i>>6&3),o=t[s+3]>>6&3|(1&i)<<2,l="mp4a.40."+a,d=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][n];let h=n;5!==a&&29!==a||(h-=3);const c=[a<<3|(14&h)>>1,(1&h)<<7|o<<3];return logger.log(`manifest codec:${r}, parsed codec:${l}, channels:${o}, rate:${d} (ADTS object type:${a} sampling index:${n})`),{config:c,samplerate:d,channelCount:o,codec:l,parsedCodec:l,manifestCodec:r}}function isHeaderPattern$1(e,t){return 255===e[t]&&240==(246&e[t+1])}function getHeaderLength(e,t){return 1&e[t+1]?7:9}function getFullFrameLength(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function canGetFrameLength(e,t){return t+5<e.length}function isHeader$1(e,t){return t+1<e.length&&isHeaderPattern$1(e,t)}function canParse$1(e,t){return canGetFrameLength(e,t)&&isHeaderPattern$1(e,t)&&getFullFrameLength(e,t)<=e.length-t}function probe$1(e,t){if(isHeader$1(e,t)){const s=getHeaderLength(e,t);if(t+s>=e.length)return!1;const r=getFullFrameLength(e,t);if(r<=s)return!1;const i=t+r;return i===e.length||isHeader$1(e,i)}return!1}function initTrackConfig(e,t,s,r,i){if(!e.samplerate){const n=getAudioConfig(t,s,r,i);if(!n)return;_extends(e,n)}}function getFrameDuration(e){return 9216e4/e}function parseFrameHeader(e,t){const s=getHeaderLength(e,t);if(t+s<=e.length){const r=getFullFrameLength(e,t)-s;if(r>0)return{headerLength:s,frameLength:r}}}function appendFrame$2(e,t,s,r,i){const n=r+i*getFrameDuration(e.samplerate),a=parseFrameHeader(t,s);let o;if(a){const{frameLength:r,headerLength:i}=a,l=i+r,d=Math.max(0,s+l-t.length);d?(o=new Uint8Array(l-i),o.set(t.subarray(s+i,t.length),0)):o=t.subarray(s+i,s+l);const h={unit:o,pts:n};return d||e.samples.push(h),{sample:h,length:l,missing:d}}const l=t.length-s;o=new Uint8Array(l),o.set(t.subarray(s,t.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}function canParseId3(e,t){return isId3Header(e,t)&&readId3Size(e,t+6)+10<=e.length-t}function decodeId3PrivFrame(e){if(e.size<2)return;const t=utf8ArrayToStr(e.data,!0),s=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:s.buffer}}function decodeId3TextFrame(e){if(e.size<2)return;if("TXXX"===e.type){let t=1;const s=utf8ArrayToStr(e.data.subarray(t),!0);t+=s.length+1;const r=utf8ArrayToStr(e.data.subarray(t));return{key:e.type,info:s,data:r}}const t=utf8ArrayToStr(e.data.subarray(1));return{key:e.type,info:"",data:t}}function decodeId3UrlFrame(e){if("WXXX"===e.type){if(e.size<2)return;let t=1;const s=utf8ArrayToStr(e.data.subarray(t),!0);t+=s.length+1;const r=utf8ArrayToStr(e.data.subarray(t));return{key:e.type,info:s,data:r}}const t=utf8ArrayToStr(e.data);return{key:e.type,info:"",data:t}}function toUint8(e,t=0,s=1/0){return view(e,t,s,Uint8Array)}function view(e,t,s,r){const i=unsafeGetArrayBuffer(e);let n=1;"BYTES_PER_ELEMENT"in r&&(n=r.BYTES_PER_ELEMENT);const a=isArrayBufferView(e)?e.byteOffset:0,o=(a+e.byteLength)/n,l=(a+t)/n,d=Math.floor(Math.max(0,Math.min(l,o)));return new r(i,d,Math.floor(Math.min(d+Math.max(s,0),o))-d)}function unsafeGetArrayBuffer(e){return e instanceof ArrayBuffer?e:e.buffer}function isArrayBufferView(e){return e&&e.buffer instanceof ArrayBuffer&&void 0!==e.byteLength&&void 0!==e.byteOffset}function toArrayBuffer(e){return e instanceof ArrayBuffer?e:0==e.byteOffset&&e.byteLength==e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}function base64encode(e){return btoa(String.fromCharCode(...e))}function roundToEven(e,t){if(e<0)return-roundToEven(-e,t);const s=Math.pow(10,t);if(Math.abs(e*s%1-.5)<Number.EPSILON){const t=Math.floor(e*s);return(t%2==0?t:t+1)/s}return Math.round(e*s)/s}function urlToRelativePath(e,t){const s=new URL(e),r=new URL(t);if(s.origin!==r.origin)return e;const i=s.pathname.split("/").slice(1),n=r.pathname.split("/").slice(1,-1);for(;i[0]===n[0];)i.shift(),n.shift();for(;n.length;)n.shift(),i.unshift("..");return i.join("/")}function uuid(){try{return crypto.randomUUID()}catch(e){try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){let t=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const s=(t+16*Math.random())%16|0;return t=Math.floor(t/16),("x"==e?s:3&s|8).toString(16)}))}}}function decodeId3ImageFrame(e){const t={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(e.size<2)return;if(3!==e.data[0])return void console.log("Ignore frame with unrecognized character encoding");const s=e.data.subarray(1).indexOf(0);if(-1===s)return;const r=utf8ArrayToStr(toUint8(e.data,1,s)),i=e.data[2+s],n=e.data.subarray(3+s).indexOf(0);if(-1===n)return;const a=utf8ArrayToStr(toUint8(e.data,3+s,n));let o;return o="--\x3e"===r?utf8ArrayToStr(toUint8(e.data,4+s+n)):toArrayBuffer(e.data.subarray(4+s+n)),t.mimeType=r,t.pictureType=i,t.description=a,t.data=o,t}function decodeId3Frame(e){return"PRIV"===e.type?decodeId3PrivFrame(e):"W"===e.type[0]?decodeId3UrlFrame(e):"APIC"===e.type?decodeId3ImageFrame(e):decodeId3TextFrame(e)}function getId3FrameData(e){const t=String.fromCharCode(e[0],e[1],e[2],e[3]),s=readId3Size(e,4);return{type:t,size:s,data:e.subarray(10,10+s)}}const HEADER_FOOTER_SIZE=10,FRAME_SIZE=10;function getId3Frames(e){let t=0;const s=[];for(;isId3Header(e,t);){const r=readId3Size(e,t+6);e[t+5]>>6&1&&(t+=HEADER_FOOTER_SIZE),t+=HEADER_FOOTER_SIZE;const i=t+r;for(;t+FRAME_SIZE<i;){const r=getId3FrameData(e.subarray(t)),i=decodeId3Frame(r);i&&s.push(i),t+=r.size+HEADER_FOOTER_SIZE}isId3Footer(e,t)&&(t+=HEADER_FOOTER_SIZE)}return s}function isId3TimestampFrame(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}function readId3Timestamp(e){if(8===e.data.byteLength){const t=new Uint8Array(e.data),s=1&t[3];let r=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return r/=45,s&&(r+=47721858.84),Math.round(r)}}function getId3Timestamp(e){const t=getId3Frames(e);for(let e=0;e<t.length;e++){const s=t[e];if(isId3TimestampFrame(s))return readId3Timestamp(s)}}let MetadataSchema=function(e){return e.audioId3="org.id3",e.dateRange="com.apple.quicktime.HLS",e.emsg="https://aomedia.org/emsg/ID3",e.misbklv="urn:misb:KLV:bin:1910.1",e}({});function dummyTrack(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class BaseAudioDemuxer{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,s,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,s){}demux(e,t){this.cachedData&&(e=appendUint8Array(this.cachedData,e),this.cachedData=null);let s,r=getId3Data(e,0),i=r?r.length:0;const n=this._audioTrack,a=this._id3Track,o=r?getId3Timestamp(r):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&isFiniteNumber(o))&&(this.basePTS=initPTSFn(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),r&&r.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:MetadataSchema.audioId3,duration:Number.POSITIVE_INFINITY});i<l;){if(this.canParse(e,i)){const t=this.appendFrame(n,e,i);t?(this.frameIndex++,this.lastPTS=t.sample.pts,i+=t.length,s=i):i=l}else canParseId3(e,i)?(r=getId3Data(e,i),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:MetadataSchema.audioId3,duration:Number.POSITIVE_INFINITY}),i+=r.length,s=i):i++;if(i===l&&s!==l){const t=sliceUint8(e,s);this.cachedData?this.cachedData=appendUint8Array(this.cachedData,t):this.cachedData=t}}return{audioTrack:n,videoTrack:dummyTrack(),id3Track:a,textTrack:dummyTrack()}}demuxSampleAes(e,t,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:dummyTrack(),id3Track:this._id3Track,textTrack:dummyTrack()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const initPTSFn=(e,t,s)=>{if(isFiniteNumber(e))return 90*e;return 9e4*t+(s?9e4*s.baseTime/s.timescale:0)};let chromeVersion$1=null;const BitratesMap=[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],SamplingRateMap=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],SamplesCoefficients=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],BytesInSlot=[0,1,1,4];function appendFrame$1(e,t,s,r,i){if(s+24>t.length)return;const n=parseHeader(t,s);if(n&&s+n.frameLength<=t.length){const a=r+i*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:t.subarray(s,s+n.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=n.channelCount,e.samplerate=n.sampleRate,e.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function parseHeader(e,t){const s=e[t+1]>>3&3,r=e[t+1]>>1&3,i=e[t+2]>>4&15,n=e[t+2]>>2&3;if(1!==s&&0!==i&&15!==i&&3!==n){const a=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*BitratesMap[14*(3===s?3-r:3===r?3:4)+i-1],d=SamplingRateMap[3*(3===s?0:2===s?1:2)+n],h=3===o?1:2,c=SamplesCoefficients[s][r],u=BytesInSlot[r],f=8*c*u,g=Math.floor(c*l/d+a)*u;if(null===chromeVersion$1){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);chromeVersion$1=e?parseInt(e[1]):0}return!!chromeVersion$1&&chromeVersion$1<=87&&2===r&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:d,channelCount:h,frameLength:g,samplesPerFrame:f}}}function isHeaderPattern(e,t){return 255===e[t]&&224==(224&e[t+1])&&0!=(6&e[t+1])}function isHeader(e,t){return t+1<e.length&&isHeaderPattern(e,t)}function canParse(e,t){return isHeaderPattern(e,t)&&4<=e.length-t}function probe(e,t){if(t+1<e.length&&isHeaderPattern(e,t)){const s=4,r=parseHeader(e,t);let i=s;null!=r&&r.frameLength&&(i=r.frameLength);const n=t+i;return n===e.length||isHeader(e,n)}return!1}class AACDemuxer extends BaseAudioDemuxer{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,s,r){super.resetInitSegment(e,t,s,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const s=getId3Data(e,0);let r=(null==s?void 0:s.length)||0;if(probe(e,r))return!1;for(let s=e.length;r<s;r++)if(probe$1(e,r))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return canParse$1(e,t)}appendFrame(e,t,s){initTrackConfig(e,this.observer,t,s,e.manifestCodec);const r=appendFrame$2(e,t,s,this.basePTS,this.frameIndex);if(r&&0===r.missing)return r}}const getAudioBSID=(e,t)=>{let s=0,r=5;t+=r;const i=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;r>0;){a[0]=e[t];const o=Math.min(r,8),l=8-o;n[0]=4278190080>>>24+l<<l,i[0]=(a[0]&n[0])>>l,s=s?s<<o|i[0]:i[0],t+=1,r-=o}return s};class AC3Demuxer extends BaseAudioDemuxer{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,r){super.resetInitSegment(e,t,s,r),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,s){const r=appendFrame(e,t,s,this.basePTS,this.frameIndex);if(-1!==r){return{sample:e.samples[e.samples.length-1],length:r,missing:0}}}static probe(e){if(!e)return!1;const t=getId3Data(e,0);if(!t)return!1;const s=t.length;return 11===e[s]&&119===e[s+1]&&void 0!==getId3Timestamp(t)&&getAudioBSID(e,s)<16}}function appendFrame(e,t,s,r,i){if(s+8>t.length)return-1;if(11!==t[s]||119!==t[s+1])return-1;const n=t[s+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&t[s+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+n];if(s+l>t.length)return-1;const d=t[s+6]>>5;let h=0;2===d?h+=2:(1&d&&1!==d&&(h+=2),4&d&&(h+=2));const c=(t[s+6]<<8|t[s+7])>>12-h&1,u=[2,1,2,3,3,4,4,5][d]+c,f=t[s+5]>>3,g=7&t[s+5],m=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|d<<3|c<<2|o>>4,o<<4&224]),p=r+i*(1536/a*9e4),E=t.subarray(s,s+l);return e.config=m,e.channelCount=u,e.samplerate=a,e.samples.push({unit:E,pts:p}),l}class MP3Demuxer extends BaseAudioDemuxer{resetInitSegment(e,t,s,r){super.resetInitSegment(e,t,s,r),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=getId3Data(e,0);let s=(null==t?void 0:t.length)||0;if(t&&11===e[s]&&119===e[s+1]&&void 0!==getId3Timestamp(t)&&getAudioBSID(e,s)<=16)return!1;for(let t=e.length;s<t;s++)if(probe(e,s))return logger.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return canParse(e,t)}appendFrame(e,t,s){if(null!==this.basePTS)return appendFrame$1(e,t,s,this.basePTS,this.frameIndex)}}const emsgSchemePattern=/\/emsg[-/]ID3/i;class MP4Demuxer{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,s,r){const i=this.videoTrack=dummyTrack("video",1),n=this.audioTrack=dummyTrack("audio",1),a=this.txtTrack=dummyTrack("text",1);if(this.id3Track=dummyTrack("id3",1),this.timeOffset=0,null==e||!e.byteLength)return;const o=parseInitSegment(e);if(o.video){const{id:e,timescale:t,codec:s}=o.video;i.id=e,i.timescale=a.timescale=t,i.codec=s}if(o.audio){const{id:e,timescale:t,codec:s}=o.audio;n.id=e,n.timescale=t,n.codec=s}a.id=RemuxerTrackIdConfig.text,i.sampleDuration=0,i.duration=n.duration=r}resetContiguity(){this.remainderData=null}static probe(e){return hasMoofData(e)}demux(e,t){this.timeOffset=t;let s=e;const r=this.videoTrack,i=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=appendUint8Array(this.remainderData,e));const t=segmentValidRange(s);this.remainderData=t.remainder,r.samples=t.valid||new Uint8Array}else r.samples=s;const n=this.extractID3Track(r,t);return i.samples=parseSamples(t,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,s=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const r=this.extractID3Track(t,this.timeOffset);return s.samples=parseSamples(e,t),{videoTrack:t,audioTrack:dummyTrack(),id3Track:r,textTrack:dummyTrack()}}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const r=findBox(e.samples,["emsg"]);r&&r.forEach((e=>{const r=parseEmsg(e);if(emsgSchemePattern.test(r.schemeIdUri)){const e=getEmsgStartTime(r,t);let i=4294967295===r.eventDuration?Number.POSITIVE_INFINITY:r.eventDuration/r.timeScale;i<=.001&&(i=Number.POSITIVE_INFINITY);const n=r.payload;s.samples.push({data:n,len:n.byteLength,dts:e,pts:e,type:MetadataSchema.emsg,duration:i})}else if(this.config.enableEmsgKLVMetadata&&r.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const e=getEmsgStartTime(r,t);s.samples.push({data:r.payload,len:r.payload.byteLength,dts:e,pts:e,type:MetadataSchema.misbklv,duration:Number.POSITIVE_INFINITY})}}))}return s}demuxSampleAes(e,t,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}}function getEmsgStartTime(e,t){return isFiniteNumber(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}class SampleAesDecrypter{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Decrypter(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,DecrypterAesMode.cbc)}decryptAacSample(e,t,s){const r=e[t].unit;if(r.length<=16)return;const i=r.subarray(16,r.length-r.length%16),n=i.buffer.slice(i.byteOffset,i.byteOffset+i.length);this.decryptBuffer(n).then((i=>{const n=new Uint8Array(i);r.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)}))}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length)return void s();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=16*Math.floor((e.length-48)/160)+16,s=new Int8Array(t);let r=0;for(let t=32;t<e.length-16;t+=160,r+=16)s.set(e.subarray(t,t+16),r);return s}getAvcDecryptedUnit(e,t){const s=new Uint8Array(t);let r=0;for(let t=32;t<e.length-16;t+=160,r+=16)e.set(s.subarray(r,r+16),t);return e}decryptAvcSample(e,t,s,r,i){const n=discardEPB(i.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then((a=>{i.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,r)}))}decryptAvcSamples(e,t,s,r){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length)return void r();const i=e[t].units;for(;!(s>=i.length);s++){const n=i[s];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(e,t,s,r,n),this.decrypter.isSync())))return}}}}class BaseVideoParser{constructor(){this.VideoSample=null}createVideoSample(e,t,s){return{key:e,frame:!1,pts:t,dts:s,units:[],length:0}}getLastNalUnit(e){var t;let s,r=this.VideoSample;if(r&&0!==r.units.length||(r=e[e.length-1]),null!=(t=r)&&t.units){const e=r.units;s=e[e.length-1]}return s}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){const s=t.samples,r=s.length;if(!r)return void t.dropped++;{const t=s[r-1];e.pts=t.pts,e.dts=t.dts}}t.samples.push(e)}}parseNALu(e,t,s){const r=t.byteLength;let i=e.naluState||0;const n=i,a=[];let o,l,d,h=0,c=-1,u=0;for(-1===i&&(c=0,u=this.getNALuType(t,0),i=0,h=1);h<r;)if(o=t[h++],i)if(1!==i)if(o)if(1===o){if(l=h-i-1,c>=0){const e={data:t.subarray(c,l),type:u};a.push(e)}else{const s=this.getLastNalUnit(e.samples);s&&(n&&h<=4-n&&s.state&&(s.data=s.data.subarray(0,s.data.byteLength-n)),l>0&&(s.data=appendUint8Array(s.data,t.subarray(0,l)),s.state=0))}h<r?(d=this.getNALuType(t,h),c=h,u=d,i=0):i=-1}else i=0;else i=3;else i=o?0:2;else i=o?0:1;if(c>=0&&i>=0){const e={data:t.subarray(c,r),type:u,state:i};a.push(e)}if(0===a.length){const s=this.getLastNalUnit(e.samples);s&&(s.data=appendUint8Array(s.data,t))}return e.naluState=i,a}}class ExpGolomb{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,s=e.byteLength-t,r=new Uint8Array(4),i=Math.min(4,t);if(0===i)throw new Error("no bytes available");r.set(e.subarray(s,s+i)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=8*i,this.bytesAvailable-=i}skipBits(e){let t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(t=(e-=this.bitsAvailable)>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const s=this.word>>>32-t;if(e>32&&logger.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return t=e-t,t>0&&this.bitsAvailable?s<<t|this.readBits(t):s}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(0!=(this.word&2147483648>>>e))return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class AvcVideoParser extends BaseVideoParser{parsePES(e,t,s,r){const i=this.parseNALu(e,s.data,r);let n,a=this.VideoSample,o=!1;s.data=null,a&&i.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),i.forEach((r=>{var i,l;switch(r.type){case 1:{let t=!1;n=!0;const i=r.data;if(o&&i.length>4){const e=this.readSliceType(i);2!==e&&4!==e&&7!==e&&9!==e||(t=!0)}var d;if(t)null!=(d=a)&&d.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.frame=!0,a.key=t;break}case 5:n=!0,null!=(i=a)&&i.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 6:n=!0,parseSEIMessageFromNALu(r.data,1,s.pts,t.samples);break;case 7:{var h,c;n=!0,o=!0;const t=r.data,s=this.readSPS(t);if(!e.sps||e.width!==s.width||e.height!==s.height||(null==(h=e.pixelRatio)?void 0:h[0])!==s.pixelRatio[0]||(null==(c=e.pixelRatio)?void 0:c[1])!==s.pixelRatio[1]){e.width=s.width,e.height=s.height,e.pixelRatio=s.pixelRatio,e.sps=[t];const r=t.subarray(1,4);let i="avc1.";for(let e=0;e<3;e++){let t=r[e].toString(16);t.length<2&&(t="0"+t),i+=t}e.codec=i}break}case 8:n=!0,e.pps=[r.data];break;case 9:n=!0,e.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:n=!0;break;default:n=!1}if(a&&n){a.units.push(r)}})),r&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return 31&e[t]}readSliceType(e){const t=new ExpGolomb(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s,r=8,i=8;for(let n=0;n<e;n++)0!==i&&(s=t.readEG(),i=(r+s+256)%256),r=0===i?r:i}readSPS(e){const t=new ExpGolomb(e);let s,r,i,n=0,a=0,o=0,l=0;const d=t.readUByte.bind(t),h=t.readBits.bind(t),c=t.readUEG.bind(t),u=t.readBoolean.bind(t),f=t.skipBits.bind(t),g=t.skipEG.bind(t),m=t.skipUEG.bind(t),p=this.skipScalingList.bind(this);d();const E=d();if(h(5),f(3),d(),m(),100===E||110===E||122===E||244===E||44===E||83===E||86===E||118===E||128===E){const e=c();if(3===e&&f(1),m(),m(),f(1),u())for(r=3!==e?8:12,i=0;i<r;i++)u()&&p(i<6?16:64,t)}m();const y=c();if(0===y)c();else if(1===y)for(f(1),g(),g(),s=c(),i=0;i<s;i++)g();m(),f(1);const v=c(),T=c(),S=h(1);0===S&&f(1),f(1),u()&&(n=c(),a=c(),o=c(),l=c());let A=[1,1];if(u()&&u()){switch(d()){case 1:A=[1,1];break;case 2:A=[12,11];break;case 3:A=[10,11];break;case 4:A=[16,11];break;case 5:A=[40,33];break;case 6:A=[24,11];break;case 7:A=[20,11];break;case 8:A=[32,11];break;case 9:A=[80,33];break;case 10:A=[18,11];break;case 11:A=[15,11];break;case 12:A=[64,33];break;case 13:A=[160,99];break;case 14:A=[4,3];break;case 15:A=[3,2];break;case 16:A=[2,1];break;case 255:A=[d()<<8|d(),d()<<8|d()]}}return{width:Math.ceil(16*(v+1)-2*n-2*a),height:(2-S)*(T+1)*16-(S?2:4)*(o+l),pixelRatio:A}}}class HevcVideoParser extends BaseVideoParser{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,s,r){const i=this.parseNALu(e,s.data,r);let n,a=this.VideoSample,o=!1;s.data=null,a&&i.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),i.forEach((r=>{var i,l;switch(r.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),a.frame=!0,n=!0;break;case 16:case 17:case 18:case 21:var d;if(n=!0,o)null!=(d=a)&&d.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:n=!0,null!=(i=a)&&i.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 39:n=!0,parseSEIMessageFromNALu(r.data,2,s.pts,t.samples);break;case 32:if(n=!0,!e.vps){const t=this.readVPS(r.data);e.params=_objectSpread2({},t),this.initVPS=r.data}e.vps=[r.data];break;case 33:if(n=!0,o=!0,"object"==typeof e.params){if(void 0===e.vps||e.vps[0]===this.initVPS||void 0===e.sps||this.matchSPS(e.sps[0],r.data)||(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const t=this.readSPS(r.data);e.width=t.width,e.height=t.height,e.pixelRatio=t.pixelRatio,e.codec=t.codecString,e.sps=[];for(const s in t.params)e.params[s]=t.params[s]}void 0!==e.vps&&e.vps[0]===this.initVPS&&e.sps.push(r.data)}a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0;break;case 34:if(n=!0,"object"==typeof e.params){if(!e.pps){e.pps=[];const t=this.readPPS(r.data);for(const s in t)e.params[s]=t[s]}void 0!==e.vps&&e.vps[0]===this.initVPS&&e.pps.push(r.data)}break;case 35:n=!0,e.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;default:n=!1}if(a&&n){a.units.push(r)}})),r&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return(126&e[t])>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let s=0;for(let r=0;r<e.byteLength;r++)r>=2&&3===e[r]&&0===e[r-1]&&0===e[r-2]||(t[s]=e[r],s++);return new Uint8Array(t.buffer,0,s)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new ExpGolomb(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);return{numTemporalLayers:t.readBits(3)+1,temporalIdNested:t.readBoolean()}}readSPS(e){const t=new ExpGolomb(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const s=t.readBits(3);t.readBoolean();const r=t.readBits(2),i=t.readBoolean(),n=t.readBits(5),a=t.readUByte(),o=t.readUByte(),l=t.readUByte(),d=t.readUByte(),h=t.readUByte(),c=t.readUByte(),u=t.readUByte(),f=t.readUByte(),g=t.readUByte(),m=t.readUByte(),p=t.readUByte(),E=[],y=[];for(let e=0;e<s;e++)E.push(t.readBoolean()),y.push(t.readBoolean());if(s>0)for(let e=s;e<8;e++)t.readBits(2);for(let e=0;e<s;e++)E[e]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),y[e]&&t.readUByte();t.readUEG();const v=t.readUEG();3==v&&t.skipBits(1);const T=t.readUEG(),S=t.readUEG(),A=t.readBoolean();let L=0,I=0,R=0,D=0;A&&(L+=t.readUEG(),I+=t.readUEG(),R+=t.readUEG(),D+=t.readUEG());const b=t.readUEG(),_=t.readUEG(),P=t.readUEG();for(let e=t.readBoolean()?0:s;e<=s;e++)t.skipUEG(),t.skipUEG(),t.skipUEG();t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.readBoolean()){if(t.readBoolean())for(let e=0;e<4;e++)for(let s=0;s<(3===e?2:6);s++){if(t.readBoolean()){const s=Math.min(64,1<<4+(e<<1));e>1&&t.readEG();for(let e=0;e<s;e++)t.readEG()}else t.readUEG()}}t.readBoolean(),t.readBoolean();t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const C=t.readUEG();let k=0;for(let e=0;e<C;e++){let s=!1;if(0!==e&&(s=t.readBoolean()),s){e===C&&t.readUEG(),t.readBoolean(),t.readUEG();let s=0;for(let e=0;e<=k;e++){const e=t.readBoolean();let r=!1;e||(r=t.readBoolean()),(e||r)&&s++}k=s}else{const e=t.readUEG(),s=t.readUEG();k=e+s;for(let s=0;s<e;s++)t.readUEG(),t.readBoolean();for(let e=0;e<s;e++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const e=t.readUEG();for(let s=0;s<e;s++){for(let e=0;e<P+4;e++)t.readBits(1);t.readBits(1)}}let M=0,w=1,x=1,O=!0,F=1,N=0;t.readBoolean(),t.readBoolean();let U=!1;if(t.readBoolean()){if(t.readBoolean()){const e=t.readUByte();e>0&&e<16?(w=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][e-1],x=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][e-1]):255===e&&(w=t.readBits(16),x=t.readBits(16))}t.readBoolean()&&t.readBoolean();if(t.readBoolean()){t.readBits(3),t.readBoolean();t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())}t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),U=t.readBoolean(),U&&(L+=t.readUEG(),I+=t.readUEG(),R+=t.readUEG(),D+=t.readUEG());if(t.readBoolean()){F=t.readBits(32),N=t.readBits(32);t.readBoolean()&&t.readUEG();if(t.readBoolean()){const e=t.readBoolean(),r=t.readBoolean();let i=!1;(e||r)&&(i=t.readBoolean(),i&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),i&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let n=0;n<=s;n++){O=t.readBoolean();let s=!1;O||t.readBoolean()?t.readEG():s=t.readBoolean();const n=s?1:t.readUEG()+1;if(e)for(let e=0;e<n;e++)t.readUEG(),t.readUEG(),i&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(r)for(let e=0;e<n;e++)t.readUEG(),t.readUEG(),i&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),M=t.readUEG())}let B=T,$=S;if(A||U){let e=1,t=1;1===v?e=t=2:2==v&&(e=2),B=T-e*I-e*L,$=S-t*D-t*R}const G=r?["A","B","C"][r]:"",H=a<<24|o<<16|l<<8|d;let K=0;for(let e=0;e<32;e++)K=(K|(H>>e&1)<<31-e)>>>0;let V=K.toString(16);1===n&&"2"===V&&(V="6");return{codecString:`hvc1.${G}${n}.${V}.${i?"H":"L"}${p}.B0`,params:{general_tier_flag:i,general_profile_idc:n,general_profile_space:r,general_profile_compatibility_flags:[a,o,l,d],general_constraint_indicator_flags:[h,c,u,f,g,m],general_level_idc:p,bit_depth:b+8,bit_depth_luma_minus8:b,bit_depth_chroma_minus8:_,min_spatial_segmentation_idc:M,chroma_format_idc:v,frame_rate:{fixed:O,fps:N/F}},width:B,height:$,pixelRatio:[w,x]}}readPPS(e){const t=new ExpGolomb(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2);t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const s=t.readBoolean(),r=t.readBoolean();let i=1;return r&&s?i=0:r?i=3:s&&(i=2),{parallelismType:i}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const PACKET_LENGTH=188;class TSDemuxer{constructor(e,t,s,r){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.logger=r,this.videoParser=null}static probe(e,t){const s=TSDemuxer.syncOffset(e);return s>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),-1!==s}static syncOffset(e){const t=e.length;let s=Math.min(940,t-188)+1,r=0;for(;r<s;){let i=!1,n=-1,a=0;for(let o=r;o<t;o+=188){if(71!==e[o]||t-o!=188&&71!==e[o+188]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(s=Math.min(n+18612,e.length-188)+1)),i||(i=0===parsePID(e,o)),i&&a>1&&(0===n&&a>2||o+188>s))return n}r++}return-1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:RemuxerTrackIdConfig[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}resetInitSegment(e,t,s,r){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=TSDemuxer.createTrack("video"),this._videoTrack.duration=r,this._audioTrack=TSDemuxer.createTrack("audio",r),this._id3Track=TSDemuxer.createTrack("id3"),this._txtTrack=TSDemuxer.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s=!1,r=!1){let i;s||(this.sampleAes=null);const n=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let d=n.pid,h=n.pesData,c=a.pid,u=o.pid,f=a.pesData,g=o.pesData,m=null,p=this.pmtParsed,E=this._pmtId,y=e.length;if(this.remainderData&&(y=(e=appendUint8Array(this.remainderData,e)).length,this.remainderData=null),y<188&&!r)return this.remainderData=e,{audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};const v=Math.max(0,TSDemuxer.syncOffset(e));y-=(y-v)%188,y<e.byteLength&&!r&&(this.remainderData=new Uint8Array(e.buffer,y,e.buffer.byteLength-y));let T=0;for(let t=v;t<y;t+=188)if(71===e[t]){const r=!!(64&e[t+1]),y=parsePID(e,t);let T;if((48&e[t+3])>>4>1){if(T=t+5+e[t+4],T===t+188)continue}else T=t+4;switch(y){case d:if(r){if(h&&(i=parsePES(h,this.logger))){if(null===this.videoParser)switch(n.segmentCodec){case"avc":this.videoParser=new AvcVideoParser;break;case"hevc":this.videoParser=new HevcVideoParser}null!==this.videoParser&&this.videoParser.parsePES(n,l,i,!1)}h={data:[],size:0}}h&&(h.data.push(e.subarray(T,t+188)),h.size+=t+188-T);break;case c:if(r){if(f&&(i=parsePES(f,this.logger)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,i);break;case"mp3":this.parseMPEGPES(a,i);break;case"ac3":this.parseAC3PES(a,i)}f={data:[],size:0}}f&&(f.data.push(e.subarray(T,t+188)),f.size+=t+188-T);break;case u:r&&(g&&(i=parsePES(g,this.logger))&&this.parseID3PES(o,i),g={data:[],size:0}),g&&(g.data.push(e.subarray(T,t+188)),g.size+=t+188-T);break;case 0:r&&(T+=e[T]+1),E=this._pmtId=parsePAT(e,T);break;case E:{r&&(T+=e[T]+1);const i=parsePMT(e,T,this.typeSupported,s,this.observer,this.logger);d=i.videoPid,d>0&&(n.pid=d,n.segmentCodec=i.segmentVideoCodec),c=i.audioPid,c>0&&(a.pid=c,a.segmentCodec=i.segmentAudioCodec),u=i.id3Pid,u>0&&(o.pid=u),null===m||p||(this.logger.warn(`MPEG-TS PMT found at ${t} after unknown PID '${m}'. Backtracking to sync byte @${v} to parse all TS packets.`),m=null,t=v-188),p=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=y}}else T++;T>0&&emitParsingError(this.observer,new Error(`Found ${T} TS packet/s that do not start with 0x47`),void 0,this.logger),n.pesData=h,a.pesData=f,o.pesData=g;const S={audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};return r&&this.extractRemainingSamples(S),S}flush(){const{remainderData:e}=this;let t;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:s,id3Track:r,textTrack:i}=e,n=s.pesData,a=t.pesData,o=r.pesData;let l;if(n&&(l=parsePES(n,this.logger))){if(null===this.videoParser)switch(s.segmentCodec){case"avc":this.videoParser=new AvcVideoParser;break;case"hevc":this.videoParser=new HevcVideoParser}null!==this.videoParser&&(this.videoParser.parsePES(s,i,l,!0),s.pesData=null)}else s.pesData=n;if(a&&(l=parsePES(a,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l)}t.pesData=null}else null!=a&&a.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=a;o&&(l=parsePES(o,this.logger))?(this.parseID3PES(r,l),r.pesData=null):r.pesData=o}demuxSampleAes(e,t,s){const r=this.demux(e,s,!0,!this.config.progressive),i=this.sampleAes=new SampleAesDecrypter(this.observer,this.config,t);return this.decrypt(r,i)}decrypt(e,t){return new Promise((s=>{const{audioTrack:r,videoTrack:i}=e;r.samples&&"aac"===r.segmentCodec?t.decryptAacSamples(r.samples,0,(()=>{i.samples?t.decryptAvcSamples(i.samples,0,0,(()=>{s(e)})):s(e)})):i.samples&&t.decryptAvcSamples(i.samples,0,0,(()=>{s(e)}))}))}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let s=0;const r=this.aacOverFlow;let i,n,a,o=t.data;if(r){this.aacOverFlow=null;const t=r.missing,i=r.sample.unit.byteLength;if(-1===t)o=appendUint8Array(r.sample.unit,o);else{const n=i-t;r.sample.unit.set(o.subarray(0,t),n),e.samples.push(r.sample),s=r.missing}}for(i=s,n=o.length;i<n-1&&!isHeader$1(o,i);i++);if(i!==s){let e;const t=i<n-1;if(e=t?`AAC PES did not start with ADTS header,offset:${i}`:"No ADTS header found in AAC PES",emitParsingError(this.observer,new Error(e),t,this.logger),!t)return}if(initTrackConfig(e,this.observer,o,i,this.audioCodec),void 0!==t.pts)a=t.pts;else{if(!r)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const t=getFrameDuration(e.samplerate);a=r.sample.pts+t}}let l,d=0;for(;i<n;){if(l=appendFrame$2(e,o,i,a,d),i+=l.length,l.missing){this.aacOverFlow=l;break}for(d++;i<n-1&&!isHeader$1(o,i);i++);}}parseMPEGPES(e,t){const s=t.data,r=s.length;let i=0,n=0;const a=t.pts;if(void 0!==a)for(;n<r;)if(isHeader(s,n)){const t=appendFrame$1(e,s,n,a,i);if(!t)break;n+=t.length,i++}else n++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(e,t){{const s=t.data,r=t.pts;if(void 0===r)return void this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");const i=s.length;let n,a=0,o=0;for(;o<i&&(n=appendFrame(e,s,o,r,a++))>0;)o+=n}}parseID3PES(e,t){if(void 0===t.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const s=_extends({},t,{type:this._videoTrack?MetadataSchema.emsg:MetadataSchema.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}}function parsePID(e,t){return((31&e[t+1])<<8)+e[t+2]}function parsePAT(e,t){return(31&e[t+10])<<8|e[t+11]}function parsePMT(e,t,s,r,i,n){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<o;){const o=parsePID(e,t),l=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!r){logEncryptedSamplesFoundInUnencryptedStream("ADTS AAC",n);break}case 15:-1===a.audioPid&&(a.audioPid=o);break;case 21:-1===a.id3Pid&&(a.id3Pid=o);break;case 219:if(!r){logEncryptedSamplesFoundInUnencryptedStream("H.264",n);break}case 27:-1===a.videoPid&&(a.videoPid=o,a.segmentVideoCodec="avc");break;case 3:case 4:s.mpeg||s.mp3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="mp3"):n.log("MPEG audio found, not supported in this browser");break;case 193:if(!r){logEncryptedSamplesFoundInUnencryptedStream("AC-3",n);break}case 129:s.ac3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===a.audioPid&&l>0){let r=t+5,i=l;for(;i>2;){if(106===e[r])!0!==s.ac3?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=o,a.segmentAudioCodec="ac3");const t=e[r+1]+2;r+=t,i-=t}}break;case 194:case 135:return emitParsingError(i,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:-1===a.videoPid&&(a.videoPid=o,a.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"))}t+=l+5}return a}function emitParsingError(e,t,s,r){r.warn(`parsing error: ${t.message}`),e.emit(Events.ERROR,Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,levelRetry:s,error:t,reason:t.message})}function logEncryptedSamplesFoundInUnencryptedStream(e,t){t.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function parsePES(e,t){let s,r,i,n,a,o=0;const l=e.data;if(!e||0===e.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=appendUint8Array(l[0],l[1]),l.splice(1,1);s=l[0];if(1===(s[0]<<16)+(s[1]<<8)+s[2]){if(r=(s[4]<<8)+s[5],r&&r>e.size-6)return null;const d=s[7];192&d&&(n=536870912*(14&s[9])+4194304*(255&s[10])+16384*(254&s[11])+128*(255&s[12])+(254&s[13])/2,64&d?(a=536870912*(14&s[14])+4194304*(255&s[15])+16384*(254&s[16])+128*(255&s[17])+(254&s[18])/2,n-a>54e5&&(t.warn(`${Math.round((n-a)/9e4)}s delta between PTS and DTS, align them`),n=a)):a=n),i=s[8];let h=i+9;if(e.size<=h)return null;e.size-=h;const c=new Uint8Array(e.size);for(let e=0,t=l.length;e<t;e++){s=l[e];let t=s.byteLength;if(h){if(h>t){h-=t;continue}s=s.subarray(h),t-=h,h=0}c.set(s,o),o+=t}return r&&(r-=i+3),{data:c,pts:n,dts:a,len:r}}return null}class AAC{static getSilentFrame(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}const UINT32_MAX=Math.pow(2,32)-1;class MP4{static init(){let e;for(e in MP4.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:[]},MP4.types)MP4.types.hasOwnProperty(e)&&(MP4.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),s=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);MP4.HDLR_TYPES={video:t,audio:s};const r=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),i=new Uint8Array([0,0,0,0,0,0,0,0]);MP4.STTS=MP4.STSC=MP4.STCO=i,MP4.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),MP4.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),MP4.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),MP4.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);MP4.FTYP=MP4.box(MP4.types.ftyp,n,o,n,a),MP4.DINF=MP4.box(MP4.types.dinf,MP4.box(MP4.types.dref,r))}static box(e,...t){let s=8,r=t.length;const i=r;for(;r--;)s+=t[r].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=255&s,n.set(e,4),r=0,s=8;r<i;r++)n.set(t[r],s),s+=t[r].byteLength;return n}static hdlr(e){return MP4.box(MP4.types.hdlr,MP4.HDLR_TYPES[e])}static mdat(e){return MP4.box(MP4.types.mdat,e)}static mdhd(e,t){t*=e;const s=Math.floor(t/(UINT32_MAX+1)),r=Math.floor(t%(UINT32_MAX+1));return MP4.box(MP4.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,s>>24,s>>16&255,s>>8&255,255&s,r>>24,r>>16&255,r>>8&255,255&r,85,196,0,0]))}static mdia(e){return MP4.box(MP4.types.mdia,MP4.mdhd(e.timescale,e.duration),MP4.hdlr(e.type),MP4.minf(e))}static mfhd(e){return MP4.box(MP4.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))}static minf(e){return"audio"===e.type?MP4.box(MP4.types.minf,MP4.box(MP4.types.smhd,MP4.SMHD),MP4.DINF,MP4.stbl(e)):MP4.box(MP4.types.minf,MP4.box(MP4.types.vmhd,MP4.VMHD),MP4.DINF,MP4.stbl(e))}static moof(e,t,s){return MP4.box(MP4.types.moof,MP4.mfhd(e),MP4.traf(s,t))}static moov(e){let t=e.length;const s=[];for(;t--;)s[t]=MP4.trak(e[t]);return MP4.box.apply(null,[MP4.types.moov,MP4.mvhd(e[0].timescale,e[0].duration)].concat(s).concat(MP4.mvex(e)))}static mvex(e){let t=e.length;const s=[];for(;t--;)s[t]=MP4.trex(e[t]);return MP4.box.apply(null,[MP4.types.mvex,...s])}static mvhd(e,t){t*=e;const s=Math.floor(t/(UINT32_MAX+1)),r=Math.floor(t%(UINT32_MAX+1)),i=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,s>>24,s>>16&255,s>>8&255,255&s,r>>24,r>>16&255,r>>8&255,255&r,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return MP4.box(MP4.types.mvhd,i)}static sdtp(e){const t=e.samples||[],s=new Uint8Array(4+t.length);let r,i;for(r=0;r<t.length;r++)i=t[r].flags,s[r+4]=i.dependsOn<<4|i.isDependedOn<<2|i.hasRedundancy;return MP4.box(MP4.types.sdtp,s)}static stbl(e){return MP4.box(MP4.types.stbl,MP4.stsd(e),MP4.box(MP4.types.stts,MP4.STTS),MP4.box(MP4.types.stsc,MP4.STSC),MP4.box(MP4.types.stsz,MP4.STSZ),MP4.box(MP4.types.stco,MP4.STCO))}static avc1(e){let t,s,r,i=[],n=[];for(t=0;t<e.sps.length;t++)s=e.sps[t],r=s.byteLength,i.push(r>>>8&255),i.push(255&r),i=i.concat(Array.prototype.slice.call(s));for(t=0;t<e.pps.length;t++)s=e.pps[t],r=s.byteLength,n.push(r>>>8&255),n.push(255&r),n=n.concat(Array.prototype.slice.call(s));const a=MP4.box(MP4.types.avcC,new Uint8Array([1,i[3],i[4],i[5],255,224|e.sps.length].concat(i).concat([e.pps.length]).concat(n))),o=e.width,l=e.height,d=e.pixelRatio[0],h=e.pixelRatio[1];return MP4.box(MP4.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,MP4.box(MP4.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),MP4.box(MP4.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,h>>24,h>>16&255,h>>8&255,255&h])))}static esds(e){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){const t=e.samplerate;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,255&t,0,0])}static mp4a(e){return MP4.box(MP4.types.mp4a,MP4.audioStsd(e),MP4.box(MP4.types.esds,MP4.esds(e)))}static mp3(e){return MP4.box(MP4.types[".mp3"],MP4.audioStsd(e))}static ac3(e){return MP4.box(MP4.types["ac-3"],MP4.audioStsd(e),MP4.box(MP4.types.dac3,e.config))}static stsd(e){return"audio"===e.type?"mp3"===e.segmentCodec&&"mp3"===e.codec?MP4.box(MP4.types.stsd,MP4.STSD,MP4.mp3(e)):"ac3"===e.segmentCodec?MP4.box(MP4.types.stsd,MP4.STSD,MP4.ac3(e)):MP4.box(MP4.types.stsd,MP4.STSD,MP4.mp4a(e)):"avc"===e.segmentCodec?MP4.box(MP4.types.stsd,MP4.STSD,MP4.avc1(e)):MP4.box(MP4.types.stsd,MP4.STSD,MP4.hvc1(e))}static tkhd(e){const t=e.id,s=e.duration*e.timescale,r=e.width,i=e.height,n=Math.floor(s/(UINT32_MAX+1)),a=Math.floor(s%(UINT32_MAX+1));return MP4.box(MP4.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,r>>8&255,255&r,0,0,i>>8&255,255&i,0,0]))}static traf(e,t){const s=MP4.sdtp(e),r=e.id,i=Math.floor(t/(UINT32_MAX+1)),n=Math.floor(t%(UINT32_MAX+1));return MP4.box(MP4.types.traf,MP4.box(MP4.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r])),MP4.box(MP4.types.tfdt,new Uint8Array([1,0,0,0,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n])),MP4.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,MP4.box(MP4.types.trak,MP4.tkhd(e),MP4.mdia(e))}static trex(e){const t=e.id;return MP4.box(MP4.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const s=e.samples||[],r=s.length,i=12+16*r,n=new Uint8Array(i);let a,o,l,d,h,c;for(t+=8+i,n.set(["video"===e.type?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,255&r,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0),a=0;a<r;a++)o=s[a],l=o.duration,d=o.size,h=o.flags,c=o.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,d>>>24&255,d>>>16&255,d>>>8&255,255&d,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,61440&h.degradPrio,15&h.degradPrio,c>>>24&255,c>>>16&255,c>>>8&255,255&c],12+16*a);return MP4.box(MP4.types.trun,n)}static initSegment(e){MP4.types||MP4.init();const t=MP4.moov(e);return appendUint8Array(MP4.FTYP,t)}static hvc1(e){const t=e.params,s=[e.vps,e.sps,e.pps],r=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),3|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),s.length]);let i=r.length;for(let e=0;e<s.length;e+=1){i+=3;for(let t=0;t<s[e].length;t+=1)i+=2+s[e][t].length}const n=new Uint8Array(i);n.set(r,0),i=r.length;const a=s.length-1;for(let e=0;e<s.length;e+=1){n.set(new Uint8Array([32+e|(e===a?128:0),0,s[e].length]),i),i+=3;for(let t=0;t<s[e].length;t+=1)n.set(new Uint8Array([s[e][t].length>>8,255&s[e][t].length]),i),i+=2,n.set(s[e][t],i),i+=s[e][t].length}const o=MP4.box(MP4.types.hvcC,n),l=e.width,d=e.height,h=e.pixelRatio[0],c=e.pixelRatio[1];return MP4.box(MP4.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,d>>8&255,255&d,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,MP4.box(MP4.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),MP4.box(MP4.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,c>>24,c>>16&255,c>>8&255,255&c])))}}MP4.types=void 0,MP4.HDLR_TYPES=void 0,MP4.STTS=void 0,MP4.STSC=void 0,MP4.STCO=void 0,MP4.STSZ=void 0,MP4.VMHD=void 0,MP4.SMHD=void 0,MP4.STSD=void 0,MP4.FTYP=void 0,MP4.DINF=void 0;const MPEG_TS_CLOCK_FREQ_HZ=9e4;function toTimescaleFromBase(e,t,s=1,r=!1){const i=e*t*s;return r?Math.round(i):i}function toTimescaleFromScale(e,t,s=1,r=!1){return toTimescaleFromBase(e,t,1/s,r)}function toMsFromMpegTsClock(e,t=!1){return toTimescaleFromBase(e,1e3,1/MPEG_TS_CLOCK_FREQ_HZ,t)}function toMpegTsClockFromTimescale(e,t=1){return toTimescaleFromBase(e,MPEG_TS_CLOCK_FREQ_HZ,1/t)}const MAX_SILENT_FRAME_DURATION=1e4,AAC_SAMPLES_PER_FRAME=1024,MPEG_AUDIO_SAMPLE_PER_FRAME=1152,AC3_SAMPLES_PER_FRAME=1536;let now,chromeVersion=null,safariWebkitVersion=null;class MP4Remuxer{constructor(e,t,s,r){if(this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.logger=r,this.ISGenerated=!1,null===chromeVersion){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);chromeVersion=e?parseInt(e[1]):0}if(null===safariWebkitVersion){const e=navigator.userAgent.match(/Safari\/(\d+)/i);safariWebkitVersion=e?parseInt(e[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){this.logger.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.logger.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.logger.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const s=e[0].pts,r=e.reduce(((e,r)=>{let i=r.pts,n=i-e;return n<-4294967296&&(t=!0,i=normalizePts(i,s),n=i-e),n>0?e:i}),s);return t&&this.logger.debug("PTS rollover detected"),r}remux(e,t,s,r,i,n,a,o){let l,d,h,c,u,f,g=i,m=i;const p=e.pid>-1,E=t.pid>-1,y=t.samples.length,v=e.samples.length>0,T=a&&y>0||y>1;if((!p||v)&&(!E||T)||this.ISGenerated||a){if(this.ISGenerated){var S,A,L,I;const e=this.videoTrackConfig;(e&&(t.width!==e.width||t.height!==e.height||(null==(S=t.pixelRatio)?void 0:S[0])!==(null==(A=e.pixelRatio)?void 0:A[0])||(null==(L=t.pixelRatio)?void 0:L[1])!==(null==(I=e.pixelRatio)?void 0:I[1]))||!e&&T||null===this.nextAudioPts&&v)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(e,t,i,n));const s=this.isVideoContiguous;let r,a=-1;if(T&&(a=findKeyframeIndex(t.samples),!s&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,a>0){this.logger.warn(`[mp4-remuxer]: Dropped ${a} out of ${y} video samples due to a missing keyframe`);const e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(a),t.dropped+=a,m+=(t.samples[0].pts-e)/t.inputTimeScale,r=m}else-1===a&&(this.logger.warn(`[mp4-remuxer]: No keyframe found out of ${y} video samples`),f=!1);if(this.ISGenerated){if(v&&T){const s=this.getVideoStartPts(t.samples),r=(normalizePts(e.samples[0].pts,s)-s)/t.inputTimeScale;g+=Math.max(0,r),m+=Math.max(0,-r)}if(v){if(e.samplerate||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),h=this.generateIS(e,t,i,n)),d=this.remuxAudio(e,g,this.isAudioContiguous,n,E||T||o===PlaylistLevelType.AUDIO?m:void 0),T){const r=d?d.endPTS-d.startPTS:0;t.inputTimeScale||(this.logger.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),h=this.generateIS(e,t,i,n)),l=this.remuxVideo(t,m,s,r)}}else T&&(l=this.remuxVideo(t,m,s,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=r)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(u=flushTextTrackMetadataCueSamples(s,i,this._initPTS,this._initDTS)),r.samples.length&&(c=flushTextTrackUserdataCueSamples(r,i,this._initPTS))),{audio:d,video:l,initSegment:h,independent:f,text:c,id3:u}}generateIS(e,t,s,r){const i=e.samples,n=t.samples,a=this.typeSupported,o={},l=this._initPTS;let d,h,c,u=!l||r,f="audio/mp4";if(u&&(d=h=1/0),e.config&&i.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}o.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&a.mpeg?new Uint8Array(0):MP4.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(c=e.inputTimeScale,l&&c===l.timescale?u=!1:d=h=i[0].pts-Math.round(c*s))}if(t.sps&&t.pps&&n.length){if(t.timescale=t.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:MP4.initSegment([t]),metadata:{width:t.width,height:t.height}},u)if(c=t.inputTimeScale,l&&c===l.timescale)u=!1;else{const e=this.getVideoStartPts(n),t=Math.round(c*s);h=Math.min(h,normalizePts(n[0].dts,e)-t),d=Math.min(d,e-t)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,u?(this._initPTS={baseTime:d,timescale:c},this._initDTS={baseTime:h,timescale:c}):d=c=void 0,{tracks:o,initPTS:d,timescale:c}}remuxVideo(e,t,s,r){const i=e.inputTimeScale,n=e.samples,a=[],o=n.length,l=this._initPTS;let d,h,c=this.nextAvcDts,u=8,f=this.videoSampleDuration,g=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,p=!1;if(!s||null===c){const e=t*i,r=n[0].pts-normalizePts(n[0].dts,n[0].pts);chromeVersion&&null!==c&&Math.abs(e-r-c)<15e3?s=!0:c=e-r}const E=l.baseTime*i/l.timescale;for(let e=0;e<o;e++){const t=n[e];t.pts=normalizePts(t.pts-E,c),t.dts=normalizePts(t.dts-E,c),t.dts<n[e>0?e-1:e].dts&&(p=!0)}p&&n.sort((function(e,t){const s=e.dts-t.dts,r=e.pts-t.pts;return s||r})),d=n[0].dts,h=n[n.length-1].dts;const y=h-d,v=y?Math.round(y/(o-1)):f||e.inputTimeScale/30;if(s){const s=d-c,r=s>v,i=s<-1;if((r||i)&&(r?this.logger.warn(`${(e.segmentCodec||"").toUpperCase()}: ${toMsFromMpegTsClock(s,!0)} ms (${s}dts) hole between fragments detected at ${t.toFixed(3)}`):this.logger.warn(`${(e.segmentCodec||"").toUpperCase()}: ${toMsFromMpegTsClock(-s,!0)} ms (${s}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!i||c>=n[0].pts||chromeVersion)){d=c;const e=n[0].pts-s;if(r)n[0].dts=d,n[0].pts=e;else{let t=!0;for(let r=0;r<n.length&&!(n[r].dts>e&&t);r++){const e=n[r].pts;if(n[r].dts-=s,n[r].pts-=s,r<n.length-1){const s=n[r+1].pts;t=s<=n[r].pts==s<=e}}}this.logger.log(`Video: Initial PTS/DTS adjusted: ${toMsFromMpegTsClock(e,!0)}/${toMsFromMpegTsClock(d,!0)}, delta: ${toMsFromMpegTsClock(s,!0)} ms`)}}d=Math.max(0,d);let T=0,S=0,A=d;for(let e=0;e<o;e++){const t=n[e],s=t.units,r=s.length;let i=0;for(let e=0;e<r;e++)i+=s[e].data.length;S+=i,T+=r,t.length=i,t.dts<A?(t.dts=A,A+=v/4|0||1):A=t.dts,g=Math.min(t.pts,g),m=Math.max(t.pts,m)}h=n[o-1].dts;const L=S+4*T+8;let I;try{I=new Uint8Array(L)}catch(e){return void this.observer.emit(Events.ERROR,Events.ERROR,{type:ErrorTypes.MUX_ERROR,details:ErrorDetails.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:L,reason:`fail allocating video mdat ${L}`})}const R=new DataView(I.buffer);R.setUint32(0,L),I.set(MP4.types.mdat,4);let D=!1,b=Number.POSITIVE_INFINITY,_=Number.POSITIVE_INFINITY,P=Number.NEGATIVE_INFINITY,C=Number.NEGATIVE_INFINITY;for(let e=0;e<o;e++){const t=n[e],s=t.units;let l,d=0;for(let e=0,t=s.length;e<t;e++){const t=s[e],r=t.data,i=t.data.byteLength;R.setUint32(u,i),u+=4,I.set(r,u),u+=i,d+=4+i}if(e<o-1)f=n[e+1].dts-t.dts,l=n[e+1].pts-t.pts;else{const s=this.config,a=e>0?t.dts-n[e-1].dts:v;if(l=e>0?t.pts-n[e-1].pts:v,s.stretchShortVideoTrack&&null!==this.nextAudioPts){const e=Math.floor(s.maxBufferHole*i),n=(r?g+r*i:this.nextAudioPts)-t.pts;n>e?(f=n-a,f<0?f=a:D=!0,this.logger.log(`[mp4-remuxer]: It is approximately ${n/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=a}else f=a}const h=Math.round(t.pts-t.dts);b=Math.min(b,f),P=Math.max(P,f),_=Math.min(_,l),C=Math.max(C,l),a.push(new Mp4Sample(t.key,f,d,h))}if(a.length)if(chromeVersion){if(chromeVersion<70){const e=a[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(safariWebkitVersion&&C-_<P-b&&v/P<.025&&0===a[0].cts){this.logger.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let e=d;for(let t=0,s=a.length;t<s;t++){const r=e+a[t].duration,i=e+a[t].cts;if(t<s-1){const e=r+a[t+1].cts;a[t].duration=e-i}else a[t].duration=t?a[t-1].duration:v;a[t].cts=0,e=r}}f=D||!f?v:f,this.nextAvcDts=c=h+f,this.videoSampleDuration=f,this.isVideoContiguous=!0;const k={data1:MP4.moof(e.sequenceNumber++,d,_extends({},e,{samples:a})),data2:I,startPTS:g/i,endPTS:(m+f)/i,startDTS:d/i,endDTS:c/i,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:e.dropped};return e.samples=[],e.dropped=0,k}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(e,t,s,r,i){const n=e.inputTimeScale,a=n/(e.samplerate?e.samplerate:n),o=this.getSamplesPerFrame(e),l=o*a,d=this._initPTS,h="mp3"===e.segmentCodec&&this.typeSupported.mpeg,c=[],u=void 0!==i;let f=e.samples,g=h?0:8,m=this.nextAudioPts||-1;const p=t*n,E=d.baseTime*n/d.timescale;if(this.isAudioContiguous=s=s||f.length&&m>0&&(r&&Math.abs(p-m)<9e3||Math.abs(normalizePts(f[0].pts-E,p)-m)<20*l),f.forEach((function(e){e.pts=normalizePts(e.pts-E,p)})),!s||m<0){if(f=f.filter((e=>e.pts>=0)),!f.length)return;m=0===i?0:r&&!u?Math.max(0,p):f[0].pts}if("aac"===e.segmentCodec){const t=this.config.maxAudioFramesDrift;for(let s=0,r=m;s<f.length;s++){const i=f[s],a=i.pts,o=a-r,d=Math.abs(1e3*o/n);if(o<=-t*l&&u)0===s&&(this.logger.warn(`Audio frame @ ${(a/n).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*o/n)} ms.`),this.nextAudioPts=m=r=a);else if(o>=t*l&&d<1e4&&u){let t=Math.round(o/l);r=a-t*l,r<0&&(t--,r+=l),0===s&&(this.nextAudioPts=m=r),this.logger.warn(`[mp4-remuxer]: Injecting ${t} audio frame @ ${(r/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n<t;n++){const t=Math.max(r,0);let n=AAC.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);n||(this.logger.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),n=i.unit.subarray()),f.splice(s,0,{unit:n,pts:t}),r+=l,s++}}i.pts=r,r+=l}}let y,v=null,T=null,S=0,A=f.length;for(;A--;)S+=f[A].unit.byteLength;for(let t=0,r=f.length;t<r;t++){const r=f[t],i=r.unit;let n=r.pts;if(null!==T){c[t-1].duration=Math.round((n-T)/a)}else{if(s&&"aac"===e.segmentCodec&&(n=m),v=n,!(S>0))return;S+=g;try{y=new Uint8Array(S)}catch(e){return void this.observer.emit(Events.ERROR,Events.ERROR,{type:ErrorTypes.MUX_ERROR,details:ErrorDetails.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:S,reason:`fail allocating audio mdat ${S}`})}if(!h){new DataView(y.buffer).setUint32(0,S),y.set(MP4.types.mdat,4)}}y.set(i,g);const l=i.byteLength;g+=l,c.push(new Mp4Sample(!0,o,l,0)),T=n}const L=c.length;if(!L)return;const I=c[c.length-1];this.nextAudioPts=m=T+a*I.duration;const R=h?new Uint8Array(0):MP4.moof(e.sequenceNumber++,v/a,_extends({},e,{samples:c}));e.samples=[];const D=v/n,b=m/n,_={data1:R,data2:y,startPTS:D,endPTS:b,startDTS:D,endDTS:b,type:"audio",hasAudio:!0,hasVideo:!1,nb:L};return this.isAudioContiguous=!0,_}}function normalizePts(e,t){let s;if(null===t)return e;for(s=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=s;return e}function findKeyframeIndex(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return-1}function flushTextTrackMetadataCueSamples(e,t,s,r){const i=e.samples.length;if(!i)return;const n=e.inputTimeScale;for(let a=0;a<i;a++){const i=e.samples[a];i.pts=normalizePts(i.pts-s.baseTime*n/s.timescale,t*n)/n,i.dts=normalizePts(i.dts-r.baseTime*n/r.timescale,t*n)/n}const a=e.samples;return e.samples=[],{samples:a}}function flushTextTrackUserdataCueSamples(e,t,s){const r=e.samples.length;if(!r)return;const i=e.inputTimeScale;for(let n=0;n<r;n++){const r=e.samples[n];r.pts=normalizePts(r.pts-s.baseTime*i/s.timescale,t*i)/i}e.samples.sort(((e,t)=>e.pts-t.pts));const n=e.samples;return e.samples=[],{samples:n}}class Mp4Sample{constructor(e,t,s,r){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=t,this.size=s,this.cts=r,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}class PassThroughRemuxer{constructor(e,t,s,r){this.logger=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.logger=r}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,t,s,r){this.audioCodec=t,this.videoCodec=s,this.generateInitSegment(patchEncyptionData(e,r)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:s}=this;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const r=this.initData=parseInitSegment(e);r.audio&&(t=getParsedTrackCodec(r.audio,ElementaryStreamTypes.AUDIO)),r.video&&(s=getParsedTrackCodec(r.video,ElementaryStreamTypes.VIDEO));const i={};r.audio&&r.video?i.audiovideo={container:"video/mp4",codec:t+","+s,initSegment:e,id:"main"}:r.audio?i.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:r.video?i.video={container:"video/mp4",codec:s,initSegment:e,id:"main"}:this.logger.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=i}remux(e,t,s,r,i,n){var a,o;let{initPTS:l,lastEndTime:d}=this;const h={audio:void 0,video:void 0,text:r,id3:s,initSegment:void 0};isFiniteNumber(d)||(d=this.lastEndTime=i||0);const c=t.samples;if(null==c||!c.length)return h;const u={initPTS:void 0,timescale:1};let f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(c),f=this.initData),null==(o=f)||!o.length)return this.logger.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),h;this.emitInitSegment&&(u.tracks=this.initTracks,this.emitInitSegment=!1);const g=getDuration(c,f),m=getStartDTS(f,c),p=null===m?i:m;(isInvalidInitPts(l,p,i,g)||u.timescale!==l.timescale&&n)&&(u.initPTS=p-i,l&&1===l.timescale&&this.logger.warn(`Adjusting initPTS @${i} from ${l.baseTime/l.timescale} to ${u.initPTS}`),this.initPTS=l={baseTime:u.initPTS,timescale:1});const E=e?p-l.baseTime/l.timescale:d,y=E+g;offsetStartDTS(f,c,l.baseTime/l.timescale),g>0?this.lastEndTime=y:(this.logger.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const v=!!f.audio,T=!!f.video;let S="";v&&(S+="audio"),T&&(S+="video");const A={data1:c,startPTS:E,startDTS:E,endPTS:y,endDTS:y,type:S,hasAudio:v,hasVideo:T,nb:1,dropped:0};return h.audio="audio"===A.type?A:void 0,h.video="audio"!==A.type?A:void 0,h.initSegment=u,h.id3=flushTextTrackMetadataCueSamples(s,i,l,l),r.samples.length&&(h.text=flushTextTrackUserdataCueSamples(r,i,l)),h}}function isInvalidInitPts(e,t,s,r){if(null===e)return!0;const i=Math.max(r,1),n=t-e.baseTime/e.timescale;return Math.abs(n-s)>i}function getParsedTrackCodec(e,t){const s=null==e?void 0:e.codec;if(s&&s.length>4)return s;if(t===ElementaryStreamTypes.AUDIO){if("ec-3"===s||"ac-3"===s||"alac"===s)return s;if("fLaC"===s||"Opus"===s){return getCodecCompatibleName(s,!1)}return logger.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"}return logger.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1"}try{now=self.performance.now.bind(self.performance)}catch(e){now=Date.now}const muxConfig=[{demux:MP4Demuxer,remux:PassThroughRemuxer},{demux:TSDemuxer,remux:MP4Remuxer},{demux:AACDemuxer,remux:MP4Remuxer},{demux:MP3Demuxer,remux:MP4Remuxer}];muxConfig.splice(2,0,{demux:AC3Demuxer,remux:MP4Remuxer});class Transmuxer{constructor(e,t,s,r,i,n){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=s,this.id=i,this.logger=n}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,r){const i=s.transmuxing;i.executeStart=now();let n=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:o}=this;r&&(this.currentTransmuxState=r);const{contiguous:l,discontinuity:d,trackSwitch:h,accurateTimeOffset:c,timeOffset:u,initSegmentChange:f}=r||a,{audioCodec:g,videoCodec:m,defaultInitPts:p,duration:E,initSegmentData:y}=o,v=getEncryptionType(n,t);if(v&&isFullSegmentEncryption(v.method)){const e=this.getDecrypter(),t=getAesModeFromFullSegmentMethod(v.method);if(!e.isSync())return this.asyncResult=!0,this.decryptionPromise=e.webCryptoDecrypt(n,v.key.buffer,v.iv.buffer,t).then((e=>{const t=this.push(e,null,s);return this.decryptionPromise=null,t})),this.decryptionPromise;{let r=e.softwareDecrypt(n,v.key.buffer,v.iv.buffer,t);if(s.part>-1){const t=e.flush();r=t?t.buffer:t}if(!r)return i.executeEnd=now(),emptyResult(s);n=new Uint8Array(r)}}const T=this.needsProbing(d,h);if(T){const e=this.configureTransmuxer(n);if(e)return this.logger.warn(`[transmuxer] ${e.message}`),this.observer.emit(Events.ERROR,Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),i.executeEnd=now(),emptyResult(s)}(d||h||f||T)&&this.resetInitSegment(y,g,m,E,t),(d||f||T)&&this.resetInitialTimestamp(p),l||this.resetContiguity();const S=this.transmux(n,v,u,c,s);this.asyncResult=isPromise(S);const A=this.currentTransmuxState;return A.contiguous=!0,A.discontinuity=!1,A.trackSwitch=!1,i.executeEnd=now(),S}flush(e){const t=e.transmuxing;t.executeStart=now();const{decrypter:s,currentTransmuxState:r,decryptionPromise:i}=this;if(i)return this.asyncResult=!0,i.then((()=>this.flush(e)));const n=[],{timeOffset:a}=r;if(s){const t=s.flush();t&&n.push(this.push(t.buffer,null,e))}const{demuxer:o,remuxer:l}=this;if(!o||!l){t.executeEnd=now();const s=[emptyResult(e)];return this.asyncResult?Promise.resolve(s):s}const d=o.flush(a);return isPromise(d)?(this.asyncResult=!0,d.then((t=>(this.flushRemux(n,t,e),n)))):(this.flushRemux(n,d,e),this.asyncResult?Promise.resolve(n):n)}flushRemux(e,t,s){const{audioTrack:r,videoTrack:i,id3Track:n,textTrack:a}=t,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===PlaylistLevelType.MAIN?"level":"track"} ${s.level}`);const d=this.remuxer.remux(r,i,n,a,l,o,!0,this.id);e.push({remuxResult:d,chunkMeta:s}),s.transmuxing.executeEnd=now()}resetInitialTimestamp(e){const{demuxer:t,remuxer:s}=this;t&&s&&(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,r,i){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(e,t,s,r),a.resetInitSegment(e,t,s,i))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,s,r,i){let n;return n=t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,s,r,i):this.transmuxUnencrypted(e,s,r,i),n}transmuxUnencrypted(e,t,s,r){const{audioTrack:i,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(i,n,a,o,t,s,!1,this.id),chunkMeta:r}}transmuxSampleAes(e,t,s,r,i){return this.demuxer.demuxSampleAes(e,t,s).then((e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,s,r,!1,this.id),chunkMeta:i})))}configureTransmuxer(e){const{config:t,observer:s,typeSupported:r}=this;let i;for(let t=0,s=muxConfig.length;t<s;t++){var n;if(null!=(n=muxConfig[t].demux)&&n.probe(e,this.logger)){i=muxConfig[t];break}}if(!i)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=i.remux,d=i.demux;o&&o instanceof l||(this.remuxer=new l(s,t,r,this.logger)),a&&a instanceof d||(this.demuxer=new d(s,t,r,this.logger),this.probe=d.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Decrypter(this.config)),e}}function getEncryptionType(e,t){let s=null;return e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(s=t),s}const emptyResult=e=>({remuxResult:{},chunkMeta:e});function isPromise(e){return"then"in e&&e.then instanceof Function}class TransmuxConfig{constructor(e,t,s,r,i){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=s,this.duration=r,this.defaultInitPts=i||null}}class TransmuxState{constructor(e,t,s,r,i,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=s,this.trackSwitch=r,this.timeOffset=i,this.initSegmentChange=n}}let transmuxerInstanceCount=0;class TransmuxerInterface{constructor(e,t,s,r){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=transmuxerInstanceCount++,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=e=>{const t=e.data,s=this.hls;if(s&&null!=t&&t.event&&t.instanceNo===this.instanceNo)switch(t.event){case"init":{var r;const e=null==(r=this.workerContext)?void 0:r.objectURL;e&&self.URL.revokeObjectURL(e);break}case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":s.logger[t.data.logType]&&s.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.part=this.part,t.data.id=this.id,s.trigger(t.event,t.data)}},this.onWorkerError=e=>{if(!this.hls)return;const t=new Error(`${e.message} (${e.filename}:${e.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})};const i=e.config;this.hls=e,this.id=t,this.useWorker=!!i.enableWorker,this.onTransmuxComplete=s,this.onFlush=r;const n=(e,t)=>{(t=t||{}).frag=this.frag||void 0,e===Events.ERROR&&(t.parent=this.id,t.part=this.part,this.error=t.error),this.hls.trigger(e,t)};this.observer=new EventEmitter,this.observer.on(Events.FRAG_DECRYPTED,n),this.observer.on(Events.ERROR,n);const a=getM2TSSupportedAudioTypes(i.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const s=this.hls.logger;if(i.workerPath||hasUMDWorker()){try{i.workerPath?(s.log(`loading Web Worker ${i.workerPath} for "${t}"`),this.workerContext=loadWorker(i.workerPath)):(s.log(`injecting Web Worker for "${t}"`),this.workerContext=injectWorker());const{worker:e}=this.workerContext;e.addEventListener("message",this.onWorkerMessage),e.addEventListener("error",this.onWorkerError),e.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:t,config:JSON.stringify(i)})}catch(r){s.warn(`Error setting up "${t}" Web Worker, fallback to inline`,r),this.terminateWorker(),this.error=null,this.transmuxer=new Transmuxer(this.observer,a,i,"",t,e.logger)}return}}this.transmuxer=new Transmuxer(this.observer,a,i,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=transmuxerInstanceCount++;const t=this.hls.config,s=getM2TSSupportedAudioTypes(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:JSON.stringify(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),removeWorkerFromStore(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,s,r,i,n,a,o,l,d){var h,c;l.transmuxing.start=self.performance.now();const{instanceNo:u,transmuxer:f}=this,g=n?n.start:i.start,m=i.decryptdata,p=this.frag,E=!(p&&i.cc===p.cc),y=!(p&&l.level===p.level),v=p?l.sn-p.sn:-1,T=this.part?l.part-this.part.index:-1,S=0===v&&l.id>1&&l.id===(null==p?void 0:p.stats.chunkCount),A=!y&&(1===v||0===v&&(1===T||S&&T<=0)),L=self.performance.now();(y||v||0===i.stats.parsing.start)&&(i.stats.parsing.start=L),!n||!T&&A||(n.stats.parsing.start=L);const I=!(p&&(null==(h=i.initSegment)?void 0:h.url)===(null==(c=p.initSegment)?void 0:c.url)),R=new TransmuxState(E,A,o,y,g,I);if(!A||E||I){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${i.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===PlaylistLevelType.MAIN?"level":"track"}: ${l.level} id: ${l.id}\n discontinuity: ${E}\n trackSwitch: ${y}\n contiguous: ${A}\n accurateTimeOffset: ${o}\n timeOffset: ${g}\n initSegmentChange: ${I}`);const e=new TransmuxConfig(s,r,t,a,d);this.configureTransmuxer(e)}if(this.frag=i,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:u,cmd:"demux",data:e,decryptdata:m,chunkMeta:l,state:R},e instanceof ArrayBuffer?[e]:[]);else if(f){const t=f.push(e,m,l,R);isPromise(t)?t.then((e=>{this.handleTransmuxComplete(e)})).catch((e=>{this.transmuxerError(e,l,"transmuxer-interface push error")})):this.handleTransmuxComplete(t)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(s){const t=s.flush(e);isPromise(t)?t.then((t=>{this.handleFlushResult(t,e)})).catch((t=>{this.transmuxerError(t,e,"transmuxer-interface flush error")})):this.handleFlushResult(t,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach((e=>{this.handleTransmuxComplete(e)})),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):s&&s.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}function subtitleOptionsIdentical(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s++)if(!mediaAttributesIdentical(e[s].attrs,t[s].attrs))return!1;return!0}function mediaAttributesIdentical(e,t,s){const r=e["STABLE-RENDITION-ID"];return r&&!s?r===t["STABLE-RENDITION-ID"]:!(s||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some((s=>e[s]!==t[s]))}function subtitleTrackMatchesTextTrack(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||"").toLowerCase())}const TICK_INTERVAL$2=100;class AudioStreamController extends BaseStreamController{constructor(e,t,s){super(e,t,s,"audio-stream-controller",PlaylistLevelType.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Events.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Events.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(Events.BUFFER_RESET,this.onBufferReset,this),e.on(Events.BUFFER_CREATED,this.onBufferCreated,this),e.on(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Events.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Events.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Events.FRAG_LOADING,this.onFragLoading,this),e.on(Events.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Events.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Events.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(Events.BUFFER_RESET,this.onBufferReset,this),e.off(Events.BUFFER_CREATED,this.onBufferCreated,this),e.off(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Events.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Events.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Events.FRAG_LOADING,this.onFragLoading,this),e.off(Events.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:s,initPTS:r,timescale:i}){if(s===PlaylistLevelType.MAIN){const e=t.cc,s=this.fragCurrent;if(this.initPTS[e]={baseTime:r,timescale:i},this.log(`InitPTS for cc: ${e} found from main: ${r}/${i}`),this.mainAnchor=t,this.state===State.WAITING_INIT_PTS){const s=this.waitingData;(!s&&!this.loadingParts||s&&s.frag.cc!==e)&&(this.nextLoadPosition=this.findSyncFrag(t).start),this.tick()}else!this.hls.hasEnoughToStart&&s&&s.cc!==e?(this.startFragRequested=!1,this.nextLoadPosition=this.findSyncFrag(t).start,s.abortRequests(),this.resetLoadingState()):this.state===State.IDLE&&this.tick()}}findSyncFrag(e){const t=this.getLevelDetails(),s=e.cc;return findNearestWithCC(t,s,e)||t&&findFragWithCC(t.fragments,s)||e}startLoad(e){if(!this.levels)return this.startPosition=e,void(this.state=State.STOPPED);const t=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),t>0&&-1===e?(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t,this.state=State.IDLE):this.state=State.WAITING_TRACK,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}doTick(){switch(this.state){case State.IDLE:this.doTickIdle();break;case State.WAITING_TRACK:{const{levels:e,trackId:t}=this,s=null==e?void 0:e[t],r=null==s?void 0:s.details;if(r&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(r))break;this.state=State.WAITING_INIT_PTS}break}case State.FRAG_LOADING_WAITING_RETRY:{var e;const t=performance.now(),s=this.retryDate;if(!s||t>=s||null!=(e=this.media)&&e.seeking){const{levels:e,trackId:t}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((null==e?void 0:e[t])||null),this.state=State.IDLE}break}case State.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:s,cache:r,complete:i}=e,n=this.mainAnchor;if(void 0!==this.initPTS[t.cc]){this.waitingData=null,this.state=State.FRAG_LOADING;const e={frag:t,part:s,payload:r.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(e),i&&super._handleFragmentLoadComplete(e)}else n&&n.cc!==e.frag.cc&&(this.log(`Waiting fragment cc (${t.cc}) cancelled because video is at cc ${n.cc}`),this.nextLoadPosition=this.findSyncFrag(n).start,this.clearWaitingFragment())}else this.state=State.IDLE}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.state!==State.STOPPED&&(this.state=State.IDLE))}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:e}=this;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:s,media:r,trackId:i}=this,n=t.config;if(!this.buffering||!r&&(this.startFragRequested||!n.startFragPrefetch)||null==s||!s[i])return;const a=s[i],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o))return this.state=State.WAITING_TRACK,void(this.startFragRequested=!1);const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,ElementaryStreamTypes.AUDIO,PlaylistLevelType.AUDIO));const d=this.getFwdBufferInfo(l,PlaylistLevelType.AUDIO);if(null===d)return;const{bufferedTrack:h,switchingTrack:c}=this;if(!c&&this._streamEnded(d,o))return t.trigger(Events.BUFFER_EOS,{type:"audio"}),void(this.state=State.ENDED);const u=d.len,f=t.maxBufferLength,g=o.fragments,m=g[0].start,p=this.getLoadPosition();let E=this.flushing?p:d.end;if(c&&r){const e=p;h&&!mediaAttributesIdentical(c.attrs,h.attrs)&&(E=e),o.PTSKnown&&e<m&&(d.end>m||d.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),r.currentTime=m+.05)}if(u>=f&&!c&&E<g[g.length-1].start)return;let y=this.getNextFragment(E,o);if(y&&this.isLoopLoading(y,E)&&(y=this.getNextFragmentLoopLoading(y,o,d,PlaylistLevelType.MAIN,f)),!y)return void(this.bufferFlushed=!0);const v=null==(e=this.mainFragLoading)?void 0:e.frag;if(!this.audioOnly&&this.startFragRequested&&v&&isMediaFragment(v)&&isMediaFragment(y)&&!y.endList&&(!o.live||!this.loadingParts&&E<this.hls.liveSyncPosition)){let e=v;if(y.start>e.end){const t=this.fragmentTracker.getFragAtPos(E,PlaylistLevelType.MAIN);t&&t.end>v.end&&(e=t,this.mainFragLoading={frag:t,targetBufferTime:null})}if(y.start>e.end)return}this.loadFragment(y,a,E)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map((e=>new Level(e)))}onAudioTrackSwitching(e,t){const s=!!t.url;this.trackId=t.id;const{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),s?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==State.STOPPED&&(this.setInterval(100),this.state=State.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.hls.trigger(Events.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(e,t){var s;const{levels:r}=this,{details:i,id:n}=t,a=this.mainDetails;if(!a||a.expired||i.endCC>a.endCC)return this.cachedTrackLoadedData=t,void(this.state!==State.STOPPED&&(this.state=State.WAITING_TRACK));if(!r)return void this.warn(`Audio tracks were reset while loading level ${n}`);this.log(`Audio track ${n} loaded [${i.startSN},${i.endSN}]${i.lastPartSn?`[part-${i.lastPartSn}-${i.lastPartIndex}]`:""},duration:${i.totalduration}`);const o=r[n];let l=0;if(i.live||null!=(s=o.details)&&s.live){if(this.checkLiveUpdate(i),i.deltaUpdateFailed)return;var d;if(o.details)l=this.alignPlaylists(i,o.details,null==(d=this.levelLastLoaded)?void 0:d.details);i.alignedSliding||(alignDiscontinuities(i,a),i.alignedSliding||alignMediaPlaylistByPDT(i,a),l=i.fragmentStart)}o.details=i,this.levelLastLoaded=o,this.startFragRequested||this.setStartPosition(a,l),this.hls.trigger(Events.AUDIO_TRACK_UPDATED,{details:i,id:n,groupId:t.groupId}),this.state!==State.WAITING_TRACK||this.waitForCdnTuneIn(i)||(this.state=State.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:r,payload:i}=e,{config:n,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const d=l.details;if(!d)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(s.start);const h=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let c=this.transmuxer;c||(c=this.transmuxer=new TransmuxerInterface(this.hls,PlaylistLevelType.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const u=this.initPTS[s.cc],f=null==(t=s.initSegment)?void 0:t.data;if(void 0!==u){const e=!1,t=r?r.index:-1,n=-1!==t,a=new ChunkMetadata(s.level,s.sn,s.stats.chunkCount,i.byteLength,t,n);c.push(i,f,h,"",s,r,d.totalduration,e,a,u)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${d.startSN} ,${d.endSN}],track ${a}`);const{cache:e}=this.waitingData=this.waitingData||{frag:s,part:r,cache:new ChunkCache,complete:!1};e.push(new Uint8Array(i)),this.state!==State.STOPPED&&(this.state=State.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===PlaylistLevelType.MAIN&&isMediaFragment(t.frag)&&(this.mainFragLoading=t,this.state===State.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:s,part:r}=t;if(s.type===PlaylistLevelType.AUDIO)if(this.fragContextChanged(s))this.warn(`Fragment ${s.sn}${r?" p: "+r.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if(isMediaFragment(s)){this.fragPrevious=s;const e=this.switchingTrack;e&&(this.bufferedTrack=e,this.switchingTrack=null,this.hls.trigger(Events.AUDIO_TRACK_SWITCHED,_objectSpread2({},e)))}this.fragBufferedComplete(s,r),this.media&&this.tick()}else this.audioOnly||s.type!==PlaylistLevelType.MAIN||s.elementaryStreams.video||s.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}onError(e,t){var s;if(t.fatal)this.state=State.ERROR;else switch(t.details){case ErrorDetails.FRAG_GAP:case ErrorDetails.FRAG_PARSING_ERROR:case ErrorDetails.FRAG_DECRYPT_ERROR:case ErrorDetails.FRAG_LOAD_ERROR:case ErrorDetails.FRAG_LOAD_TIMEOUT:case ErrorDetails.KEY_LOAD_ERROR:case ErrorDetails.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(PlaylistLevelType.AUDIO,t);break;case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:case ErrorDetails.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==State.WAITING_TRACK||(null==(s=t.context)?void 0:s.type)!==PlaylistContextType.AUDIO_TRACK||(this.state=State.IDLE);break;case ErrorDetails.BUFFER_APPEND_ERROR:case ErrorDetails.BUFFER_FULL_ERROR:if(!t.parent||"audio"!==t.parent)return;if(t.details===ErrorDetails.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case ErrorDetails.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushing(e,{type:t}){t!==ElementaryStreamTypes.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==ElementaryStreamTypes.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===State.ENDED&&(this.state=State.IDLE);const e=this.mediaBuffer||this.media;e&&(this.afterBufferFlushed(e,t,PlaylistLevelType.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const s="audio",{hls:r}=this,{remuxResult:i,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:d}=a,{details:h}=d,{audio:c,text:u,id3:f,initSegment:g}=i;if(!this.fragContextChanged(o)&&h){if(this.state=State.PARSING,this.switchingTrack&&c&&this.completeAudioSwitch(this.switchingTrack),null!=g&&g.tracks){const e=o.initSegment||o;this._bufferInitSegment(d,g.tracks,e,n),r.trigger(Events.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:s,tracks:g.tracks})}if(c){const{startPTS:e,endPTS:t,startDTS:s,endDTS:r}=c;l&&(l.elementaryStreams[ElementaryStreamTypes.AUDIO]={startPTS:e,endPTS:t,startDTS:s,endDTS:r}),o.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO,e,t,s,r),this.bufferFragmentData(c,o,l,n)}if(null!=f&&null!=(t=f.samples)&&t.length){const e=_extends({id:s,frag:o,details:h},f);r.trigger(Events.FRAG_PARSING_METADATA,e)}if(u){const e=_extends({id:s,frag:o,details:h},u);r.trigger(Events.FRAG_PARSING_USERDATA,e)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(e,t,s,r){if(this.state!==State.PARSING)return;if(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio)return;const i=t.audio;i.id="audio";const n=e.audioCodec;this.log(`Init audio buffer, container:${i.container}, codecs[level/parsed]=[${n}/${i.codec}]`),n&&1===n.split(",").length&&(i.levelCodec=n),this.hls.trigger(Events.BUFFER_CODECS,t);const a=i.initSegment;if(null!=a&&a.byteLength){const e={type:"audio",frag:s,part:null,chunkMeta:r,parent:s.type,data:a};this.hls.trigger(Events.BUFFER_APPENDING,e)}this.tickImmediate()}loadFragment(e,t,s){const r=this.fragmentTracker.getState(e);var i;if(this.switchingTrack||r===FragmentState.NOT_LOADED||r===FragmentState.PARTIAL)if(isMediaFragment(e))if(null!=(i=t.details)&&i.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=State.WAITING_INIT_PTS;const s=this.mainDetails;s&&s.fragmentStart!==t.details.fragmentStart&&alignMediaPlaylistByPDT(t.details,s)}else super.loadFragment(e,t,s);else this._loadInitSegment(e,t);else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){const{media:t,bufferedTrack:s}=this,r=null==s?void 0:s.attrs,i=e.attrs;t&&r&&(r.CHANNELS!==i.CHANNELS||s.name!==e.name||s.lang!==e.lang)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null)}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(Events.AUDIO_TRACK_SWITCHED,_objectSpread2({},e))}}class BasePlaylistController extends Logger{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,s){const r=null==t?void 0:t.renditionReports;if(r){let i=-1;for(let s=0;s<r.length;s++){const n=r[s];let a;try{a=new self.URL(n.URI,t.url).href}catch(e){this.warn(`Could not construct new URL for Rendition Report: ${e}`),a=n.URI||""}if(a===e){i=s;break}a===e.substring(0,a.length)&&(i=s)}if(-1!==i){const e=r[i],n=parseInt(e["LAST-MSN"])||(null==t?void 0:t.lastPartSn);let a=parseInt(e["LAST-PART"])||(null==t?void 0:t.lastPartIndex);if(this.hls.config.lowLatencyMode){const e=Math.min(t.age-t.partTarget,t.targetduration);a>=0&&e>t.partTarget&&(a+=1)}const o=s&&getSkipValue(s);return new HlsUrlParameters(n,a>=0?a:void 0,o)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}return e}playlistLoaded(e,t,s){const{details:r,stats:i}=t,n=self.performance.now(),a=i.loading.first?Math.max(0,n-i.loading.first):0;r.advancedDateTime=Date.now()-a;const o=this.hls.config.timelineOffset;if(o!==r.appliedTimelineOffset){const e=Math.max(o||0,0);r.appliedTimelineOffset=e,r.fragments.forEach((t=>{t.start=t.playlistOffset+e}))}if(r.live||null!=s&&s.live){const o="levelInfo"in t?t.levelInfo:t.track;r.reloaded(s),s&&r.fragments.length>0&&mergeDetails(s,r),-1===r.requestScheduled&&(r.requestScheduled=i.loading.start);const l=this.hls.mainForwardBufferInfo,d=l?l.end-l.len:0,h=computeReloadInterval(r,1e3*(r.edge-d));if(r.requestScheduled+h<n?r.requestScheduled=n:r.requestScheduled+=h,this.log(`live playlist ${e} ${r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED"}`),!this.canLoad||!r.live)return;let c,u,f;if(r.canBlockReload&&r.endSN&&r.advanced){const e=this.hls.config.lowLatencyMode,i=r.lastPartSn,a=r.endSN,l=r.lastPartIndex,d=i===a;-1!==l?d?(u=a+1,f=e?0:l):(u=i,f=e?l+1:r.maxPartIndex):u=a+1;const h=r.age,g=h+r.ageHeader;let m=Math.min(g-r.partTarget,1.5*r.targetduration);if(m>0){if(g>3*r.targetduration)this.log(`Playlist last advanced ${h.toFixed(2)}s ago. Omitting segment and part directives.`),u=void 0,f=void 0;else if(null!=s&&s.tuneInGoal&&g-r.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${m} with playlist age: ${r.age}`),m=0;else{const e=Math.floor(m/r.targetduration);if(u+=e,void 0!==f){f+=Math.round(m%r.targetduration/r.partTarget)}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${h.toFixed(2)}s goal: ${m} skip sn ${e} to part ${f}`)}r.tuneInGoal=m}if(c=this.getDeliveryDirectives(r,t.deliveryDirectives,u,f),e||!d)return r.requestScheduled=n,void this.loadingPlaylist(o,c)}else(r.canBlockReload||r.canSkipUntil)&&(c=this.getDeliveryDirectives(r,t.deliveryDirectives,u,f));c&&void 0!==u&&r.canBlockReload&&(r.requestScheduled=i.loading.first+Math.max(h-2*a,h/2)),this.scheduleLoading(o,c,r)}else this.clearTimer()}scheduleLoading(e,t,s){const r=s||e.details;if(!r)return void this.loadingPlaylist(e,t);const i=self.performance.now(),n=r.requestScheduled;if(i>=n)return void this.loadingPlaylist(e,t);const a=n-i;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout((()=>this.loadingPlaylist(e,t)),a)}getDeliveryDirectives(e,t,s,r){let i=getSkipValue(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,r=t.part,i=HlsSkip.No),new HlsUrlParameters(s,r,i)}checkRetry(e){const t=e.details,s=isTimeoutError(e),r=e.errorAction,{action:i,retryCount:n=0,retryConfig:a}=r||{},o=!!r&&!!a&&(i===NetworkErrorAction.RetryRequest||!r.resolved&&i===NetworkErrorAction.SendAlternateToPenaltyBox);if(o){var l;if(n>=a.maxNumRetry)return!1;if(s&&null!=(l=e.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const e=getRetryDelay(a,n);this.clearTimer(),this.timer=self.setTimeout((()=>this.loadPlaylist()),e),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,r.resolved=!0}return o}}class AudioTrackController extends BasePlaylistController{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Events.LEVEL_LOADING,this.onLevelLoading,this),e.on(Events.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Events.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(Events.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Events.LEVEL_LOADING,this.onLevelLoading,this),e.off(Events.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Events.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(Events.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:s,groupId:r,details:i}=t,n=this.tracksInGroup[s];if(!n||n.groupId!==r)return void this.warn(`Audio track with id:${s} and group:${r} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=t.details,this.log(`Audio track ${s} "${n.name}" lang:${n.lang} group:${r} loaded [${i.startSN}-${i.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.audioGroups||null,r=this.groupIds;let i=this.currentTrack;if(!s||(null==r?void 0:r.length)!==(null==s?void 0:s.length)||null!=s&&s.some((e=>-1===(null==r?void 0:r.indexOf(e))))){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const e=this.tracks.filter((e=>!s||-1!==s.indexOf(e.groupId)));if(e.length)this.selectDefaultTrack&&!e.some((e=>e.default))&&(this.selectDefaultTrack=!1),e.forEach(((e,t)=>{e.id=t}));else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=e;const t=this.hls.config.audioPreference;if(!i&&t){const s=findMatchingOption(t,e,audioMatchPredicate);if(s>-1)i=e[s];else{const e=findMatchingOption(t,this.tracks);i=this.tracks[e]}}let r=this.findTrackId(i);-1===r&&i&&(r=this.findTrackId(null));const a={audioTracks:e};this.log(`Updating audio tracks, ${e.length} track(s) found in group(s): ${null==s?void 0:s.join(",")}`),this.hls.trigger(Events.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==r&&-1===o)this.setAudioTrack(r);else if(e.length&&-1===o){var n;const t=new Error(`No audio track selected for current audio group-ID(s): ${null==(n=this.groupIds)?void 0:n.join(",")} track count: ${e.length}`);this.warn(t.message),this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}}onError(e,t){!t.fatal&&t.context&&(t.context.type!==PlaylistContextType.AUDIO_TRACK||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const r=this.currentTrack;if(r&&matchesOption(e,r,audioMatchPredicate))return r;const i=findMatchingOption(e,this.tracksInGroup,audioMatchPredicate);if(i>-1){const e=this.tracksInGroup[i];return this.setAudioTrack(i),e}if(r){let r=t.loadLevel;-1===r&&(r=t.firstAutoLevel);const i=findClosestLevelWithAudioGroup(e,t.levels,s,r,audioMatchPredicate);if(-1===i)return null;t.nextLoadLevel=i}if(e.channels||e.audioCodec){const t=findMatchingOption(e,s);if(t>-1)return s[t]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length)return void this.warn(`Invalid audio track id: ${e}`);this.selectDefaultTrack=!1;const s=this.currentTrack,r=t[e],i=r.details&&!r.details.live;if(e===this.trackId&&r===s&&i)return;if(this.log(`Switching to audio-track ${e} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=e,this.currentTrack=r,this.hls.trigger(Events.AUDIO_TRACK_SWITCHING,_objectSpread2({},r)),i)return;const n=this.switchParams(r.url,null==s?void 0:s.details,r.details);this.loadPlaylist(n)}findTrackId(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const r=t[s];if((!this.selectDefaultTrack||r.default)&&(!e||matchesOption(e,r,audioMatchPredicate)))return s}if(e){const{name:s,lang:r,assocLang:i,characteristics:n,audioCodec:a,channels:o}=e;for(let e=0;e<t.length;e++){if(matchesOption({name:s,lang:r,assocLang:i,characteristics:n,audioCodec:a,channels:o},t[e],audioMatchPredicate))return e}for(let s=0;s<t.length;s++){const r=t[s];if(mediaAttributesIdentical(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<t.length;s++){const r=t[s];if(mediaAttributesIdentical(e.attrs,r.attrs,["LANGUAGE"]))return s}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&useAlternateAudio(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,r=e.groupId,i=this.getUrlWithDirectives(e.url,t),n=e.details,a=null==n?void 0:n.age;this.log(`Loading audio-track ${s} "${e.name}" lang:${e.lang} group:${r}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${i}`),this.hls.trigger(Events.AUDIO_TRACK_LOADING,{url:i,id:s,groupId:r,deliveryDirectives:t||null,track:e})}}class BufferOperationQueue{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,s){if(null===this.queues||null===this.tracks)return;const r=this.queues[t];r.push(e),1!==r.length||s||this.executeNext(t)}appendBlocker(e){return new Promise((t=>{const s={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,e)}))}prependBlocker(e){return new Promise((t=>{if(this.queues){const s={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(s)}}))}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach((e=>{var t;const s=null==(t=e[0])?void 0:t.label;"async-blocker"!==s&&"async-blocker-prepend"!==s||(e[0].execute(),e.splice(0,1))}))}unblockAudio(e){if(null===this.queues)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(null===this.queues||null===this.tracks)return;const t=this.queues[e];if(t.length){const r=t[0];try{r.execute()}catch(t){var s;if(r.onError(t),null===this.queues||null===this.tracks)return;const i=null==(s=this.tracks[e])?void 0:s.buffer;null!=i&&i.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){null!==this.queues&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return(null==(t=this.queues)?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return null===e||null===t?"<destroyed>":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(e){var t,s;return null!=(t=this.queues)&&t[e]||null!=(s=this.tracks)&&s[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const s=null==(t=this.tracks)?void 0:t[e],r=null==s?void 0:s.buffer;return r?`SourceBuffer${r.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(e){var t;return(null==(t=this.queues)?void 0:t[e].map((e=>e.label)).join(", "))||""}}const VIDEO_CODEC_PROFILE_REPLACE=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,TRACK_REMOVED_ERROR_NAME="HlsJsTrackRemovedError";class HlsJsTrackRemovedError extends Error{constructor(e){super(e),this.name="HlsJsTrackRemovedError"}}class BufferController extends Logger{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=e=>{var t;this.hls&&"open"===(null==(t=this.mediaSource)?void 0:t.readyState)&&this.hls.pauseBuffering()},this._onStartStreaming=e=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=e=>{const{media:t,mediaSource:s}=this;e&&this.log("Media source opened"),t&&s&&(t.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(Events.MEDIA_ATTACHED,{media:t,mediaSource:s}),s.removeEventListener("sourceopen",this._onMediaSourceOpen),null!==this.mediaSource&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:e,_objectUrl:t}=this;e!==t&&this.error(`Media element src was set while attaching MediaSource (${t} > ${e})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=isManagedMediaSource(getMediaSource(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Events.BUFFER_RESET,this.onBufferReset,this),e.on(Events.BUFFER_APPENDING,this.onBufferAppending,this),e.on(Events.BUFFER_CODECS,this.onBufferCodecs,this),e.on(Events.BUFFER_EOS,this.onBufferEos,this),e.on(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Events.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Events.FRAG_PARSED,this.onFragParsed,this),e.on(Events.FRAG_CHANGED,this.onFragChanged,this),e.on(Events.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Events.BUFFER_RESET,this.onBufferReset,this),e.off(Events.BUFFER_APPENDING,this.onBufferAppending,this),e.off(Events.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Events.BUFFER_EOS,this.onBufferEos,this),e.off(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Events.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Events.FRAG_PARSED,this.onFragParsed,this),e.off(Events.FRAG_CHANGED,this.onFragChanged,this),e.off(Events.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const s={};if(this.operationQueue){const e=this.isUpdating();e||this.operationQueue.removeBlockers();const t=this.isQueued();(e||t)&&this.warn(`Transfering MediaSource with${t?" operations in queue":""}${e?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const r=this.transferData;return!this.sourceBufferCount&&r&&r.mediaSource===t?_extends(s,r.tracks):this.sourceBuffers.forEach((e=>{const[t]=e;t&&(s[t]=_extends({},this.tracks[t]),this.removeBuffer(t)),e[0]=e[1]=null})),{media:e,mediaSource:t,tracks:s}}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(e,t){var s;let r=2;(t.audio&&!t.video||!t.altAudio)&&(r=1),this.bufferCodecEventsTotal=r,this.log(`${r} bufferCodec event(s) expected.`),null!=(s=this.transferData)&&s.mediaSource&&this.sourceBufferCount&&r&&this.bufferCreated()}onMediaAttaching(e,t){const s=this.media=t.media,r=getMediaSource(this.appendSource);if(this.transferData=this.overrides=void 0,s&&r){const e=!!t.mediaSource;(e||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const i=this.mediaSource=t.mediaSource||new r;if(this.assignMediaSource(i),e)this._objectUrl=s.src,this.attachTransferred();else{const e=this._objectUrl=self.URL.createObjectURL(i);if(this.appendSource)try{s.removeAttribute("src");const t=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||t&&i instanceof t,removeSourceChildren(s),addSource(s,e),s.load()}catch(t){s.src=e}else s.src=e}s.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,s;this.log(`${(null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${null==(s=e.constructor)?void 0:s.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const s=this.tracks,r=t.tracks,i=r?Object.keys(r):null,n=i?i.length:0,a=()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()};if(r&&i&&n){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: ${JSON.stringify(s,((e,t)=>"initSegment"===e?void 0:t))};\ntransfer tracks: ${JSON.stringify(r,((e,t)=>"initSegment"===e?void 0:t))}}`),!isCompatibleTrackChange(r,s)){t.mediaSource=null,t.tracks=void 0;const i=e.currentTime,n=this.details,a=Math.max(i,(null==n?void 0:n.fragments[0].start)||0);return a-i>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${i} -> ${a}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(r)}"->"${Object.keys(s)}") start time: ${a} currentTime: ${i}`),this.onMediaDetaching(Events.MEDIA_DETACHING,{}),this.onMediaAttaching(Events.MEDIA_ATTACHING,t),void(e.currentTime=a))}this.transferData=void 0,i.forEach((e=>{const t=e,s=r[t];if(s){const e=s.buffer;if(e){const r=this.fragmentTracker,i=s.id;if(r.hasFragments(i)||r.hasParts(i)){const s=BufferHelper.getBuffered(e);r.detectEvictedFragments(t,s,i,null,!0)}const n=sourceBufferNameToIndex(t),a=[t,e];this.sourceBuffers[n]=a,e.updating&&this.operationQueue&&this.operationQueue.prependBlocker(t),this.trackSourceBuffer(t,s)}}})),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var e;const t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}onMediaDetaching(e,t){const s=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:r,mediaSource:i,_objectUrl:n}=this;if(i){if(this.log("media source "+(s?"transferring":"detaching")),s)this.sourceBuffers.forEach((([e])=>{e&&this.removeBuffer(e)})),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const e="open"===i.readyState;try{const t=i.sourceBuffers;for(let s=t.length;s--;)e&&t[s].abort(),i.removeSourceBuffer(t[s]);e&&i.endOfStream()}catch(e){this.warn(`onMediaDetaching: ${e.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}i.removeEventListener("sourceopen",this._onMediaSourceOpen),i.removeEventListener("sourceended",this._onMediaSourceEnded),i.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(i.removeEventListener("startstreaming",this._onStartStreaming),i.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}r&&(r.removeEventListener("emptied",this._onMediaEmptied),s||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(r.removeAttribute("src"),this.appendSource&&removeSourceChildren(r),r.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(Events.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach((([e])=>{e&&this.resetBuffer(e)})),this.initTracks()}resetBuffer(e){var t;const s=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),s)try{var r;null!=(r=this.mediaSource)&&r.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(t){this.warn(`onBufferReset ${e}`,t)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[sourceBufferNameToIndex(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new BufferOperationQueue(this.tracks)}onBufferCodecs(e,t){const s=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const i="audiovideo"in t&&(s.audio||s.video)||s.audiovideo&&("audio"in t||"video"in t),n=!i&&this.sourceBufferCount&&this.media&&r.some((e=>!s[e]));i||n?this.warn(`Unsupported transition between "${Object.keys(s)}" and "${r}" SourceBuffers`):(r.forEach((e=>{var r,i,n;const a=t[e],{id:o,codec:l,levelCodec:d,container:h,metadata:c}=a;let u=s[e];const f=null==(r=this.transferData)||null==(i=r.tracks)?void 0:i[e],g=null!=f&&f.buffer?f:u,m=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),p=null==g?void 0:g.levelCodec,E=!g||!!this.hls.config.assetPlayerId;u||(u=s[e]={buffer:void 0,listeners:[],codec:l,container:h,levelCodec:d,metadata:c,id:o});const y=pickMostCompleteCodecName(m,p),v=null==y?void 0:y.replace(VIDEO_CODEC_PROFILE_REPLACE,"$1");let T=pickMostCompleteCodecName(l,d);const S=null==(n=T)?void 0:n.replace(VIDEO_CODEC_PROFILE_REPLACE,"$1");T&&(v!==S||E)&&("audio"===e.slice(0,5)&&(T=getCodecCompatibleName(T,this.appendSource)),this.log(`switching codec ${m} to ${T}`),T!==(u.pendingCodec||u.codec)&&(u.pendingCodec=T),u.container=h,this.appendChangeType(e,h,T))})),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce(((e,t)=>{const s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e}),{})}appendChangeType(e,t,s){const r=`${t};codecs=${s}`,i={label:`change-type=${r}`,execute:()=>{const i=this.tracks[e];if(i){const n=i.buffer;null!=n&&n.changeType&&(this.log(`changing ${e} sourceBuffer type to ${r}`),n.changeType(r),i.codec=s,i.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn(`Failed to change ${e} SourceBuffer type`,t)}};this.append(i,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const s=e.start,r=s+.05*e.duration;if(!0===(null==(t=this.fragmentTracker.getAppendedFrag(s,PlaylistLevelType.MAIN))?void 0:t.gap))return;const i={label:"block-audio",execute:()=>{var e;const t=this.tracks.video;(this.lastVideoAppendEnd>r||null!=t&&t.buffer&&BufferHelper.isBuffered(t.buffer,r)||!0===(null==(e=this.fragmentTracker.getAppendedFrag(r,PlaylistLevelType.MAIN))?void 0:e.gap))&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn("Error executing block-audio operation",e)}};this.blockedAudioAppend={op:i,frag:e},this.append(i,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:s}=this,{data:r,type:i,parent:n,frag:a,part:o,chunkMeta:l}=t,d=l.buffering[i],h=a.sn,c=self.performance.now();d.start=c;const u=a.stats.buffering,f=o?o.stats.buffering:null;0===u.start&&(u.start=c),f&&0===f.start&&(f.start=c);const g=s.audio;let m=!1;"audio"===i&&"audio/mpeg"===(null==g?void 0:g.container)&&(m=!this.lastMpegAudioChunk||1===l.id||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const p=this.tracks.video,E=null==p?void 0:p.buffer;if(E&&"initSegment"!==h){const e=o||a,t=this.blockedAudioAppend;if("audio"!==i||"main"===n||this.blockedAudioAppend){if("video"===i){const s=e.end;if(t){const e=t.frag.start;(s>e||s<this.lastVideoAppendEnd||BufferHelper.isBuffered(E,e))&&this.unblockAudio()}this.lastVideoAppendEnd=s}}else{const t=e.start+.05*e.duration,s=E.buffered,r=this.currentOp("video");s.length||r?!r&&!BufferHelper.isBuffered(E,t)&&this.lastVideoAppendEnd<t&&this.blockAudio(e):this.blockAudio(e)}}const y=(o||a).start,v={label:`append-${i}`,execute:()=>{if(d.executeStart=self.performance.now(),m){const e=this.tracks[i];if(e){const t=e.buffer;if(t){const e=y-t.timestampOffset;Math.abs(e)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${y} (delta: ${e}) sn: ${h})`),t.timestampOffset=y)}}}this.appendExecutor(r,i)},onStart:()=>{},onComplete:()=>{const e=self.performance.now();d.executeEnd=d.end=e,0===u.first&&(u.first=e),f&&0===f.first&&(f.first=e);const t={};this.sourceBuffers.forEach((([e,s])=>{e&&(t[e]=BufferHelper.getBuffered(s))})),this.appendErrors[i]=0,"audio"===i||"video"===i?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(Events.BUFFER_APPENDED,{type:i,frag:a,part:o,chunkMeta:l,parent:a.type,timeRanges:t})},onError:e=>{var t;const s={type:ErrorTypes.MEDIA_ERROR,parent:a.type,details:ErrorDetails.BUFFER_APPEND_ERROR,sourceBufferName:i,frag:a,part:o,chunkMeta:l,error:e,err:e,fatal:!1};if(e.code===DOMException.QUOTA_EXCEEDED_ERR)s.details=ErrorDetails.BUFFER_FULL_ERROR;else if(e.code!==DOMException.INVALID_STATE_ERR||!this.mediaSourceOpenOrEnded||null!=(t=this.media)&&t.error)if("HlsJsTrackRemovedError"===e.name)0===this.sourceBufferCount?s.errorAction=createDoNothingErrorAction(!0):++this.appendErrors[i];else{const e=++this.appendErrors[i];this.warn(`Failed ${e}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${i}" sourceBuffer`),e>=this.hls.config.appendErrorMaxRetry&&(s.fatal=!0)}else s.errorAction=createDoNothingErrorAction(!0);this.hls.trigger(Events.ERROR,s)}};this.append(v,i,this.isPending(this.tracks[i]))}getFlushOp(e,t,s){return this.log(`queuing "${e}" remove ${t}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{this.hls.trigger(Events.BUFFER_FLUSHED,{type:e})},onError:r=>{this.warn(`Failed to remove ${t}-${s} from "${e}" SourceBuffer`,r)}}}onBufferFlushing(e,t){const{type:s,startOffset:r,endOffset:i}=t;s?this.append(this.getFlushOp(s,r,i),s):this.sourceBuffers.forEach((([e])=>{e&&this.append(this.getFlushOp(e,r,i),e)}))}onFragParsed(e,t){const{frag:s,part:r}=t,i=[],n=r?r.elementaryStreams:s.elementaryStreams;n[ElementaryStreamTypes.AUDIOVIDEO]?i.push("audiovideo"):(n[ElementaryStreamTypes.AUDIO]&&i.push("audio"),n[ElementaryStreamTypes.VIDEO]&&i.push("video"));0===i.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers((()=>{const e=self.performance.now();s.stats.buffering.end=e,r&&(r.stats.buffering.end=e);const t=r?r.stats:s.stats;this.hls.trigger(Events.FRAG_BUFFERED,{frag:s,part:r,stats:t,id:s.type})}),i)}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some((([e])=>{var t,s;return e&&(!(null!=(t=this.tracks[e])&&t.ended)||(null==(s=this.tracks[e])?void 0:s.ending))}))}onBufferEos(e,t){var s;this.sourceBuffers.forEach((([e])=>{if(e){const s=this.tracks[e];t.type&&t.type!==e||(s.ending=!0,s.ended||(s.ended=!0,this.log(`${e} buffer reached EOS`)))}}));const r=!1!==(null==(s=this.overrides)?void 0:s.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some((([e])=>{var t;return e&&!(null!=(t=this.tracks[e])&&t.ended)}))&&(this.log("Queueing EOS"),this.blockUntilOpen((()=>{if(this.sourceBuffers.forEach((([e])=>{if(null!==e){const t=this.tracks[e];t&&(t.ending=!1)}})),r){const{mediaSource:e}=this;if(!e||"open"!==e.readyState)return void(e&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`));this.log("Calling mediaSource.endOfStream()"),e.endOfStream()}this.hls.trigger(Events.BUFFERED_TO_END,void 0)})))}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){const e=this.getDurationAndRange();e&&this.blockUntilOpen((()=>this.updateMediaSource(e)))}onError(e,t){if(t.details===ErrorDetails.BUFFER_APPEND_ERROR&&t.frag){var s;const e=null==(s=t.errorAction)?void 0:s.nextAutoLevel;isFiniteNumber(e)&&e!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:s}=this;if(!s||null===t)return;if(!this.sourceBufferCount)return;const r=e.config,i=s.currentTime,n=t.levelTargetDuration,a=t.live&&null!==r.liveBackBufferLength?r.liveBackBufferLength:r.backBufferLength;if(isFiniteNumber(a)&&a>=0){const e=Math.max(a,n),t=Math.floor(i/n)*n-e;this.flushBackBuffer(i,n,t)}if(isFiniteNumber(r.frontBufferFlushThreshold)&&r.frontBufferFlushThreshold>0){const e=Math.max(r.maxBufferLength,r.frontBufferFlushThreshold),t=Math.max(e,n),s=Math.floor(i/n)*n+t;this.flushFrontBuffer(i,n,s)}}flushBackBuffer(e,t,s){this.sourceBuffers.forEach((([r,i])=>{if(i){const a=BufferHelper.getBuffered(i);if(a.length>0&&s>a.start(0)){var n;this.hls.trigger(Events.BACK_BUFFER_REACHED,{bufferEnd:s});const i=this.tracks[r];if(null!=(n=this.details)&&n.live)this.hls.trigger(Events.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(null!=i&&i.ended&&a.end(a.length-1)-e<2*t)return void this.log(`Cannot flush ${r} back buffer while SourceBuffer is in ended state`);this.hls.trigger(Events.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:r})}}}))}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach((([r,i])=>{if(i){const n=BufferHelper.getBuffered(i),a=n.length;if(a<2)return;const o=n.start(a-1),l=n.end(a-1),d=this.tracks[r];if(s>o||e>=o&&e<=l)return;if(null!=d&&d.ended&&e-l<2*t)return void this.log(`Cannot flush ${r} front buffer while SourceBuffer is in ended state`);this.hls.trigger(Events.BUFFER_FLUSHING,{startOffset:o,endOffset:1/0,type:r})}}))}getDurationAndRange(){var e;const{details:t,mediaSource:s}=this;if(!t||!this.media||"open"!==(null==s?void 0:s.readyState))return null;const r=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){s.duration=1/0;if(t.fragments.length&&t.live&&s.setLiveSeekableRange){const e=Math.max(0,t.fragmentStart);return{duration:1/0,start:e,end:Math.max(e,r)}}return{duration:1/0}}const i=null==(e=this.overrides)?void 0:e.duration;if(i)return{duration:i};const n=this.media.duration;return r>(isFiniteNumber(s.duration)?s.duration:0)&&r>n||!isFiniteNumber(n)?{duration:r}:null}updateMediaSource({duration:e,start:t,end:s}){const r=this.mediaSource;this.media&&r&&"open"===r.readyState&&(r.duration!==e&&(isFiniteNumber(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),r.duration=e),void 0!==t&&void 0!==s&&(this.log(`MediaSource duration is set to ${r.duration}. Setting seekable range to ${t}-${s}.`),r.setLiveSeekableRange(t,s)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${JSON.stringify(s)}`),this.tracksReady){var r;const e=null==(r=this.transferData)?void 0:r.tracks;e&&Object.keys(e).length?this.attachTransferred():(this.createSourceBuffers(),this.bufferCreated())}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach((([t,s])=>{if(t){const r=this.tracks[t];e[t]={buffer:s,container:r.container,codec:r.codec,levelCodec:r.levelCodec,id:r.id,metadata:r.metadata}}})),this.hls.trigger(Events.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach((([e])=>{this.executeNext(e)}))}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in e){const i=r,n=e[i];if(this.isPending(n)){const e=this.getTrackCodec(n,i),r=`${n.container};codecs=${e}`;n.codec=e,this.log(`creating sourceBuffer(${r})${this.currentOp(i)?" Queued":""} ${JSON.stringify(n)}`);try{const e=s.addSourceBuffer(r),a=sourceBufferNameToIndex(i),o=[i,e];t[a]=o,n.buffer=e}catch(e){this.error(`error while trying to add sourceBuffer: ${e.message}`),this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:i,mimeType:r});break}this.trackSourceBuffer(i,n)}}}getTrackCodec(e,t){const s=pickMostCompleteCodecName(e.codec,e.levelCodec);return s?"audio"===t.slice(0,5)?getCodecCompatibleName(s,this.appendSource):s:""}trackSourceBuffer(e,t){const s=t.buffer;if(!s)return;const r=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,codec:r,container:t.container,levelCodec:t.levelCodec,metadata:t.metadata,id:t.id,listeners:[]},this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",((e,t)=>{const s=t.removedRanges;null!=s&&s.length&&this.hls.trigger(Events.BUFFER_FLUSHED,{type:e})}))}get mediaSrc(){var e,t;const s=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==s?void 0:s.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if("closed"===(null==(t=this.mediaSource)?void 0:t.readyState))return void this.resetBuffer(e);const s=this.currentOp(e);s&&(s.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var s;const r=new Error(`${e} SourceBuffer error. MediaSource readyState: ${null==(s=this.mediaSource)?void 0:s.readyState}`);this.error(`${r}`,t),this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});const i=this.currentOp(e);i&&i.onError(r)}removeExecutor(e,t,s){const{media:r,mediaSource:i}=this,n=this.tracks[e],a=null==n?void 0:n.buffer;if(!r||!i||!a)return this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),void this.shiftAndExecuteNext(e);const o=isFiniteNumber(r.duration)?r.duration:1/0,l=isFiniteNumber(i.duration)?i.duration:1/0,d=Math.max(0,t),h=Math.min(s,o,l);h>d&&(!n.ending||n.ended)?(n.ended=!1,this.log(`Removing [${d},${h}] from the ${e} SourceBuffer`),a.remove(d,h)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const s=this.tracks[t],r=null==s?void 0:s.buffer;if(!r)throw new HlsJsTrackRemovedError(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);s.ending=!1,s.ended=!1,r.appendBuffer(e)}blockUntilOpen(e){this.isUpdating()||this.isQueued()?this.blockBuffers(e):e()}isUpdating(){return this.sourceBuffers.some((([e,t])=>e&&t.updating))}isQueued(){return this.sourceBuffers.some((([e])=>e&&!!this.currentOp(e)))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve().then(e);const{operationQueue:s}=this,r=t.map((e=>this.appendBlocker(e)));t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(r).then((r=>{s===this.operationQueue&&(e(),this.stepOperationQueue(t))}))}stepOperationQueue(e){e.forEach((e=>{var t;const s=null==(t=this.tracks[e])?void 0:t.buffer;s&&!s.updating&&this.shiftAndExecuteNext(e)}))}append(e,t,s){this.operationQueue&&this.operationQueue.append(e,t,s)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce(((e,t)=>e+(this.isPending(this.tracks[t])?1:0)),0)}get sourceBufferCount(){return this.sourceBuffers.reduce(((e,[t])=>e+(t?1:0)),0)}get sourceBufferTypes(){return this.sourceBuffers.map((([e])=>e)).filter((e=>!!e))}addBufferListener(e,t,s){const r=this.tracks[e];if(!r)return;const i=r.buffer;if(!i)return;const n=s.bind(this,e);r.listeners.push({event:t,listener:n}),i.addEventListener(t,n)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const s=t.buffer;s&&(t.listeners.forEach((e=>{s.removeEventListener(e.event,e.listener)})),t.listeners.length=0)}}function removeSourceChildren(e){const t=e.querySelectorAll("source");[].slice.call(t).forEach((t=>{e.removeChild(t)}))}function addSource(e,t){const s=self.document.createElement("source");s.type="video/mp4",s.src=t,e.appendChild(s)}function sourceBufferNameToIndex(e){return"audio"===e?1:0}class CapLevelController{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(Events.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Events.BUFFER_CODECS,this.onBufferCodecs,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(Events.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Events.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const s=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,s.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&isFiniteNumber(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const e=this.hls.levels;if(e.length){const t=this.hls,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const s=t.filter(((t,s)=>this.isLevelAllowed(t)&&s<=e));return this.clientRect=null,CapLevelController.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,t.width||t.height||(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(e){}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some((t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height))}static getMaxLevelByMediaSize(e,t,s){if(null==e||!e.length)return-1;let r=e.length-1;const i=Math.max(t,s);for(let t=0;t<e.length;t+=1){const s=e[t];if((s.width>=i||s.height>=i)&&(n=s,!(a=e[t+1])||n.width!==a.width||n.height!==a.height)){r=t;break}}var n,a;return r}}const CmObjectType={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},CmcdObjectType=CmObjectType,CmStreamingFormat={DASH:"d",HLS:"h",SMOOTH:"s",OTHER:"o"},CmcdStreamingFormat=CmStreamingFormat,CMCD_OBJECT="CMCD-Object",CMCD_REQUEST="CMCD-Request",CMCD_SESSION="CMCD-Session",CMCD_STATUS="CMCD-Status",CmcdHeaderField={OBJECT:CMCD_OBJECT,REQUEST:CMCD_REQUEST,SESSION:CMCD_SESSION,STATUS:CMCD_STATUS},CmcdHeaderMap={[CmcdHeaderField.OBJECT]:["br","d","ot","tb"],[CmcdHeaderField.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[CmcdHeaderField.SESSION]:["cid","pr","sf","sid","st","v"],[CmcdHeaderField.STATUS]:["bs","rtp"]};class SfItem{constructor(e,t){Array.isArray(e)&&(e=e.map((e=>e instanceof SfItem?e:new SfItem(e)))),this.value=e,this.params=t}}const DICT="Dict";function format(e){return Array.isArray(e)?JSON.stringify(e):e instanceof Map?"Map{}":e instanceof Set?"Set{}":"object"==typeof e?JSON.stringify(e):String(e)}function throwError(e,t,s,r){return new Error(`failed to ${e} "${format(t)}" as ${s}`,{cause:r})}function serializeError(e,t,s){return throwError("serialize",e,t,s)}class SfToken{constructor(e){this.description=e}}const BARE_ITEM="Bare Item",BOOLEAN="Boolean";function serializeBoolean(e){if("boolean"!=typeof e)throw serializeError(e,BOOLEAN);return e?"?1":"?0"}const BYTES="Byte Sequence";function serializeByteSequence(e){if(!1===ArrayBuffer.isView(e))throw serializeError(e,BYTES);return`:${base64encode(e)}:`}const INTEGER="Integer";function isInvalidInt(e){return e<-999999999999999||999999999999999<e}function serializeInteger(e){if(isInvalidInt(e))throw serializeError(e,INTEGER);return e.toString()}function serializeDate(e){return`@${serializeInteger(e.getTime()/1e3)}`}const DECIMAL="Decimal";function serializeDecimal(e){const t=roundToEven(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw serializeError(e,DECIMAL);const s=t.toString();return s.includes(".")?s:`${s}.0`}const STRING="String",STRING_REGEX=/[\x00-\x1f\x7f]+/;function serializeString(e){if(STRING_REGEX.test(e))throw serializeError(e,STRING);return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function symbolToStr(e){return e.description||e.toString().slice(7,-1)}const TOKEN="Token";function serializeToken(e){const t=symbolToStr(e);if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t))throw serializeError(t,TOKEN);return t}function serializeBareItem(e){switch(typeof e){case"number":if(!isFiniteNumber(e))throw serializeError(e,BARE_ITEM);return Number.isInteger(e)?serializeInteger(e):serializeDecimal(e);case"string":return serializeString(e);case"symbol":return serializeToken(e);case"boolean":return serializeBoolean(e);case"object":if(e instanceof Date)return serializeDate(e);if(e instanceof Uint8Array)return serializeByteSequence(e);if(e instanceof SfToken)return serializeToken(e);default:throw serializeError(e,BARE_ITEM)}}const KEY="Key";function serializeKey(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw serializeError(e,KEY);return e}function serializeParams(e){return null==e?"":Object.entries(e).map((([e,t])=>!0===t?`;${serializeKey(e)}`:`;${serializeKey(e)}=${serializeBareItem(t)}`)).join("")}function serializeItem(e){return e instanceof SfItem?`${serializeBareItem(e.value)}${serializeParams(e.params)}`:serializeBareItem(e)}function serializeInnerList(e){return`(${e.value.map(serializeItem).join(" ")})${serializeParams(e.params)}`}function serializeDict(e,t={whitespace:!0}){if("object"!=typeof e)throw serializeError(e,DICT);const s=e instanceof Map?e.entries():Object.entries(e),r=(null==t?void 0:t.whitespace)?" ":"";return Array.from(s).map((([e,t])=>{t instanceof SfItem==!1&&(t=new SfItem(t));let s=serializeKey(e);return!0===t.value?s+=serializeParams(t.params):(s+="=",Array.isArray(t.value)?s+=serializeInnerList(t):s+=serializeItem(t)),s})).join(`,${r}`)}function encodeSfDict(e,t){return serializeDict(e,t)}function isTokenField(e){return"ot"===e||"sf"===e||"st"===e}function isValid(e){return"number"==typeof e?isFiniteNumber(e):null!=e&&""!==e&&!1!==e}const toRounded=e=>Math.round(e),toUrlSafe=(e,t)=>((null==t?void 0:t.baseUrl)&&(e=urlToRelativePath(e,t.baseUrl)),encodeURIComponent(e)),toHundred=e=>100*toRounded(e/100),CmcdFormatters={br:toRounded,d:toRounded,bl:toHundred,dl:toHundred,mtp:toHundred,nor:toUrlSafe,rtp:toHundred,tb:toRounded};function processCmcd(e,t){const s={};if(null==e||"object"!=typeof e)return s;const r=Object.keys(e).sort(),i=_extends({},CmcdFormatters,null==t?void 0:t.formatters),n=null==t?void 0:t.filter;return r.forEach((r=>{if(null==n?void 0:n(r))return;let a=e[r];const o=i[r];o&&(a=o(a,t)),"v"===r&&1===a||"pr"==r&&1===a||isValid(a)&&(isTokenField(r)&&"string"==typeof a&&(a=new SfToken(a)),s[r]=a)})),s}function encodeCmcd(e,t={}){return e?encodeSfDict(processCmcd(e,t),_extends({whitespace:!1},t)):""}function toCmcdHeaders(e,t={}){const s={};if(!e)return s;const r=Object.entries(e),i=Object.entries(CmcdHeaderMap).concat(Object.entries((null==t?void 0:t.customHeaderMap)||{})),n=r.reduce(((e,t)=>{var s,r;const[n,a]=t,o=(null===(s=i.find((e=>e[1].includes(n))))||void 0===s?void 0:s[0])||CmcdHeaderField.REQUEST;return null!==(r=e[o])&&void 0!==r||(e[o]={}),e[o][n]=a,e}),{});return Object.entries(n).reduce(((e,[s,r])=>(e[s]=encodeCmcd(r,t),e)),s)}function appendCmcdHeaders(e,t,s){return _extends(e,toCmcdHeaders(t,s))}const CMCD_PARAM="CMCD";function toCmcdQuery(e,t={}){if(!e)return"";const s=encodeCmcd(e,t);return`${CMCD_PARAM}=${encodeURIComponent(s)}`}const REGEX=/CMCD=[^&#]+/;function appendCmcdQuery(e,t,s){const r=toCmcdQuery(t,s);if(!r)return e;if(REGEX.test(e))return e.replace(REGEX,r);const i=e.includes("?")?"&":"?";return`${e}${i}${r}`}class CMCDController{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=e=>{try{this.apply(e,{ot:CmcdObjectType.MANIFEST,su:!this.initialized})}catch(e){this.hls.logger.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=e=>{try{const{frag:t,part:s}=e,r=this.hls.levels[t.level],i=this.getObjectType(t),n={d:1e3*(s||t).duration,ot:i};i!==CmcdObjectType.VIDEO&&i!==CmcdObjectType.AUDIO&&i!=CmcdObjectType.MUXED||(n.br=r.bitrate/1e3,n.tb=this.getTopBandwidth(i)/1e3,n.bl=this.getBufferLength(i));const a=s?this.getNextPart(s):this.getNextFrag(t);null!=a&&a.url&&a.url!==t.url&&(n.nor=a.url),this.apply(e,n)}catch(e){this.hls.logger.warn("Could not generate segment CMCD data.",e)}},this.hls=e;const t=this.config=e.config,{cmcd:s}=t;null!=s&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||e.sessionId,this.cid=s.contentId,this.useHeaders=!0===s.useHeaders,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events.MEDIA_DETACHED,this.onMediaDetached,this),e.on(Events.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events.MEDIA_DETACHED,this.onMediaDetached,this),e.off(Events.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var s,r;this.audioBuffer=null==(s=t.tracks.audio)?void 0:s.buffer,this.videoBuffer=null==(r=t.tracks.video)?void 0:r.buffer}createData(){var e;return{v:1,sf:CmcdStreamingFormat.HLS,sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){_extends(t,this.createData());const s=t.ot===CmcdObjectType.INIT||t.ot===CmcdObjectType.VIDEO||t.ot===CmcdObjectType.MUXED;this.starved&&s&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);const{includeKeys:r}=this;r&&(t=Object.keys(t).reduce(((e,s)=>(r.includes(s)&&(e[s]=t[s]),e)),{}));const i={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),appendCmcdHeaders(e.headers,t,i)):e.url=appendCmcdQuery(e.url,t,i)}getNextFrag(e){var t;const s=null==(t=this.hls.levels[e.level])?void 0:t.details;if(s){const t=e.sn-s.startSN;return s.fragments[t+1]}}getNextPart(e){var t,s;const{index:r,fragment:i}=e,n=null==(t=this.hls.levels[i.level])||null==(s=t.details)?void 0:s.partList;if(n){const{sn:e}=i;for(let t=n.length-1;t>=0;t--){const s=n[t];if(s.index===r&&s.fragment.sn===e)return n[t+1]}}}getObjectType(e){const{type:t}=e;return"subtitle"===t?CmcdObjectType.TIMED_TEXT:"initSegment"===e.sn?CmcdObjectType.INIT:"audio"===t?CmcdObjectType.AUDIO:"main"===t?this.hls.audioTracks.length?CmcdObjectType.VIDEO:CmcdObjectType.MUXED:void 0}getTopBandwidth(e){let t,s=0;const r=this.hls;if(e===CmcdObjectType.AUDIO)t=r.audioTracks;else{const e=r.maxAutoLevel,s=e>-1?e+1:r.levels.length;t=r.levels.slice(0,s)}for(const e of t)e.bitrate>s&&(s=e.bitrate);return s>0?s:NaN}getBufferLength(e){const t=this.media,s=e===CmcdObjectType.AUDIO?this.audioBuffer:this.videoBuffer;if(!s||!t)return NaN;return 1e3*BufferHelper.bufferInfo(s,t.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new s(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,s,r){t(e),this.loader.load(e,s,r)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,s=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new s(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,s,r){t(e),this.loader.load(e,s,r)}}}}const PATHWAY_PENALTY_DURATION_MS=3e5;class ContentSteeringController extends Logger{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Events.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Events.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce(((e,t)=>(-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e)),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter((t=>t!==e)))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:s}=t;null!==s&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:s}=t;if((null==s?void 0:s.action)===NetworkErrorAction.SendAlternateToPenaltyBox&&s.flags===ErrorActionFlags.MoveAllAlternatesMatchingHost){const e=this.levels;let r=this._pathwayPriority,i=this.pathwayId;if(t.context){const{groupId:s,pathwayId:r,type:n}=t.context;s&&e?i=this.getPathwayForGroupId(s,n,i):r&&(i=r)}i in this.penalizedPathways||(this.penalizedPathways[i]=performance.now()),!r&&e&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),s.resolved=this.pathwayId!==i),s.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${i} levels: ${e?e.length:e} priorities: ${JSON.stringify(r)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){const s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return null===this.levels?[]:this.levels.filter((t=>e===t.pathwayId))}updatePathwayPriority(e){let t;this._pathwayPriority=e;const s=this.penalizedPathways,r=performance.now();Object.keys(s).forEach((e=>{r-s[e]>3e5&&delete s[e]}));for(let r=0;r<e.length;r++){const i=e[r];if(i in s)continue;if(i===this.pathwayId)return;const n=this.hls.nextLoadLevel,a=this.hls.levels[n];if(t=this.getLevelsForPathway(i),t.length>0){this.log(`Setting Pathway to "${i}"`),this.pathwayId=i,reassignFragmentLevelIndexes(t),this.hls.trigger(Events.LEVELS_UPDATED,{levels:t});const e=this.hls.levels[n];a&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(e,t,s){const r=this.getLevelsForPathway(s).concat(this.levels||[]);for(let s=0;s<r.length;s++)if(t===PlaylistContextType.AUDIO_TRACK&&r[s].hasAudioGroup(e)||t===PlaylistContextType.SUBTITLE_TRACK&&r[s].hasSubtitleGroup(e))return r[s].pathwayId;return s}clonePathways(e){const t=this.levels;if(!t)return;const s={},r={};e.forEach((e=>{const{ID:i,"BASE-ID":n,"URI-REPLACEMENT":a}=e;if(t.some((e=>e.pathwayId===i)))return;const o=this.getLevelsForPathway(n).map((e=>{const t=new AttrList(e.attrs);t["PATHWAY-ID"]=i;const n=t.AUDIO&&`${t.AUDIO}_clone_${i}`,o=t.SUBTITLES&&`${t.SUBTITLES}_clone_${i}`;n&&(s[t.AUDIO]=n,t.AUDIO=n),o&&(r[t.SUBTITLES]=o,t.SUBTITLES=o);const l=performUriReplacement(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),d=new Level({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:l,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(let t=1;t<e.audioGroups.length;t++)d.addGroupId("audio",`${e.audioGroups[t]}_clone_${i}`);if(e.subtitleGroups)for(let t=1;t<e.subtitleGroups.length;t++)d.addGroupId("text",`${e.subtitleGroups[t]}_clone_${i}`);return d}));t.push(...o),cloneRenditionGroups(this.audioTracks,s,a,i),cloneRenditionGroups(this.subtitleTracks,r,a,i)}))}loadSteeringManifest(e){const t=this.hls.config,s=t.loader;let r;this.loader&&this.loader.destroy(),this.loader=new s(t);try{r=new self.URL(e)}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${e}`)}if("data:"!==r.protocol){const e=0|(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate);r.searchParams.set("_HLS_pathway",this.pathwayId),r.searchParams.set("_HLS_throughput",""+e)}const i={responseType:"json",url:r.href},n=t.steeringManifestLoadPolicy.default,a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(e,t,s,i)=>{this.log(`Loaded steering manifest: "${r}"`);const n=e.data;if(1!==(null==n?void 0:n.VERSION))return void this.log(`Steering VERSION ${n.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=n.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=n;if(a)try{this.uri=new self.URL(a,r).href}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||s.url),o&&this.clonePathways(o);const d={steeringManifest:n,url:r.toString()};this.hls.trigger(Events.STEERING_MANIFEST_LOADED,d),l&&this.updatePathwayPriority(l)},onError:(e,t,s,r)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),410===e.code)return this.enabled=!1,void this.log(`Steering manifest ${t.url} no longer available`);let i=1e3*this.timeToLoad;if(429!==e.code)this.scheduleRefresh(this.uri||t.url,i);else{const e=this.loader;if("function"==typeof(null==e?void 0:e.getResponseHeader)){const t=e.getResponseHeader("Retry-After");t&&(i=1e3*parseFloat(t))}this.log(`Steering manifest ${t.url} rate limited`)}},onTimeout:(e,t,s)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}};this.log(`Requesting steering manifest: ${r}`),this.loader.load(i,o,l)}scheduleRefresh(e,t=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout((()=>{var t;const s=null==(t=this.hls)?void 0:t.media;!s||s.ended?this.scheduleRefresh(e,1e3*this.timeToLoad):this.loadSteeringManifest(e)}),t)}}function cloneRenditionGroups(e,t,s,r){e&&Object.keys(t).forEach((i=>{const n=e.filter((e=>e.groupId===i)).map((e=>{const n=_extends({},e);return n.details=void 0,n.attrs=new AttrList(n.attrs),n.url=n.attrs.URI=performUriReplacement(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",s),n.groupId=n.attrs["GROUP-ID"]=t[i],n.attrs["PATHWAY-ID"]=r,n}));e.push(...n)}))}function performUriReplacement(e,t,s,r){const{HOST:i,PARAMS:n,[s]:a}=r;let o;t&&(o=null==a?void 0:a[t],o&&(e=o));const l=new self.URL(e);return i&&!o&&(l.host=i),n&&Object.keys(n).sort().forEach((e=>{e&&l.searchParams.set(e,n[e])})),l.href}class EMEController extends Logger{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=EMEController.CDMCleanupPromise?[EMEController.CDMCleanupPromise]:[],this.onMediaEncrypted=e=>{const{initDataType:t,initData:s}=e,r=`"${e.type}" event: init data type: "${t}"`;if(this.debug(r),null===s)return;let i,n;if("sinf"===t&&this.getLicenseServerUrl(KeySystems.FAIRPLAY)){const e=bin2str(new Uint8Array(s));try{const t=parseSinf(base64Decode(JSON.parse(e).sinf));if(!t)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");i=t.subarray(8,24),n=KeySystems.FAIRPLAY}catch(e){return void this.warn(`${r} Failed to parse sinf: ${e}`)}}else if(this.getLicenseServerUrl(KeySystems.WIDEVINE)){const e=parseMultiPssh(s);let t=Object.keys(this.keySystemAccessPromises);t.length||(t=getKeySystemsForConfig(this.config));const a=e.filter((e=>{const s=e.systemId?keySystemIdToKeySystemDomain(e.systemId):null;return!!s&&t.indexOf(s)>-1}))[0];if(!a)return void(0===e.length||e.some((e=>!e.systemId))?this.warn(`${r} contains incomplete or invalid pssh data`):this.log(`ignoring ${r} for ${e.map((e=>keySystemIdToKeySystemDomain(e.systemId))).join(",")} pssh data in favor of playlist keys`));if(n=keySystemIdToKeySystemDomain(a.systemId),0===a.version&&a.data)if(n===KeySystems.WIDEVINE){const e=a.data.length-22;i=a.data.subarray(e,e+16)}else n===KeySystems.PLAYREADY&&(i=parsePlayReadyWRM(a.data))}if(!n||!i)return;const a=Hex.hexDump(i),{keyIdToKeySessionPromise:o,mediaKeySessions:l}=this;let d=o[a];for(let e=0;e<l.length;e++){const r=l[e],n=r.decryptdata;if(!n.keyId)continue;const h=Hex.hexDump(n.keyId);if(a===h||-1!==n.uri.replace(/-/g,"").indexOf(a)){if(d=o[h],n.pssh)break;delete o[h],n.pssh=new Uint8Array(s),n.keyId=i,d=o[a]=d.then((()=>this.generateRequestWithPreferredKeySession(r,t,s,"encrypted-event-key-match"))),d.catch((e=>this.handleError(e)));break}}d||(d=o[a]=this.getKeySystemSelectionPromise([n]).then((({keySystem:e,mediaKeys:r})=>{var n;this.throwIfDestroyed();const o=new LevelKey("ISO-23001-7",a,null!=(n=keySystemDomainToKeySystemFormat(e))?n:"");return o.pssh=new Uint8Array(s),o.keyId=i,this.attemptSetMediaKeys(e,r).then((()=>{this.throwIfDestroyed();const i=this.createMediaKeySessionContext({decryptdata:o,keySystem:e,mediaKeys:r});return this.generateRequestWithPreferredKeySession(i,t,s,"encrypted-event-no-match")}))})),d.catch((e=>this.handleError(e))))},this.onWaitingForKey=e=>{this.log(`"${e.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(Events.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(Events.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(Events.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(Events.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:s}=this.config,r=t[e];return r?r.licenseUrl:e===KeySystems.WIDEVINE&&s?s:void 0}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(void 0===t)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,s=t[e];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,s=(e,t,s)=>!!e&&s.indexOf(e)===t,r=t.map((e=>e.audioCodec)).filter(s),i=t.map((e=>e.videoCodec)).filter(s);return r.length+i.length===0&&i.push("avc1.42e01e"),new Promise(((t,s)=>{const n=e=>{const a=e.shift();this.getMediaKeysPromise(a,r,i).then((e=>t({keySystem:a,mediaKeys:e}))).catch((t=>{e.length?n(e):s(t instanceof EMEKeyError?t:new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))}))};n(e)}))}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:s}=this.config;if("function"!=typeof s){let e=`Configured requestMediaKeySystemAccess is not a function ${s}`;return null===requestMediaKeySystemAccess&&"http:"===self.location.protocol&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(e))}return s(e,t)}getMediaKeysPromise(e,t,s){const r=getSupportedMediaKeySystemConfigurations(e,t,s,this.config.drmSystemOptions),i=this.keySystemAccessPromises[e];let n=null==i?void 0:i.keySystemAccess;if(!n){this.log(`Requesting encrypted media "${e}" key-system access with config: ${JSON.stringify(r)}`),n=this.requestMediaKeySystemAccess(e,r);const t=this.keySystemAccessPromises[e]={keySystemAccess:n};return n.catch((t=>{this.log(`Failed to obtain access to key-system "${e}": ${t}`)})),n.then((s=>{this.log(`Access for key-system "${s.keySystem}" obtained`);const r=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),t.mediaKeys=s.createMediaKeys().then((t=>(this.log(`Media-keys created for "${e}"`),r.then((s=>s?this.setMediaKeysServerCertificate(t,e,s):t))))),t.mediaKeys.catch((t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)})),t.mediaKeys}))}return n.then((()=>i.mediaKeys))}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:s}){this.log(`Creating key-system session "${t}" keyId: ${Hex.hexDump(e.keyId||[])}`);const r=s.createSession(),i={decryptdata:e,keySystem:t,mediaKeys:s,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(i),i}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const s=this.createMediaKeySessionContext(e),r=this.getKeyIdString(t),i="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(s,i,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw new Error("keyId is null");return Hex.hexDump(e.keyId)}updateKeySession(e,t){var s;const r=e.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyID ${Hex.hexDump((null==(s=e.decryptdata)?void 0:s.keyId)||[])}\n } (data length: ${t?t.byteLength:t})`),r.update(t)}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise(((t,s)=>{const r=getKeySystemsForConfig(this.config),i=e.map(keySystemFormatToKeySystemDomain).filter((e=>!!e&&-1!==r.indexOf(e)));return this.getKeySystemSelectionPromise(i).then((({keySystem:e})=>{const r=keySystemDomainToKeySystemFormat(e);r?t(r):s(new Error(`Unable to find format for key-system "${e}"`))})).catch(s)}))}loadKey(e){const t=e.keyInfo.decryptdata,s=this.getKeyIdString(t),r=`(keyId: ${s} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);let i=this.keyIdToKeySessionPromise[s];if(!i){i=this.getKeySystemForKeyPromise(t).then((({keySystem:s,mediaKeys:i})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(s,i).then((()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:s,mediaKeys:i,decryptdata:t})))))));(this.keyIdToKeySessionPromise[s]=i.then((e=>{const s=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(e,"cenc",s,"playlist-key")}))).catch((e=>this.handleError(e)))}return i}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof EMEKeyError?this.hls.trigger(Events.ERROR,e.data):this.hls.trigger(Events.ERROR,{type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),s=this.keyIdToKeySessionPromise[t];if(!s){const t=keySystemFormatToKeySystemDomain(e.keyFormat),s=t?[t]:getKeySystemsForConfig(this.config);return this.attemptKeySystemAccess(s)}return s}getKeySystemSelectionPromise(e){if(e.length||(e=getKeySystemsForConfig(this.config)),0===e.length)throw new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const r=Promise.all(s).then((()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)}));return this.setMediaKeysQueue.push(r),r.then((()=>{this.log(`Media-keys set for "${e}"`),s.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter((e=>-1===s.indexOf(e)))}))}generateRequestWithPreferredKeySession(e,t,s,r){var i,n;const a=null==(i=this.config.drmSystems)||null==(n=i[e.keySystem])?void 0:n.generateRequest;if(a)try{const r=a.call(this.hls,t,s,e);if(!r)throw new Error("Invalid response from configured generateRequest filter");t=r.initDataType,s=r.initData?r.initData:null,e.decryptdata.pssh=s?new Uint8Array(s):null}catch(e){var o;if(this.warn(e.message),null!=(o=this.hls)&&o.config.debug)throw e}if(null===s)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);const l=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${r}": ${l} (init data type: ${t} length: ${s?s.byteLength:null})`);const d=new EventEmitter,h=e._onmessage=t=>{const s=e.mediaKeysSession;if(!s)return void d.emit("error",new Error("invalid state"));const{messageType:r,message:i}=t;this.log(`"${r}" message event for session "${s.sessionId}" message size: ${i.byteLength}`),"license-request"===r||"license-renewal"===r?this.renewLicense(e,i).catch((e=>{d.eventNames().length?d.emit("error",e):this.handleError(e)})):"license-release"===r?e.keySystem===KeySystems.FAIRPLAY&&(this.updateKeySession(e,strToUtf8array("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${r}"`)},c=e._onkeystatuseschange=t=>{if(!e.mediaKeysSession)return void d.emit("error",new Error("invalid state"));this.onKeyStatusChange(e);const s=e.keyStatus;d.emit("keyStatus",s),"expired"===s&&(this.warn(`${e.keySystem} expired for key ${l}`),this.renewKeySession(e))};e.mediaKeysSession.addEventListener("message",h),e.mediaKeysSession.addEventListener("keystatuseschange",c);const u=new Promise(((e,t)=>{d.on("error",t),d.on("keyStatus",(s=>{s.startsWith("usable")?e():"output-restricted"===s?t(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===s?t(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${s}"`)):"expired"===s?t(new Error("key expired while generating request")):this.warn(`unhandled key status change "${s}"`)}))}));return e.mediaKeysSession.generateRequest(t,s).then((()=>{var t;this.log(`Request generated for key-session "${null==(t=e.mediaKeysSession)?void 0:t.sessionId}" keyId: ${l}`)})).catch((e=>{throw new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_NO_SESSION,error:e,fatal:!1},`Error generating key-session request: ${e}`)})).then((()=>u)).catch((t=>{throw d.removeAllListeners(),this.removeSession(e),t})).then((()=>(d.removeAllListeners(),e)))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach(((t,s)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${Hex.hexDump("buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s))} session keyId: ${Hex.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t}))}fetchServerCertificate(e){const t=this.config,s=new(0,t.loader)(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise(((i,n)=>{const a={responseType:"arraybuffer",url:r},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(e,t,s,r)=>{i(e.data)},onError:(t,s,i,o)=>{n(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:i,response:_objectSpread2({url:a.url,data:void 0},t)},`"${e}" certificate request failed (${r}). Status: ${t.code} (${t.text})`))},onTimeout:(t,s,i)=>{n(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:i,response:{url:a.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(e,t,s)=>{n(new Error("aborted"))}};s.load(a,l,d)}))):Promise.resolve()}setMediaKeysServerCertificate(e,t,s){return new Promise(((r,i)=>{e.setServerCertificate(s).then((i=>{this.log(`setServerCertificate ${i?"success":"not supported by CDM"} (${null==s?void 0:s.byteLength}) on "${t}"`),r(e)})).catch((e=>{i(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))}))}))}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then((t=>this.updateKeySession(e,new Uint8Array(t)).catch((e=>{throw new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:e,fatal:!0},e.message)}))))}unpackPlayReadyKeyMessage(e,t){const s=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!s.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const r=(new DOMParser).parseFromString(s,"application/xml"),i=r.querySelectorAll("HttpHeader");if(i.length>0){let t;for(let s=0,r=i.length;s<r;s++){var n,a;t=i[s];const r=null==(n=t.querySelector("name"))?void 0:n.textContent,o=null==(a=t.querySelector("value"))?void 0:a.textContent;r&&o&&e.setRequestHeader(r,o)}}const o=r.querySelector("Challenge"),l=null==o?void 0:o.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return strToUtf8array(atob(l))}setupLicenseXHR(e,t,s,r){const i=this.config.licenseXhrSetup;return i?Promise.resolve().then((()=>{if(!s.decryptdata)throw new Error("Key removed");return i.call(this.hls,e,t,s,r)})).catch((n=>{if(!s.decryptdata)throw n;return e.open("POST",t,!0),i.call(this.hls,e,t,s,r)})).then((s=>{e.readyState||e.open("POST",t,!0);return{xhr:e,licenseChallenge:s||r}})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){const s=this.config.keyLoadPolicy.default;return new Promise(((r,i)=>{const n=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${n}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return i(new Error("invalid state"));if(4===a.readyState)if(200===a.status){this._requestLicenseFailureCount=0;let t=a.response;this.log(`License received ${t instanceof ArrayBuffer?t.byteLength:t}`);const s=this.config.licenseResponseCallback;if(s)try{t=s.call(this.hls,a,n,e)}catch(e){this.error(e)}r(t)}else{const o=s.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)i(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:{url:n,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${n}). Status: ${a.status} (${a.statusText})`));else{const s=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${s} attempts left`),this.requestLicense(e,t).then(r,i)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=a,this.setupLicenseXHR(a,n,e,t).then((({xhr:t,licenseChallenge:s})=>{e.keySystem==KeySystems.PLAYREADY&&(s=this.unpackPlayReadyKeyMessage(t,s)),t.send(s)}))}))}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const s=t.media;this.media=s,s.removeEventListener("encrypted",this.onMediaEncrypted),s.removeEventListener("waitingforkey",this.onWaitingForKey),s.addEventListener("encrypted",this.onMediaEncrypted),s.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){var e;const t=this.media,s=this.mediaKeySessions;t&&(t.removeEventListener("encrypted",this.onMediaEncrypted),t.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},LevelKey.clearKeyUriToKeyIdMap();const r=s.length;EMEController.CDMCleanupPromise=Promise.all(s.map((e=>this.removeSession(e))).concat(null==t||null==(e=t.setMediaKeys(null))?void 0:e.catch((e=>{var t;this.log(`Could not clear media keys: ${e}`),null==(t=this.hls)||t.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${e}`)})})))).then((()=>{r&&(this.log("finished closing key sessions and clearing media keys"),s.length=0)})).catch((e=>{var t;this.log(`Could not close sessions and clear media keys: ${e}`),null==(t=this.hls)||t.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${e}`)})}))}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(t&&this.config.emeEnabled&&!this.keyFormatPromise){const e=t.reduce(((e,t)=>(-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e)),[]);this.log(`Selecting key-system from session-keys ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:s}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(e);return r>-1&&this.mediaKeySessions.splice(r,1),t.remove().catch((e=>{var t;this.log(`Could not remove session: ${e}`),null==(t=this.hls)||t.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${e}`)})})).then((()=>t.close())).catch((e=>{var t;this.log(`Could not close session: ${e}`),null==(t=this.hls)||t.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${e}`)})}))}}}EMEController.CDMCleanupPromise=void 0;class EMEKeyError extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}class FPSController{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const s=this.hls.config;if(s.capLevelOnFPSDrop){const e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&"function"==typeof e.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){const r=performance.now();if(t){if(this.lastTime){const e=r-this.lastTime,i=s-this.lastDroppedFrames,n=t-this.lastDecodedFrames,a=1e3*i/e,o=this.hls;if(o.trigger(Events.FPS_DROP,{currentDropped:i,currentDecoded:n,totalDroppedFrames:s}),a>0&&i>o.config.fpsDroppedMonitoringThreshold*n){let e=o.currentLevel;o.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=e)&&(e-=1,o.trigger(Events.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:o.currentLevel}),o.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=s,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}function sendAddTrackEvent(e,t){let s;try{s=new Event("addtrack")}catch(e){s=document.createEvent("Event"),s.initEvent("addtrack",!1,!1)}s.track=e,t.dispatchEvent(s)}function addCueToTrack(e,t){const s=e.mode;if("disabled"===s&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(s){logger.debug(`[texttrack-utils]: ${s}`);try{const s=new self.TextTrackCue(t.startTime,t.endTime,t.text);s.id=t.id,e.addCue(s)}catch(e){logger.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}"disabled"===s&&(e.mode=s)}function clearCurrentCues(e,t){const s=e.mode;if("disabled"===s&&(e.mode="hidden"),e.cues)for(let s=e.cues.length;s--;)t&&e.cues[s].removeEventListener("enter",t),e.removeCue(e.cues[s]);"disabled"===s&&(e.mode=s)}function removeCuesInRange(e,t,s,r){const i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues&&e.cues.length>0){const i=getCuesInRange(e.cues,t,s);for(let t=0;t<i.length;t++)r&&!r(i[t])||e.removeCue(i[t])}"disabled"===i&&(e.mode=i)}function getFirstCueIndexAfterTime(e,t){if(t<e[0].startTime)return 0;const s=e.length-1;if(t>e[s].endTime)return-1;let r=0,i=s;for(;r<=i;){const n=Math.floor((i+r)/2);if(t<e[n].startTime)i=n-1;else{if(!(t>e[n].startTime&&r<s))return n;r=n+1}}return e[r].startTime-t<t-e[i].startTime?r:i}function getCuesInRange(e,t,s){const r=[],i=getFirstCueIndexAfterTime(e,t);if(i>-1)for(let n=i,a=e.length;n<a;n++){const i=e[n];if(i.startTime>=t&&i.endTime<=s)r.push(i);else if(i.startTime>s)return r}return r}function filterSubtitleTracks(e){const t=[];for(let s=0;s<e.length;s++){const r=e[s];"subtitles"!==r.kind&&"captions"!==r.kind||!r.label||t.push(e[s])}return t}class SubtitleTrackController extends BasePlaylistController{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=null;const t=filterSubtitleTracks(this.media.textTracks);for(let s=0;s<t.length;s++)if("hidden"===t[s].mode)e=t[s];else if("showing"===t[s].mode){e=t[s];break}const s=this.findTrackForTextTrack(e);this.subtitleTrack!==s&&this.setSubtitleTrack(s)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Events.LEVEL_LOADING,this.onLevelLoading,this),e.on(Events.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Events.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(Events.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Events.LEVEL_LOADING,this.onLevelLoading,this),e.off(Events.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Events.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(Events.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const s=this.media;if(!s)return;const r=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,r)return;filterSubtitleTracks(s.textTracks).forEach((e=>{clearCurrentCues(e)}))}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:s,groupId:r,details:i}=t,n=this.tracksInGroup[s];if(!n||n.groupId!==r)return void this.warn(`Subtitle track with id:${s} and group:${r} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=t.details,this.log(`Subtitle track ${s} "${n.name}" lang:${n.lang} group:${r} loaded [${i.startSN}-${i.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.subtitleGroups||null,r=this.groupIds;let i=this.currentTrack;if(!s||(null==r?void 0:r.length)!==(null==s?void 0:s.length)||null!=s&&s.some((e=>-1===(null==r?void 0:r.indexOf(e))))){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const e=this.tracks.filter((e=>!s||-1!==s.indexOf(e.groupId)));if(e.length)this.selectDefaultTrack&&!e.some((e=>e.default))&&(this.selectDefaultTrack=!1),e.forEach(((e,t)=>{e.id=t}));else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=e;const t=this.hls.config.subtitlePreference;if(!i&&t){this.selectDefaultTrack=!1;const s=findMatchingOption(t,e);if(s>-1)i=e[s];else{const e=findMatchingOption(t,this.tracks);i=this.tracks[e]}}let r=this.findTrackId(i);-1===r&&i&&(r=this.findTrackId(null));const n={subtitleTracks:e};this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${null==s?void 0:s.join(",")}" group-id`),this.hls.trigger(Events.SUBTITLE_TRACKS_UPDATED,n),-1!==r&&-1===this.trackId&&this.setSubtitleTrack(r)}}findTrackId(e){const t=this.tracksInGroup,s=this.selectDefaultTrack;for(let r=0;r<t.length;r++){const i=t[r];if((!s||i.default)&&(s||e)&&(!e||matchesOption(i,e)))return r}if(e){for(let s=0;s<t.length;s++){const r=t[s];if(mediaAttributesIdentical(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<t.length;s++){const r=t[s];if(mediaAttributesIdentical(e.attrs,r.attrs,["LANGUAGE"]))return s}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){if(subtitleTrackMatchesTextTrack(t[s],e))return s}}return-1}onError(e,t){!t.fatal&&t.context&&(t.context.type!==PlaylistContextType.SUBTITLE_TRACK||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(-1===e.id)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const s=this.currentTrack;if(s&&matchesOption(e,s))return s;const r=findMatchingOption(e,this.tracksInGroup);if(r>-1){const e=this.tracksInGroup[r];return this.setSubtitleTrack(r),e}if(s)return null;{const s=findMatchingOption(e,t);if(s>-1)return t[s]}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,r=e.groupId,i=this.getUrlWithDirectives(e.url,t),n=e.details,a=null==n?void 0:n.age;this.log(`Loading subtitle ${s} "${e.name}" lang:${e.lang} group:${r}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${i}`),this.hls.trigger(Events.SUBTITLE_TRACK_LOADING,{url:i,id:s,groupId:r,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=filterSubtitleTracks(e.textTracks),s=this.currentTrack;let r;if(s&&(r=t.filter((e=>subtitleTrackMatchesTextTrack(s,e)))[0],r||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(t).forEach((e=>{"disabled"!==e.mode&&e!==r&&(e.mode="disabled")})),r){const e=this.subtitleDisplay?"showing":"hidden";r.mode!==e&&(r.mode=e)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=e);if(e<-1||e>=t.length||!isFiniteNumber(e))return void this.warn(`Invalid subtitle track id: ${e}`);this.selectDefaultTrack=!1;const s=this.currentTrack,r=t[e]||null;if(this.trackId=e,this.currentTrack=r,this.toggleTrackModes(),!r)return void this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH,{id:e});const i=!!r.details&&!r.details.live;if(e===this.trackId&&r===s&&i)return;this.log(`Switching to subtitle-track ${e}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));const{id:n,groupId:a="",name:o,type:l,url:d}=r;this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH,{id:n,groupId:a,name:o,type:l,url:d});const h=this.switchParams(r.url,null==s?void 0:s.details,r.details);this.loadPlaylist(h)}}function hash(e){let t=5381,s=e.length;for(;s;)t=33*t^e.charCodeAt(--s);return(t>>>0).toString()}const ALIGNED_END_THRESHOLD_SECONDS=.02;let TimelineOccupancy=function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e}({});function generateAssetIdentifier(e,t,s){return`${e.identifier}-${s+1}-${hash(t)}`}class InterstitialEvent{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;null==(e=this.assetListLoader)||e.destroy(),this.assetListLoader=this.error=void 0}isAssetPastPlayoutLimit(e){if(e>=this.assetList.length)return!0;const t=this.playoutLimit;if(e<=0||isNaN(t))return!1;return this.assetList[e].startOffset>t}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return getSnapToFragmentTime(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get resumptionOffset(){const e=this.resumeOffset,t=isFiniteNumber(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return getSnapToFragmentTime(e,t)}return e}get appendInPlace(){return!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||0!==this.startTime&&!this.snapOptions.out||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<.02))}set appendInPlace(e){this.appendInPlaceStarted||(this.appendInPlaceDisabled=!e)}get timelineStart(){return null!==this._timelineStart?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return t=this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?TimelineOccupancy.Range:TimelineOccupancy.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}toString(){return eventToString(this)}}function getSnapToFragmentTime(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<.02)?t.start:t.start+t.duration}function getInterstitialUrl(e,t,s){const r=new self.URL(e,s);return"data:"!==r.protocol&&r.searchParams.set("_HLS_primary_id",t),r}function eventToString(e){return`["${e.identifier}" ${e.cue.pre?"<pre>":e.cue.post?"<post>":""}${e.timelineStart.toFixed(2)}-${e.resumeTime.toFixed(2)}]`}function eventAssetToString(e){const t=e.timelineStart,s=e.duration||0;return`["${e.identifier}" ${t.toFixed(2)}-${(t+s).toFixed(2)}]`}class HlsAssetPlayer{constructor(e,t,s,r){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this.playoutOffset=0,this.checkPlayout=()=>{const e=this.interstitial.playoutLimit;this.playoutOffset+this.currentTime>=e&&this.hls.trigger(Events.PLAYOUT_LIMIT_REACHED,{})};const i=this.hls=new e(t);this.interstitial=s,this.assetItem=r;let n=r.uri;try{n=getInterstitialUrl(n,i.sessionId).href}catch(e){}i.loadSource(n);const a=()=>{this.hasDetails=!0};i.once(Events.LEVEL_LOADED,a),i.once(Events.AUDIO_TRACK_LOADED,a),i.once(Events.SUBTITLE_TRACK_LOADED,a),i.on(Events.MEDIA_ATTACHING,((e,{media:t})=>{this.removeMediaListeners(),this.mediaAttached=t;const s=this.interstitial;var i;s.playoutLimit&&(this.playoutOffset=(null==(i=s.assetList[s.assetList.indexOf(r)])?void 0:i.startOffset)||0,t.addEventListener("timeupdate",this.checkPlayout))}))}get destroyed(){var e;return!(null!=(e=this.hls)&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){return this.hls.media}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return 0;const t=BufferHelper.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):0}get duration(){var e;const t=null==(e=this.assetItem)?void 0:e.duration;return t||0}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get timelineOffset(){return this.hls.config.timelineOffset||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const s=e-t;if(Math.abs(s)>1/9e4){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,s=this.duration;return Math.min(Math.max(0,e-t),s)}removeMediaListeners(){const e=this.mediaAttached;e&&e.removeEventListener("timeupdate",this.checkPlayout)}destroy(){this.removeMediaListeners(),this.hls.destroy(),this.hls=this.interstitial=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){this.hls.attachMedia(e)}detachMedia(){this.removeMediaListeners(),this.hls.detachMedia()}resumeBuffering(){this.hls.resumeBuffering()}pauseBuffering(){this.hls.pauseBuffering()}transferMedia(){return this.hls.transferMedia()}on(e,t,s){this.hls.on(e,t)}once(e,t,s){this.hls.once(e,t)}off(e,t,s){this.hls.off(e,t)}toString(){return`HlsAssetPlayer: ${eventAssetToString(this.assetItem)} ${this.hls.sessionId} ${this.interstitial.appendInPlace?"append-in-place":""}`}}const ABUTTING_THRESHOLD_SECONDS=.033;class InterstitialsSchedule extends Logger{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach((e=>e.reset())),this.events=this.items=null}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let s=-1;e.nextEvent?s=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(s=this.findEventIndex(e.previousEvent.identifier)+1);const r=this.items;if(r)for(r[s]||(void 0===t&&(t=e.start),s=this.findItemIndexAtTime(t));s>=0&&null!=(i=r[s])&&i.event;){var i;s--}return s}findItemIndexAtTime(e,t){const s=this.items;if(s)for(let r=0;r<s.length;r++){let i=s[r];if(t&&"primary"!==t&&(i=i[t]),e===i.start||e>i.start&&e<i.end)return r}return-1}findJumpRestrictedIndex(e,t){const s=this.items;if(s)for(let r=e;r<=t&&s[r];r++){const e=s[r].event;if(null!=e&&e.restrictions.jump&&!e.appendInPlace)return r}return-1}findEventIndex(e){const t=this.items;if(t)for(let r=t.length;r--;){var s;if((null==(s=t[r].event)?void 0:s.identifier)===e)return r}return-1}findAssetIndex(e,t){const s=e.assetList,r=s.length;if(r>1)for(let e=0;e<r;e++){const r=s[e];if(!r.error){const s=r.timelineStart;if(t===s||t>s&&t<s+(r.duration||0))return e}}return 0}get assetIdAtEnd(){var e,t;const s=null==(e=this.items)||null==(t=e[this.length-1])?void 0:t.event;if(s){const e=s.assetList,t=e[e.length-1];if(t)return t.identifier}return null}parseInterstitialDateRanges(e){const t=e.main.details,{dateRanges:s}=t,r=this.events,i=this.parseDateRanges(s,{url:t.url}),n=Object.keys(s),a=r?r.filter((e=>!n.includes(e.identifier))):[];i.length&&i.sort(((e,t)=>{const s=e.cue.pre,r=e.cue.post,i=t.cue.pre,n=t.cue.post;if(s&&!i)return-1;if(i&&!s)return 1;if(r&&!n)return 1;if(n&&!r)return-1;if(!(s||i||r||n)){const s=e.startTime,r=t.startTime;if(s!==r)return s-r}return e.dateRange.tagOrder-t.dateRange.tagOrder})),this.events=i,a.forEach((e=>{this.removeEvent(e)})),this.updateSchedule(e,a)}updateSchedule(e,t=[]){const s=this.events||[];if(s.length||t.length||this.length<2){const r=this.items,i=this.parseSchedule(s,e);(t.length||(null==r?void 0:r.length)!==i.length||i.some(((e,t)=>Math.abs(e.playout.start-r[t].playout.start)>.005||Math.abs(e.playout.end-r[t].playout.end)>.005)))&&(this.items=i,this.onScheduleUpdate(t,r))}}parseDateRanges(e,t){const s=[],r=Object.keys(e);for(let i=0;i<r.length;i++){const n=r[i],a=e[n];if(a.isInterstitial){let e=this.eventMap[n];e?e.setDateRange(a):(e=new InterstitialEvent(a,t),this.eventMap[n]=e),s.push(e)}}return s}parseSchedule(e,t){const s=[],r=t.main.details,i=r.live?1/0:r.edge;let n=0;if((e=e.filter((e=>!(e.error||e.cue.once&&e.hasPlayed)))).length){this.resolveOffsets(e,t);let r=0,o=0;if(e.forEach(((t,a)=>{const l=t.cue.pre,d=t.cue.post,h=e[a-1]||null,c=t.appendInPlace,u=d?i:t.startOffset,f=t.duration,g=t.timelineOccupancy===TimelineOccupancy.Range?f:0,m=t.resumptionOffset,p=(null==h?void 0:h.startTime)===u,E=u+t.cumulativeDuration;let y=c?E+f:u+m;if(l||!d&&u<=0){const e=o;o+=g,t.timelineStart=E;const r=n;n+=f,s.push({event:t,start:E,end:y,playout:{start:r,end:n},integrated:{start:e,end:o}})}else{if(!(u<=i))return;{if(!p){const i=u-r;if(i>.033){const l=r,d=o;o+=i;const h=n;n+=i;const c={previousEvent:e[a-1]||null,nextEvent:t,start:l,end:l+i,playout:{start:h,end:n},integrated:{start:d,end:o}};s.push(c)}else i>0&&h&&(h.cumulativeDuration+=i,s[s.length-1].end=u)}d&&(y=E),t.timelineStart=E;const i=o;o+=g;const l=n;n+=f,s.push({event:t,start:E,end:y,playout:{start:l,end:n},integrated:{start:i,end:o}})}}const v=t.resumeTime;r=d||v>i?i:v})),r<i){var a;const e=r,t=o,l=i-r;o+=l;const d=n;n+=l,s.push({previousEvent:(null==(a=s[s.length-1])?void 0:a.event)||null,nextEvent:null,start:r,end:e+l,playout:{start:d,end:n},integrated:{start:t,end:o}})}this.setDurations(i,n,o)}else{const e=0;s.push({previousEvent:null,nextEvent:null,start:e,end:i,playout:{start:e,end:i},integrated:{start:e,end:i}}),this.setDurations(i,i,i)}return s}setDurations(e,t,s){this.durations={primary:e,playout:t,integrated:s}}resolveOffsets(e,t){const s=t.main.details,r=s.live?1/0:s.edge;let i=0,n=-1;e.forEach(((a,o)=>{const l=a.cue.pre,d=a.cue.post,h=l?0:d?r:a.startTime;this.updateAssetDurations(a);if(n===h?a.cumulativeDuration=i:(i=0,n=h),!d&&a.snapOptions.in&&(a.resumeAnchor=findFragmentByPTS(null,s.fragments,a.startOffset+a.resumptionOffset,0,0)||void 0),a.appendInPlace&&!a.appendInPlaceStarted){this.primaryCanResumeInPlaceAt(a,t)||(a.appendInPlace=!1)}if(!a.appendInPlace)for(let t=o-1;o--;){e[t+1].startTime-e[t].resumeTime<.033&&(e[t].appendInPlace=!1)}const c=isFiniteNumber(a.resumeOffset)?a.resumeOffset:a.duration;i+=c}))}primaryCanResumeInPlaceAt(e,t){const s=e.resumeTime,r=e.startTime+e.resumptionOffset;return Math.abs(s-r)>.02?(this.log(`"${e.identifier}" resumption ${s} not aligned with estimated timeline end ${r}`),!1):t?!Object.keys(t).some((r=>{const i=t[r].details,n=i.edge;if(s>n)return this.log(`"${e.identifier}" resumption ${s} past ${r} playlist end ${n}`),!0;const a=findFragmentByPTS(null,i.fragments,s);if(!a)return this.log(`"${e.identifier}" resumption ${s} does not align with any fragments in ${r} playlist`),!0;const o="audio"===r?.175:0;return!(Math.abs(a.start-s)<.02||Math.abs(a.end-s)<.02+o)&&(this.log(`"${e.identifier}" resumption ${s} not aligned with ${r} fragment bounds (${a.start}-${a.end} sn: ${a.sn} cc: ${a.cc})`),!0)})):(this.log(`"${e.identifier}" resumption ${s} can not be aligned with media (none selected)`),!1)}updateAssetDurations(e){const t=e.timelineStart;let s=0,r=!1,i=!1;e.assetList.forEach(((e,n)=>{const a=t+s;e.startOffset=s,e.timelineStart=a,r||(r=null===e.duration),i||(i=!!e.error);const o=e.error?0:e.duration||0;s+=o})),e.duration=r&&!i?Math.max(s,e.duration):s}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function segmentToString(e){return`[${e.event?'"'+e.event.identifier+'"':"primary"}: ${e.start.toFixed(2)}-${e.end.toFixed(2)}]`}class AssetListLoader{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const s=e.assetListUrl;let r;try{r=getInterstitialUrl(s,this.hls.sessionId,e.baseUrl)}catch(t){const r=this.assignAssetListError(e,ErrorDetails.ASSET_LIST_LOAD_ERROR,t,s);return void this.hls.trigger(Events.ERROR,r)}if(t&&!e.cue.pre&&!e.cue.post&&"data:"!==r.protocol){const s=t-e.startTime;s>0&&r.searchParams.set("_HLS_start_offset",""+Math.round(1e3*s)/1e3)}const i=this.hls.config,n=new(0,i.loader)(i),a={responseType:"json",url:r.href},o=i.interstitialAssetListLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(t,s,r,i)=>{const n=t.data,a=null==n?void 0:n.ASSETS;if(Array.isArray(a))e.assetListResponse=n,this.hls.trigger(Events.ASSET_LIST_LOADED,{event:e,assetListResponse:n,networkDetails:i});else{const t=this.assignAssetListError(e,ErrorDetails.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),r.url,s,i);this.hls.trigger(Events.ERROR,t)}},onError:(t,s,r,i)=>{const n=this.assignAssetListError(e,ErrorDetails.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${t.code} ${t.text} (${s.url})`),s.url,i,r);this.hls.trigger(Events.ERROR,n)},onTimeout:(t,s,r)=>{const i=this.assignAssetListError(e,ErrorDetails.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${s.url})`),s.url,t,r);this.hls.trigger(Events.ERROR,i)}};return n.load(a,l,d),this.hls.trigger(Events.ASSET_LIST_LOADING,{event:e}),n}assignAssetListError(e,t,s,r,i,n){return e.error=s,{type:ErrorTypes.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:r,error:s,networkDetails:n,stats:i}}}function playWithCatch(e){null==e||e.play().catch()}class InterstitialsController extends Logger{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.playingAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const e=this.currentTime;if(void 0===e||this.playbackDisabled)return;const t=e-this.timelinePos;if(Math.abs(t)<1/7056e5)return;const s=t<=-.01;this.timelinePos=e,this.bufferedPos=e,this.checkBuffer();const r=this.playingItem;if(!r)return;if(s&&e<r.start||e>=r.end){var i;const e=this.schedule.findItemIndexAtTime(this.timelinePos);if(!this.isInterstitial(r)&&null!=(i=this.media)&&i.paused&&(this.shouldPlay=!1),!s){const t=this.findItemIndex(r);if(e>t){const s=this.schedule.findJumpRestrictedIndex(t+1,e);if(s>t)return void this.setSchedulePosition(s)}}return void this.setSchedulePosition(e)}const n=this.playingAsset;if(!n){if(this.playingLastItem&&this.isInterstitial(r)){const t=r.event.assetList[0];t&&(this.playingItem=null,this.setScheduleToAssetAtTime(e,t))}return}const a=n.timelineStart,o=n.duration||0;(s&&e<a||e>=a+o)&&this.setScheduleToAssetAtTime(e,n)},this.onTimeupdate=()=>{const e=this.currentTime;if(void 0===e||this.playbackDisabled)return;if(!(e>this.timelinePos))return;e>this.bufferedPos&&this.checkBuffer(),this.timelinePos=e;const t=this.playingItem;if(!t||this.playingLastItem)return;if(e>=t.end){this.timelinePos=t.end;const e=this.findItemIndex(t);this.setSchedulePosition(e+1)}const s=this.playingAsset;if(!s)return;e>=s.timelineStart+(s.duration||0)&&this.setScheduleToAssetAtTime(e,s)},this.onScheduleUpdate=(e,t)=>{const s=this.schedule,r=this.playingItem,i=s.events||[],n=s.items||[],a=s.durations,o=e.map((e=>e.identifier)),l=!(!i.length&&!o.length);l&&(!1===this.hls.config.interstitialAppendInPlace&&i.forEach((e=>e.appendInPlace=!1)),this.log(`INTERSTITIALS_UPDATED (${i.length}): ${i}\nSchedule: ${n.map((e=>segmentToString(e)))}`)),o.length&&this.log(`Removed events ${o}`),this.playerQueue.forEach((e=>{if(e.interstitial.appendInPlace){const t=e.assetItem.timelineStart,s=e.timelineOffset-t;if(s)try{e.timelineOffset=t}catch(r){Math.abs(s)>.02&&this.warn(`${r} ("${e.assetId}" ${e.timelineOffset}->${t})`)}}})),r&&!r.event&&(this.playingItem=this.updateItem(r,this.timelinePos));const d=this.bufferingItem;if(d&&(d.event?this.updateItem(d)||(this.bufferingItem=null,this.clearInterstitial(d.event,null)):this.bufferingItem=this.updateItem(d,this.bufferedPos)),this.waitingItem=this.updateItem(this.waitingItem),e.forEach((e=>{e.assetList.forEach((e=>{this.clearAssetPlayer(e.identifier,null)}))})),l||t){if(this.hls.trigger(Events.INTERSTITIALS_UPDATED,{events:i.slice(0),schedule:n.slice(0),durations:a,removedIds:o}),this.isInterstitial(r)&&o.includes(r.event.identifier))return this.warn(`Interstitial "${r.event.identifier}" removed while playing`),void this.primaryFallback(r.event);this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new AssetListLoader(e),this.schedule=new InterstitialsSchedule(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e.on(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Events.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(Events.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(Events.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(Events.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(Events.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(Events.BUFFER_APPENDED,this.onBufferAppended,this),e.on(Events.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Events.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(Events.MEDIA_ENDED,this.onMediaEnded,this),e.on(Events.ERROR,this.onError,this),e.on(Events.DESTROYING,this.onDestroying,this)}unregisterListeners(){const e=this.hls;e&&(e.off(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Events.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(Events.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(Events.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(Events.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(Events.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(Events.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Events.BUFFER_APPENDED,this.onBufferAppended,this),e.off(Events.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Events.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(Events.MEDIA_ENDED,this.onMediaEnded,this),e.off(Events.ERROR,this.onError,this),e.off(Events.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){this.playerQueue.forEach((e=>e.resumeBuffering()))}pauseBuffering(){this.playerQueue.forEach((e=>e.pauseBuffering()))}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.manager=null,this.hls=this.HlsPlayerClass=this.schedule=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia;e&&this.removeMediaListeners(e)}removeMediaListeners(e){e.removeEventListener("play",this.onPlay),e.removeEventListener("pause",this.onPause),e.removeEventListener("seeking",this.onSeeking),e.removeEventListener("timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const s=this.media=t.media;this.removeMediaListeners(s),s.addEventListener("seeking",this.onSeeking),s.addEventListener("timeupdate",this.onTimeupdate),s.addEventListener("play",this.onPlay),s.addEventListener("pause",this.onPause)}onMediaAttached(e,t){const s=this.playingItem,r=this.detachedData;if(this.detachedData=null,null===s)this.checkStart();else if(!r){this.clearScheduleState();const e=this.findItemIndex(s);this.setSchedulePosition(e)}}clearScheduleState(){this.playingItem=this.bufferingItem=this.waitingItem=this.playingAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const s=!!t.transferMedia,r=this.media;if(this.media=null,!s&&(r&&this.removeMediaListeners(r),this.detachedData)){const e=this.getBufferingPlayer();e&&(this.playingAsset=null,this.bufferingAsset=null,this.bufferingItem=null,this.waitingItem=null,this.detachedData=null,e.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.manager){if(!this.hls||!this.schedule.events)return null;const e=this,t=()=>e.bufferingItem||e.waitingItem,s=()=>e.playingItem||e.waitingItem,r=t=>t?e.getAssetPlayer(t.identifier):t,i=(t,s,i,n,o)=>{if(t){let l=t[s].start;const d=t.event;if(d){if("playout"===s||d.timelineOccupancy!==TimelineOccupancy.Point){const e=r(i);(null==e?void 0:e.interstitial)===d&&(l+=e.assetItem.startOffset+e[o])}}else{l+=("bufferedPos"===n?a():e[n])-t.start}return l}return 0},n=(t,s)=>{if(0!==t&&"primary"!==s&&e.schedule.length){var r;const i=e.schedule.findItemIndexAtTime(t),n=null==(r=e.schedule.items)?void 0:r[i];if(n){return t+(n[s].start-n.start)}}return t},a=()=>{const t=e.bufferedPos;return t===Number.MAX_VALUE?o("primary"):t},o=t=>{var s;return null!=(s=e.primaryDetails)&&s.live?e.primaryDetails.edge:e.schedule.durations[t]},l=(t,n)=>{var a,o;const l=s();if(null!=l&&null!=(a=l.event)&&a.restrictions.skip)return;e.log(`seek to ${t} "${n}"`);const d=s(),h=e.schedule.findItemIndexAtTime(t,n),c=null==(o=e.schedule.items)?void 0:o[h],u=null==d?void 0:d.event,f=null==u?void 0:u.appendInPlace,g=d&&e.itemsMatch(d,c);if(d&&(f||g)){const s=r(e.playingAsset),a=(null==s?void 0:s.media)||e.hls.media;if(a){const r=t-("primary"===n?a.currentTime:i(d,n,e.playingAsset,"timelinePos","currentTime")),o=a.currentTime+r;if(o>=0&&(!s||f||o<=s.duration))return void(a.currentTime=o)}}if(c){let s=t;if("primary"!==n){const e=t-c[n].start;s=c.start+e}const r=!e.isInterstitial(c);if(e.isInterstitial(d)||!r&&!c.event.appendInPlace){if(d){const i=e.findItemIndex(d);if(h>i){const t=e.schedule.findJumpRestrictedIndex(i+1,h);if(t>i)return void e.setSchedulePosition(t)}let a=0;if(r)e.timelinePos=s;else{var m;const e=null==c||null==(m=c.event)?void 0:m.assetList;if(e){const s=t-(c[n]||c).start;for(let t=e.length;t--;){const r=e[t];if(r.duration&&s>=r.startOffset&&s<r.startOffset+r.duration){a=t;break}}}}e.setSchedulePosition(h,a)}}else{const t=e.hls.media;t&&(t.currentTime=s)}}};this.manager={get events(){var t,s;return(null==(t=e.schedule)||null==(s=t.events)?void 0:s.slice(0))||[]},get schedule(){var t,s;return(null==(t=e.schedule)||null==(s=t.items)?void 0:s.slice(0))||[]},get playerQueue(){return e.playerQueue.slice(0)},get bufferingPlayer(){return e.getBufferingPlayer()},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return e.bufferingItem},get playingAsset(){return e.playingAsset},get playingItem(){return e.playingItem},get bufferingIndex(){const s=t();return e.findItemIndex(s)},get playingIndex(){const t=s();return e.findItemIndex(t)},get waitingIndex(){return e.findItemIndex(e.waitingItem)},primary:{get bufferedEnd(){return a()},get currentTime(){const t=e.timelinePos;return t>0?t:0},get duration(){return o("primary")},get seekableStart(){var t;return(null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0},seekTo:e=>l(e,"primary")},playout:{get bufferedEnd(){return i(t(),"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(s(),"playout",e.playingAsset,"timelinePos","currentTime")},get duration(){return o("playout")},get seekableStart(){var t;return n((null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0,"playout")},seekTo:e=>l(e,"playout")},integrated:{get bufferedEnd(){return i(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(s(),"integrated",e.playingAsset,"timelinePos","currentTime")},get duration(){return o("integrated")},get seekableStart(){var t;return n((null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0,"integrated")},seekTo:e=>l(e,"integrated")},skip:()=>{const t=s(),r=null==t?void 0:t.event;if(r&&!r.restrictions.skip){const s=e.findItemIndex(t);if(r.appendInPlace){const e=t.playout.start+t.event.duration;l(e+.001,"playout")}else e.advanceAfterAssetEnded(r,s,1/0)}}}}return this.manager}get playingLastItem(){var e;const t=this.playingItem;if(!this.playbackStarted||!t)return!1;const s=null==(e=this.schedule)?void 0:e.items;return this.itemsMatch(t,s?s[s.length-1]:null)}get playbackStarted(){return null!==this.playingItem}get currentTime(){var e,t,s;if(null===this.mediaSelection)return;const r=this.waitingItem||this.playingItem;if(this.isInterstitial(r)&&!r.event.appendInPlace)return;let i=this.media;!i&&null!=(e=this.bufferingItem)&&null!=(t=e.event)&&t.appendInPlace&&(i=this.primaryMedia);const n=null==(s=i)?void 0:s.currentTime;return void 0!==n&&isFiniteNumber(n)?n:void 0}get primaryMedia(){var e;return this.media||(null==(e=this.detachedData)?void 0:e.media)||null}isInterstitial(e){return!(null==e||!e.event)}retreiveMediaSource(e,t){const s=this.getAssetPlayer(e);s&&this.transferMediaFromPlayer(s,t)}transferMediaFromPlayer(e,t){const s=e.interstitial.appendInPlace,r=e.media;if(s&&r===this.primaryMedia){if(!t||this.isInterstitial(t)&&!t.event.appendInPlace)return void(t&&r&&(this.detachedData={media:r}));const s=e.transferMedia();this.log(`transfer MediaSource from ${e} ${JSON.stringify(s)}`),this.bufferingAsset=null,this.detachedData=s}else t&&r&&(this.shouldPlay||(this.shouldPlay=!r.paused))}transferMediaTo(e,t){var s,r;let i=null;const n=this.hls,a=e!==n,o=a&&e.interstitial.appendInPlace,l=null==(s=this.detachedData)?void 0:s.mediaSource;let d;if(n.media&&o)i=n.transferMedia(),this.detachedData=i,d="Primary";else if(l){const e=this.getBufferingPlayer();e&&(i=e.transferMedia()),d=`${e}`}else d="<unknown>";this.log(`transferring to ${a?e:"Primary"}\nMediaSource ${JSON.stringify(i)} from ${d}`),i||(l?(i=this.detachedData,this.log(`using detachedData: MediaSource ${JSON.stringify(i)}`)):this.detachedData&&this.hls.media!==t||(this.hls.detachMedia(),this.detachedData={media:t}));const h=i&&"mediaSource"in i&&"closed"!==(null==(r=i.mediaSource)?void 0:r.readyState),c=h&&i?i:t;if(this.log(`${h?"transfering MediaSource":"attaching media"} to ${a?e:"Primary"}`),c===i){const t=a&&e.assetId===this.schedule.assetIdAtEnd;c.overrides={duration:this.schedule.duration,endOfStream:!a||t,cueRemoval:!1}}e.attachMedia(c)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e.events;if(!t||this.playbackDisabled)return;-1===this.bufferedPos&&(this.bufferedPos=0);const s=this.timelinePos,r=this.waitingItem;if(-1===s){const s=this.hls.startPosition;if(this.timelinePos=s,t.length&&t[0].cue.pre){const s=e.findEventIndex(t[0].identifier);this.setSchedulePosition(s)}else if(s>=0||!this.primaryLive){const t=this.timelinePos=s>0?s:0,r=e.findItemIndexAtTime(t);this.setSchedulePosition(r)}}else if(r&&!this.playingItem){const t=e.findItemIndex(r);this.setSchedulePosition(t)}}advanceAfterAssetEnded(e,t,s){const r=s+1;if(e.isAssetPastPlayoutLimit(r)||e.assetList[r].error){const e=this.schedule.items;if(e){const s=t+1;if(s>=e.length)return void this.setSchedulePosition(-1);this.setSchedulePosition(s)}}else this.setSchedulePosition(t,r)}setScheduleToAssetAtTime(e,t){const s=this.schedule,r=t.parentIdentifier,i=s.getEvent(r);if(i){const t=s.findEventIndex(r),n=s.findAssetIndex(i,e);this.setSchedulePosition(t,n)}}setSchedulePosition(e,t){const s=this.schedule.items;if(!s||this.playbackDisabled)return;this.log(`setSchedulePosition ${e}, ${t}`);const r=e>=0?s[e]:null,i=this.primaryMedia,n=this.playingItem,a=this.playingLastItem;if(this.isInterstitial(n)){var o;const i=n.event,a=this.playingAsset,l=null==a?void 0:a.identifier,d=l?this.getAssetPlayer(l):null;if(d&&l&&(!this.eventItemsMatch(n,r)||void 0!==t&&l!==(null==(o=i.assetList)?void 0:o[t].identifier))){this.playingAsset=null;const t=i.findAssetIndex(a);this.log(`INTERSTITIAL_ASSET_ENDED ${t+1}/${i.assetList.length} ${eventAssetToString(a)}`),this.hls.trigger(Events.INTERSTITIAL_ASSET_ENDED,{asset:a,assetListIndex:t,event:i,schedule:s.slice(0),scheduleIndex:e,player:d}),this.retreiveMediaSource(l,r),d.media&&!this.detachedData&&d.detachMedia(),this.clearAssetPlayer(l,r)}if(!this.eventItemsMatch(n,r)&&(this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${i} ${segmentToString(n)}`),i.hasPlayed=!0,this.hls.trigger(Events.INTERSTITIAL_ENDED,{event:i,schedule:s.slice(0),scheduleIndex:e}),this.clearInterstitial(i,r),i.cue.once)){if(this.updateSchedule(),r){const e=this.schedule.findItemIndex(r);this.setSchedulePosition(e,t)}return}}const l=this.playerQueue;if(l.length&&l.forEach((t=>{const s=t.interstitial,i=this.schedule.findEventIndex(s.identifier);(i<e||i>e+1)&&this.clearInterstitial(s,r)})),this.isInterstitial(r)){this.timelinePos=Math.min(Math.max(this.timelinePos,r.start),r.end);const a=r.event;void 0===t&&(t=this.schedule.findAssetIndex(a,this.timelinePos));const o=this.waitingItem;let l=this.preloadAssets(a,t);l||this.setBufferingItem(r),this.eventItemsMatch(r,n||o)||(this.waitingItem=r,this.log(`INTERSTITIAL_STARTED ${segmentToString(r)} ${a.appendInPlace?"append in place":""}`),this.hls.trigger(Events.INTERSTITIAL_STARTED,{event:a,schedule:s.slice(0),scheduleIndex:e}));const d=a.assetList.length;if(0===d&&!a.assetListResponse)return void this.log(`Waiting for ASSET-LIST to complete loading ${a}`);if(a.assetListLoader&&(a.assetListLoader.destroy(),a.assetListLoader=void 0),!i)return void this.log(`Waiting for attachMedia to start Interstitial ${a}`);this.waitingItem=null,this.playingItem=r;const h=a.assetList[t];if(!h){const r=s[e+1],i=this.media;return r&&i&&!this.isInterstitial(r)&&i.currentTime<r.start&&(i.currentTime=this.timelinePos=r.start),void this.advanceAfterAssetEnded(a,e,t||0)}if(l||(l=this.getAssetPlayer(h.identifier)),(null===l||l.destroyed)&&(this.warn(`asset ${t+1}/${d} player destroyed ${a}`),l=this.createAssetPlayer(a,h,t)),!this.eventItemsMatch(r,this.bufferingItem)&&a.appendInPlace&&this.isAssetBuffered(h))return;this.startAssetPlayer(l,t,s,e,i),this.shouldPlay&&playWithCatch(l.media)}else null!==r?(this.resumePrimary(r,e,n),this.shouldPlay&&playWithCatch(this.hls.media)):a&&this.isInterstitial(n)&&(this.playingItem=n,n.event.appendInPlace||this.attachPrimary(this.schedule.durations.primary,null))}get playbackDisabled(){return!1===this.hls.config.enableInterstitialPlayback}get primaryDetails(){var e,t;return null==(e=this.mediaSelection)||null==(t=e.main)?void 0:t.details}get primaryLive(){var e;return!(null==(e=this.primaryDetails)||!e.live)}resumePrimary(e,t,s){var r;if(this.playingItem=e,this.playingAsset=null,this.waitingItem=null,this.bufferedToItem(e),this.log(`resuming ${segmentToString(e)}`),null==(r=this.detachedData)||!r.mediaSource){let s=this.timelinePos;(s<e.start||s>=e.end)&&(s=this.getPrimaryResumption(e,t),this.timelinePos=s),this.attachPrimary(s,e)}if(!s)return;const i=this.schedule.items;i&&(this.log(`resumed ${segmentToString(e)}`),this.hls.trigger(Events.INTERSTITIALS_PRIMARY_RESUMED,{schedule:i.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const s=e.start;if(this.primaryLive){const e=this.primaryDetails;if(0===t)return this.hls.startPosition;if(e&&(s<e.fragmentStart||s>e.edge))return this.hls.liveSyncPosition||-1}return s}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);if(null!=t&&t.hls)return t.hls.bufferedToEnd;return BufferHelper.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,s){t?this.setBufferingItem(t):this.bufferingItem=null,this.bufferingAsset=null;const r=this.primaryMedia;if(!r)return;const i=this.hls;i.media?this.checkBuffer():(this.transferMediaTo(i,r),s&&this.startLoadingPrimaryAt(e,s)),s||(this.timelinePos=e,this.startLoadingPrimaryAt(e,s))}startLoadingPrimaryAt(e,t){this.hls.loadingEnabled&&this.hls.startLoad(e,t)}onManifestLoading(){this.stopLoad(),this.schedule.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(Events.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(Events.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(-1===t.level)return;const s=this.hls.levels[t.level],r=_objectSpread2(_objectSpread2({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=r,this.schedule.parseInterstitialDateRanges(r),!this.playingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const s=this.hls.audioTracks[t.id],r=this.mediaSelection;if(!r)return void(this.altSelection=_objectSpread2(_objectSpread2({},this.altSelection),{},{audio:s}));const i=_objectSpread2(_objectSpread2({},r),{},{audio:s});this.mediaSelection=i}onSubtitleTrackUpdated(e,t){const s=this.hls.subtitleTracks[t.id],r=this.mediaSelection;if(!r)return void(this.altSelection=_objectSpread2(_objectSpread2({},this.altSelection),{},{subtitles:s}));const i=_objectSpread2(_objectSpread2({},r),{},{subtitles:s});this.mediaSelection=i}onAudioTrackSwitching(e,t){const s=getBasicSelectionOption(t);this.playerQueue.forEach((e=>e.hls.setAudioOption(t)||e.hls.setAudioOption(s)))}onSubtitleTrackSwitch(e,t){const s=getBasicSelectionOption(t);this.playerQueue.forEach((e=>e.hls.setSubtitleOption(t)||-1!==t.id&&e.hls.setSubtitleOption(s)))}onBufferCodecs(e,t){const s=t.tracks;s&&(this.requiredTracks=s)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const{playingItem:s}=this;if(s&&s!==this.bufferingItem&&!this.isInterstitial(s)){const e=this.timelinePos;this.bufferedPos=e,this.setBufferingItem(s)}}onBufferedToEnd(e){const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let e=0;e<t.length;e++){const r=t[e];if(r.cue.post){var s;const e=this.schedule.findEventIndex(r.identifier),t=null==(s=this.schedule.items)?void 0:s[e];this.isInterstitial(t)&&this.eventItemsMatch(t,this.bufferingItem)&&this.bufferedToItem(t,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const e=this.findItemIndex(t);this.setSchedulePosition(e+1)}}updateItem(e,t){const s=this.schedule.items;if(e&&s){return s[this.findItemIndex(e,t)]||null}return null}itemsMatch(e,t){var s,r;return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&(null==(s=e.nextEvent)?void 0:s.identifier)===(null==(r=t.nextEvent)?void 0:r.identifier))}eventItemsMatch(e,t){var s;return!!t&&(e===t||e.event.identifier===(null==(s=t.event)?void 0:s.identifier))}findItemIndex(e,t){return e?this.schedule.findItemIndex(e,t):-1}updateSchedule(){const e=this.mediaSelection;e&&this.schedule.updateSchedule(e,[])}checkBuffer(){const e=this.schedule.items;if(!e)return;const t=BufferHelper.bufferInfo(this.primaryMedia,this.timelinePos,0);this.updateBufferedPos(t.end,e,0===t.len)}updateBufferedPos(e,t,s){const r=this.schedule,i=this.bufferingItem;if(this.bufferedPos>e)return;if(1===t.length&&this.itemsMatch(t[0],i))return void(this.bufferedPos=e);const n=this.playingItem,a=this.findItemIndex(n);let o=r.findItemIndexAtTime(e);if(this.bufferedPos<e){var l;const s=this.findItemIndex(i),r=Math.min(s+1,t.length-1),n=t[r];if(-1===o&&i&&e>=i.end&&(o=r),r-a>1&&!1===(null==i||null==(l=i.event)?void 0:l.appendInPlace))return;if(this.bufferedPos=e,o>s&&o>a)this.bufferedToItem(n);else{const t=this.primaryDetails;this.primaryLive&&t&&e>t.edge-t.targetduration&&n.start<t.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(n)&&this.preloadAssets(n.event,0)}}else s&&n&&i!==n&&o===a&&this.bufferedToItem(n)}setBufferingItem(e){const t=this.bufferingItem,s=this.schedule,{items:r,events:i}=s;if(r&&i&&(!t||s.findItemIndex(t)!==s.findItemIndex(e))){const s=this.isInterstitial(e),n=this.getBufferingPlayer(),a=n?n.remaining:t?t.end-this.timelinePos:0;this.log(`buffered to boundary ${segmentToString(e)}`+(t?` (${a.toFixed(2)} remaining)`:"")),this.bufferingItem=e,this.bufferedPos=e.start,this.playbackDisabled||(s?this.playerQueue.forEach((e=>e.resumeBuffering())):(this.hls.resumeBuffering(),this.playerQueue.forEach((e=>e.pauseBuffering())))),this.hls.trigger(Events.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:i.slice(0),schedule:r.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}return t}bufferedToItem(e,t=0){const s=this.setBufferingItem(e);if(!this.playbackDisabled)if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(null!==s){this.bufferingAsset=null;const t=this.detachedData;if(t)if(t.mediaSource){const t=!0;this.attachPrimary(e.start,e,t)}else this.preloadPrimary(e);else this.preloadPrimary(e)}}preloadPrimary(e){const t=this.findItemIndex(e),s=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(s)}bufferedToEvent(e,t){const s=e.event,r=0===s.assetList.length&&!s.assetListLoader,i=s.cue.once;if(r||!i){const e=this.preloadAssets(s,t);if(null!=e&&e.interstitial.appendInPlace){const r=s.assetList[t],i=this.primaryMedia;r&&i&&this.bufferAssetPlayer(e,i)}}}preloadAssets(e,t){const s=e.assetList.length,r=0===s&&!e.assetListLoader,i=e.cue.once;if(r){this.log(`Load interstitial asset ${t+1}/${s} ${e}`);const r=e.timelineStart;e.appendInPlace&&this.flushFrontBuffer(r);const i=e.assetUrl;if(i)return this.createAsset(e,0,0,r,e.duration,i);let n=0;!this.playingItem&&this.primaryLive&&(n=this.hls.startPosition,-1===n&&(n=this.hls.liveSyncPosition||0));const a=this.assetListLoader.loadAssetList(e,n);a&&(e.assetListLoader=a)}else if(!i&&s){for(let r=t;r<s;r++){const t=e.assetList[r],s=this.getAssetPlayerQueueIndex(t.identifier);-1!==s&&!this.playerQueue[s].destroyed||t.error||this.createAssetPlayer(e,t,r)}return this.getAssetPlayer(e.assetList[t].identifier)}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;Object.keys(t).forEach((t=>{this.hls.trigger(Events.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:t})}))}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let s=0;s<t.length;s++)if(e===t[s].assetId)return s;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t)for(let s=0;s<e.length;s++)if(e[s].media===t)return e[s];return null}createAsset(e,t,s,r,i,n){const a={parentIdentifier:e.identifier,identifier:generateAssetIdentifier(e,n,t),duration:i,startOffset:s,timelineStart:r,uri:n};return this.createAssetPlayer(e,a,t)}createAssetPlayer(e,t,s){this.log(`create HLSAssetPlayer for ${eventAssetToString(t)}`);const r=this.hls,i=r.userConfig;let n=i.videoPreference;const a=r.levels[r.loadLevel]||r.levels[r.currentLevel];(n||a)&&(n=_extends({},n),a.videoCodec&&(n.videoCodec=a.videoCodec),a.videoRange&&(n.allowedVideoRanges=[a.videoRange]));const o=r.audioTracks[r.audioTrack],l=r.subtitleTracks[r.subtitleTrack];let d=0;if(this.primaryLive){const e=this.timelinePos-t.timelineStart;if(e>1){const s=t.duration;s&&e<s&&(d=e)}}const h=_objectSpread2(_objectSpread2({},i),{},{autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:r.sessionId,assetPlayerId:t.identifier,abrEwmaDefaultEstimate:r.bandwidthEstimate,interstitialsController:void 0,startPosition:d,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:n,audioPreference:o||i.audioPreference,subtitlePreference:l||i.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(h.timelineOffset=t.timelineStart));const c=h.cmcd;null!=c&&c.sessionId&&c.contentId&&(h.cmcd=_extends({},c,{contentId:hash(t.uri)}));const u=new HlsAssetPlayer(this.HlsPlayerClass,h,e,t);this.playerQueue.push(u),e.assetList[s]=t;const f=t.identifier,g=r=>{if(r.live){const t=new Error(`Interstitials MUST be VOD assets ${e}`),r={fatal:!0,type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};return void this.handleAssetItemError(r,e,this.schedule.findEventIndex(e.identifier),s,t.message)}const i=r.edge-r.fragmentStart,n=t.duration;(null===n||i>n)&&(this.log(`Interstitial asset "${f}" duration change ${n} > ${i}`),t.duration=i,this.updateSchedule())};u.on(Events.LEVEL_UPDATED,((e,{details:t})=>g(t))),u.on(Events.LEVEL_PTS_UPDATED,((e,{details:t})=>g(t)));const m=(e,t)=>{const s=this.getAssetPlayer(f);if(s&&t.tracks){s.off(Events.BUFFER_CODECS,m),s.tracks=t.tracks;const e=this.primaryMedia;this.bufferingAsset===s.assetItem&&e&&!s.media&&this.bufferAssetPlayer(s,e)}};u.on(Events.BUFFER_CODECS,m);const p=s=>{var r;const i=this.getAssetPlayer(f);if(this.log(`buffered to end of asset ${i}`),!i)return;i.off(Events.BUFFERED_TO_END,p);const n=this.schedule.findEventIndex(e.identifier),a=e.findAssetIndex(t),o=a+1,l=null==(r=this.schedule.items)?void 0:r[n];if(this.isInterstitial(l))if(-1===a||e.isAssetPastPlayoutLimit(o)||e.assetList[o].error){var d;const e=null==(d=this.schedule.items)?void 0:d[n+1];e&&this.bufferedToItem(e)}else this.bufferedToItem(l,a+1)};u.on(Events.BUFFERED_TO_END,p);const E=t=>()=>{if(!this.getAssetPlayer(f))return;this.shouldPlay=!0;const s=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,s,t)};return u.once(Events.MEDIA_ENDED,E(s)),u.once(Events.PLAYOUT_LIMIT_REACHED,E(1/0)),u.on(Events.ERROR,((t,r)=>{this.handleAssetItemError(r,e,this.schedule.findEventIndex(e.identifier),s,`Asset player error ${r.error} ${e}`)})),u.on(Events.DESTROYING,(()=>{if(!this.getAssetPlayer(f))return;const t=new Error(`Asset player destroyed unexpectedly ${f}`),r={fatal:!0,type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};this.handleAssetItemError(r,e,this.schedule.findEventIndex(e.identifier),s,t.message)})),this.hls.trigger(Events.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:u}),u}clearInterstitial(e,t){e.assetList.forEach((e=>{this.clearAssetPlayer(e.identifier,t)})),e.appendInPlaceStarted=!1}clearAssetPlayer(e,t){if(null===t)return;const s=this.getAssetPlayerQueueIndex(e);if(-1!==s){this.log(`clearAssetPlayer "${e}" toSegment: ${t?segmentToString(t):t}`);const r=this.playerQueue[s];this.transferMediaFromPlayer(r,t),this.playerQueue.splice(s,1),r.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,s,r,i){const{interstitial:n,assetItem:a,assetId:o}=e,l=n.assetList.length,d=this.playingAsset;this.playingAsset=a,d&&d.identifier===o||(d&&(this.clearAssetPlayer(d.identifier,s[r]),delete d.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${e}`),this.hls.trigger(Events.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:t,event:n,schedule:s.slice(0),scheduleIndex:r,player:e})),e.media||this.bufferAssetPlayer(e,i)}bufferAssetPlayer(e,t){var s,r;const{interstitial:i,assetItem:n,assetId:a}=e,o=this.schedule.findEventIndex(i.identifier),l=null==(s=this.schedule.items)?void 0:s[o];if(!l)return;this.setBufferingItem(l),this.bufferingAsset=n;const d=this.getBufferingPlayer();if(d===e)return;const h=(null==d?void 0:d.tracks)||(null==(r=this.detachedData)?void 0:r.tracks)||this.requiredTracks;if(i.appendInPlace&&n!==this.playingAsset){if(!e.tracks)return;if(h&&!isCompatibleTrackChange(h,e.tracks)){const t=new Error(`Asset "${a}" SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(h)}')`),s={fatal:!0,type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},r=i.findAssetIndex(n);return void this.handleAssetItemError(s,i,o,r,t.message)}}this.transferMediaTo(e,t)}handleAssetItemError(e,t,s,r,i){if(e.details===ErrorDetails.BUFFER_STALLED_ERROR)return;const n=t.assetList[r]||null;let a=null;if(n){const e=this.getAssetPlayerQueueIndex(n.identifier);a=this.playerQueue[e]||null}const o=this.schedule.items,l=_extends({},e,{fatal:!1,errorAction:createDoNothingErrorAction(!0),asset:n,assetListIndex:r,event:t,schedule:o,scheduleIndex:s,player:a});if(this.warn(`Asset item error: ${e.error}`),this.hls.trigger(Events.INTERSTITIAL_ASSET_ERROR,l),!e.fatal)return;const d=new Error(i);n&&(this.playingAsset!==n&&this.clearAssetPlayer(n.identifier,null),n.error=d),t.assetList.some((e=>!e.error))?t.appendInPlace&&(t.error=d):t.error=d,this.primaryFallback(t)}primaryFallback(e){const t=e.timelineStart,s=this.playingItem||this.waitingItem;if(this.updateSchedule(),s){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${this.timelinePos} playing: ${s?segmentToString(s):"<none>"} error: ${e.error}`),e.appendInPlace&&(e.appendInPlace=!1,this.attachPrimary(t,null),this.flushFrontBuffer(t));let r=this.timelinePos;-1===r&&(r=this.hls.startPosition);const i=this.updateItem(s,r);if(!this.itemsMatch(s,i)){const e=this.schedule.findItemIndexAtTime(r);this.setSchedulePosition(e)}}else this.checkStart()}onAssetListLoaded(e,t){var s;const r=t.event,i=r.identifier,n=t.assetListResponse.ASSETS;if(!this.schedule.hasEvent(i))return;const a=r.timelineStart;let o=0;n.forEach(((e,t)=>{const s=parseFloat(e.DURATION);this.createAsset(r,t,o,a+o,s,e.URI),o+=s})),r.duration=o;const l=this.waitingItem,d=(null==l?void 0:l.event.identifier)===i;this.updateSchedule();const h=null==(s=this.bufferingItem)?void 0:s.event;if(d){var c;const e=this.schedule.findEventIndex(i),t=null==(c=this.schedule.items)?void 0:c[e];t&&this.setBufferingItem(t),this.setSchedulePosition(e)}else if((null==h?void 0:h.identifier)===i&&h.appendInPlace){const e=r.assetList[0],t=this.getAssetPlayer(e.identifier),s=this.primaryMedia;e&&t&&s&&this.bufferAssetPlayer(t,s)}}onError(e,t){switch(t.details){case ErrorDetails.ASSET_LIST_PARSING_ERROR:case ErrorDetails.ASSET_LIST_LOAD_ERROR:case ErrorDetails.ASSET_LIST_LOAD_TIMEOUT:{const e=t.interstitial;e&&this.primaryFallback(e)}}}}const TICK_INTERVAL$1=500;class SubtitleStreamController extends BaseStreamController{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",PlaylistLevelType.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Events.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(Events.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(Events.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(Events.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(Events.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Events.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(Events.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(Events.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(Events.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(Events.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e){this.stopLoad(),this.state=State.IDLE,this.setInterval(500),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:s,success:r}=t;if(isMediaFragment(s)&&(this.fragPrevious=s),this.state=State.IDLE,!r)return;const i=this.tracksBuffered[this.currentTrackId];if(!i)return;let n;const a=s.start;for(let e=0;e<i.length;e++)if(a>=i[e].start&&a<=i[e].end){n=i[e];break}const o=s.start+s.duration;n?n.end=o:(n={start:a,end:o},i.push(n)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:s,endOffset:r}=t;if(0===s&&r!==Number.POSITIVE_INFINITY){const e=r-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach((t=>{for(let s=0;s<t.length;)if(t[s].end<=e)t.shift();else{if(!(t[s].start<e))break;t[s].start=e,s++}})),this.fragmentTracker.removeFragmentsInRange(s,e,PlaylistLevelType.SUBTITLE)}}onError(e,t){const s=t.frag;(null==s?void 0:s.type)===PlaylistLevelType.SUBTITLE&&(t.details===ErrorDetails.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==State.STOPPED&&(this.state=State.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){this.levels&&subtitleOptionsIdentical(this.levels,t)?this.levels=t.map((e=>new Level(e))):(this.tracksBuffered=[],this.levels=t.map((e=>{const t=new Level(e);return this.tracksBuffered[t.id]=[],t})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,PlaylistLevelType.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,null==(s=this.levels)||!s.length||-1===this.currentTrackId)return void this.clearInterval();const r=this.levels[this.currentTrackId];null!=r&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.state!==State.STOPPED&&this.setInterval(500)}onSubtitleTrackLoaded(e,t){var s;const{currentTrackId:r,levels:i}=this,{details:n,id:a}=t;if(!i)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=i[a];if(a>=i.length||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||null!=(s=o.details)&&s.live){const e=this.mainDetails;if(n.deltaUpdateFailed||!e)return;const t=e.fragments[0];var d;if(o.details)l=this.alignPlaylists(n,o.details,null==(d=this.levelLastLoaded)?void 0:d.details),0===l&&t&&(l=t.start,addSliding(n,l));else n.hasProgramDateTime&&e.hasProgramDateTime?(alignMediaPlaylistByPDT(n,e),l=n.fragmentStart):t&&(l=t.start,addSliding(n,l))}if(o.details=n,this.levelLastLoaded=o,a===r&&(this.hls.trigger(Events.SUBTITLE_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===State.IDLE)){findFragmentByPTS(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}_handleFragmentLoadComplete(e){const{frag:t,payload:s}=e,r=t.decryptdata,i=this.hls;if(!this.fragContextChanged(t)&&s&&s.byteLength>0&&null!=r&&r.key&&r.iv&&isFullSegmentEncryption(r.method)){const e=performance.now();this.decrypter.decrypt(new Uint8Array(s),r.key.buffer,r.iv.buffer,getAesModeFromFullSegmentMethod(r.method)).catch((e=>{throw i.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e})).then((s=>{const r=performance.now();i.trigger(Events.FRAG_DECRYPTED,{frag:t,payload:s,stats:{tstart:e,tdecrypt:r}})})).catch((e=>{this.warn(`${e.name}: ${e.message}`),this.state=State.IDLE}))}}doTick(){if(this.media){if(this.state===State.IDLE){const{currentTrackId:e,levels:t}=this,s=null==t?void 0:t[e];if(!s||!t.length||!s.details)return;if(this.waitForLive(s))return;const{config:r}=this,i=this.getLoadPosition(),n=BufferHelper.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],i,r.maxBufferHole),{end:a,len:o}=n,l=s.details;if(o>this.hls.maxBufferLength+l.levelTargetDuration)return;const d=l.fragments,h=d.length,c=l.edge;let u=null;const f=this.fragPrevious;if(a<c){const e=r.maxFragLookUpTolerance,t=a>c-e?0:e;u=findFragmentByPTS(f,d,Math.max(d[0].start,a),t),!u&&f&&f.start<d[0].start&&(u=d[0])}else u=d[h-1];if(!u)return;if(u=this.mapToInitFragWhenRequired(u),isMediaFragment(u)){const e=d[u.sn-l.startSN-1];e&&e.cc===u.cc&&this.fragmentTracker.getState(e)===FragmentState.NOT_LOADED&&(u=e)}this.fragmentTracker.getState(u)===FragmentState.NOT_LOADED&&this.loadFragment(u,s,a)}}else this.state=State.IDLE}loadFragment(e,t,s){isMediaFragment(e)?super.loadFragment(e,t,s):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new BufferableInstance(this.tracksBuffered[this.currentTrackId]||[])}}class BufferableInstance{constructor(e){this.buffered=void 0;const t=(t,s,r)=>{if((s>>>=0)>r-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${r})`);return e[s][t]};this.buffered={get length(){return e.length},end:s=>t("end",s,e.length),start:s=>t("start",s,e.length)}}}const specialCea608CharsCodes={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},getCharForByte=e=>String.fromCharCode(specialCea608CharsCodes[e]||e),NR_ROWS=15,NR_COLS=100,rowsLowCh1={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},rowsHighCh1={17:2,18:4,21:6,22:8,23:10,19:13,20:15},rowsLowCh2={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},rowsHighCh2={25:2,26:4,29:6,30:8,31:10,27:13,28:15},backgroundColors=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class CaptionsLogger{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const s="function"==typeof t?t():t;logger.log(`${this.time} [${e}] ${s}`)}}}const numArrayToHexArray=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t};class PenState{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let s=0;s<t.length;s++){const r=t[s];e.hasOwnProperty(r)&&(this[r]=e[r])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class StyledUnicodeChar{constructor(){this.uchar=" ",this.penState=new PenState}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}}class Row{constructor(e){this.chars=[],this.pos=0,this.currPenState=new PenState,this.cueStartTime=null,this.logger=void 0;for(let e=0;e<100;e++)this.chars.push(new StyledUnicodeChar);this.logger=e}equals(e){for(let t=0;t<100;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<100;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<100;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>100&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=100)}moveCursor(e){const t=this.pos+e;if(e>1)for(let e=this.pos+1;e<t+1;e++)this.chars[e].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=getCharForByte(e);this.pos>=100?this.logger.log(0,(()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!")):(this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1))}clearFromPos(e){let t;for(t=e;t<100;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let s=0;s<100;s++){const r=this.chars[s].uchar;" "!==r&&(t=!1),e.push(r)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e);this.chars[this.pos].setPenState(this.currPenState)}}class CaptionScreen{constructor(e){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<15;t++)this.rows.push(new Row(e));this.logger=e}reset(){for(let e=0;e<15;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let s=0;s<15;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<15;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<15;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e);this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,(()=>"pacData = "+JSON.stringify(e)));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let e=0;e<15;e++)this.rows[e].clear();const e=this.currRow+1-this.nrRollUpRows,s=this.lastOutputScreen;if(s){const r=s.rows[e].cueStartTime,i=this.logger.time;if(null!==r&&null!==i&&r<i)for(let r=0;r<this.nrRollUpRows;r++)this.rows[t-this.nrRollUpRows+r+1].copy(s.rows[e+r])}}this.currRow=t;const s=this.rows[this.currRow];if(null!==e.indent){const t=e.indent,r=Math.max(t-1,0);s.setCursor(e.indent),e.color=s.chars[r].penState.foreground}const r={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(r)}setBkgData(e){this.logger.log(2,(()=>"bkgData = "+JSON.stringify(e))),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,(()=>this.getDisplayText()));const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let s="",r=-1;for(let s=0;s<15;s++){const i=this.rows[s].getTextString();i&&(r=s+1,e?t.push("Row "+r+": '"+i+"'"):t.push(i.trim()))}return t.length>0&&(s=e?"["+t.join(" | ")+"]":t.join("\n")),s}getTextAndFormat(){return this.rows}}class Cea608Channel{constructor(e,t,s){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new CaptionScreen(s),this.nonDisplayedMemory=new CaptionScreen(s),this.lastOutputScreen=new CaptionScreen(s),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,(()=>"MODE="+e)),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let t=0;t<e.length;t++)this.writeScreen.insertChar(e[t]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,(()=>t+": "+this.writeScreen.getDisplayText(!0))),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,(()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0))),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,(()=>"DISP: "+this.displayedMemory.getDisplayText()))}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{const s=Math.floor(e/2)-16,r=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=r[s]}this.logger.log(2,"MIDROW: "+JSON.stringify(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class Cea608Parser{constructor(e,t,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory=createCmdHistory(),this.logger=void 0;const r=this.logger=new CaptionsLogger;this.channels=[null,new Cea608Channel(e,t,r),new Cea608Channel(e+1,s,r)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let e=0;e<t.length;e+=2){const s=127&t[e],r=127&t[e+1];let i=!1,n=null;if(0===s&&0===r)continue;this.logger.log(3,(()=>"["+numArrayToHexArray([t[e],t[e+1]])+"] -> ("+numArrayToHexArray([s,r])+")"));const a=this.cmdHistory;if(s>=16&&s<=31){if(hasCmdRepeated(s,r,a)){setLastCmd(null,null,a),this.logger.log(3,(()=>"Repeated command ("+numArrayToHexArray([s,r])+") is dropped"));continue}setLastCmd(s,r,this.cmdHistory),i=this.parseCmd(s,r),i||(i=this.parseMidrow(s,r)),i||(i=this.parsePAC(s,r)),i||(i=this.parseBackgroundAttributes(s,r))}else setLastCmd(null,null,a);if(!i&&(n=this.parseChars(s,r),n)){const e=this.currentChannel;if(e&&e>0){this.channels[e].insertChars(n)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}i||n||this.logger.log(2,(()=>"Couldn't parse cleaned data "+numArrayToHexArray([s,r])+" orig: "+numArrayToHexArray([t[e],t[e+1]])))}}parseCmd(e,t){if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=33&&t<=35))return!1;const s=20===e||21===e||23===e?1:2,r=this.channels[s];return 20===e||21===e||28===e||29===e?32===t?r.ccRCL():33===t?r.ccBS():34===t?r.ccAOF():35===t?r.ccAON():36===t?r.ccDER():37===t?r.ccRU(2):38===t?r.ccRU(3):39===t?r.ccRU(4):40===t?r.ccFON():41===t?r.ccRDC():42===t?r.ccTR():43===t?r.ccRTD():44===t?r.ccEDM():45===t?r.ccCR():46===t?r.ccENM():47===t&&r.ccEOC():r.ccTO(t-32),this.currentChannel=s,!0}parseMidrow(e,t){let s=0;if((17===e||25===e)&&t>=32&&t<=47){if(s=17===e?1:2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const r=this.channels[s];return!!r&&(r.ccMIDROW(t),this.logger.log(3,(()=>"MIDROW ("+numArrayToHexArray([e,t])+")")),!0)}return!1}parsePAC(e,t){let s;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127)&&!((16===e||24===e)&&t>=64&&t<=95))return!1;const r=e<=23?1:2;s=t>=64&&t<=95?1===r?rowsLowCh1[e]:rowsLowCh2[e]:1===r?rowsHighCh1[e]:rowsHighCh2[e];const i=this.channels[r];return!!i&&(i.setPAC(this.interpretPAC(s,t)),this.currentChannel=r,!0)}interpretPAC(e,t){let s;const r={color:null,italics:!1,indent:null,underline:!1,row:e};return s=t>95?t-96:t-64,r.underline=1==(1&s),s<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(r.italics=!0,r.color="white"):r.indent=4*Math.floor((s-16)/2),r}parseChars(e,t){let s,r=null,i=null;if(e>=25?(s=2,i=e-8):(s=1,i=e),i>=17&&i<=19){let e;e=17===i?t+80:18===i?t+112:t+144,this.logger.log(2,(()=>"Special char '"+getCharForByte(e)+"' in channel "+s)),r=[e]}else e>=32&&e<=127&&(r=0===t?[e]:[e,t]);return r&&this.logger.log(3,(()=>"Char codes = "+numArrayToHexArray(r).join(","))),r}parseBackgroundAttributes(e,t){if(!((16===e||24===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=45&&t<=47))return!1;let s;const r={};16===e||24===e?(s=Math.floor((t-32)/2),r.background=backgroundColors[s],t%2==1&&(r.background=r.background+"_semi")):45===t?r.background="transparent":(r.foreground="black",47===t&&(r.underline=!0));const i=e<=23?1:2;return this.channels[i].setBkgData(r),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}setLastCmd(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const s=this.channels[t];s&&s.cueSplitAtTime(e)}}}function setLastCmd(e,t,s){s.a=e,s.b=t}function hasCmdRepeated(e,t,s){return s.a===e&&s.b===t}function createCmdHistory(){return{a:null,b:null}}var VTTCue=function(){if(null!=optionalSelf&&optionalSelf.VTTCue)return self.VTTCue;const e=["","lr","rl"],t=["start","middle","end","left","right"];function s(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;const s=t.toLowerCase();return!!~e.indexOf(s)&&s}function r(e){return s(t,e)}function i(e,...t){let s=1;for(;s<arguments.length;s++){const t=arguments[s];for(const s in t)e[s]=t[s]}return e}function n(t,n,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let d="",h=!1,c=t,u=n,f=a,g=null,m="",p=!0,E="auto",y="start",v=50,T="middle",S=50,A="middle";Object.defineProperty(o,"id",i({},l,{get:function(){return d},set:function(e){d=""+e}})),Object.defineProperty(o,"pauseOnExit",i({},l,{get:function(){return h},set:function(e){h=!!e}})),Object.defineProperty(o,"startTime",i({},l,{get:function(){return c},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");c=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",i({},l,{get:function(){return u},set:function(e){if("number"!=typeof e)throw new TypeError("End time must be set to a number.");u=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",i({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",i({},l,{get:function(){return g},set:function(e){g=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",i({},l,{get:function(){return m},set:function(t){const r=function(t){return s(e,t)}(t);if(!1===r)throw new SyntaxError("An invalid or illegal string was specified.");m=r,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",i({},l,{get:function(){return p},set:function(e){p=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",i({},l,{get:function(){return E},set:function(e){if("number"!=typeof e&&"auto"!==e)throw new SyntaxError("An invalid number or illegal string was specified.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",i({},l,{get:function(){return y},set:function(e){const t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");y=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",i({},l,{get:function(){return v},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");v=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",i({},l,{get:function(){return T},set:function(e){const t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");T=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",i({},l,{get:function(){return S},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");S=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",i({},l,{get:function(){return A},set:function(e){const t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");A=t,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class StringDecoder{decode(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function parseTimeStamp(e){function t(e,t,s,r){return 3600*(0|e)+60*(0|t)+(0|s)+parseFloat(r||0)}const s=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return s?parseFloat(s[2])>59?t(s[2],s[3],0,s[4]):t(s[1],s[2],s[3],s[4]):null}class Settings{constructor(){this.values=Object.create(null)}set(e,t){this.get(e)||""===t||(this.values[e]=t)}get(e,t,s){return s?this.has(e)?this.values[e]:t[s]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,s){for(let r=0;r<s.length;++r)if(t===s[r]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}}function parseOptions(e,t,s,r){const i=r?e.split(r):[e];for(const e in i){if("string"!=typeof i[e])continue;const r=i[e].split(s);if(2!==r.length)continue;t(r[0],r[1])}}const defaults=new VTTCue(0,0,""),center="middle"===defaults.align?"middle":"center";function parseCue(e,t,s){const r=e;function i(){const t=parseTimeStamp(e);if(null===t)throw new Error("Malformed timestamp: "+r);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function n(){e=e.replace(/^\s+/,"")}if(n(),t.startTime=i(),n(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+r);e=e.slice(3),n(),t.endTime=i(),n(),function(e,t){const r=new Settings;parseOptions(e,(function(e,t){let i;switch(e){case"region":for(let i=s.length-1;i>=0;i--)if(s[i].id===t){r.set(e,s[i].region);break}break;case"vertical":r.alt(e,t,["rl","lr"]);break;case"line":i=t.split(","),r.integer(e,i[0]),r.percent(e,i[0])&&r.set("snapToLines",!1),r.alt(e,i[0],["auto"]),2===i.length&&r.alt("lineAlign",i[1],["start",center,"end"]);break;case"position":i=t.split(","),r.percent(e,i[0]),2===i.length&&r.alt("positionAlign",i[1],["start",center,"end","line-left","line-right","auto"]);break;case"size":r.percent(e,t);break;case"align":r.alt(e,t,["start",center,"end","left","right"])}}),/:/,/\s/),t.region=r.get("region",null),t.vertical=r.get("vertical","");let i=r.get("line","auto");"auto"===i&&-1===defaults.line&&(i=-1),t.line=i,t.lineAlign=r.get("lineAlign","start"),t.snapToLines=r.get("snapToLines",!0),t.size=r.get("size",100),t.align=r.get("align",center);let n=r.get("position","auto");"auto"===n&&50===defaults.position&&(n="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=n}(e,t)}function fixLineBreaks(e){return e.replace(/<br(?: \/)?>/gi,"\n")}class VTTParser{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new StringDecoder,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;function s(){let e=t.buffer,s=0;for(e=fixLineBreaks(e);s<e.length&&"\r"!==e[s]&&"\n"!==e[s];)++s;const r=e.slice(0,s);return"\r"===e[s]&&++s,"\n"===e[s]&&++s,t.buffer=e.slice(s),r}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{let e="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;e=s();const r=e.match(/^()?WEBVTT([ \t].*)?$/);if(null==r||!r[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let r=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(r?r=!1:e=s(),t.state){case"HEADER":/:/.test(e)?parseOptions(e,(function(e,t){}),/:/):e||(t.state="ID");continue;case"NOTE":e||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(e)){t.state="NOTE";break}if(!e)continue;if(t.cue=new VTTCue(0,0,""),t.state="CUE",-1===e.indexOf("--\x3e")){t.cue.id=e;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{parseCue(e,t.cue,t.regionList)}catch(e){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const s=-1!==e.indexOf("--\x3e");if(!e||s&&(r=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=e}continue;case"BADCUE":e||(t.state="ID")}}}catch(e){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||"HEADER"===e.state)&&(e.buffer+="\n\n",e.parse()),"INITIAL"===e.state||"BADWEBVTT"===e.state)throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const LINEBREAKS=/\r\n|\n\r|\n|\r/g,startsWith=function(e,t,s=0){return e.slice(s,s+t.length)===t},cueString2millis=function(e){let t=parseInt(e.slice(-3));const s=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),i=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(isFiniteNumber(t)&&isFiniteNumber(s)&&isFiniteNumber(r)&&isFiniteNumber(i)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*s,t+=6e4*r,t+=36e5*i,t};function generateCueId(e,t,s){return hash(e.toString())+hash(t.toString())+hash(s)}const calculateOffset=function(e,t,s){let r=e[t],i=e[r.prevCC];if(!i||!i.new&&r.new)return e.ccOffset=e.presentationOffset=r.start,void(r.new=!1);for(;null!=(n=i)&&n.new;){var n;e.ccOffset+=r.start-i.start,r.new=!1,r=i,i=e[r.prevCC]}e.presentationOffset=s};function parseWebVTT(e,t,s,r,i,n,a){const o=new VTTParser,l=utf8ArrayToStr(new Uint8Array(e)).trim().replace(LINEBREAKS,"\n").split("\n"),d=[],h=t?toMpegTsClockFromTimescale(t.baseTime,t.timescale):0;let c,u="00:00.000",f=0,g=0,m=!0;o.oncue=function(e){const n=s[r];let a=s.ccOffset;const o=(f-h)/9e4;if(null!=n&&n.new&&(void 0!==g?a=s.ccOffset=n.start:calculateOffset(s,r,o)),o){if(!t)return void(c=new Error("Missing initPTS for VTT MPEGTS"));a=o-s.presentationOffset}const l=e.endTime-e.startTime,u=normalizePts(9e4*(e.startTime+a-g),9e4*i)/9e4;e.startTime=Math.max(u,0),e.endTime=Math.max(u+l,0);const m=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(m)),e.id||(e.id=generateCueId(e.startTime,e.endTime,m)),e.endTime>0&&d.push(e)},o.onparsingerror=function(e){c=e},o.onflush=function(){c?a(c):n(d)},l.forEach((e=>{if(m){if(startsWith(e,"X-TIMESTAMP-MAP=")){m=!1,e.slice(16).split(",").forEach((e=>{startsWith(e,"LOCAL:")?u=e.slice(6):startsWith(e,"MPEGTS:")&&(f=parseInt(e.slice(7)))}));try{g=cueString2millis(u)/1e3}catch(e){c=e}return}""===e&&(m=!1)}o.parse(e+"\n")})),o.flush()}const IMSC1_CODEC="stpp.ttml.im1t",HMSF_REGEX=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,TIME_UNIT_REGEX=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,textAlignToLineAlign={left:"start",center:"center",right:"end",start:"start",end:"end"};function parseIMSC1(e,t,s,r){const i=findBox(new Uint8Array(e),["mdat"]);if(0===i.length)return void r(new Error("Could not parse IMSC1 mdat"));const n=i.map((e=>utf8ArrayToStr(e))),a=toTimescaleFromScale(t.baseTime,1,t.timescale);try{n.forEach((e=>s(parseTTML(e,a))))}catch(e){r(e)}}function parseTTML(e,t){const s=(new DOMParser).parseFromString(e,"text/xml").getElementsByTagName("tt")[0];if(!s)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},i=Object.keys(r).reduce(((e,t)=>(e[t]=s.getAttribute(`ttp:${t}`)||r[t],e)),{}),n="preserve"!==s.getAttribute("xml:space"),a=collectionToDictionary(getElementCollection(s,"styling","style")),o=collectionToDictionary(getElementCollection(s,"layout","region")),l=getElementCollection(s,"body","[begin]");return[].map.call(l,(e=>{const s=getTextContent(e,n);if(!s||!e.hasAttribute("begin"))return null;const r=parseTtmlTime(e.getAttribute("begin"),i),l=parseTtmlTime(e.getAttribute("dur"),i);let d=parseTtmlTime(e.getAttribute("end"),i);if(null===r)throw timestampParsingError(e);if(null===d){if(null===l)throw timestampParsingError(e);d=r+l}const h=new VTTCue(r-t,d-t,s);h.id=generateCueId(h.startTime,h.endTime,h.text);const c=getTtmlStyles(o[e.getAttribute("region")],a[e.getAttribute("style")],a),{textAlign:u}=c;if(u){const e=textAlignToLineAlign[u];e&&(h.lineAlign=e),h.align=u}return _extends(h,c),h})).filter((e=>null!==e))}function getElementCollection(e,t,s){const r=e.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(s)):[]}function collectionToDictionary(e){return e.reduce(((e,t)=>{const s=t.getAttribute("xml:id");return s&&(e[s]=t),e}),{})}function getTextContent(e,t){return[].slice.call(e.childNodes).reduce(((e,s,r)=>{var i;return"br"===s.nodeName&&r?e+"\n":null!=(i=s.childNodes)&&i.length?getTextContent(s,t):t?e+s.textContent.trim().replace(/\s+/g," "):e+s.textContent}),"")}function getTtmlStyles(e,t,s){const r="http://www.w3.org/ns/ttml#styling";let i=null;const n=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;return n&&s.hasOwnProperty(n)&&(i=s[n]),["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"].reduce(((s,n)=>{const a=getAttributeNS(t,r,n)||getAttributeNS(e,r,n)||getAttributeNS(i,r,n);return a&&(s[n]=a),s}),{})}function getAttributeNS(e,t,s){return e&&e.hasAttributeNS(t,s)?e.getAttributeNS(t,s):null}function timestampParsingError(e){return new Error(`Could not parse ttml timestamp ${e}`)}function parseTtmlTime(e,t){if(!e)return null;let s=parseTimeStamp(e);return null===s&&(HMSF_REGEX.test(e)?s=parseHoursMinutesSecondsFrames(e,t):TIME_UNIT_REGEX.test(e)&&(s=parseTimeUnits(e,t))),s}function parseHoursMinutesSecondsFrames(e,t){const s=HMSF_REGEX.exec(e),r=(0|s[4])+(0|s[5])/t.subFrameRate;return 3600*(0|s[1])+60*(0|s[2])+(0|s[3])+r/t.frameRate}function parseTimeUnits(e,t){const s=TIME_UNIT_REGEX.exec(e),r=Number(s[1]);switch(s[2]){case"h":return 3600*r;case"m":return 60*r;case"ms":return 1e3*r;case"f":return r/t.frameRate;case"t":return r/t.tickRate}return r}class OutputFilter{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,s){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class TimelineController{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=newVTTCCs(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Events.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(Events.FRAG_LOADING,this.onFragLoading,this),e.on(Events.FRAG_LOADED,this.onFragLoaded,this),e.on(Events.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(Events.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(Events.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Events.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(Events.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Events.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(Events.FRAG_LOADING,this.onFragLoading,this),e.off(Events.FRAG_LOADED,this.onFragLoaded,this),e.off(Events.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(Events.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(Events.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Events.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new OutputFilter(this,"textTrack1"),t=new OutputFilter(this,"textTrack2"),s=new OutputFilter(this,"textTrack3"),r=new OutputFilter(this,"textTrack4");this.cea608Parser1=new Cea608Parser(1,e,t),this.cea608Parser2=new Cea608Parser(3,s,r)}addCues(e,t,s,r,i){let n=!1;for(let e=i.length;e--;){const r=i[e],a=intersection(r[0],r[1],t,s);if(a>=0&&(r[0]=Math.min(r[0],t),r[1]=Math.max(r[1],s),n=!0,a/(s-t)>.5))return}if(n||i.push([t,s]),this.config.renderTextTracksNatively){const i=this.captionsTracks[e];this.Cues.newCue(i,t,s,r)}else{const i=this.Cues.newCue(null,t,s,r);this.hls.trigger(Events.CUES_PARSED,{type:"captions",cues:i,track:e})}}onInitPtsFound(e,{frag:t,id:s,initPTS:r,timescale:i}){const{unparsedVttFrags:n}=this;s===PlaylistLevelType.MAIN&&(this.initPTS[t.cc]={baseTime:r,timescale:i}),n.length&&(this.unparsedVttFrags=[],n.forEach((e=>{this.onFragLoaded(Events.FRAG_LOADED,e)})))}getExistingTrack(e,t){const{media:s}=this;if(s)for(let r=0;r<s.textTracks.length;r++){const i=s.textTracks[r];if(canReuseVttTextTrack(i,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound",attrs:{}}))return i}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:s,media:r}=this,{label:i,languageCode:n}=t[e],a=this.getExistingTrack(i,n);if(a)s[e]=a,clearCurrentCues(s[e]),sendAddTrackEvent(s[e],r);else{const t=this.createTextTrack("captions",i,n);t&&(t[e]=!0,s[e]=t)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const s={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=s,this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}createTextTrack(e,t,s){const r=this.media;if(r)return r.addTextTrack(e,t,s)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const s=!!t.transferMedia;if(this.media=null,s)return;const{captionsTracks:r}=this;Object.keys(r).forEach((e=>{clearCurrentCues(r[e]),delete r[e]})),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=newVTTCCs(),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:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let e=0;e<t.length;e++)clearCurrentCues(t[e])}onSubtitleTracksUpdated(e,t){const s=t.subtitleTracks||[],r=s.some((e=>e.textCodec===IMSC1_CODEC));if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(subtitleOptionsIdentical(this.tracks,s))return void(this.tracks=s);if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const e=this.media,t=e?filterSubtitleTracks(e.textTracks):null;if(this.tracks.forEach(((e,s)=>{let r;if(t){let s=null;for(let r=0;r<t.length;r++)if(t[r]&&canReuseVttTextTrack(t[r],e)){s=t[r],t[r]=null;break}s&&(r=s)}if(r)clearCurrentCues(r);else{const t=captionsOrSubtitlesFromCharacteristics(e);r=this.createTextTrack(t,e.name,e.lang),r&&(r.mode="disabled")}r&&this.textTracks.push(r)})),null!=t&&t.length){const e=t.filter((e=>null!==e)).map((e=>e.label));e.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${e.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const e=this.tracks.map((e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e})));this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach((e=>{const t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;const s=`textTrack${t[1]}`,r=this.captionsProperties[s];r&&(r.label=e.name,e.lang&&(r.languageCode=e.lang),r.media=e)}))}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===PlaylistLevelType.MAIN){var s,r;const{cea608Parser1:e,cea608Parser2:i,lastSn:n}=this,{cc:a,sn:o}=t.frag,l=null!=(s=null==(r=t.part)?void 0:r.index)?s:-1;e&&i&&(o!==n+1||o===n&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(e.reset(),i.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(e,t){const{frag:s,payload:r}=t;if(s.type===PlaylistLevelType.SUBTITLE)if(r.byteLength){const e=s.decryptdata,i="stats"in t;if(null==e||!e.encrypted||i){const e=this.tracks[s.level],i=this.vttCCs;i[s.cc]||(i[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),e&&e.textCodec===IMSC1_CODEC?this._parseIMSC1(s,r):this._parseVTTs(t)}}else this.hls.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const s=this.hls;parseIMSC1(t,this.initPTS[e.cc],(t=>{this._appendCues(t,e.level),s.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})}),(t=>{s.logger.log(`Failed to parse IMSC1: ${t}`),s.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})}))}_parseVTTs(e){var t;const{frag:s,payload:r}=e,{initPTS:i,unparsedVttFrags:n}=this,a=i.length-1;if(!i[s.cc]&&-1===a)return void n.push(e);const o=this.hls;parseWebVTT(null!=(t=s.initSegment)&&t.data?appendUint8Array(s.initSegment.data,new Uint8Array(r)).buffer:r,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,(e=>{this._appendCues(e,s.level),o.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})}),(t=>{const i="Missing initPTS for VTT MPEGTS"===t.message;i?n.push(e):this._fallbackToIMSC1(s,r),o.logger.log(`Failed to parse VTT cue: ${t}`),i&&a>s.cc||o.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:t})}))}_fallbackToIMSC1(e,t){const s=this.tracks[e.level];s.textCodec||parseIMSC1(t,this.initPTS[e.cc],(()=>{s.textCodec=IMSC1_CODEC,this._parseIMSC1(e,t)}),(()=>{s.textCodec="wvtt"}))}_appendCues(e,t){const s=this.hls;if(this.config.renderTextTracksNatively){const s=this.textTracks[t];if(!s||"disabled"===s.mode)return;e.forEach((e=>addCueToTrack(s,e)))}else{const r=this.tracks[t];if(!r)return;const i=r.default?"default":"subtitles"+t;s.trigger(Events.CUES_PARSED,{type:"subtitles",cues:e,track:i})}}onFragDecrypted(e,t){const{frag:s}=t;s.type===PlaylistLevelType.SUBTITLE&&this.onFragLoaded(Events.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:r}=t;if(s.type!==PlaylistLevelType.MAIN||"NONE"!==this.closedCaptionsForLevel(s))for(let e=0;e<r.length;e++){const t=r[e].bytes;if(t){this.cea608Parser1||this.initCea608Parsers();const s=this.extractCea608Data(t);this.cea608Parser1.addData(r[e].pts,s[0]),this.cea608Parser2.addData(r[e].pts,s[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:s,endOffsetSubtitles:r,type:i}){const{media:n}=this;if(n&&!(n.currentTime<s)){if(!i||"video"===i){const{captionsTracks:e}=this;Object.keys(e).forEach((r=>removeCuesInRange(e[r],t,s)))}if(this.config.renderTextTracksNatively&&0===t&&void 0!==r){const{textTracks:e}=this;Object.keys(e).forEach((s=>removeCuesInRange(e[s],t,r)))}}}extractCea608Data(e){const t=[[],[]],s=31&e[0];let r=2;for(let i=0;i<s;i++){const s=e[r++],i=127&e[r++],n=127&e[r++];if(0===i&&0===n)continue;if(0!=(4&s)){const e=3&s;0!==e&&1!==e||(t[e].push(i),t[e].push(n))}}return t}}function captionsOrSubtitlesFromCharacteristics(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function canReuseVttTextTrack(e,t){return!!e&&e.kind===captionsOrSubtitlesFromCharacteristics(t)&&subtitleTrackMatchesTextTrack(t,e)}function intersection(e,t,s,r){return Math.min(t,r)-Math.max(e,s)}function newVTTCCs(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const WHITESPACE_CHAR=/\s/,Cues={newCue(e,t,s,r){const i=[];let n,a,o,l,d;const h=self.VTTCue||self.TextTrackCue;for(let u=0;u<r.rows.length;u++)if(n=r.rows[u],o=!0,l=0,d="",!n.isEmpty()){var c;for(let e=0;e<n.chars.length;e++)WHITESPACE_CHAR.test(n.chars[e].uchar)&&o?l++:(d+=n.chars[e].uchar,o=!1);n.cueStartTime=t,t===s&&(s+=1e-4),l>=16?l--:l++;const r=fixLineBreaks(d.trim()),f=generateCueId(t,s,r);null!=e&&null!=(c=e.cues)&&c.getCueById(f)||(a=new h(t,s,r),a.id=f,a.line=u+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),i.push(a))}return e&&i.length&&(i.sort(((e,t)=>"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line)),i.forEach((t=>addCueToTrack(e,t)))),i}};function fetchSupported(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}const BYTERANGE=/(\d+)-(\d+)\/(\d+)/;class FetchLoader{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||getRequest,this.controller=new self.AbortController,this.stats=new LoadStats}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,s){const r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();const i=getRequestParameters(e,this.controller.signal),n=s.onProgress,a="arraybuffer"===e.responseType,o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:d}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=s,this.request=this.fetchSetup(e,i),self.clearTimeout(this.requestTimeout),t.timeout=l&&isFiniteNumber(l)?l:d,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),s.onTimeout(r,e,this.response)}),t.timeout);(isPromise(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then((i=>{this.response=this.loader=i;const o=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=d,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),s.onTimeout(r,e,this.response)}),d-(o-r.loading.start)),!i.ok){const{status:e,statusText:t}=i;throw new FetchError(t||"fetch, bad network response",e,i)}return r.loading.first=o,r.total=getContentLength(i.headers)||r.total,n&&isFiniteNumber(t.highWaterMark)?this.loadProgressively(i,r,e,t.highWaterMark,n):a?i.arrayBuffer():"json"===e.responseType?i.json():i.text()})).then((i=>{const a=this.response;if(!a)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);const l=i[o];l&&(r.loaded=r.total=l);const d={url:a.url,data:i,code:a.status};n&&!isFiniteNumber(t.highWaterMark)&&n(r,e,i,a),s.onSuccess(d,r,e,a)})).catch((t=>{if(self.clearTimeout(this.requestTimeout),r.aborted)return;const i=t&&t.code||0,n=t?t.message:null;s.onError({code:i,text:n},e,t?t.details:null,r)}))}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,s,r=0,i){const n=new ChunkCache,a=e.body.getReader(),o=()=>a.read().then((a=>{if(a.done)return n.dataLength&&i(t,s,n.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const l=a.value,d=l.length;return t.loaded+=d,d<r||n.dataLength?(n.push(l),n.dataLength>=r&&i(t,s,n.flush().buffer,e)):i(t,s,l.buffer,e),o()})).catch((()=>Promise.reject()));return o()}}function getRequestParameters(e,t){const s={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(_extends({},e.headers))};return e.rangeEnd&&s.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1)),s}function getByteRangeLength(e){const t=BYTERANGE.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}function getContentLength(e){const t=e.get("Content-Range");if(t){const e=getByteRangeLength(t);if(isFiniteNumber(e))return e}const s=e.get("Content-Length");if(s)return parseInt(s)}function getRequest(e,t){return new self.Request(e.url,t)}class FetchError extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const AGE_HEADER_LINE_REGEX=/^age:\s*[\d.]+\s*$/im;class XhrLoader{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new LoadStats,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const s=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;const i=this.xhrSetup;i?Promise.resolve().then((()=>{if(this.loader===s&&!this.stats.aborted)return i(s,t.url)})).catch((e=>{if(this.loader===s&&!this.stats.aborted)return s.open("GET",t.url,!0),i(s,t.url)})).then((()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)})).catch((e=>{this.callbacks.onError({code:s.status,text:e.message},t,s,r)})):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const r=t.headers,{maxTimeToFirstByteMs:i,maxLoadTimeMs:n}=s.loadPolicy;if(r)for(const t in r)e.setRequestHeader(t,r[t]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),s.timeout=i&&isFiniteNumber(i)?i:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:s}=this;if(!e||!t)return;const r=t.readyState,i=this.config;if(!s.aborted&&r>=2&&(0===s.loading.first&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),i.timeout!==i.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),i.timeout=i.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),4===r)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const r=t.status,n="text"===t.responseType?t.responseText:null;if(r>=200&&r<300){const i=null!=n?n:t.response;if(null!=i){s.loading.end=Math.max(self.performance.now(),s.loading.first);const n="arraybuffer"===t.responseType?i.byteLength:i.length;if(s.loaded=s.total=n,s.bwEstimate=8e3*s.total/(s.loading.end-s.loading.first),!this.callbacks)return;const a=this.callbacks.onProgress;if(a&&a(s,e,i,t),!this.callbacks)return;const o={url:t.responseURL,data:i,code:r};return void this.callbacks.onSuccess(o,s,e,t)}}const a=i.loadPolicy.errorRetry;shouldRetry(a,s.retry,!1,{url:e.url,data:void 0,code:r})?this.retry(a):(logger.error(`${r} while loading ${e.url}`),this.callbacks.onError({code:r,text:t.statusText},e,t,s))}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry;if(shouldRetry(e,this.stats.retry,!0))this.retry(e);else{var t;logger.warn(`timeout while loading ${null==(t=this.context)?void 0:t.url}`);const e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=getRetryDelay(e,s.retry),s.retry++,logger.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==t?void 0:t.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const defaultLoadPolicy={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},hlsDefaultConfig=_objectSpread2(_objectSpread2({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,maxBufferSize:6e7,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,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,loader:XhrLoader,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:AbrController,bufferController:BufferController,capLevelController:CapLevelController,errorController:ErrorController,fpsController:FPSController,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:requestMediaKeySystemAccess,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,certLoadPolicy:{default:defaultLoadPolicy},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},timelineConfig()),{},{subtitleStreamController:SubtitleStreamController,subtitleTrackController:SubtitleTrackController,timelineController:TimelineController,audioStreamController:AudioStreamController,audioTrackController:AudioTrackController,emeController:EMEController,cmcdController:CMCDController,contentSteeringController:ContentSteeringController,interstitialsController:InterstitialsController});function timelineConfig(){return{cueHandler:Cues,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function mergeConfig(e,t,s){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const r=deepCpy(e),i=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((e=>{const n=`${"level"===e?"playlist":e}LoadPolicy`,a=void 0===t[n],o=[];i.forEach((s=>{const i=`${e}Loading${s}`,l=t[i];if(void 0!==l&&a){o.push(i);const e=r[n].default;switch(t[n]={default:e},s){case"TimeOut":e.maxLoadTimeMs=l,e.maxTimeToFirstByteMs=l;break;case"MaxRetry":e.errorRetry.maxNumRetry=l,e.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":e.errorRetry.retryDelayMs=l,e.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":e.errorRetry.maxRetryDelayMs=l,e.timeoutRetry.maxRetryDelayMs=l}}})),o.length&&s.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${n}": ${JSON.stringify(t[n])}`)})),_objectSpread2(_objectSpread2({},r),t)}function deepCpy(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(deepCpy):Object.keys(e).reduce(((t,s)=>(t[s]=deepCpy(e[s]),t)),{}):e}function enableStreamingMode(e,t){const s=e.loader;if(s!==FetchLoader&&s!==XhrLoader)t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1;else{fetchSupported()&&(e.loader=FetchLoader,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}}const MIN_CUE_DURATION=.25;function getCueClass(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function createCueWithDataFields(e,t,s,r,i){let n=new e(t,s,"");try{n.value=r,i&&(n.type=i)}catch(a){n=new e(t,s,JSON.stringify(i?_objectSpread2({type:i},r):r))}return n}const MAX_CUE_ENDTIME=(()=>{const e=getCueClass();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function hexToArrayBuffer(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}class ID3TrackController{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(Events.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e.on(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Events.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Events.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}_unregisterListeners(){const{hls:e}=this;e.off(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Events.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Events.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}onMediaAttaching(e,t){var s;this.media=t.media,!1===(null==(s=t.overrides)?void 0:s.cueRemoval)&&(this.removeCues=!1)}onMediaAttached(){const e=this.hls.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(e,t){this.media=null;!!t.transferMedia||(this.id3Track&&(this.removeCues&&clearCurrentCues(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const s=e[t];if("metadata"===s.kind&&"id3"===s.label)return sendAddTrackEvent(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:s,enableID3MetadataCues:r}}}=this;if(!s&&!r)return;const{samples:i}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=getCueClass();if(n)for(let e=0;e<i.length;e++){const t=i[e].type;if(t===MetadataSchema.emsg&&!s||!r)continue;const a=getId3Frames(i[e].data);if(a){const s=i[e].pts;let r=s+i[e].duration;r>MAX_CUE_ENDTIME&&(r=MAX_CUE_ENDTIME);r-s<=0&&(r=s+.25);for(let e=0;e<a.length;e++){const i=a[e];if(!isId3TimestampFrame(i)){this.updateId3CueEnds(s,t);const e=createCueWithDataFields(n,s,r,i,t);e&&this.id3Track.addCue(e)}}}}}updateId3CueEnds(e,t){var s;const r=null==(s=this.id3Track)?void 0:s.cues;if(r)for(let s=r.length;s--;){const i=r[s];i.type===t&&i.startTime<e&&i.endTime===MAX_CUE_ENDTIME&&(i.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:r}){const{id3Track:i,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(i&&(a||o)){let e;e="audio"===r?e=>e.type===MetadataSchema.audioId3&&o:"video"===r?e=>e.type===MetadataSchema.emsg&&a:e=>e.type===MetadataSchema.audioId3&&o||e.type===MetadataSchema.emsg&&a,removeCuesInRange(i,t,s,e)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.media||!e.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{id3Track:s}=this,{dateRanges:r}=e,i=Object.keys(r);let n=this.dateRangeCuesAppended;var a;if(s&&t)if(null!=(a=s.cues)&&a.length){const e=Object.keys(n).filter((e=>!i.includes(e)));for(let t=e.length;t--;){const r=e[t],i=n[r].cues;delete n[r],Object.keys(i).forEach((e=>{try{const t=i[e];t.removeEventListener("enter",this.onEventCueEnter),s.removeCue(t)}catch(e){}}))}}else n=this.dateRangeCuesAppended={};const o=e.fragments[e.fragments.length-1];if(0===i.length||!isFiniteNumber(null==o?void 0:o.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const l=getCueClass();for(let e=0;e<i.length;e++){const t=i[e],s=r[t],a=s.startTime,o=n[t],d=(null==o?void 0:o.cues)||{};let h=(null==o?void 0:o.durationKnown)||!1,c=MAX_CUE_ENDTIME;const{duration:u,endDate:f}=s;if(f&&null!==u)c=a+u,h=!0;else if(s.endOnNext&&!h){const e=i.reduce(((e,t)=>{if(t!==s.id){const i=r[t];if(i.class===s.class&&i.startDate>s.startDate&&(!e||s.startDate<e.startDate))return i}return e}),null);e&&(c=e.startTime,h=!0)}const g=Object.keys(s.attr);for(let e=0;e<g.length;e++){const r=g[e];if(!isDateRangeCueAttribute(r))continue;const i=d[r];if(i)h&&!o.durationKnown?i.endTime=c:Math.abs(i.startTime-a)>.01&&(i.startTime=a,i.endTime=c);else if(l){let e=s.attr[r];isSCTE35Attribute(r)&&(e=hexToArrayBuffer(e));const i=createCueWithDataFields(l,a,c,{key:r,data:e},MetadataSchema.dateRange);i&&(i.id=t,this.id3Track.addCue(i),d[r]=i,this.hls.config.interstitialsController&&("X-ASSET-LIST"!==r&&"X-ASSET-URL"!==r||i.addEventListener("enter",this.onEventCueEnter)))}}n[t]={cues:d,dateRange:s,durationKnown:h}}}}class LatencyController{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:e}=this,t=this.hls.latestLevelDetails;if(!e||!t)return;this.currentTime=e.currentTime;const s=this.computeLatency();if(null===s)return;this._latency=s;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:i}=this.config;if(!r||1===i||!t.live)return;const n=this.targetLatency;if(null===n)return;const a=s-n;if(a<Math.min(this.maxLatency,n+t.targetduration)&&a>.05&&this.forwardBufferLength>1){const t=Math.min(2,Math.max(1,i)),s=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20;e.playbackRate=Math.min(t,Math.max(1,s))}else 1!==e.playbackRate&&0!==e.playbackRate&&(e.playbackRate=1)},this.hls=e,this.config=e.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){var e;const{config:t}=this;if(void 0!==t.liveMaxLatencyDuration)return t.liveMaxLatencyDuration;const s=null==(e=this.hls)?void 0:e.latestLevelDetails;return s?t.liveMaxLatencyDurationCount*s.targetduration:0}get targetLatency(){const e=this.hls.latestLevelDetails;if(null===e)return null;const{holdBack:t,partHoldBack:s,targetduration:r}=e,{liveSyncDuration:i,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&s||t;(this._targetLatencyUpdated||o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==i?i:n*r);const d=r;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,d)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t)return null;const s=this.hls.latestLevelDetails;if(null===s)return null;const r=s.edge,i=e-t-this.edgeStalled,n=r-s.totalduration,a=r-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(n,i),a)}get drift(){const e=this.hls.latestLevelDetails;return null===e?1:e.drift}get edgeStalled(){const e=this.hls.latestLevelDetails;if(null===e)return 0;const t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.hls.latestLevelDetails;if(!e||!t)return 0;const s=e.buffered.length;return(s?e.buffered.end(s-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){this.hls.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(Events.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(Events.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(Events.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(Events.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var s;t.details===ErrorDetails.BUFFER_STALLED_ERROR&&(this.stallCount++,null!=(s=this.hls.latestLevelDetails)&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}estimateLiveEdge(){const e=this.hls.latestLevelDetails;return null===e?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}class LevelController extends BasePlaylistController{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Events.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Events.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Events.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Events.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach((e=>{e.loadError=0,e.fragmentError=0})),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const s=this.hls.config.preferManagedMediaSource,r=[],i={},n={};let a=!1,o=!1,l=!1;t.levels.forEach((e=>{var t;const d=e.attrs;let{audioCodec:h,videoCodec:c}=e;h&&(e.audioCodec=h=getCodecCompatibleName(h,s)||void 0),0===(null==(t=c)?void 0:t.indexOf("avc1"))&&(c=e.videoCodec=convertAVC1ToAVCOTI(c));const{width:u,height:f,unknownCodecs:g}=e;let m=g?g.length:0;if(g)for(let t=m;t--;){const s=g[t];this.isAudioSupported(s)?(e.audioCodec=h=h?`${h},${s}`:s,m--,sampleEntryCodesISO.audio[h.substring(0,4)]=2):this.isVideoSupported(s)&&(e.videoCodec=c=c?`${c},${s}`:s,m--,sampleEntryCodesISO.video[c.substring(0,4)]=2)}if(a||(a=!(!u||!f)),o||(o=!!c),l||(l=!!h),m||h&&!this.isAudioSupported(h)||c&&!this.isVideoSupported(c))return;const{CODECS:p,"FRAME-RATE":E,"HDCP-LEVEL":y,"PATHWAY-ID":v,RESOLUTION:T,"VIDEO-RANGE":S}=d,A=`${`${v||"."}-`}${e.bitrate}-${T}-${E}-${p}-${S}-${y}`;if(i[A])if(i[A].uri===e.url||e.attrs["PATHWAY-ID"])i[A].addGroupId("audio",d.AUDIO),i[A].addGroupId("text",d.SUBTITLES);else{const t=n[A]+=1;e.attrs["PATHWAY-ID"]=new Array(t+1).join(".");const s=new Level(e);i[A]=s,r.push(s)}else{const t=new Level(e);i[A]=t,n[A]=1,r.push(t)}})),this.filterAndSortMediaOptions(r,t,a,o,l)}isAudioSupported(e){return areCodecsMediaSourceSupported(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return areCodecsMediaSourceSupported(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,s,r,i){let n=[],a=[],o=e;if((s||r)&&i&&(o=o.filter((({videoCodec:e,videoRange:t,width:s,height:r})=>(!!e||!(!s||!r))&&isVideoRange(t)))),0===o.length)return void Promise.resolve().then((()=>{if(this.hls){t.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(t.levels[0].attrs)}`);const e=new Error("no level with compatible codecs found in manifest");this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:e,reason:e.message})}}));t.audioTracks&&(n=t.audioTracks.filter((e=>!e.audioCodec||this.isAudioSupported(e.audioCodec))),assignTrackIdsByGroup(n)),t.subtitles&&(a=t.subtitles,assignTrackIdsByGroup(a));const l=o.slice(0);o.sort(((e,t)=>{if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return VideoRangeValues.indexOf(e.videoRange)-VideoRangeValues.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){const s=videoCodecPreferenceValue(e.videoCodec),r=videoCodecPreferenceValue(t.videoCodec);if(s!==r)return r-s}if(e.uri===t.uri&&e.codecSet!==t.codecSet){const s=codecsSetSelectionPreferenceValue(e.codecSet),r=codecsSetSelectionPreferenceValue(t.codecSet);if(s!==r)return r-s}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0}));let d=l[0];if(this.steering&&(o=this.steering.filterParsedLevels(o),o.length!==l.length))for(let e=0;e<l.length;e++)if(l[e].pathwayId===o[0].pathwayId){d=l[e];break}this._levels=o;for(let e=0;e<o.length;e++)if(o[e]===d){var h;this._firstLevel=e;const t=d.bitrate,s=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${o.length} level(s) found, first bitrate: ${t}`),void 0===(null==(h=this.hls.userConfig)?void 0:h.abrEwmaDefaultEstimate)){const e=Math.min(t,this.hls.config.abrEwmaDefaultEstimateMax);e>s&&s===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=e)}break}const c=i&&!r,u={levels:o,audioTracks:n,subtitleTracks:a,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:i,video:r,altAudio:!c&&n.some((e=>!!e.url))};this.hls.trigger(Events.MANIFEST_PARSED,u)}get levels(){return 0===this._levels.length?null:this._levels}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(0===t.length)return;if(e<0||e>=t.length){const s=new Error("invalid level idx"),r=e<0;if(this.hls.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.LEVEL_SWITCH_ERROR,level:e,fatal:r,error:s,reason:s.message}),r)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,r=this.currentLevel,i=r?r.attrs["PATHWAY-ID"]:void 0,n=t[e],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=n,s===e&&r&&i===a)return;this.log(`Switching to level ${e} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${s}${i?" with Pathway "+i:""}`);const o={level:e,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(Events.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const e=this.switchParams(n.uri,null==r?void 0:r.details,l);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(void 0===this._startLevel){const e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),s=e.filter((e=>-1!==t.indexOf(e)));if(e.length<1)return void this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);this.steering.pathwayPriority=s}}onError(e,t){!t.fatal&&t.context&&t.context.type===PlaylistContextType.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(void 0!==t&&t.type===PlaylistLevelType.MAIN){const e=t.elementaryStreams;if(!Object.keys(e).some((t=>!!e[t])))return;const s=this._levels[t.level];null!=s&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(e,t){var s;const{level:r,details:i}=t,n=t.levelInfo;var a;if(!n)return this.warn(`Invalid level index ${r}`),void(null!=(a=t.deliveryDirectives)&&a.skip&&(i.deltaUpdateFailed=!0));if(n===this.currentLevel||t.withoutMultiVariant){0===n.fragmentError&&(n.loadError=0);let e=n.details;e===t.details&&e.advanced&&(e=void 0),this.playlistLoaded(r,t,e)}else null!=(s=t.deliveryDirectives)&&s.skip&&(i.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=this.getUrlWithDirectives(e.uri,t),r=this.currentLevelIndex,i=e.attrs["PATHWAY-ID"],n=e.details,a=null==n?void 0:n.age;this.log(`Loading level index ${r}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${i?" Pathway "+i:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${s}`),this.hls.trigger(Events.LEVEL_LOADING,{url:s,level:r,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(1===this._levels.length)return;const s=this._levels.filter(((t,s)=>s!==e||(this.steering&&this.steering.removeLevel(t),t===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,t.details&&t.details.fragments.forEach((e=>e.level=-1))),!1)));reassignFragmentLevelIndexes(s),this._levels=s,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const r=s.length-1;this._firstLevel=Math.min(this._firstLevel,r),this._startLevel&&(this._startLevel=Math.min(this._startLevel,r)),this.hls.trigger(Events.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(Events.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function assignTrackIdsByGroup(e){const t={};e.forEach((e=>{const s=e.groupId||"";e.id=t[s]=t[s]||0,t[s]++}))}const STALL_MINIMUM_DURATION_MS=250,MAX_START_GAP_JUMP=2,SKIP_BUFFER_HOLE_STEP_SECONDS=.1,SKIP_BUFFER_RANGE_START=.05;class GapController extends Logger{constructor(e,t,s,r){super("gap-controller",r.logger),this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.ended=0,this.config=e,this.media=t,this.fragmentTracker=s,this.hls=r}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,t,s,r){const{config:i,media:n,stalled:a}=this;if(null===n)return;const{currentTime:o,seeking:l}=n,d=this.seeking&&!l,h=!this.seeking&&l;if(this.seeking=l,o!==e){if(e&&(this.ended=0),this.moved=!0,l||(this.nudgeRetry=0),null!==a){if(this.stallReported){const e=self.performance.now()-a;this.warn(`playback not stuck anymore @${o}, after ${Math.round(e)}ms`),this.stallReported=!1}this.stalled=null}return}if(h||d)return void(this.stalled=null);if(n.paused&&!l||n.ended||0===n.playbackRate||!BufferHelper.getBuffered(n).length)return!this.ended&&n.ended&&(this.ended=o||1,this.hls.trigger(Events.MEDIA_ENDED,{stalled:!1})),void(this.nudgeRetry=0);const c=BufferHelper.bufferInfo(n,o,0),u=c.nextStart||0;if(l){const e=c.len>2,s=!u||t&&t.start<=o||u-o>2&&!this.fragmentTracker.getPartialFragment(o);if(e||s)return;this.moved=!1}if(!this.moved&&null!==this.stalled){if(!(c.len>0)&&!u)return;const e=Math.max(u,c.start||0)-o,t=!(null==s||!s.live)?2*s.targetduration:2,r=this.fragmentTracker.getPartialFragment(o);if(e>0&&(e<=t||r))return void(n.paused||this._trySkipBufferHole(r))}const f=self.performance.now();if(null===a)return void(this.stalled=f);const g=f-a;if(!l&&g>=250){if(r===State.ENDED&&(null==s||!s.live)&&Math.abs(o-((null==s?void 0:s.edge)||0))<1){if(g<1e3||this.ended)return;return this.ended=o||1,void this.hls.trigger(Events.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(c),!this.media)return}const m=BufferHelper.bufferInfo(n,o,i.maxBufferHole);this._tryFixBufferStall(m,g)}_tryFixBufferStall(e,t){const{config:s,fragmentTracker:r,media:i}=this;if(null===i)return;const n=i.currentTime,a=r.getPartialFragment(n);if(a){if(this._trySkipBufferHole(a)||!this.media)return}(e.len>s.maxBufferHole||e.nextStart&&e.nextStart-n<s.maxBufferHole)&&t>1e3*s.highBufferWatchdogPeriod&&(this.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){const{hls:t,media:s,stallReported:r}=this;if(!r&&s){this.stallReported=!0;const r=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${JSON.stringify(e)})`);this.warn(r.message),t.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:e.len})}}_trySkipBufferHole(e){const{config:t,hls:s,media:r}=this;if(null===r)return 0;const i=r.currentTime,n=BufferHelper.bufferInfo(r,i,0),a=i<n.start?n.start:n.nextStart;if(a){const o=n.len<=t.maxBufferHole,l=n.len>0&&n.len<1&&r.readyState<3,d=a-i;if(d>0&&(o||l)){if(d>t.maxBufferHole){const{fragmentTracker:t}=this;let s=!1;if(0===i){const e=t.getAppendedFrag(0,PlaylistLevelType.MAIN);e&&a<e.end&&(s=!0)}if(!s){const s=e||t.getAppendedFrag(i,PlaylistLevelType.MAIN);if(s){let e=!1,r=s.end;for(;r<a;){const s=t.getPartialFragment(r);if(!s){e=!0;break}r+=s.duration}if(e)return 0}}}const n=Math.max(a+.05,i+.1);if(this.warn(`skipping hole, adjusting currentTime from ${i} to ${n}`),this.moved=!0,this.stalled=null,r.currentTime=n,e&&!e.gap){const t=new Error(`fragment loaded with buffer holes, seeking from ${i} to ${n}`);s.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:t,reason:t.message,frag:e})}return n}}return 0}_tryNudgeBuffer(){const{config:e,hls:t,media:s,nudgeRetry:r}=this;if(null===s)return;const i=s.currentTime;if(this.nudgeRetry++,r<e.nudgeMaxRetry){const n=i+(r+1)*e.nudgeOffset,a=new Error(`Nudging 'currentTime' from ${i} to ${n}`);this.warn(a.message),s.currentTime=n,t.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_NUDGE_ON_STALL,error:a,fatal:!1})}else{const s=new Error(`Playhead still not moving while enough data buffered @${i} after ${e.nudgeMaxRetry} nudges`);this.error(s.message),t.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_STALLED_ERROR,error:s,fatal:!0})}}}function getSourceBuffer(){return self.SourceBuffer||self.WebKitSourceBuffer}function isMSESupported(){if(!getMediaSource())return!1;const e=getSourceBuffer();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}function isSupported(){if(!isMSESupported())return!1;const e=getMediaSource();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((t=>e.isTypeSupported(mimeTypeForCodec(t,"video"))))||["mp4a.40.2","fLaC"].some((t=>e.isTypeSupported(mimeTypeForCodec(t,"audio")))))}function changeTypeSupported(){var e;const t=getSourceBuffer();return"function"==typeof(null==t||null==(e=t.prototype)?void 0:e.changeType)}const TICK_INTERVAL=100;class StreamController extends BaseStreamController{constructor(e,t,s){super(e,t,s,"stream-controller",PlaylistLevelType.MAIN),this.audioCodecSwap=!1,this.gapController=null,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=()=>{const e=this.gapController;e&&(e.ended=0),this.tick()},this.onMediaSeeked=()=>{const e=this.media,t=e?e.currentTime:null;isFiniteNumber(t)&&this.log(`Media seeked to ${t.toFixed(3)}`);const s=this.getMainFwdBufferInfo();null!==s&&0!==s.len?this.tick():this.warn(`Main forward buffer length on "seeked" event ${s?s.len:"empty"})`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Events.LEVEL_LOADING,this.onLevelLoading,this),e.on(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Events.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Events.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(Events.BUFFER_CREATED,this.onBufferCreated,this),e.on(Events.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Events.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Events.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Events.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(Events.BUFFER_CREATED,this.onBufferCreated,this),e.off(Events.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Events.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:s,hls:r}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let e=r.startLevel;-1===e&&(r.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=r.firstAutoLevel),r.nextLoadLevel=e,this.level=r.loadLevel,this._hasEnoughToStart=!1}s>0&&-1===e&&!t&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=State.IDLE,this.nextLoadPosition=this.lastCurrentTime=e,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=State.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case State.WAITING_LEVEL:{const{levels:e,level:t}=this,s=null==e?void 0:e[t],r=null==s?void 0:s.details;if(r&&(!r.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(r))break;this.state=State.IDLE;break}if(this.hls.nextLoadLevel!==this.level){this.state=State.IDLE;break}break}case State.FRAG_LOADING_WAITING_RETRY:{var e;const t=self.performance.now(),s=this.retryDate;if(!s||t>=s||null!=(e=this.media)&&e.seeking){const{levels:e,level:t}=this,s=null==e?void 0:e[t];this.resetStartWhenNotLoaded(s||null),this.state=State.IDLE}}}this.state===State.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:s,media:r}=this;if(null===t||!r&&(this.startFragRequested||!e.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const i=this.buffering?e.nextLoadLevel:e.loadLevel;if(null==s||!s[i])return;const n=s[i],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const e={};return 2===this.altAudio&&(e.type="video"),this.hls.trigger(Events.BUFFER_EOS,e),void(this.state=State.ENDED)}if(!this.buffering)return;e.loadLevel!==i&&-1===e.manualLevel&&this.log(`Adapting to level ${i} from level ${this.level}`),this.level=e.nextLoadLevel=i;const l=n.details;if(!l||this.state===State.WAITING_LEVEL||this.waitForLive(n))return this.level=i,this.state=State.WAITING_LEVEL,void(this.startFragRequested=!1);const d=a.len,h=this.getMaxBufferLength(n.maxBitrate);if(d>=h)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const c=this.backtrackFragment?this.backtrackFragment.start:a.end;let u=this.getNextFragment(c,l);if(this.couldBacktrack&&!this.fragPrevious&&u&&isMediaFragment(u)&&this.fragmentTracker.getState(u)!==FragmentState.OK){var f;const e=(null!=(f=this.backtrackFragment)?f:u).sn-l.startSN,t=l.fragments[e-1];t&&u.cc===t.cc&&(u=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(u&&this.isLoopLoading(u,c)){if(!u.gap){const e=this.audioOnly&&!this.altAudio?ElementaryStreamTypes.AUDIO:ElementaryStreamTypes.VIDEO,t=(e===ElementaryStreamTypes.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,PlaylistLevelType.MAIN)}u=this.getNextFragmentLoopLoading(u,l,a,PlaylistLevelType.MAIN,h)}u&&(!u.initSegment||u.initSegment.data||this.bitrateTest||(u=u.initSegment),this.loadFragment(u,n,c))}loadFragment(e,t,s){const r=this.fragmentTracker.getState(e);r===FragmentState.NOT_LOADED||r===FragmentState.PARTIAL?isMediaFragment(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,s):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,PlaylistLevelType.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(null!=t&&t.readyState){let s;const r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);const i=this.getLevelDetails();if(null!=i&&i.live){const e=this.getMainFwdBufferInfo();if(!e||e.len<2*i.targetduration)return}if(!t.paused&&e){const t=e[this.hls.nextLoadLevel],r=this.fragLastKbps;s=r&&this.fragCurrent?this.fragCurrent.duration*t.maxBitrate/(1e3*r)+1:0}else s=0;const n=this.getBufferedFrag(t.currentTime+s);if(n){const e=this.followingBufferedFrag(n);if(e){this.abortCurrentFrag();const t=e.maxStartPTS?e.maxStartPTS:e.start,s=e.duration,r=Math.max(n.end,t+Math.min(Math.max(s-this.config.maxFragLookUpTolerance,s*(this.couldBacktrack?.5:.125)),s*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(r,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case State.KEY_LOADING:case State.FRAG_LOADING:case State.FRAG_LOADING_WAITING_RETRY:case State.PARSING:case State.PARSED:this.state=State.IDLE}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,2===this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const s=t.media;s.removeEventListener("playing",this.onMediaPlaying),s.removeEventListener("seeked",this.onMediaSeeked),s.addEventListener("playing",this.onMediaPlaying),s.addEventListener("seeked",this.onMediaSeeked),this.gapController=new GapController(this.config,s,this.fragmentTracker,this.hls)}onMediaDetaching(e,t){const{media:s}=this;s&&(s.removeEventListener("playing",this.onMediaPlaying),s.removeEventListener("seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching(e,t);!!t.transferMedia||(this._hasEnoughToStart=!1)}triggerEnded(){const e=this.gapController;if(e){var t;if(e.ended)return;e.ended=(null==(t=this.media)?void 0:t.currentTime)||1}this.hls.trigger(Events.MEDIA_ENDED,{stalled:!1})}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(Events.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let s=!1,r=!1;t.levels.forEach((e=>{const t=e.audioCodec;t&&(s=s||-1!==t.indexOf("mp4a.40.2"),r=r||-1!==t.indexOf("mp4a.40.5"))})),this.audioCodecSwitch=s&&r&&!changeTypeSupported(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:s}=this;if(!s||this.state!==State.IDLE)return;const r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=State.WAITING_LEVEL)}onLevelLoaded(e,t){var s;const{levels:r,startFragRequested:i}=this,n=t.level,a=t.details,o=a.totalduration;if(!r)return void this.warn(`Levels were reset while loading level ${n}`);this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=t.levelInfo,d=this.fragCurrent;!d||this.state!==State.FRAG_LOADING&&this.state!==State.FRAG_LOADING_WAITING_RETRY||d.level!==t.level&&d.loader&&this.abortCurrentFrag();let h=0;if(a.live||null!=(s=l.details)&&s.live){var c;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;h=this.alignPlaylists(a,l.details,null==(c=this.levelLastLoaded)?void 0:c.details)}if(l.details=a,this.levelLastLoaded=l,i||this.setStartPosition(a,h),this.hls.trigger(Events.LEVEL_UPDATED,{details:a,level:n}),this.state===State.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=State.IDLE}i&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:s}=this;if(!s)return;const r=this.hls.liveSyncPosition,i=s.currentTime,n=e.fragmentStart,a=e.edge,o=i>=n-t.maxFragLookUpTolerance&&i<=a;if(null!==r&&s.duration>r&&(i<r||!o)){const n=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;(!o&&s.readyState<4||i<a-n)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),s.readyState&&(this.warn(`Playback: ${i.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${r.toFixed(3)}`),s.currentTime=r))}}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:r,payload:i}=e,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const a=n[s.level];if(!a)return void this.warn(`Level ${s.level} not found on progress`);const o=a.details;if(!o)return this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),void this.fragmentTracker.removeFragment(s);const l=a.videoCodec,d=o.PTSKnown||!o.live,h=null==(t=s.initSegment)?void 0:t.data,c=this._getAudioCodec(a),u=this.transmuxer=this.transmuxer||new TransmuxerInterface(this.hls,PlaylistLevelType.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=r?r.index:-1,g=-1!==f,m=new ChunkMetadata(s.level,s.sn,s.stats.chunkCount,i.byteLength,f,g),p=this.initPTS[s.cc];u.push(i,h,c,l,s,r,o.totalduration,d,m,p)}onAudioTrackSwitching(e,t){const s=this.hls,r=2===this.altAudio;if(useAlternateAudio(t.url,s))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const e=this.fragCurrent;e&&(this.log("Switching to main audio track, cancel main fragment load"),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();r&&(s.trigger(Events.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),s.trigger(Events.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const s=useAlternateAudio(t.url,this.hls);if(s){const e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=e)}this.altAudio=s?2:0,this.tick()}onBufferCreated(e,t){const s=t.tracks;let r,i,n=!1;for(const e in s){const t=s[e];if("main"===t.id){if(i=e,r=t,"video"===e){const t=s[e];t&&(this.videoBuffer=t.buffer)}}else n=!0}n&&r?(this.log(`Alternate track found, use ${i}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:s,part:r}=t,i=s.type===PlaylistLevelType.MAIN;if(i){if(this.fragContextChanged(s))return this.warn(`Fragment ${s.sn}${r?" p: "+r.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===State.PARSED&&(this.state=State.IDLE));const e=r?r.stats:s.stats;this.fragLastKbps=Math.round(8*e.total/(e.buffering.end-e.loading.first)),isMediaFragment(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,r)}const n=this.media;n&&(!this._hasEnoughToStart&&n.buffered.length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),i&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal)this.state=State.ERROR;else switch(t.details){case ErrorDetails.FRAG_GAP:case ErrorDetails.FRAG_PARSING_ERROR:case ErrorDetails.FRAG_DECRYPT_ERROR:case ErrorDetails.FRAG_LOAD_ERROR:case ErrorDetails.FRAG_LOAD_TIMEOUT:case ErrorDetails.KEY_LOAD_ERROR:case ErrorDetails.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(PlaylistLevelType.MAIN,t);break;case ErrorDetails.LEVEL_LOAD_ERROR:case ErrorDetails.LEVEL_LOAD_TIMEOUT:case ErrorDetails.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==State.WAITING_LEVEL||(null==(s=t.context)?void 0:s.type)!==PlaylistContextType.LEVEL||(this.state=State.IDLE);break;case ErrorDetails.BUFFER_APPEND_ERROR:case ErrorDetails.BUFFER_FULL_ERROR:if(!t.parent||"main"!==t.parent)return;if(t.details===ErrorDetails.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case ErrorDetails.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}checkBuffer(){const{media:e,gapController:t}=this;if(e&&t&&e.readyState){if(this._hasEnoughToStart||!BufferHelper.getBuffered(e).length){const e=this.state,s=e!==State.IDLE?this.fragCurrent:null,r=this.getLevelDetails();t.poll(this.lastCurrentTime,s,r,e)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=State.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==ElementaryStreamTypes.AUDIO||this.audioOnly&&!this.altAudio){const e=(t===ElementaryStreamTypes.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(e,t,PlaylistLevelType.MAIN),this.tick()}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let s=this.startPosition;if(s>=0){if(e.seeking)return void this.log(`could not seek to ${s}, already seeking at ${t}`);const r=this.getLevelDetails(),i=this.config.timelineOffset;i&&s&&(s+=(null==r?void 0:r.appliedTimelineOffset)||i);const n=BufferHelper.getBuffered(e),a=n.length?n.start(0):0,o=a-s,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);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`),s+=o,this.startPosition=s),t<s&&(this.log(`seek to target start position ${s} from current time ${t} buffer start ${a}`),e.currentTime=s)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then((e=>{const{hls:s}=this,r=null==e?void 0:e.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=State.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const i=r.stats;i.parsing.start=i.parsing.end=i.buffering.start=i.buffering.end=self.performance.now(),s.trigger(Events.FRAG_LOADED,e),r.bitrateTest=!1}))}_handleTransmuxComplete(e){var t;const s=this.playlistType,{hls:r}=this,{remuxResult:i,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:d}=a,{video:h,text:c,id3:u,initSegment:f}=i,{details:g}=d,m=this.altAudio?void 0:i.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=State.PARSING,f){if(null!=f&&f.tracks){const e=o.initSegment||o;this._bufferInitSegment(d,f.tracks,e,n),r.trigger(Events.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:s,tracks:f.tracks})}const e=f.initPTS,t=f.timescale;isFiniteNumber(e)&&(this.initPTS[o.cc]={baseTime:e,timescale:t},r.trigger(Events.INIT_PTS_FOUND,{frag:o,id:s,initPTS:e,timescale:t}))}if(h&&g){const e=g.fragments[o.sn-1-g.startSN],t=o.sn===g.startSN,s=!e||o.cc>e.cc;if(!1!==i.independent){const{startPTS:e,endPTS:r,startDTS:i,endDTS:a}=h;if(l)l.elementaryStreams[h.type]={startPTS:e,endPTS:r,startDTS:i,endDTS:a};else if(h.firstKeyFrame&&h.independent&&1===n.id&&!s&&(this.couldBacktrack=!0),h.dropped&&h.independent){const i=this.getMainFwdBufferInfo(),n=(i?i.end:this.getLoadPosition())+this.config.maxBufferHole,l=h.firstKeyFramePTS?h.firstKeyFramePTS:e;if(!t&&n<l-this.config.maxBufferHole&&!s)return void this.backtrack(o);s&&(o.gap=!0),o.setElementaryStreamInfo(h.type,o.start,r,o.start,a,!0)}else t&&e-(g.appliedTimelineOffset||0)>2&&(o.gap=!0);o.setElementaryStreamInfo(h.type,e,r,i,a),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(h,o,l,n,t||s)}else{if(!t&&!s)return void this.backtrack(o);o.gap=!0}}if(m){const{startPTS:e,endPTS:t,startDTS:s,endDTS:r}=m;l&&(l.elementaryStreams[ElementaryStreamTypes.AUDIO]={startPTS:e,endPTS:t,startDTS:s,endDTS:r}),o.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO,e,t,s,r),this.bufferFragmentData(m,o,l,n)}if(g&&null!=u&&null!=(t=u.samples)&&t.length){const e={id:s,frag:o,details:g,samples:u.samples};r.trigger(Events.FRAG_PARSING_METADATA,e)}if(g&&c){const e={id:s,frag:o,details:g,samples:c.samples};r.trigger(Events.FRAG_PARSING_USERDATA,e)}}}_bufferInitSegment(e,t,s,r){if(this.state!==State.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;const{audio:i,video:n,audiovideo:a}=t;if(i){let s=pickMostCompleteCodecName(i.codec,e.audioCodec);"mp4a"===s&&(s="mp4a.40.5");const r=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){s&&(s=-1!==s.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const e=i.metadata;e&&"channelCount"in e&&1!==(e.channelCount||1)&&-1===r.indexOf("firefox")&&(s="mp4a.40.5")}s&&-1!==s.indexOf("mp4a.40.5")&&-1!==r.indexOf("android")&&"audio/mpeg"!==i.container&&(s="mp4a.40.2",this.log(`Android: force audio codec to ${s}`)),e.audioCodec&&e.audioCodec!==s&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${s}"`),i.levelCodec=s,i.id="main",this.log(`Init audio buffer, container:${i.container}, codecs[selected/level/parsed]=[${s||""}/${e.audioCodec||""}/${i.codec}]`),delete t.audiovideo}if(n){n.levelCodec=e.videoCodec,n.id="main";const s=n.codec;if(4===(null==s?void 0:s.length))switch(s){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e"}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${e.videoCodec||""}/${s}${n.codec!==s?" parsed-corrected="+n.codec:""}}]`),delete t.audiovideo}a&&(this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.codecs}/${a.codec}]`),delete t.video,delete t.audio);const o=Object.keys(t);if(o.length){if(this.hls.trigger(Events.BUFFER_CODECS,t),!this.hls)return;o.forEach((e=>{const i=t[e].initSegment;null!=i&&i.byteLength&&this.hls.trigger(Events.BUFFER_APPENDING,{type:e,data:i,frag:s,part:null,chunkMeta:r,parent:s.type})}))}this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,PlaylistLevelType.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,s=null==e?void 0:e[t];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=State.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&!1===e.seeking){const s=e.currentTime;if(BufferHelper.isBuffered(e,s)?t=this.getAppendedFrag(s):BufferHelper.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;const e=this.fragPlaying,s=t.level;e&&t.sn===e.sn&&e.level===s||(this.fragPlaying=t,this.hls.trigger(Events.FRAG_CHANGED,{frag:t}),e&&e.level===s||this.hls.trigger(Events.LEVEL_SWITCHED,{level:s}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return isFiniteNumber(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(isFiniteNumber(t)){const e=this.getLevelDetails(),s=this.currentFrag||(e?findFragmentByPTS(null,e.fragments,t):null);if(s){const e=s.programDateTime;if(null!==e){const r=e+1e3*(t-s.start);return new Date(r)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class KeyLoader{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const s in this.keyUriToKeyInfo){const r=this.keyUriToKeyInfo[s].loader;if(r){var t;if(e&&e!==(null==(t=r.context)?void 0:t.frag.type))return;r.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=ErrorDetails.KEY_LOAD_ERROR,s,r,i){return new LoadError({type:ErrorTypes.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:i,error:s,networkDetails:r})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:s,cc:r}=e;for(let e=0;e<t.length;e++){const i=t[e];if(r<=i.cc&&("initSegment"===s||"initSegment"===i.sn||s<i.sn)){this.emeController.selectKeySystemFormat(i).then((e=>{i.setKeyFormat(e)}));break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(e).then((t=>this.loadInternal(e,t))):this.loadInternal(e)}loadInternal(e,t){var s,r;t&&e.setKeyFormat(t);const i=e.decryptdata;if(!i){const s=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,ErrorDetails.KEY_LOAD_ERROR,s))}const n=i.uri;if(!n)return Promise.reject(this.createKeyLoadError(e,ErrorDetails.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));let a=this.keyUriToKeyInfo[n];if(null!=(s=a)&&s.decryptdata.key)return i.key=a.decryptdata.key,Promise.resolve({frag:e,keyInfo:a});var o;if(null!=(r=a)&&r.keyLoadPromise)switch(null==(o=a.mediaKeySessionContext)?void 0:o.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return a.keyLoadPromise.then((t=>(i.key=t.keyInfo.decryptdata.key,{frag:e,keyInfo:a})))}switch(a=this.keyUriToKeyInfo[n]={decryptdata:i,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},i.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===i.keyFormat?this.loadKeyHTTP(a,e):this.loadKeyEME(a,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(a,e);default:return Promise.reject(this.createKeyLoadError(e,ErrorDetails.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${i.method}"`)))}}loadKeyEME(e,t){const s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const t=this.emeController.loadKey(s);if(t)return(e.keyLoadPromise=t.then((t=>(e.mediaKeySessionContext=t,s)))).catch((t=>{throw e.keyLoadPromise=null,t}))}return Promise.resolve(s)}loadKeyHTTP(e,t){const s=this.config,r=new(0,s.loader)(s);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise(((i,n)=>{const a={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},o=s.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(e,t,s,r)=>{const{frag:a,keyInfo:o,url:l}=s;if(!a.decryptdata||o!==this.keyUriToKeyInfo[l])return n(this.createKeyLoadError(a,ErrorDetails.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),r));o.decryptdata.key=a.decryptdata.key=new Uint8Array(e.data),a.keyLoader=null,o.loader=null,i({frag:a,keyInfo:o})},onError:(e,s,r,i)=>{this.resetLoader(s),n(this.createKeyLoadError(t,ErrorDetails.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),r,_objectSpread2({url:a.url,data:void 0},e)))},onTimeout:(e,s,r)=>{this.resetLoader(s),n(this.createKeyLoadError(t,ErrorDetails.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),r))},onAbort:(e,s,r)=>{this.resetLoader(s),n(this.createKeyLoadError(t,ErrorDetails.INTERNAL_ABORTED,new Error("key loading aborted"),r))}};r.load(a,l,d)}))}resetLoader(e){const{frag:t,keyInfo:s,url:r}=e,i=s.loader;t.keyLoader===i&&(t.keyLoader=null,s.loader=null),delete this.keyUriToKeyInfo[r],i&&i.destroy()}}function mapContextToLevelType(e){const{type:t}=e;switch(t){case PlaylistContextType.AUDIO_TRACK:return PlaylistLevelType.AUDIO;case PlaylistContextType.SUBTITLE_TRACK:return PlaylistLevelType.SUBTITLE;default:return PlaylistLevelType.MAIN}}function getResponseUrl(e,t){let s=e.url;return void 0!==s&&0!==s.indexOf("data:")||(s=t.url),s}class PlaylistLoader{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.LEVEL_LOADING,this.onLevelLoading,this),e.on(Events.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(Events.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(Events.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.LEVEL_LOADING,this.onLevelLoading,this),e.off(Events.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(Events.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(Events.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,s=t.pLoader,r=t.loader,i=new(s||r)(t);return this.loaders[e.type]=i,i}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:PlaylistContextType.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:s,level:r,pathwayId:i,url:n,deliveryDirectives:a,levelInfo:o}=t;this.load({id:s,level:r,pathwayId:i,responseType:"text",type:PlaylistContextType.LEVEL,url:n,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(e,t){const{id:s,groupId:r,url:i,deliveryDirectives:n,track:a}=t;this.load({id:s,groupId:r,level:null,responseType:"text",type:PlaylistContextType.AUDIO_TRACK,url:i,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(e,t){const{id:s,groupId:r,url:i,deliveryDirectives:n,track:a}=t;this.load({id:s,groupId:r,level:null,responseType:"text",type:PlaylistContextType.SUBTITLE_TRACK,url:i,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(e,t){const s=this.loaders[PlaylistContextType.LEVEL];if(s){const e=s.context;e&&!t.levels.some((t=>t===e.levelOrTrack))&&(s.abort(),delete this.loaders[PlaylistContextType.LEVEL])}}load(e){var t;const s=this.hls.config;let r,i=this.getInternalLoader(e);if(i){const t=this.hls.logger,s=i.context;if(s&&s.levelOrTrack===e.levelOrTrack&&(s.url===e.url||s.deliveryDirectives&&!e.deliveryDirectives))return void(s.url===e.url?t.log(`[playlist-loader]: ignore ${e.url} ongoing request`):t.log(`[playlist-loader]: ignore ${e.url} in favor of ${s.url}`));t.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),i.abort()}if(r=e.type===PlaylistContextType.MANIFEST?s.manifestLoadPolicy.default:_extends({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(e),isFiniteNumber(null==(t=e.deliveryDirectives)?void 0:t.part)){let t;if(e.type===PlaylistContextType.LEVEL&&null!==e.level?t=this.hls.levels[e.level].details:e.type===PlaylistContextType.AUDIO_TRACK&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===PlaylistContextType.SUBTITLE_TRACK&&null!==e.id&&(t=this.hls.subtitleTracks[e.id].details),t){const e=t.partTarget,s=t.targetduration;if(e&&s){const t=1e3*Math.max(3*e,.8*s);r=_extends({},r,{maxTimeToFirstByteMs:Math.min(t,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,r.maxTimeToFirstByteMs)})}}}const n=r.errorRetry||r.timeoutRetry||{},a={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},o={onSuccess:(e,t,s,r)=>{const i=this.getInternalLoader(s);this.resetInternalLoader(s.type);const n=e.data;0===n.indexOf("#EXTM3U")?(t.parsing.start=performance.now(),M3U8Parser.isMediaPlaylist(n)||s.type!==PlaylistContextType.MANIFEST?this.handleTrackOrLevelPlaylist(e,t,s,r||null,i):this.handleMasterPlaylist(e,t,s,r)):this.handleManifestParsingError(e,s,new Error("no EXTM3U delimiter"),r||null,t)},onError:(e,t,s,r)=>{this.handleNetworkError(t,s,!1,e,r)},onTimeout:(e,t,s)=>{this.handleNetworkError(t,s,!0,void 0,e)}};i.load(e,a,o)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,r){const i=this.hls,n=e.data,a=getResponseUrl(e,s),o=M3U8Parser.parseMasterPlaylist(n,a);if(o.playlistParsingError)return void this.handleManifestParsingError(e,s,o.playlistParsingError,r,t);const{contentSteering:l,levels:d,sessionData:h,sessionKeys:c,startTimeOffset:u,variableList:f}=o;this.variableList=f;const{AUDIO:g=[],SUBTITLES:m,"CLOSED-CAPTIONS":p}=M3U8Parser.parseMasterPlaylistMedia(n,a,o);if(g.length){g.some((e=>!e.url))||!d[0].audioCodec||d[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 AttrList({}),bitrate:0,url:""}))}i.trigger(Events.MANIFEST_LOADED,{levels:d,audioTracks:g,subtitles:m,captions:p,contentSteering:l,url:a,stats:t,networkDetails:r,sessionData:h,sessionKeys:c,startTimeOffset:u,variableList:f})}handleTrackOrLevelPlaylist(e,t,s,r,i){const n=this.hls,{id:a,level:o,type:l}=s,d=getResponseUrl(e,s),h=isFiniteNumber(o)?o:isFiniteNumber(a)?a:0,c=mapContextToLevelType(s),u=M3U8Parser.parseLevelPlaylist(e.data,d,h,c,0,this.variableList);if(l===PlaylistContextType.MANIFEST){const e={attrs:new AttrList({}),bitrate:0,details:u,name:"",url:d};u.requestScheduled=t.loading.start+computeReloadInterval(u,0),n.trigger(Events.MANIFEST_LOADED,{levels:[e],audioTracks:[],url:d,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=u,this.handlePlaylistLoaded(u,e,t,s,r,i)}handleManifestParsingError(e,t,s,r,i){this.hls.trigger(Events.ERROR,{type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.MANIFEST_PARSING_ERROR,fatal:t.type===PlaylistContextType.MANIFEST,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:r,stats:i})}handleNetworkError(e,t,s=!1,r,i){let n=`A network ${s?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${e.type}`;e.type===PlaylistContextType.LEVEL?n+=`: ${e.level} id: ${e.id}`:e.type!==PlaylistContextType.AUDIO_TRACK&&e.type!==PlaylistContextType.SUBTITLE_TRACK||(n+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let o=ErrorDetails.UNKNOWN,l=!1;const d=this.getInternalLoader(e);switch(e.type){case PlaylistContextType.MANIFEST:o=s?ErrorDetails.MANIFEST_LOAD_TIMEOUT:ErrorDetails.MANIFEST_LOAD_ERROR,l=!0;break;case PlaylistContextType.LEVEL:o=s?ErrorDetails.LEVEL_LOAD_TIMEOUT:ErrorDetails.LEVEL_LOAD_ERROR,l=!1;break;case PlaylistContextType.AUDIO_TRACK:o=s?ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:ErrorDetails.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case PlaylistContextType.SUBTITLE_TRACK:o=s?ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:ErrorDetails.SUBTITLE_LOAD_ERROR,l=!1}d&&this.resetInternalLoader(e.type);const h={type:ErrorTypes.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:d,context:e,error:a,networkDetails:t,stats:i};if(r){const s=(null==t?void 0:t.url)||e.url;h.response=_objectSpread2({url:s,data:void 0},r)}this.hls.trigger(Events.ERROR,h)}handlePlaylistLoaded(e,t,s,r,i,n){const a=this.hls,{type:o,level:l,id:d,groupId:h,deliveryDirectives:c}=r,u=getResponseUrl(t,r),f=mapContextToLevelType(r),g="number"==typeof r.level&&f===PlaylistLevelType.MAIN?l:void 0;if(!e.fragments.length){const n=e.playlistParsingError=new Error("No Segments found in Playlist");return void a.trigger(Events.ERROR,{type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.LEVEL_EMPTY_ERROR,fatal:!1,url:u,error:n,reason:n.message,response:t,context:r,level:g,parent:f,networkDetails:i,stats:s})}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const m=e.playlistParsingError;if(m)a.trigger(Events.ERROR,{type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.LEVEL_PARSING_ERROR,fatal:!1,url:u,error:m,reason:m.message,response:t,context:r,level:g,parent:f,networkDetails:i,stats:s});else switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case PlaylistContextType.MANIFEST:case PlaylistContextType.LEVEL:a.trigger(Events.LEVEL_LOADED,{details:e,levelInfo:r.levelOrTrack||a.levels[0],level:g||0,id:d||0,stats:s,networkDetails:i,deliveryDirectives:c,withoutMultiVariant:o===PlaylistContextType.MANIFEST});break;case PlaylistContextType.AUDIO_TRACK:a.trigger(Events.AUDIO_TRACK_LOADED,{details:e,track:r.levelOrTrack,id:d||0,groupId:h||"",stats:s,networkDetails:i,deliveryDirectives:c});break;case PlaylistContextType.SUBTITLE_TRACK:a.trigger(Events.SUBTITLE_TRACK_LOADED,{details:e,track:r.levelOrTrack,id:d||0,groupId:h||"",stats:s,networkDetails:i,deliveryDirectives:c})}}}class Hls{static get version(){return version}static isMSESupported(){return isMSESupported()}static isSupported(){return isSupported()}static getMediaSource(){return getMediaSource()}static get Events(){return Events}static get MetadataSchema(){return MetadataSchema}static get ErrorTypes(){return ErrorTypes}static get ErrorDetails(){return ErrorDetails}static get DefaultConfig(){return Hls.defaultConfig?Hls.defaultConfig:hlsDefaultConfig}static set DefaultConfig(e){Hls.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new EventEmitter,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=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 t=this.logger=enableLogs(e.debug||!1,"Hls instance",e.assetPlayerId),s=this.config=mergeConfig(Hls.DefaultConfig,e,t);this.userConfig=e,s.progressive&&enableStreamingMode(s,t);const{abrController:r,bufferController:i,capLevelController:n,errorController:a,fpsController:o}=s,l=new a(this),d=this.abrController=new r(this),h=new FragmentTracker(this),c=s.interstitialsController,u=c?this.interstitialsController=new c(this,Hls):null,f=this.bufferController=new i(this,h),g=this.capLevelController=new n(this),m=new o(this),p=new PlaylistLoader(this),E=s.contentSteeringController,y=E?new E(this):null,v=this.levelController=new LevelController(this,y),T=new ID3TrackController(this),S=new KeyLoader(this.config),A=this.streamController=new StreamController(this,h,S);g.setStreamController(A),m.setStreamController(A);const L=[p,v,A];u&&L.splice(1,0,u),y&&L.splice(1,0,y),this.networkControllers=L;const I=[d,f,g,m,T,h];this.audioTrackController=this.createController(s.audioTrackController,L);const R=s.audioStreamController;R&&L.push(new R(this,h,S)),this.subtitleTrackController=this.createController(s.subtitleTrackController,L);const D=s.subtitleStreamController;D&&L.push(new D(this,h,S)),this.createController(s.timelineController,I),S.emeController=this.emeController=this.createController(s.emeController,I),this.cmcdController=this.createController(s.cmcdController,I),this.latencyController=this.createController(LatencyController,I),this.coreComponents=I,L.push(l);const b=l.onErrorOut;"function"==typeof b&&this.on(Events.ERROR,b,l),this.on(Events.MANIFEST_LOADED,p.onManifestLoaded,p)}createController(e,t){if(e){const s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,r){this._emitter.off(e,t,s,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;const s=e===Events.ERROR;this.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERNAL_EXCEPTION,fatal:s,event:e,error:t}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(Events.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach((e=>e.destroy())),this.networkControllers.length=0,this.coreComponents.forEach((e=>e.destroy())),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const t=new Error(`attachMedia failed: invalid argument (${e})`);return void this.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.ATTACH_MEDIA_ERROR,fatal:!0,error:t})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,s=t?e.media:e,r=t?e:{media:s};this._media=s,this.trigger(Events.MEDIA_ATTACHING,r)}detachMedia(){this.logger.log("detachMedia"),this.trigger(Events.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(Events.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,s=this._url,r=this._url=urlToolkitExports.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),t&&s&&(s!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(Events.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(e,t),this.started&&this.networkControllers);s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!this.started&&this.networkControllers);e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach((e=>{e.resumeBuffering&&e.resumeBuffering()})))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach((e=>{e.pauseBuffering&&e.pauseBuffering()})))}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=null==e?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=uuid()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){isHdcpLevel(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const s=e.length;for(let r=0;r<s;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this;let r;if(r=-1===t&&null!=e&&e.length?e.length-1:t,s)for(let t=r;t--;){const r=e[t].attrs["HDCP-LEVEL"];if(r&&r<=s)return t}return r}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return(null==(t=this.audioTrackController)?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return(null==(t=this.subtitleTrackController)?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return!!e&&e.subtitleDisplay}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!(null==(e=this.bufferController)||!e.bufferedToEnd)}get interstitialsManager(){var e;return(null==(e=this.interstitialsController)?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){return getMediaDecodingInfoPromise(e,getAudioTracksByGroup(t),navigator.mediaCapabilities)}}Hls.defaultConfig=void 0;const OPTIONS_MAP={liveSyncDuration:{key:"targetLatency",val:10},liveMaxLatencyDuration:{key:"maxLatency",val:20},backBufferLength:{key:"bufferBehind",val:10},initialLiveManifestSize:{key:"minSegmentsStartPlay",val:3},preferManagedMediaSource:[{key:"preferMMS",val:!1},{key:"preferMMSStreaming",val:!1}],lowLatencyMode:{key:"useLowLatency",val:!0},startPosition:{key:"startTime",val:0},interstitialLiveLookAhead:{key:"preloadTime",val:30}};function getHlsConfig(e){const t={};Object.keys(OPTIONS_MAP).forEach((s=>{const r=OPTIONS_MAP[s];r instanceof Array?r.forEach((e=>{t[s]=e.val})):t[s]=e[r.key]||r.val}));const s="number"==typeof e.retryCount?e.retryCount:3,r="number"==typeof e.retryDelay?e.retryDelay:1e3,i=e.loadTimeout||1e4,n="number"==typeof e.manifestLoadTimeout?e.manifestLoadTimeout:1e4,a={maxNumRetry:s,retryDelayMs:r,maxRetryDelayMs:r,shouldRetry:(e,t)=>t<e.maxNumRetry},o={maxNumRetry:s,retryDelayMs:r,maxRetryDelayMs:r,shouldRetry:(e,t)=>t<e.maxNumRetry};return t.manifestLoadPolicy={default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:n,timeoutRetry:a,errorRetry:o}},t.playlistLoadPolicy={default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:i,timeoutRetry:a,errorRetry:o}},t.fragLoadPolicy={default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:i,timeoutRetry:a,errorRetry:o}},{...t,...e}}function initHlsEvents(e,t){e.on(Hls.Events.SUBTITLE_FRAG_PROCESSED,((e,{frag:s})=>{t.emit("core_event",{eventName:"core.subtitlesegments",list:s})})),e.on(Hls.Events.MANIFEST_PARSED,((e,{levels:s})=>{t.emit("core_event",{eventName:"core.hlsManifestParsed",list:s})})),e.on(Hls.Events.MANIFEST_LOADING,((e,{url:s})=>{t.emit("core_event",{eventName:"core.loadstart",url:s})})),e.on(Hls.Events.LEVEL_LOADING,((e,{url:s})=>{t.emit("core_event",{eventName:"core.loadstart",url:s})})),e.on(Hls.Events.FRAG_LOADING,((e,{frag:s})=>{t.emit("core_event",{eventName:"core.loadstart",url:s.url})})),e.on(Hls.Events.MANIFEST_LOADED,((e,s)=>{const{url:r}=s;t.emit("core_event",{eventName:"core.loadcomplete",url:r})})),e.on(Hls.Events.LEVEL_LOADED,((e,s)=>{const{details:r,stats:i}=s;t.emit("core_event",{eventName:"core.loadcomplete",...i,url:null==r?void 0:r.url})})),e.on(Hls.Events.FRAG_LOADED,((e,s)=>{const{frag:r}=s;t.emit("core_event",{eventName:"core.loadcomplete",url:r.url})})),e.on(Hls.Events.FRAG_PARSING_USERDATA,((e,{samples:s})=>{t.emit("core_event",{eventName:"core.sei",sei:s})})),e.on(Hls.Events.MANIFEST_LOADED,((e,{levels:s,networkDetails:r})=>{t.emit("core_event",{eventName:"core.hlsmanifestloaded",playlist:s}),t.emit("core_event",{eventName:"core.loadresponseheaders",headers:r.headers})})),e.on(Hls.Events.LEVEL_LOADED,((e,{details:s})=>{const r={};Object.keys(s.dateRanges).forEach((e=>{r[e]=s.dateRanges[e].attr["START-DATE"]})),t.emit("core_event",{eventName:"core.hlslevelloaded",playlist:{...s,segments:s.fragments,dateRanges:r}})})),[Hls.Events.AUDIO_TRACKS_UPDATED,Hls.Events.AUDIO_TRACK_SWITCHING,Hls.Events.AUDIO_TRACK_SWITCHED,Hls.Events.AUDIO_TRACK_LOADING,Hls.Events.AUDIO_TRACK_LOADED].forEach((s=>e.on(s,((e,r)=>t.emit(s,r))))),e.on(Hls.Events.ERROR,((s,r)=>{const{details:i,fatal:n,type:a,response:o,reason:l,error:d}=r;if(!n)return;let h,c;switch(a){case Hls.ErrorTypes.NETWORK_ERROR:h=2100,i.includes("TimeOut")?h=2101:403===(null==o?void 0:o.code)?h=2103:404===(null==o?void 0:o.code)&&(h=2104),t.emit("error",{errorType:"network",errorCode:h,message:(null==d?void 0:d.message)||i,originError:r});break;case Hls.ErrorTypes.MEDIA_ERROR:c="media",i===Hls.ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR?h=5104:i===Hls.ErrorDetails.FRAG_DECRYPT_ERROR?h=5105:i===Hls.ErrorDetails.FRAG_PARSING_ERROR?(h=1100,c="manifest"):i===Hls.ErrorDetails.FRAG_GAP?h=5104:i===Hls.ErrorDetails.BUFFER_ADD_CODEC_ERROR?h=5200:i===Hls.ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR?h=5104:i===Hls.ErrorDetails.BUFFER_APPEND_ERROR||i===Hls.ErrorDetails.BUFFER_APPENDING_ERROR?h=5201:i===Hls.ErrorDetails.BUFFER_STALLED_ERROR||i===Hls.ErrorDetails.BUFFER_FULL_ERROR?h=5203:(i===Hls.ErrorDetails.BUFFER_SEEK_OVER_HOLE||i===Hls.ErrorDetails.BUFFER_NUDGE_ON_STALL)&&(h=5202),t.emit("error",{errorType:c||a,errorCode:h,message:(null==d?void 0:d.message)||i,originError:r});break;case Hls.ErrorTypes.MUX_ERROR:h=4100,t.emit("error",{errorType:"remux",errorCode:h,message:(null==d?void 0:d.message)||i,originError:r});break;case Hls.ErrorTypes.KEY_SYSTEM_ERROR:h=7111,i===Hls.ErrorDetails.KEY_SYSTEM_NO_KEYS?h=7103:i===Hls.ErrorDetails.KEY_SYSTEM_NO_ACCESS?h=7101:i===Hls.ErrorDetails.KEY_SYSTEM_NO_SESSION?h=7104:i===Hls.ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE?h=7107:i===Hls.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED?h=7108:i===Hls.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED||i===Hls.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED?h=7110:i===Hls.ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED?h=7104:i===Hls.ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR&&(h=7111),t.emit("error",{errorType:"drm",errorCode:h,message:(null==d?void 0:d.message)||l||i,originError:r});break;default:i===Hls.ErrorDetails.LEVEL_SWITCH_ERROR&&(h=2100,c="network"),t.emit("error",{errorType:c||"other",errorCode:h,message:(null==d?void 0:d.message)||l||i,originError:r})}try{e.stopLoad(),t.pause()}catch(e){}})),e.on(Hls.Events.MEDIA_ATTACHED,(()=>{t.emit("sourceopen")})),e.on(Hls.Events.BUFFER_APPENDED,(()=>{t.emit("bufferappend")})),e.on(Hls.Events.AUDIO_TRACKS_UPDATED,((e,{audioTracks:s})=>{t.emit("core_event",{eventName:"core.audiotracksupdate",audioTracks:s})})),e.on(Hls.Events.AUDIO_TRACK_SWITCHING,((e,s)=>{t.emit("core_event",{eventName:"core.audiotrackswitching",...s})})),e.on(Hls.Events.AUDIO_TRACK_SWITCHED,((e,s)=>{t.emit("core_event",{eventName:"core.audiotrackswitched",...s})})),e.on(Hls.Events.SUBTITLE_TRACKS_UPDATED,((e,{subtitleTracks:s})=>{t.emit("core_event",{eventName:"core.subtitleplaylist",subtitleTracks:s})})),e.on(Hls.Events.SUBTITLE_TRACKS_CLEARED,(()=>{t.emit("core_event",{eventName:"core.subtitletracksclear"})})),e.on(Hls.Events.SUBTITLE_TRACK_SWITCH,((e,s)=>{t.emit("core_event",{eventName:"core.subtitletrackswitch",...s})})),e.on(Hls.Events.SUBTITLE_TRACK_LOADING,((e,s)=>{t.emit("core_event",{eventName:"core.subtitletrackloading",...s})})),e.on(Hls.Events.SUBTITLE_TRACK_LOADED,((e,s)=>{t.emit("core_event",{eventName:"core.subtitletrackloaded",...s})}))}class TrackManager{constructor(e,t){this.hls=e,this.player=t}getAudioTracks(){if(!this.hls)return console.warn("HLS instance not initialized"),[];try{return this.hls.audioTracks||[]}catch(e){return console.error("Failed to get audio tracks:",e),[]}}getCurrentAudioTrack(){if(!this.hls)return console.warn("HLS instance not initialized"),-1;try{return this.hls.audioTrack}catch(e){return console.error("Failed to get current audio track:",e),-1}}switchAudioTrack(e){if(!this.hls)return console.warn("HLS instance not initialized"),!1;const t=this.getAudioTracks();if(0===t.length)return console.warn("No audio tracks available"),!1;if(!t.some(((t,s)=>s===e)))return console.warn(`Audio track with ID ${e} not found`),!1;try{return this.hls.audioTrack=e,this.player.emit("core_event",{eventName:"core.audiotrackchange",trackId:e,trackInfo:t[e]||null}),!0}catch(e){return console.error("Failed to switch audio track:",e),!1}}getSubtitleTracks(){if(!this.hls)return console.warn("HLS instance not initialized"),[];try{return this.hls.subtitleTracks||[]}catch(e){return console.error("Failed to get subtitle tracks:",e),[]}}getAllSubtitleTracks(){if(!this.hls)return console.warn("HLS instance not initialized"),[];try{return this.hls.allSubtitleTracks||[]}catch(e){return console.error("Failed to get all subtitle tracks:",e),[]}}getCurrentSubtitleTrack(){if(!this.hls)return console.warn("HLS instance not initialized"),-1;try{return this.hls.subtitleTrack}catch(e){return console.error("Failed to get current subtitle track:",e),-1}}switchSubtitleTrack(e){if(!this.hls)return console.warn("HLS instance not initialized"),!1;const t=this.getSubtitleTracks();if(-1===e)try{return this.hls.subtitleTrack=-1,this.player.emit("core_event",{eventName:"core.subtitletrackchange",trackId:-1,trackInfo:null}),!0}catch(e){return console.error("Failed to disable subtitle track:",e),!1}if(0===t.length)return console.warn("No subtitle tracks available"),!1;if(!t.some(((t,s)=>s===e)))return console.warn(`Subtitle track with ID ${e} not found`),!1;try{return this.hls.subtitleTrack=e,this.player.emit("core_event",{eventName:"core.subtitletrackchange",trackId:e,trackInfo:t[e]||null}),!0}catch(e){return console.error("Failed to switch subtitle track:",e),!1}}getSubtitleDisplay(){if(!this.hls)return console.warn("HLS instance not initialized"),!1;try{return this.hls.subtitleDisplay}catch(e){return console.error("Failed to get subtitle display status:",e),!1}}setSubtitleDisplay(e){if(!this.hls)return console.warn("HLS instance not initialized"),!1;try{return this.hls.subtitleDisplay=e,this.player.emit("core_event",{eventName:"core.subtitledisplaychange",enabled:e}),!0}catch(e){return console.error("Failed to set subtitle display:",e),!1}}}const MAX_HOLE=.1;class XgHls extends BasePlugin{constructor(e){super({...e,pluginName:XgHls.pluginName}),this._tickInterval=500,this._currentIndex=0,this._onPlay=()=>{this.hls.startLoad()},this.onUrlChange=e=>{/^blob/.test(e)||(this.playerConfig.url=e,this.register(e))},this._getBufferend=e=>{const{buffered:t}=e;let s=0;return s=t&&t.length?t.end(t.length-1):0,s},this._tick=()=>{clearTimeout(this._tickTimer);const e=this.player.media;if(!e)return;this._tickTimer=setTimeout(this._tick,this._tickInterval);const t=this._getBufferend(e);t<.1||!e.readyState||this.player.config.isLive&&4===e.readyState&&e.paused&&t-e.currentTime>this.config.disconnectTime&&this.hls.stopLoad()},this.on=(e,t)=>{var s;null==(s=this.hls)||s.on(e,t)},this.config=e.config||{},this.player.handleSource=!1}static get pluginName(){return"hls"}beforePlayerInit(){this.register(this.player.config.url)}initEvt(){initHlsEvents(this.hls,this.player)}afterCreate(){const e=this.player.media;this.player.on(URL_CHANGE,this.onUrlChange);try{BasePlugin.defineGetterOrSetter(this.player,{url:{get:()=>{try{return e.src}catch(e){return null}},configurable:!0}})}catch(e){}}register(e){const{player:t}=this;this.hls&&this.hls.destroy();const s=getHlsConfig(this.config);if(this.hls=new Hls(s),this._trackManager=new TrackManager(this.hls,this.player),this.initEvt(),t.config.preProcessUrl){const{url:s}=t.config.preProcessUrl(e);e=s}this.hls.loadSource(e);const r=this.player.media;this.hls.attachMedia(r),clearTimeout(this._tickTimer),this._tickTimer=setTimeout(this._tick,this._tickInterval),r.removeEventListener("play",this._onPlay),r.addEventListener("play",this._onPlay)}switchUrl(e,{startTime:t,bitrate:s,seamless:r}){if(this.hls.loadSource(e),void 0!==t){this.player.media.currentTime=t}}getAudioTracks(){return this._trackManager.getAudioTracks()}getCurrentAudioTrack(){return this._trackManager.getCurrentAudioTrack()}switchAudioTrack(e){return this._trackManager.switchAudioTrack(e)}getSubtitleTracks(){return this._trackManager.getSubtitleTracks()}getAllSubtitleTracks(){return this._trackManager.getAllSubtitleTracks()}getCurrentSubtitleTrack(){return this._trackManager.getCurrentSubtitleTrack()}switchSubtitleTrack(e){return this._trackManager.switchSubtitleTrack(e)}getSubtitleDisplay(){return this._trackManager.getSubtitleDisplay()}setSubtitleDisplay(e){return this._trackManager.setSubtitleDisplay(e)}destroy(){clearTimeout(this._tickTimer),this.player.off(URL_CHANGE,this.onUrlChange),this.hls.destroy()}}export{XgHls as default};
|
|
1
|
+
// @byteplus/veplayer@1.19.0-rc.1 Built @9/3/2026, 9:33:56 PM
|
|
2
|
+
function ownKeys$1(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,r)}return s}function _objectSpread2$1(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?ownKeys$1(Object(s),!0).forEach((function(t){_defineProperty$1(e,t,s[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):ownKeys$1(Object(s)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))}))}return e}function _typeof(e){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var s=0;s<t.length;s++){var r=t[s];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,_toPropertyKey$1(r.key),r)}}function _createClass(e,t,s){return t&&_defineProperties(e.prototype,t),s&&_defineProperties(e,s),Object.defineProperty(e,"prototype",{writable:!1}),e}function _defineProperty$1(e,t,s){return(t=_toPropertyKey$1(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function _toConsumableArray(e){return _arrayWithoutHoles(e)||_iterableToArray(e)||_unsupportedIterableToArray(e)||_nonIterableSpread()}function _arrayWithoutHoles(e){if(Array.isArray(e))return _arrayLikeToArray(e)}function _iterableToArray(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function _unsupportedIterableToArray(e,t){if(e){if("string"==typeof e)return _arrayLikeToArray(e,t);var s=Object.prototype.toString.call(e).slice(8,-1);return"Object"===s&&e.constructor&&(s=e.constructor.name),"Map"===s||"Set"===s?Array.from(e):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?_arrayLikeToArray(e,t):void 0}}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var s=0,r=new Array(t);s<t;s++)r[s]=e[s];return r}function _nonIterableSpread(){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 _toPrimitive$1(e,t){if("object"!=typeof e||null===e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var r=s.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}function _toPropertyKey$1(e){var t=_toPrimitive$1(e,"string");return"symbol"==typeof t?t:String(t)}var XG_DEBUG_OPEN="undefined"!=typeof window&&window.location&&window.location.href.indexOf("xgplayerdebugger=1")>-1,STYLE={info:"color: #525252; background-color: #90ee90;",error:"color: #525252; background-color: red;",warn:"color: #525252; background-color: yellow; "},XGTAG="%c[xgplayer]",XG_DEBUG={config:{debug:XG_DEBUG_OPEN?3:0},logInfo:function(e){for(var t,s=arguments.length,r=new Array(s>1?s-1:0),i=1;i<s;i++)r[i-1]=arguments[i];this.config.debug>=3&&(t=console).log.apply(t,[XGTAG,STYLE.info,e].concat(r))},logWarn:function(e){for(var t,s=arguments.length,r=new Array(s>1?s-1:0),i=1;i<s;i++)r[i-1]=arguments[i];this.config.debug>=1&&(t=console).warn.apply(t,[XGTAG,STYLE.warn,e].concat(r))},logError:function(e){var t;if(!(this.config.debug<1)){for(var s=this.config.debug>=2?"trace":"error",r=arguments.length,i=new Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];(t=console)[s].apply(t,[XGTAG,STYLE.error,e].concat(i))}}},XgplayerTimeRange=function(){function e(t){_classCallCheck(this,e),this.bufferedList=t}return _createClass(e,[{key:"start",value:function(e){return this.bufferedList[e].start}},{key:"end",value:function(e){return this.bufferedList[e].end}},{key:"length",get:function(){return this.bufferedList.length}}]),e}(),util={};function checkIsIn(e,t){for(var s=0,r=t.length;s<r;s++)if(e.indexOf(t[s])>-1)return!0;return!1}util.createDom=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"div",t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",i=document.createElement(e);return i.className=r,i.innerHTML=t,Object.keys(s).forEach((function(t){var r=t,n=s[t];"video"===e||"audio"===e||"live-video"===e?n&&i.setAttribute(r,n):i.setAttribute(r,n)})),i},util.createDomFromHtml=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";try{var r=document.createElement("div");r.innerHTML=e;var i=r.children;return r=null,i.length>0?(i=i[0],s&&util.addClass(i,s),t&&Object.keys(t).forEach((function(e){i.setAttribute(e,t[e])})),i):null}catch(e){return XG_DEBUG.logError("util.createDomFromHtml",e),null}},util.hasClass=function(e,t){if(!e||!t)return!1;try{return Array.prototype.some.call(e.classList,(function(e){return e===t}))}catch(r){var s=e.className&&"object"===_typeof(e.className)?e.getAttribute("class"):e.className;return s&&!!s.match(new RegExp("(\\s|^)"+t+"(\\s|$)"))}},util.addClass=function(e,t){if(e&&t)try{t.replace(/(^\s+|\s+$)/g,"").split(/\s+/g).forEach((function(t){t&&e.classList.add(t)}))}catch(s){util.hasClass(e,t)||(e.className&&"object"===_typeof(e.className)?e.setAttribute("class",e.getAttribute("class")+" "+t):e.className+=" "+t)}},util.removeClass=function(e,t){if(e&&t)try{t.replace(/(^\s+|\s+$)/g,"").split(/\s+/g).forEach((function(t){t&&e.classList.remove(t)}))}catch(s){util.hasClass(e,t)&&t.split(/\s+/g).forEach((function(t){var s=new RegExp("(\\s|^)"+t+"(\\s|$)");e.className&&"object"===_typeof(e.className)?e.setAttribute("class",e.getAttribute("class").replace(s," ")):e.className=e.className.replace(s," ")}))}},util.toggleClass=function(e,t){e&&t.split(/\s+/g).forEach((function(t){util.hasClass(e,t)?util.removeClass(e,t):util.addClass(e,t)}))},util.classNames=function(){for(var e=arguments,t=[],s=function(s){"String"===util.typeOf(e[s])?t.push(e[s]):"Object"===util.typeOf(e[s])&&Object.keys(e[s]).map((function(r){e[s][r]&&t.push(r)}))},r=0;r<arguments.length;r++)s(r);return t.join(" ")},util.findDom=function(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:document,s=arguments.length>1?arguments[1]:void 0;try{e=t.querySelector(s)}catch(r){XG_DEBUG.logError("util.findDom",r),0===s.indexOf("#")&&(e=t.getElementById(s.slice(1)))}return e},util.getCss=function(e,t){return e.currentStyle?e.currentStyle[t]:document.defaultView.getComputedStyle(e,!1)[t]},util.padStart=function(e,t,s){for(var r=String(s),i=t>>0,n=Math.ceil(i/r.length),a=[],o=String(e);n--;)a.push(r);return a.join("").substring(0,i-o.length)+o},util.format=function(e){if(window.isNaN(e))return"";e=Math.round(e);var t=util.padStart(Math.floor(e/3600),2,0),s=util.padStart(Math.floor((e-3600*t)/60),2,0),r=util.padStart(Math.floor(e-3600*t-60*s),2,0);return("00"===t?[s,r]:[t,s,r]).join(":")},util.event=function(e){if(e.touches){var t=e.touches[0]||e.changedTouches[0];e.clientX=t.clientX||0,e.clientY=t.clientY||0,e.offsetX=t.pageX-t.target.offsetLeft,e.offsetY=t.pageY-t.target.offsetTop}e._target=e.target||e.srcElement},util.typeOf=function(e){return Object.prototype.toString.call(e).match(/([^\s.*]+)(?=]$)/g)[0]},util.deepCopy=function(e,t){if("Object"===util.typeOf(t)&&"Object"===util.typeOf(e))return Object.keys(t).forEach((function(s){"Object"!==util.typeOf(t[s])||t[s]instanceof Node?"Array"===util.typeOf(t[s])?e[s]="Array"===util.typeOf(e[s])?e[s].concat(t[s]):t[s]:e[s]=t[s]:void 0===e[s]||void 0===e[s]?e[s]=t[s]:util.deepCopy(e[s],t[s])})),e},util.deepMerge=function(e,t){return Object.keys(t).map((function(s){var r;"Array"===util.typeOf(t[s])&&"Array"===util.typeOf(e[s])?"Array"===util.typeOf(e[s])&&(r=e[s]).push.apply(r,_toConsumableArray(t[s])):util.typeOf(e[s])!==util.typeOf(t[s])||null===e[s]||"Object"!==util.typeOf(e[s])||t[s]instanceof window.Node?null!==t[s]&&(e[s]=t[s]):util.deepMerge(e[s],t[s])})),e},util.getBgImage=function(e){var t=(e.currentStyle||window.getComputedStyle(e,null)).backgroundImage;if(!t||"none"===t)return"";var s=document.createElement("a");return s.href=t.replace(/url\("|"\)/g,""),s.href},util.copyDom=function(e){if(e&&1===e.nodeType){var t=document.createElement(e.tagName);return Array.prototype.forEach.call(e.attributes,(function(e){t.setAttribute(e.name,e.value)})),e.innerHTML&&(t.innerHTML=e.innerHTML),t}return""},util.setInterval=function(e,t,s,r){e._interval[t]||(e._interval[t]=window.setInterval(s.bind(e),r))},util.clearInterval=function(e,t){clearInterval(e._interval[t]),e._interval[t]=null},util.setTimeout=function(e,t,s){e._timers||(e._timers=[]);var r=setTimeout((function(){t(),util.clearTimeout(e,r)}),s);return e._timers.push(r),r},util.clearTimeout=function(e,t){var s=e._timers;if("Array"===util.typeOf(s)){for(var r=0;r<s.length;r++)if(s[r]===t){s.splice(r,1),clearTimeout(t);break}}else clearTimeout(t)},util.clearAllTimers=function(e){var t=e._timers;"Array"===util.typeOf(t)&&(t.map((function(e){clearTimeout(e)})),e._timerIds=[])},util.createImgBtn=function(e,t,s,r){var i,n,a,o=util.createDom("xg-".concat(e),"",{},"xgplayer-".concat(e,"-img"));(o.style.backgroundImage='url("'.concat(t,'")'),s&&r)&&(["px","rem","em","pt","dp","vw","vh","vm","%"].every((function(e){return!(s.indexOf(e)>-1&&r.indexOf(e)>-1)||(i=parseFloat(s.slice(0,s.indexOf(e)).trim()),n=parseFloat(r.slice(0,r.indexOf(e)).trim()),a=e,!1)})),o.style.width="".concat(i).concat(a),o.style.height="".concat(n).concat(a),o.style.backgroundSize="".concat(i).concat(a," ").concat(n).concat(a),o.style.margin="start"===e?"-".concat(n/2).concat(a," auto auto -").concat(i/2).concat(a):"auto 5px auto 5px");return o},util.Hex2RGBA=function(e,t){var s=[];if(/^\#[0-9A-F]{3}$/i.test(e)){var r="#";e.replace(/[0-9A-F]/gi,(function(e){r+=e+e})),e=r}return/^#[0-9A-F]{6}$/i.test(e)?(e.replace(/[0-9A-F]{2}/gi,(function(e){s.push(parseInt(e,16))})),"rgba(".concat(s.join(","),", ").concat(t,")")):"rgba(255, 255, 255, 0.1)"},util.getFullScreenEl=function(){return document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement},util.checkIsFunction=function(e){return e&&"function"==typeof e},util.checkIsObject=function(e){return null!==e&&"object"===_typeof(e)},util.hide=function(e){e.style.display="none"},util.show=function(e,t){e.style.display=t||"block"},util.isUndefined=function(e){if(null==e)return!0},util.isNotNull=function(e){return!(null==e)},util.setStyleFromCsstext=function(e,t){t&&("String"===util.typeOf(t)?t.replace(/\s+/g,"").split(";").map((function(t){if(t){var s=t.split(":");s.length>1&&(e.style[s[0]]=s[1])}})):Object.keys(t).map((function(s){e.style[s]=t[s]})))},util.filterStyleFromText=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:["width","height","top","left","bottom","right","position","z-index","padding","margin","transform"],s=e.style.cssText;if(!s)return{};var r=s.replace(/\s+/g,"").split(";"),i={},n={};return r.map((function(e){if(e){var s=e.split(":");s.length>1&&(checkIsIn(s[0],t)?i[s[0]]=s[1]:n[s[0]]=s[1])}})),e.setAttribute("style",""),Object.keys(n).map((function(t){e.style[t]=n[t]})),i},util.getStyleFromCsstext=function(e){var t=e.style.cssText;if(!t)return{};var s=t.replace(/\s+/g,"").split(";"),r={};return s.map((function(e){if(e){var t=e.split(":");t.length>1&&(r[t[0]]=t[1])}})),r},util.preloadImg=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(){},s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){};if(e){var r=new window.Image;r.onload=function(e){r=null,t&&t(e)},r.onerror=function(e){r=null,s&&s(e)},r.src=e}},util.stopPropagation=function(e){e&&e.stopPropagation()},util.scrollTop=function(){return window.pageYOffset||document.documentElement.scrollTop||document.body.scrollTop||0},util.scrollLeft=function(){return window.pageXOffset||document.documentElement.scrollLeft||document.body.scrollLeft||0},util.checkTouchSupport=function(){return"ontouchstart"in window},util.getBuffered2=function(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:.5,s=[],r=0;r<e.length;r++)s.push({start:e.start(r)<.5?0:e.start(r),end:e.end(r)});s.sort((function(e,t){var s=e.start-t.start;return s||t.end-e.end}));var i=[];if(t)for(var n=0;n<s.length;n++){var a=i.length;if(a){var o=i[a-1].end;s[n].start-o<t?s[n].end>o&&(i[a-1].end=s[n].end):i.push(s[n])}else i.push(s[n])}else i=s;return new XgplayerTimeRange(i)},util.getEventPos=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return e.touches&&e.touches.length>0&&(e=e.touches[0]),{x:e.x/t,y:e.y/t,clientX:e.clientX/t,clientY:e.clientY/t,offsetX:e.offsetX/t,offsetY:e.offsetY/t,pageX:e.pageX/t,pageY:e.pageY/t}},util.requestAnimationFrame=function(e){var t=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame;if(t)return t(e)},util.getHostFromUrl=function(e){if("String"!==util.typeOf(e))return"";var t=e.split("/"),s="";return t.length>3&&t[2]&&(s=t[2]),s},util.cancelAnimationFrame=function(e){var t=window.cancelAnimationFrame||window.mozCancelAnimationFrame||window.cancelRequestAnimationFrame;t&&t(e)},util.isMSE=function(e){return e.media&&(e=e.media),!!(e&&e instanceof HTMLMediaElement)&&(/^blob/.test(e.currentSrc)||/^blob/.test(e.src))},util.isBlob=function(e){return"string"==typeof e&&/^blob/.test(e)},util.generateSessionId=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=(new Date).getTime();try{e=parseInt(e)}catch(t){e=0}return t+=e,window.performance&&"function"==typeof window.performance.now&&(t+=parseInt(window.performance.now())),"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var s=(t+16*Math.random())%16|0;return t=Math.floor(t/16),("x"===e?s:3&s|8).toString(16)}))},util.createEvent=function(e){var t;return"function"==typeof window.Event?t=new Event(e):(t=document.createEvent("Event")).initEvent(e,!0,!0),t},util.adjustTimeByDuration=function(e,t,s){return t&&e&&(e>t||s&&e<t)?t:e},util.createPositionBar=function(e,t){var s=util.createDom("xg-bar","",{"data-index":-1},e);return t.appendChild(s),s},util.getTransformStyle=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{x:0,y:0,scale:1,rotate:0},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",s={scale:"".concat(e.scale||1),translate:"".concat(e.x||0,"%, ").concat(e.y||0,"%"),rotate:"".concat(e.rotate||0,"deg")};return Object.keys(s).forEach((function(e){var r=new RegExp("".concat(e,"\\([^\\(]+\\)"),"g"),i="".concat(e,"(").concat(s[e],")");r.test(t)?(r.lastIndex=-1,t=t.replace(r,i)):t+="".concat(i," ")})),t},util.convertDeg=function(e){return Math.abs(e)<=1?360*e:e%360},util.getIndexByTime=function(e,t){var s=t.length,r=-1;if(s<1)return r;if(e<=t[0].end||s<2)r=0;else if(e>t[s-1].end)r=s-1;else for(var i=1;i<s;i++)if(e>t[i-1].end&&e<=t[i].end){r=i;break}return r},util.getOffsetCurrentTime=function(e,t){var s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:-1,r=-1;if((r=s>=0&&s<t.length?s:util.getIndexByTime(e,t))<0)return-1;var i=t.length,n=t[r],a=n.start,o=n.end,l=n.cTime,d=n.offset;return e<a?l:e>=a&&e<=o?e-d:e>o&&r>=i-1?o:-1},util.getCurrentTimeByOffset=function(e,t){var s=-1;if(!t||t.length<0)return e;for(var r=0;r<t.length;r++)if(e<=t[r].duration){s=r;break}if(-1!==s){var i=t[s].start;return s-1<0?i+e:i+(e-t[s-1].duration)}return e};var URL_CHANGE="urlchange";function callHandler(e,t,s){for(var r=arguments.length,i=new Array(r>3?r-3:0),n=3;n<r;n++)i[n-3]=arguments[n];var a=t.call.apply(t,[e].concat(i));s&&"function"==typeof s&&(a&&a.then?a.then((function(){for(var t=arguments.length,r=new Array(t),i=0;i<t;i++)r[i]=arguments[i];s.call.apply(s,[e].concat(r))})):s.call.apply(s,[e].concat(i)))}function hook(e,t){var s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{pre:null,next:null};return this.__hooks||(this.__hooks={}),!this.__hooks[e]&&(this.__hooks[e]=null),function(){var r=arguments,i=this;if(s.pre)try{var n;(n=s.pre).call.apply(n,[this].concat(Array.prototype.slice.call(arguments)))}catch(t){throw t.message="[pluginName: ".concat(this.pluginName,":").concat(e,":pre error] >> ").concat(t.message),t}if(this.__hooks&&this.__hooks[e])try{var a=runHooks.apply(void 0,[this,e,t].concat(Array.prototype.slice.call(arguments)));a?a.then?a.then((function(e){!1!==e&&callHandler.apply(void 0,[i,t,s.next].concat(_toConsumableArray(r)))})).catch((function(e){throw e})):callHandler.apply(void 0,[this,t,s.next].concat(Array.prototype.slice.call(arguments))):void 0===a&&callHandler.apply(void 0,[this,t,s.next].concat(Array.prototype.slice.call(arguments)))}catch(t){throw t.message="[pluginName: ".concat(this.pluginName,":").concat(e,"] >> ").concat(t.message),t}else callHandler.apply(void 0,[this,t,s.next].concat(Array.prototype.slice.call(arguments)))}.bind(this)}function findHookIndex(e,t){var s=this.__hooks;if(!s||!Array.isArray(s[e]))return-1;for(var r=s[e],i=0;i<r.length;i++)if(r[i]===t)return i;return-1}function useHooks(e,t){var s=this.__hooks;if(s)return s.hasOwnProperty(e)?(Array.isArray(s[e])||(s[e]=[]),-1===findHookIndex.call(this,e,t)&&s[e].push(t),!0):(console.warn("has no supported hook which name [".concat(e,"]")),!1)}function removeHooks(e,t){var s=this.__hooks;if(s)if(Array.isArray(s[e])){var r=s[e],i=findHookIndex.call(this,e,t);-1!==i&&r.splice(i,1)}else s[e]&&(s[e]=null)}function hooksDescriptor(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];e.__hooks={},t&&t.map((function(t){e.__hooks[t]=null})),Object.defineProperty(e,"hooks",{get:function(){return e.__hooks&&Object.keys(e.__hooks).map((function(t){if(e.__hooks[t])return t}))}})}function delHooksDescriptor(e){e.__hooks=null}function runHooks(e,t,s){for(var r=arguments.length,i=new Array(r>3?r-3:0),n=3;n<r;n++)i[n-3]=arguments[n];if(e.__hooks&&Array.isArray(e.__hooks[t])){var a=e.__hooks[t],o=-1;return function e(t,s,r){for(var i=arguments.length,n=new Array(i>3?i-3:0),l=3;l<i;l++)n[l-3]=arguments[l];if(o++,0===a.length||o===a.length)return r.call.apply(r,[t,t].concat(n));var d=a[o],h=d.call.apply(d,[t,t].concat(n));return h&&h.then?h.then((function(i){return!1===i?null:e.apply(void 0,[t,s,r].concat(n))})).catch((function(e){console.warn("[runHooks]".concat(s," reject"),e.message)})):!1!==h?e.apply(void 0,[t,s,r].concat(n)):void 0}.apply(void 0,[e,t,s].concat(i))}return s.call.apply(s,[e,e].concat(i))}function showErrorMsg(e,t){XG_DEBUG.logError("[".concat(e,"] event or callback cant be undefined or null when call ").concat(t))}var BasePlugin=function(){function e(t){_classCallCheck(this,e),util.checkIsFunction(this.beforeCreate)&&this.beforeCreate(t),hooksDescriptor(this),this.__args=t,this.__events={},this.__onceEvents={},this.config=t.config||{},this.player=null,this.playerConfig={},this.pluginName="",this.__init(t)}return _createClass(e,[{key:"beforeCreate",value:function(e){}},{key:"afterCreate",value:function(){}},{key:"beforePlayerInit",value:function(){}},{key:"onPluginsReady",value:function(){}},{key:"afterPlayerInit",value:function(){}},{key:"destroy",value:function(){}},{key:"__init",value:function(e){this.player=e.player,this.playerConfig=e.player&&e.player.config,this.pluginName=e.pluginName?e.pluginName.toLowerCase():this.constructor.pluginName.toLowerCase(),this.logger=e.player&&e.player.logger}},{key:"updateLang",value:function(e){e||(e=this.lang)}},{key:"lang",get:function(){return this.player.lang}},{key:"i18n",get:function(){return this.player.i18n}},{key:"i18nKeys",get:function(){return this.player.i18nKeys}},{key:"domEventType",get:function(){var e=util.checkTouchSupport()?"touch":"mouse";return!this.playerConfig||"touch"!==this.playerConfig.domEventType&&"mouse"!==this.playerConfig.domEventType||(e=this.playerConfig.domEventType),e}},{key:"on",value:function(e,t){var s=this;e&&t&&this.player?"string"==typeof e?(this.__events[e]=t,this.player.on(e,t)):Array.isArray(e)&&e.forEach((function(e){s.__events[e]=t,s.player.on(e,t)})):showErrorMsg(this.pluginName,"plugin.on(event, callback)")}},{key:"once",value:function(e,t){var s=this;e&&t&&this.player?"string"==typeof e?(this.__onceEvents[e]=t,this.player.once(e,t)):Array.isArray(e)&&e.forEach((function(r){s.__onceEvents[r]=t,s.player.once(e,t)})):showErrorMsg(this.pluginName,"plugin.once(event, callback)")}},{key:"off",value:function(e,t){var s=this;e&&t&&this.player?"string"==typeof e?(delete this.__events[e],this.player.off(e,t)):Array.isArray(e)&&e.forEach((function(r){delete s.__events[e],s.player.off(r,t)})):showErrorMsg(this.pluginName,"plugin.off(event, callback)")}},{key:"offAll",value:function(){var e=this;["__events","__onceEvents"].forEach((function(t){Object.keys(e[t]).forEach((function(s){e[t][s]&&e.off(s,e[t][s]),s&&delete e[t][s]}))})),this.__events={},this.__onceEvents={}}},{key:"emit",value:function(e){var t;if(this.player){for(var s=arguments.length,r=new Array(s>1?s-1:0),i=1;i<s;i++)r[i-1]=arguments[i];(t=this.player).emit.apply(t,[e].concat(r))}}},{key:"emitUserAction",value:function(e,t){var s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(this.player){var r=_objectSpread2$1(_objectSpread2$1({},s),{},{pluginName:this.pluginName});this.player.emitUserAction(e,t,r)}}},{key:"hook",value:function(e,t){return hook.call.apply(hook,[this].concat(Array.prototype.slice.call(arguments)))}},{key:"useHooks",value:function(e,t){for(var s=arguments.length,r=new Array(s>2?s-2:0),i=2;i<s;i++)r[i-2]=arguments[i];return useHooks.call.apply(useHooks,[this].concat(Array.prototype.slice.call(arguments)))}},{key:"removeHooks",value:function(e,t){for(var s=arguments.length,r=new Array(s>2?s-2:0),i=2;i<s;i++)r[i-2]=arguments[i];return removeHooks.call.apply(removeHooks,[this].concat(Array.prototype.slice.call(arguments)))}},{key:"registerPlugin",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";if(this.player)return s&&(t.pluginName=s),this.player.registerPlugin({plugin:e,options:t})}},{key:"getPlugin",value:function(e){return this.player?this.player.getPlugin(e):null}},{key:"__destroy",value:function(){var e=this,t=this.player,s=this.pluginName;this.offAll(),util.clearAllTimers(this),util.checkIsFunction(this.destroy)&&this.destroy(),["player","playerConfig","pluginName","logger","__args","__hooks"].map((function(t){e[t]=null})),t.unRegisterPlugin(s),delHooksDescriptor(this)}}],[{key:"defineGetterOrSetter",value:function(e,t){for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&Object.defineProperty(e,s,t[s])}},{key:"defineMethod",value:function(e,t){for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&"function"==typeof t[s]&&Object.defineProperty(e,s,{configurable:!0,value:t[s]})}},{key:"defaultConfig",get:function(){return{}}},{key:"pluginName",get:function(){return"pluginName"}}]),e}();const isFiniteNumber=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},isSafeInteger=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=MAX_SAFE_INTEGER},MAX_SAFE_INTEGER=Number.MAX_SAFE_INTEGER||9007199254740991;let ErrorTypes=function(e){return e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError",e}({}),ErrorDetails=function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",e.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",e.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.ASSET_LIST_LOAD_ERROR="assetListLoadError",e.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",e.ASSET_LIST_PARSING_ERROR="assetListParsingError",e.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.ATTACH_MEDIA_ERROR="attachMediaError",e.UNKNOWN="unknown",e}({}),Events=function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.MEDIA_ENDED="hlsMediaEnded",e.STALL_RESOLVED="hlsStallResolved",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFERED_TO_END="hlsBufferedToEnd",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",e.ASSET_LIST_LOADING="hlsAssetListLoading",e.ASSET_LIST_LOADED="hlsAssetListLoaded",e.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",e.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",e.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",e.INTERSTITIAL_STARTED="hlsInterstitialStarted",e.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",e.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",e.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",e.INTERSTITIAL_ENDED="hlsInterstitialEnded",e.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",e.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",e.EVENT_CUE_ENTER="hlsEventCueEnter",e}({});var PlaylistContextType={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},PlaylistLevelType={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class EWMA{constructor(e,t=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=s}sample(e,t){const s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class EwmaBandWidthEstimator{constructor(e,t,s,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new EWMA(e),this.fast_=new EWMA(t),this.defaultTTFB_=r,this.ttfb_=new EWMA(e)}update(e,t){const{slow_:s,fast_:r,ttfb_:i}=this;s.halfLife!==e&&(this.slow_=new EWMA(e,s.getEstimate(),s.getTotalWeight())),r.halfLife!==t&&(this.fast_=new EWMA(t,r.getEstimate(),r.getTotalWeight())),i.halfLife!==e&&(this.ttfb_=new EWMA(e,i.getEstimate(),i.getTotalWeight()))}sample(e,t){const s=(e=Math.max(e,this.minDelayMs_))/1e3,r=8*t/s;this.fast_.sample(s,r),this.slow_.sample(s,r)}sampleTTFB(e){const t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function _defineProperty(e,t,s){return(t=_toPropertyKey(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function _extends(){return _extends=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var s=arguments[t];for(var r in s)({}).hasOwnProperty.call(s,r)&&(e[r]=s[r])}return e},_extends.apply(null,arguments)}function ownKeys(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,r)}return s}function _objectSpread2(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?ownKeys(Object(s),!0).forEach((function(t){_defineProperty(e,t,s[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):ownKeys(Object(s)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))}))}return e}function _toPrimitive(e,t){if("object"!=typeof e||!e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var r=s.call(e,t);if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}function _toPropertyKey(e){var t=_toPrimitive(e,"string");return"symbol"==typeof t?t:t+""}class Logger{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const s=`[${e}]:`;this.trace=noop,this.debug=t.debug.bind(null,s),this.log=t.log.bind(null,s),this.warn=t.warn.bind(null,s),this.info=t.info.bind(null,s),this.error=t.error.bind(null,s)}}const noop=function(){},fakeLogger={trace:noop,debug:noop,log:noop,warn:noop,info:noop,error:noop};function createLogger(){return _extends({},fakeLogger)}function consolePrintFn(e,t){const s=self.console[e];return s?s.bind(self.console,`${t?"["+t+"] ":""}[${e}] >`):noop}function getLoggerFn(e,t,s){return t[e]?t[e].bind(t):consolePrintFn(e,s)}const exportedLogger=createLogger();function enableLogs(e,t,s){const r=createLogger();if("object"==typeof console&&!0===e||"object"==typeof e){const i=["debug","log","info","warn","error"];i.forEach((t=>{r[t]=getLoggerFn(t,e,s)}));try{r.log(`Debug logs enabled for "${t}" in hls.js version 1.6.13-beta.4`)}catch(e){return createLogger()}i.forEach((t=>{exportedLogger[t]=getLoggerFn(t,e)}))}else _extends(exportedLogger,r);return r}const logger=exportedLogger;function getMediaSource(e=!0){if("undefined"==typeof self)return;return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function isManagedMediaSource(e){return"undefined"!=typeof self&&e===self.ManagedMediaSource}function isCompatibleTrackChange(e,t){const s=Object.keys(e),r=Object.keys(t),i=s.length,n=r.length;return!i||!n||i===n&&!s.some((e=>-1===r.indexOf(e)))}function utf8ArrayToStr(e,t=!1){if("undefined"!=typeof TextDecoder){const s=new TextDecoder("utf-8").decode(e);if(t){const e=s.indexOf("\0");return-1!==e?s.substring(0,e):s}return s.replace(/\0/g,"")}const s=e.length;let r,i,n,a="",o=0;for(;o<s;){if(r=e[o++],0===r&&t)return a;if(0!==r&&3!==r)switch(r>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(r);break;case 12:case 13:i=e[o++],a+=String.fromCharCode((31&r)<<6|63&i);break;case 14:i=e[o++],n=e[o++],a+=String.fromCharCode((15&r)<<12|(63&i)<<6|(63&n)<<0)}}return a}function arrayToHex(e){let t="";for(let s=0;s<e.length;s++){let r=e[s].toString(16);r.length<2&&(r="0"+r),t+=r}return t}function hexToArrayBuffer(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var hasRequiredUrlToolkit,urlToolkit={exports:{}};function requireUrlToolkit(){return hasRequiredUrlToolkit||(hasRequiredUrlToolkit=1,e=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,t=/^(?=([^\/?#]*))\1([^]*)$/,s=/(?:\/|^)\.(?=\/)/g,r=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,i={buildAbsoluteURL:function(e,s,r){if(r=r||{},e=e.trim(),!(s=s.trim())){if(!r.alwaysNormalize)return e;var n=i.parseURL(e);if(!n)throw new Error("Error trying to parse base URL.");return n.path=i.normalizePath(n.path),i.buildURLFromParts(n)}var a=i.parseURL(s);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return r.alwaysNormalize?(a.path=i.normalizePath(a.path),i.buildURLFromParts(a)):s;var o=i.parseURL(e);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=t.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var d={scheme:o.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(d.netLoc=o.netLoc,"/"!==a.path[0]))if(a.path){var h=o.path,c=h.substring(0,h.lastIndexOf("/")+1)+a.path;d.path=i.normalizePath(c)}else d.path=o.path,a.params||(d.params=o.params,a.query||(d.query=o.query));return null===d.path&&(d.path=r.alwaysNormalize?i.normalizePath(a.path):a.path),i.buildURLFromParts(d)},parseURL:function(t){var s=e.exec(t);return s?{scheme:s[1]||"",netLoc:s[2]||"",path:s[3]||"",params:s[4]||"",query:s[5]||"",fragment:s[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(s,"");e.length!==(e=e.replace(r,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},urlToolkit.exports=i),urlToolkit.exports;var e,t,s,r,i}var urlToolkitExports=requireUrlToolkit();class LoadStats{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 ElementaryStreamTypes={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class BaseSegment{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof e&&(e={url:e}),this.base=e,makeEnumerable(this,"stats")}setByteRange(e,t){const s=e.split("@",2);let r;r=1===s.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(s[1]),this._byteRange=[r,parseInt(s[0])+r]}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={[ElementaryStreamTypes.AUDIO]:null,[ElementaryStreamTypes.VIDEO]:null,[ElementaryStreamTypes.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new LoadStats),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=urlToolkitExports.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[ElementaryStreamTypes.AUDIO]=null,e[ElementaryStreamTypes.VIDEO]=null,e[ElementaryStreamTypes.AUDIOVIDEO]=null}}function isMediaFragment(e){return"initSegment"!==e.sn}class Fragment extends BaseSegment{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(isFiniteNumber(e)&&isFiniteNumber(t))return t-e}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(null==(e=this._decryptdata)||!e.keyId){const e=Object.keys(t);if(1===e.length){const s=this._decryptdata=t[e[0]]||null;s&&(this._decryptdata=s.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;const e=isFiniteNumber(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){var t;const e=Object.keys(this.levelkeys),s=e.length;if(s>1||1===s&&null!=(t=this.levelkeys[e[0]])&&t.encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){isFiniteNumber(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}get ref(){return isMediaFragment(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var s;const r=t[e];!r||null!=(s=this._decryptdata)&&s.keyId||(this._decryptdata=r.getDecryptData(this.sn,t))}}abortRequests(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}setElementaryStreamInfo(e,t,s,r,i,n=!1){const{elementaryStreams:a}=this,o=a[e];o?(o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,s),o.startDTS=Math.min(o.startDTS,r),o.endDTS=Math.max(o.endDTS,i)):a[e]={startPTS:t,endPTS:s,startDTS:r,endDTS:i,partial:n}}}class Part extends BaseSegment{constructor(e,t,s,r,i){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=r;const n=e.enumeratedString("BYTERANGE");n&&this.setByteRange(n,i),i&&(this.fragOffset=i.fragOffset+i.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function getOwnPropertyDescriptorFromPrototypeChain(e,t){const s=Object.getPrototypeOf(e);if(s){const e=Object.getOwnPropertyDescriptor(s,t);return e||getOwnPropertyDescriptorFromPrototypeChain(s,t)}}function makeEnumerable(e,t){const s=getOwnPropertyDescriptorFromPrototypeChain(e,t);s&&(s.enumerable=!0,Object.defineProperty(e,t,s))}const UINT32_MAX$1=Math.pow(2,32)-1,push=[].push,RemuxerTrackIdConfig={video:1,audio:2,id3:3,text:4};function bin2str(e){return String.fromCharCode.apply(null,e)}function readUint16(e,t){const s=e[t]<<8|e[t+1];return s<0?65536+s:s}function readUint32(e,t){const s=readSint32(e,t);return s<0?4294967296+s:s}function readUint64(e,t){let s=readUint32(e,t);return s*=Math.pow(2,32),s+=readUint32(e,t+4),s}function readSint32(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function hasMoofData(e){const t=e.byteLength;for(let s=0;s<t;){const r=readUint32(e,s);if(r>8&&109===e[s+4]&&111===e[s+5]&&111===e[s+6]&&102===e[s+7])return!0;s=r>1?s+r:t}return!1}function findBox(e,t){const s=[];if(!t.length)return s;const r=e.byteLength;for(let i=0;i<r;){const n=readUint32(e,i),a=n>1?i+n:r;if(bin2str(e.subarray(i+4,i+8))===t[0])if(1===t.length)s.push(e.subarray(i+8,a));else{const r=findBox(e.subarray(i+8,a),t.slice(1));r.length&&push.apply(s,r)}i=a}return s}function parseSegmentIndex(e){const t=[],s=e[0];let r=8;const i=readUint32(e,r);r+=4;let n=0,a=0;0===s?(n=readUint32(e,r),a=readUint32(e,r+4),r+=8):(n=readUint64(e,r),a=readUint64(e,r+8),r+=16),r+=2;let o=e.length+a;const l=readUint16(e,r);r+=2;for(let s=0;s<l;s++){let s=r;const n=readUint32(e,s);s+=4;const a=2147483647&n;if(1===(2147483648&n)>>>31)return logger.warn("SIDX has hierarchical references (not supported)"),null;const l=readUint32(e,s);s+=4,t.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/i,start:o,end:o+a-1}}),o+=a,s+=4,r=s}return{earliestPresentationTime:n,timescale:i,version:s,referencesCount:l,references:t}}function parseInitSegment(e){const t=[],s=findBox(e,["moov","trak"]);for(let e=0;e<s.length;e++){const r=s[e],i=findBox(r,["tkhd"])[0];if(i){let e=i[0];const s=readUint32(i,0===e?12:20),n=findBox(r,["mdia","mdhd"])[0];if(n){e=n[0];const i=readUint32(n,0===e?12:20),a=findBox(r,["mdia","hdlr"])[0];if(a){const e=bin2str(a.subarray(8,12)),n={soun:ElementaryStreamTypes.AUDIO,vide:ElementaryStreamTypes.VIDEO}[e],o=parseStsd(findBox(r,["mdia","minf","stbl","stsd"])[0]);n?(t[s]={timescale:i,type:n,stsd:o},t[n]=_objectSpread2({timescale:i,id:s},o)):t[s]={timescale:i,type:e,stsd:o}}}}}return findBox(e,["moov","mvex","trex"]).forEach((e=>{const s=readUint32(e,4),r=t[s];r&&(r.default={duration:readUint32(e,12),flags:readUint32(e,20)})})),t}function parseStsd(e){const t=e.subarray(8),s=t.subarray(86),r=bin2str(t.subarray(4,8));let i,n=r;const a="enca"===r||"encv"===r;if(a){const e=findBox(t,[r])[0];findBox(e.subarray("enca"===r?28:78),["sinf"]).forEach((e=>{const t=findBox(e,["schm"])[0];if(t){const s=bin2str(t.subarray(4,8));if("cbcs"===s||"cenc"===s){const t=findBox(e,["frma"])[0];t&&(n=bin2str(t))}}}))}const o=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const e=findBox(s,["avcC"])[0];e&&e.length>3&&(n+="."+toHex(e[1])+toHex(e[2])+toHex(e[3]),i=parseSupplementalDoViCodec("avc1"===o?"dva1":"dvav",s));break}case"mp4a":{const e=findBox(t,[r])[0],s=findBox(e.subarray(28),["esds"])[0];if(s&&s.length>7){let e=4;if(3!==s[e++])break;e=skipBERInteger(s,e),e+=2;const t=s[e++];if(128&t&&(e+=2),64&t&&(e+=s[e++]),4!==s[e++])break;e=skipBERInteger(s,e);const r=s[e++];if(64!==r)break;if(n+="."+toHex(r),e+=12,5!==s[e++])break;e=skipBERInteger(s,e);const i=s[e++];let a=(248&i)>>3;31===a&&(a+=1+((7&i)<<3)+((224&s[e])>>5)),n+="."+a}break}case"hvc1":case"hev1":{const e=findBox(s,["hvcC"])[0];if(e&&e.length>12){const t=e[1],s=["","A","B","C"][t>>6],r=31&t,i=readUint32(e,2),a=(32&t)>>5?"H":"L",o=e[12],l=e.subarray(6,12);n+="."+s+r,n+="."+reverse32BitInt(i).toString(16).toUpperCase(),n+="."+a+o;let d="";for(let e=l.length;e--;){const t=l[e];if(t||d){d="."+t.toString(16).toUpperCase()+d}}n+=d}i=parseSupplementalDoViCodec("hev1"==o?"dvhe":"dvh1",s);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=parseSupplementalDoViCodec(n,s)||n;break;case"vp09":{const e=findBox(s,["vpcC"])[0];if(e&&e.length>6){const t=e[4],s=e[5],r=e[6]>>4&15;n+="."+addLeadingZero(t)+"."+addLeadingZero(s)+"."+addLeadingZero(r)}break}case"av01":{const e=findBox(s,["av1C"])[0];if(e&&e.length>2){const t=e[1]>>>5,r=31&e[1],a=e[2]>>>7?"H":"M",o=(64&e[2])>>6,l=(32&e[2])>>5,d=2===t&&o?l?12:10:o?10:8,h=(16&e[2])>>4,c=(8&e[2])>>3,u=(4&e[2])>>2,f=3&e[2],g=1,m=1,p=1,E=0;n+="."+t+"."+addLeadingZero(r)+a+"."+addLeadingZero(d)+"."+h+"."+c+u+f+"."+addLeadingZero(g)+"."+addLeadingZero(m)+"."+addLeadingZero(p)+"."+E,i=parseSupplementalDoViCodec("dav1",s)}break}}return{codec:n,encrypted:a,supplemental:i}}function parseSupplementalDoViCodec(e,t){const s=findBox(t,["dvvC"]),r=s.length?s[0]:findBox(t,["dvcC"])[0];if(r){const t=r[2]>>1&127,s=r[2]<<5&32|r[3]>>3&31;return e+"."+addLeadingZero(t)+"."+addLeadingZero(s)}}function reverse32BitInt(e){let t=0;for(let s=0;s<32;s++)t|=(e>>s&1)<<31-s;return t>>>0}function skipBERInteger(e,t){const s=t+5;for(;128&e[t++]&&t<s;);return t}function toHex(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function addLeadingZero(e){return(e<10?"0":"")+e}function patchEncyptionData(e,t){if(!e||!t)return;const s=t.keyId;s&&t.isCommonEncryption&&applyToTencBoxes(e,((e,t)=>{const r=e.subarray(8,24);r.some((e=>0!==e))||(logger.log(`[eme] Patching keyId in 'enc${t?"a":"v"}>sinf>>tenc' box: ${arrayToHex(r)} -> ${arrayToHex(s)}`),e.set(s,8))}))}function parseKeyIdsFromTenc(e){const t=[];return applyToTencBoxes(e,(e=>t.push(e.subarray(8,24)))),t}function applyToTencBoxes(e,t){findBox(e,["moov","trak"]).forEach((e=>{const s=findBox(e,["mdia","minf","stbl","stsd"])[0];if(!s)return;const r=s.subarray(8);let i=findBox(r,["enca"]);const n=i.length>0;n||(i=findBox(r,["encv"])),i.forEach((e=>{findBox(n?e.subarray(28):e.subarray(78),["sinf"]).forEach((e=>{const s=parseSinf(e);s&&t(s,n)}))}))}))}function parseSinf(e){const t=findBox(e,["schm"])[0];if(t){const s=bin2str(t.subarray(4,8));if("cbcs"===s||"cenc"===s){const t=findBox(e,["schi","tenc"])[0];if(t)return t}}}function getSampleData(e,t,s){const r={},i=findBox(e,["moof","traf"]);for(let e=0;e<i.length;e++){const n=i[e],a=findBox(n,["tfhd"])[0],o=readUint32(a,4),l=t[o];if(!l)continue;r[o]||(r[o]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type});const d=r[o],h=findBox(n,["tfdt"])[0];if(h){const e=h[0];let t=readUint32(h,4);1===e&&(t===UINT32_MAX$1?s.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(t*=UINT32_MAX$1+1,t+=readUint32(h,8))),isFiniteNumber(t)&&(!isFiniteNumber(d.start)||t<d.start)&&(d.start=t)}const c=l.default,u=readUint32(a,0)|(null==c?void 0:c.flags);let f=(null==c?void 0:c.duration)||0;8&u&&(f=readUint32(a,2&u?12:8));const g=findBox(n,["trun"]);let m=d.start||0,p=0,E=f;for(let e=0;e<g.length;e++){const t=g[e],s=readUint32(t,4),r=d.sampleCount;d.sampleCount+=s;const i=1&t[3],n=4&t[3],a=1&t[2],o=2&t[2],l=4&t[2],h=8&t[2];let c=8,u=s;if(i&&(c+=4),n&&s){1&t[c+1]||void 0!==d.keyFrameIndex||(d.keyFrameIndex=r),c+=4,a?(E=readUint32(t,c),c+=4):E=f,o&&(c+=4),h&&(c+=4),m+=E,p+=E,u--}for(;u--;){if(a?(E=readUint32(t,c),c+=4):E=f,o&&(c+=4),l){1&t[c+1]||void 0===d.keyFrameIndex&&(d.keyFrameIndex=d.sampleCount-(u+1),d.keyFrameStart=m),c+=4}h&&(c+=4),m+=E,p+=E}!p&&f&&(p+=f*s)}d.duration+=p}if(!Object.keys(r).some((e=>r[e].duration))){let t=1/0,s=0;const i=findBox(e,["sidx"]);for(let e=0;e<i.length;e++){const r=parseSegmentIndex(i[e]);if(null!=r&&r.references){t=Math.min(t,r.earliestPresentationTime/r.timescale);const e=r.references.reduce(((e,t)=>e+t.info.duration||0),0);s=Math.max(s,e+r.earliestPresentationTime/r.timescale)}}s&&isFiniteNumber(s)&&Object.keys(r).forEach((e=>{r[e].duration||(r[e].duration=s*r[e].timescale-r[e].start)}))}return r}function segmentValidRange(e){const t={valid:null,remainder:null},s=findBox(e,["moof"]);if(s.length<2)return t.remainder=e,t;const r=s[s.length-1];return t.valid=e.slice(0,r.byteOffset-8),t.remainder=e.slice(r.byteOffset-8),t}function appendUint8Array(e,t){const s=new Uint8Array(e.length+t.length);return s.set(e),s.set(t,e.length),s}function parseSamples(e,t){const s=[],r=t.samples,i=t.timescale,n=t.id;let a=!1;return findBox(r,["moof"]).map((o=>{const l=o.byteOffset-8;findBox(o,["traf"]).map((o=>{const d=findBox(o,["tfdt"]).map((e=>{const t=e[0];let s=readUint32(e,4);return 1===t&&(s*=Math.pow(2,32),s+=readUint32(e,8)),s/i}))[0];return void 0!==d&&(e=d),findBox(o,["tfhd"]).map((d=>{const h=readUint32(d,4),c=16777215&readUint32(d,0);let u=0;const f=0!=(16&c);let g=0;const m=0!=(32&c);let p=8;h===n&&(0!=(1&c)&&(p+=8),0!=(2&c)&&(p+=4),0!=(8&c)&&(u=readUint32(d,p),p+=4),f&&(g=readUint32(d,p),p+=4),m&&(p+=4),"video"===t.type&&(a=isHEVC(t.codec)),findBox(o,["trun"]).map((n=>{const o=n[0],d=16777215&readUint32(n,0),h=0!=(1&d);let c=0;const f=0!=(4&d),m=0!=(256&d);let p=0;const E=0!=(512&d);let y=0;const v=0!=(1024&d),T=0!=(2048&d);let S=0;const A=readUint32(n,4);let L=8;h&&(c=readUint32(n,L),L+=4),f&&(L+=4);let I=c+l;for(let l=0;l<A;l++){if(m?(p=readUint32(n,L),L+=4):p=u,E?(y=readUint32(n,L),L+=4):y=g,v&&(L+=4),T&&(S=0===o?readUint32(n,L):readSint32(n,L),L+=4),t.type===ElementaryStreamTypes.VIDEO){let t=0;for(;t<y;){const n=readUint32(r,I);if(I+=4,isSEIMessage(a,r[I])){parseSEIMessageFromNALu(r.subarray(I,I+n),a?2:1,e+S/i,s)}I+=n,t+=n+4}}e+=p/i}})))}))}))})),s}function isHEVC(e){if(!e)return!1;const t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function isSEIMessage(e,t){if(e){const e=t>>1&63;return 39===e||40===e}return 6===(31&t)}function parseSEIMessageFromNALu(e,t,s,r){const i=discardEPB(e);let n=0;n+=t;let a=0,o=0,l=0;for(;n<i.length;){a=0;do{if(n>=i.length)break;l=i[n++],a+=l}while(255===l);o=0;do{if(n>=i.length)break;l=i[n++],o+=l}while(255===l);const e=i.length-n;let t=n;if(o<e)n+=o;else if(o>e){logger.error(`Malformed SEI payload. ${o} is too small, only ${e} bytes left to parse.`);break}if(4===a){if(181===i[t++]){const e=readUint16(i,t);if(t+=2,49===e){const e=readUint32(i,t);if(t+=4,1195456820===e){const e=i[t++];if(3===e){const n=i[t++],o=64&n,l=o?2+3*(31&n):0,d=new Uint8Array(l);if(o){d[0]=n;for(let e=1;e<l;e++)d[e]=i[t++]}r.push({type:e,payloadType:a,pts:s,bytes:d})}}}}}else if(5===a){if(o>16){const e=[];for(let s=0;s<16;s++){const r=i[t++].toString(16);e.push(1==r.length?"0"+r:r),3!==s&&5!==s&&7!==s&&9!==s||e.push("-")}const n=o-16,l=new Uint8Array(n);for(let e=0;e<n;e++)l[e]=i[t++];r.push({payloadType:a,pts:s,uuid:e.join(""),userData:utf8ArrayToStr(l),userDataBytes:l})}}else o>0&&r.push({payloadType:a,pts:s,payloadSize:o,payload:i.subarray(t,t+o),customSeiMessage:!0})}}function discardEPB(e){const t=e.byteLength,s=[];let r=1;for(;r<t-2;)0===e[r]&&0===e[r+1]&&3===e[r+2]?(s.push(r+2),r+=2):r++;if(0===s.length)return e;const i=t-s.length,n=new Uint8Array(i);let a=0;for(r=0;r<i;a++,r++)a===s[0]&&(a++,s.shift()),n[r]=e[a];return n}function parseEmsg(e){const t=e[0];let s="",r="",i=0,n=0,a=0,o=0,l=0,d=0;if(0===t){for(;"\0"!==bin2str(e.subarray(d,d+1));)s+=bin2str(e.subarray(d,d+1)),d+=1;for(s+=bin2str(e.subarray(d,d+1)),d+=1;"\0"!==bin2str(e.subarray(d,d+1));)r+=bin2str(e.subarray(d,d+1)),d+=1;r+=bin2str(e.subarray(d,d+1)),d+=1,i=readUint32(e,12),n=readUint32(e,16),o=readUint32(e,20),l=readUint32(e,24),d=28}else if(1===t){d+=4,i=readUint32(e,d),d+=4;const t=readUint32(e,d);d+=4;const n=readUint32(e,d);for(d+=4,a=2**32*t+n,isSafeInteger(a)||(a=Number.MAX_SAFE_INTEGER,logger.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=readUint32(e,d),d+=4,l=readUint32(e,d),d+=4;"\0"!==bin2str(e.subarray(d,d+1));)s+=bin2str(e.subarray(d,d+1)),d+=1;for(s+=bin2str(e.subarray(d,d+1)),d+=1;"\0"!==bin2str(e.subarray(d,d+1));)r+=bin2str(e.subarray(d,d+1)),d+=1;r+=bin2str(e.subarray(d,d+1)),d+=1}return{schemeIdUri:s,value:r,timeScale:i,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:e.subarray(d,e.byteLength)}}function mp4Box(e,...t){const s=t.length;let r=8,i=s;for(;i--;)r+=t[i].byteLength;const n=new Uint8Array(r);for(n[0]=r>>24&255,n[1]=r>>16&255,n[2]=r>>8&255,n[3]=255&r,n.set(e,4),i=0,r=8;i<s;i++)n.set(t[i],r),r+=t[i].byteLength;return n}function mp4pssh(e,t,s){if(16!==e.byteLength)throw new RangeError("Invalid system id");let r,i,n;r=0,i=new Uint8Array,n=new Uint8Array;const a=new Uint8Array(4);return s.byteLength>0&&new DataView(a.buffer).setUint32(0,s.byteLength,!1),mp4Box([112,115,115,104],new Uint8Array([0,0,0,0]),e,n,i,a,s)}function parseMultiPssh(e){const t=[];if(e instanceof ArrayBuffer){const s=e.byteLength;let r=0;for(;r+32<s;){const s=parsePssh(new DataView(e,r));t.push(s),r+=s.size}}return t}function parsePssh(e){const t=e.getUint32(0),s=e.byteOffset,r=e.byteLength;if(r<t)return{offset:s,size:r};if(1886614376!==e.getUint32(4))return{offset:s,size:t};const i=e.getUint32(8)>>>24;if(0!==i&&1!==i)return{offset:s,size:t};const n=e.buffer,a=arrayToHex(new Uint8Array(n,s+12,16));let o=null,l=null,d=0;if(0===i)d=28;else{const i=e.getUint32(28);if(!i||r<32+16*i)return{offset:s,size:t};o=[];for(let e=0;e<i;e++)o.push(new Uint8Array(n,s+32+16*e,16));d=32+16*i}if(!d)return{offset:s,size:t};const h=e.getUint32(d);return t-32<h?{offset:s,size:t}:(l=new Uint8Array(n,s+d+4,h),{version:i,systemId:a,kids:o,data:l,offset:s,size:t})}const userAgentHevcSupportIsInaccurate=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),sampleEntryCodesISO={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 isCodecType(e,t){const s=sampleEntryCodesISO[t];return!!s&&!!s[e.slice(0,4)]}function areCodecsMediaSourceSupported(e,t,s=!0){return!e.split(",").some((e=>!isCodecMediaSourceSupported(e,t,s)))}function isCodecMediaSourceSupported(e,t,s=!0){var r;const i=getMediaSource(s);return null!=(r=null==i?void 0:i.isTypeSupported(mimeTypeForCodec(e,t)))&&r}function mimeTypeForCodec(e,t){return`${t}/mp4;codecs=${e}`}function videoCodecPreferenceValue(e){if(e){const t=e.substring(0,4);return sampleEntryCodesISO.video[t]}return 2}function codecsSetSelectionPreferenceValue(e){const t=userAgentHevcSupportIsInaccurate();return e.split(",").reduce(((e,s)=>{const r=t&&isHEVC(s)?9:sampleEntryCodesISO.video[s];return r?(2*r+e)/(e?3:2):(sampleEntryCodesISO.audio[s]+e)/(e?2:1)}),0)}const CODEC_COMPATIBLE_NAMES={};function getCodecCompatibleNameLower(e,t=!0){if(CODEC_COMPATIBLE_NAMES[e])return CODEC_COMPATIBLE_NAMES[e];const s={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e];for(let i=0;i<s.length;i++){var r;if(isCodecMediaSourceSupported(s[i],"audio",t))return CODEC_COMPATIBLE_NAMES[e]=s[i],s[i];if("mp3"===s[i]&&null!=(r=getMediaSource(t))&&r.isTypeSupported("audio/mpeg"))return""}return e}const AUDIO_CODEC_REGEXP=/flac|opus|mp4a\.40\.34/i;function getCodecCompatibleName(e,t=!0){return e.replace(AUDIO_CODEC_REGEXP,(e=>getCodecCompatibleNameLower(e.toLowerCase(),t)))}function replaceVideoCodec(e,t){const s=[];if(e){const t=e.split(",");for(let e=0;e<t.length;e++)isCodecType(t[e],"video")||s.push(t[e])}return t&&s.push(t),s.join(",")}function pickMostCompleteCodecName(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e))&&(isCodecSupportedAsType(e,"audio")||isCodecSupportedAsType(e,"video")))return e;if(t){const s=t.split(",");if(s.length>1){if(e)for(let t=s.length;t--;)if(s[t].substring(0,4)===e.substring(0,4))return s[t];return s[0]}}return t||e}function isCodecSupportedAsType(e,t){return isCodecType(e,t)&&isCodecMediaSourceSupported(e,t)}function convertAVC1ToAVCOTI(e){const t=e.split(",");for(let e=0;e<t.length;e++){const s=t[e].split(".");s.length>2&&"avc1"===s[0]&&(t[e]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return t.join(",")}function fillInMissingAV01Params(e){if(e.startsWith("av01.")){const t=e.split("."),s=["0","111","01","01","01","0"];for(let e=t.length;e>4&&e<10;e++)t[e]=s[e-4];return t.join(".")}return e}function getM2TSSupportedAudioTypes(e){const t=getMediaSource(e)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function getCodecsForMimeType(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const supportedResult={supported:!0,powerEfficient:!0,smooth:!0},unsupportedResult={supported:!1,smooth:!1,powerEfficient:!1},SUPPORTED_INFO_DEFAULT={supported:!0,configurations:[],decodingInfoResults:[supportedResult]};function getUnsupportedResult(e,t){return{supported:!1,configurations:t,decodingInfoResults:[unsupportedResult],error:e}}function requiresMediaCapabilitiesDecodingInfo(e,t,s,r,i,n){const a=e.videoCodec,o=e.audioCodec?e.audioGroups:null,l=null==n?void 0:n.audioCodec,d=null==n?void 0:n.channels,h=d?parseInt(d):l?1/0:2;let c=null;if(null!=o&&o.length)try{c=1===o.length&&o[0]?t.groups[o[0]].channels:o.reduce(((e,s)=>{if(s){const r=t.groups[s];if(!r)throw new Error(`Audio track group ${s} not found`);Object.keys(r.channels).forEach((t=>{e[t]=(e[t]||0)+r.channels[t]}))}return e}),{2:0})}catch(e){return!0}return void 0!==a&&(a.split(",").some((e=>isHEVC(e)))||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(r,30)||"SDR"!==e.videoRange&&e.videoRange!==s||e.bitrate>Math.max(i,8e6))||!!c&&isFiniteNumber(h)&&Object.keys(c).some((e=>parseInt(e)>h))}function getMediaDecodingInfoPromise(e,t,s,r={}){const i=e.videoCodec;if(!i&&!e.audioCodec||!s)return Promise.resolve(SUPPORTED_INFO_DEFAULT);const n=[],a=makeVideoConfigurations(e),o=a.length,l=makeAudioConfigurations(e,t,o>0),d=l.length;for(let e=o||1*d||1;e--;){const t={type:"media-source"};if(o&&(t.video=a[e%o]),d){t.audio=l[e%d];const s=t.audio.bitrate;t.video&&s&&(t.video.bitrate-=s)}n.push(t)}if(i){const e=navigator.userAgent;if(i.split(",").some((e=>isHEVC(e)))&&userAgentHevcSupportIsInaccurate())return Promise.resolve(getUnsupportedResult(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${e})`),n))}return Promise.all(n.map((e=>{const t=getMediaDecodingInfoKey(e);return r[t]||(r[t]=s.decodingInfo(e))}))).then((e=>({supported:!e.some((e=>!e.supported)),configurations:n,decodingInfoResults:e}))).catch((e=>({supported:!1,configurations:n,decodingInfoResults:[],error:e})))}function makeVideoConfigurations(e){var t;const s=null==(t=e.videoCodec)?void 0:t.split(","),r=getVariantDecodingBitrate(e),i=e.width||640,n=e.height||480,a=e.frameRate||30,o=e.videoRange.toLowerCase();return s?s.map((e=>{const t={contentType:mimeTypeForCodec(fillInMissingAV01Params(e),"video"),width:i,height:n,bitrate:r,framerate:a};return"sdr"!==o&&(t.transferFunction=o),t})):[]}function makeAudioConfigurations(e,t,s){var r;const i=null==(r=e.audioCodec)?void 0:r.split(","),n=getVariantDecodingBitrate(e);return i&&e.audioGroups?e.audioGroups.reduce(((e,r)=>{var a;const o=r?null==(a=t.groups[r])?void 0:a.tracks:null;return o?o.reduce(((e,t)=>{if(t.groupId===r){const r=parseFloat(t.channels||"");i.forEach((t=>{const i={contentType:mimeTypeForCodec(t,"audio"),bitrate:s?estimatedAudioBitrate(t,n):n};r&&(i.channels=""+r),e.push(i)}))}return e}),e):e}),[]):[]}function estimatedAudioBitrate(e,t){if(t<=1)return 1;let s=128e3;return"ec-3"===e?s=768e3:"ac-3"===e&&(s=64e4),Math.min(t/2,s)}function getVariantDecodingBitrate(e){return 1e3*Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)/1e3)||1}function getMediaDecodingInfoKey(e){let t="";const{audio:s,video:r}=e;if(r){t+=`${getCodecsForMimeType(r.contentType)}_r${r.height}x${r.width}f${Math.ceil(r.framerate)}${r.transferFunction||"sd"}_${Math.ceil(r.bitrate/1e5)}`}if(s){t+=`${r?"_":""}${getCodecsForMimeType(s.contentType)}_c${s.channels}`}return t}const HdcpLevels=["NONE","TYPE-0","TYPE-1",null];function isHdcpLevel(e){return HdcpLevels.indexOf(e)>-1}const VideoRangeValues=["SDR","PQ","HLG"];function isVideoRange(e){return!!e&&VideoRangeValues.indexOf(e)>-1}var HlsSkip={No:"",Yes:"YES",v2:"v2"};function getSkipValue(e){const{canSkipUntil:t,canSkipDateRanges:s,age:r}=e;return t&&r<t/2?s?HlsSkip.v2:HlsSkip.Yes:HlsSkip.No}class HlsUrlParameters{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){const t=new self.URL(e);return void 0!==this.msn&&t.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class Level{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter((e=>!!e)).map((e=>e.substring(0,4))).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const s=null==(t=e.supplemental)?void 0:t.videoCodec;s&&s!==e.videoCodec&&(this.codecSet+=`,${s.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return hasGroup(this._audioGroups,e)}hasSubtitleGroup(e){return hasGroup(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t)if("audio"===e){let e=this._audioGroups;e||(e=this._audioGroups=[]),-1===e.indexOf(t)&&e.push(t)}else if("text"===e){let e=this._subtitleGroups;e||(e=this._subtitleGroups=[]),-1===e.indexOf(t)&&e.push(t)}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return null==(e=this.audioGroups)?void 0:e[0]}get textGroupId(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}addFallback(){}}function hasGroup(e,t){return!(!t||!e)&&-1!==e.indexOf(t)}function isHdrSupported(){if("function"==typeof matchMedia){const e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}function getVideoSelectionOptions(e,t){let s=!1,r=[];if(e&&(s="SDR"!==e,r=[e]),t){r=t.allowedVideoRanges||VideoRangeValues.slice(0);const e="SDR"!==r.join("")&&!t.videoCodec;s=void 0!==t.preferHDR?t.preferHDR:e&&isHdrSupported(),s||(r=["SDR"])}return{preferHDR:s,allowedVideoRanges:r}}const omitCircularRefsReplacer=e=>{const t=new WeakSet;return(s,r)=>{if(e&&(r=e(s,r)),"object"==typeof r&&null!==r){if(t.has(r))return;t.add(r)}return r}},stringify=(e,t)=>JSON.stringify(e,omitCircularRefsReplacer(t));function getStartCodecTier(e,t,s,r,i){const n=Object.keys(e),a=null==r?void 0:r.channels,o=null==r?void 0:r.audioCodec,l=null==i?void 0:i.videoCodec,d=a&&2===parseInt(a);let h=!1,c=!1,u=1/0,f=1/0,g=1/0,m=1/0,p=0,E=[];const{preferHDR:y,allowedVideoRanges:v}=getVideoSelectionOptions(t,i);for(let t=n.length;t--;){const s=e[n[t]];h||(h=s.channels[2]>0),u=Math.min(u,s.minHeight),f=Math.min(f,s.minFramerate),g=Math.min(g,s.minBitrate);v.filter((e=>s.videoRanges[e]>0)).length>0&&(c=!0)}u=isFiniteNumber(u)?u:0,f=isFiniteNumber(f)?f:0;const T=Math.max(1080,u),S=Math.max(30,f);g=isFiniteNumber(g)?g:s,s=Math.max(g,s),c||(t=void 0);const A=n.length>1;return{codecSet:n.reduce(((t,r)=>{const i=e[r];if(r===t)return t;if(E=c?v.filter((e=>i.videoRanges[e]>0)):[],A){if(i.minBitrate>s)return logStartCodecCandidateIgnored(r,`min bitrate of ${i.minBitrate} > current estimate of ${s}`),t;if(!i.hasDefaultAudio)return logStartCodecCandidateIgnored(r,"no renditions with default or auto-select sound found"),t;if(o&&r.indexOf(o.substring(0,4))%5!=0)return logStartCodecCandidateIgnored(r,`audio codec preference "${o}" not found`),t;if(a&&!d){if(!i.channels[a])return logStartCodecCandidateIgnored(r,`no renditions with ${a} channel sound found (channels options: ${Object.keys(i.channels)})`),t}else if((!o||d)&&h&&0===i.channels[2])return logStartCodecCandidateIgnored(r,"no renditions with stereo sound found"),t;if(i.minHeight>T)return logStartCodecCandidateIgnored(r,`min resolution of ${i.minHeight} > maximum of ${T}`),t;if(i.minFramerate>S)return logStartCodecCandidateIgnored(r,`min framerate of ${i.minFramerate} > maximum of ${S}`),t;if(!E.some((e=>i.videoRanges[e]>0)))return logStartCodecCandidateIgnored(r,`no variants with VIDEO-RANGE of ${stringify(E)} found`),t;if(l&&r.indexOf(l.substring(0,4))%5!=0)return logStartCodecCandidateIgnored(r,`video codec preference "${l}" not found`),t;if(i.maxScore<p)return logStartCodecCandidateIgnored(r,`max score of ${i.maxScore} < selected max of ${p}`),t}return t&&(codecsSetSelectionPreferenceValue(r)>=codecsSetSelectionPreferenceValue(t)||i.fragmentError>e[t].fragmentError)?t:(m=i.minIndex,p=i.maxScore,r)}),void 0),videoRanges:E,preferHDR:y,minFramerate:f,minBitrate:g,minIndex:m}}function logStartCodecCandidateIgnored(e,t){logger.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function getAudioTracksByGroup(e){return e.reduce(((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);const r=t.channels||"2";return s.channels[r]=(s.channels[r]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function getCodecTiers(e,t,s,r){return e.slice(s,r+1).reduce(((e,s,r)=>{if(!s.codecSet)return e;const i=s.audioGroups;let n=e[s.codecSet];n||(e[s.codecSet]=n={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:r,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!i,fragmentError:0}),n.minBitrate=Math.min(n.minBitrate,s.bitrate);const a=Math.min(s.height,s.width);return n.minHeight=Math.min(n.minHeight,a),n.minFramerate=Math.min(n.minFramerate,s.frameRate),n.minIndex=Math.min(n.minIndex,r),n.maxScore=Math.max(n.maxScore,s.score),n.fragmentError+=s.fragmentError,n.videoRanges[s.videoRange]=(n.videoRanges[s.videoRange]||0)+1,i&&i.forEach((e=>{if(!e)return;const s=t.groups[e];s&&(n.hasDefaultAudio=n.hasDefaultAudio||t.hasDefaultAudio?s.hasDefault:s.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(s.channels).forEach((e=>{n.channels[e]=(n.channels[e]||0)+s.channels[e]})))})),e}),{})}function getBasicSelectionOption(e){if(!e)return e;const{lang:t,assocLang:s,characteristics:r,channels:i,audioCodec:n}=e;return{lang:t,assocLang:s,characteristics:r,channels:i,audioCodec:n}}function findMatchingOption(e,t,s){if("attrs"in e){const s=t.indexOf(e);if(-1!==s)return s}for(let r=0;r<t.length;r++){if(matchesOption(e,t[r],s))return r}return-1}function matchesOption(e,t,s){const{groupId:r,name:i,lang:n,assocLang:a,default:o}=e,l=e.forced;return(void 0===r||t.groupId===r)&&(void 0===i||t.name===i)&&(void 0===n||languagesMatch(n,t.lang))&&(void 0===n||t.assocLang===a)&&(void 0===o||t.default===o)&&(void 0===l||t.forced===l)&&(!("characteristics"in e)||characteristicsMatch(e.characteristics||"",t.characteristics))&&(void 0===s||s(e,t))}function languagesMatch(e,t="--"){return e.length===t.length?e===t:e.startsWith(t)||t.startsWith(e)}function characteristicsMatch(e,t=""){const s=e.split(","),r=t.split(",");return s.length===r.length&&!s.some((e=>-1===r.indexOf(e)))}function audioMatchPredicate(e,t){const{audioCodec:s,channels:r}=e;return!(void 0!==s&&(t.audioCodec||"").substring(0,4)!==s.substring(0,4)||void 0!==r&&r!==(t.channels||"2"))}function findClosestLevelWithAudioGroup(e,t,s,r,i){const n=t[r],a=t.reduce(((e,t,s)=>{const r=t.uri;return(e[r]||(e[r]=[])).push(s),e}),{})[n.uri];a.length>1&&(r=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,d=n.codecSet.substring(0,4),h=searchDownAndUpList(t,r,(t=>{if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==d)return!1;const r=t.audioGroups,n=s.filter((e=>!r||-1!==r.indexOf(e.groupId)));return findMatchingOption(e,n,i)>-1}));return h>-1?h:searchDownAndUpList(t,r,(t=>{const r=t.audioGroups,n=s.filter((e=>!r||-1!==r.indexOf(e.groupId)));return findMatchingOption(e,n,i)>-1}))}function searchDownAndUpList(e,t,s){for(let r=t;r>-1;r--)if(s(e[r]))return r;for(let r=t+1;r<e.length;r++)if(s(e[r]))return r;return-1}function useAlternateAudio(e,t){var s;return!!e&&e!==(null==(s=t.loadLevelObj)?void 0:s.uri)}class AbrController extends Logger{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=e=>{var t;const{fragCurrent:s,partCurrent:r,hls:i}=this,{autoLevelEnabled:n,media:a}=i;if(!s||!a)return;const o=performance.now(),l=r?r.stats:s.stats,d=r?r.duration:s.duration,h=o-l.loading.start,c=i.minAutoLevel,u=s.level,f=this._nextAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||u<=c)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!n)return;const g=f>-1&&f!==u,m=!!e||g;if(!m&&(a.paused||!a.playbackRate||!a.readyState))return;const p=i.mainForwardBufferInfo;if(!m&&null===p)return;const E=this.bwEstimator.getEstimateTTFB(),y=Math.abs(a.playbackRate);if(h<=Math.max(E,d/(2*y)*1e3))return;const v=p?p.len/y:0,T=l.loading.first?l.loading.first-l.loading.start:-1,S=l.loaded&&T>-1,A=this.getBwEstimate(),L=i.levels,I=L[u],R=Math.max(l.loaded,Math.round(d*(s.bitrate||I.averageBitrate)/8));let D=S?h-T:h;D<1&&S&&(D=Math.min(h,8*l.loaded/A));const b=S?1e3*l.loaded/D:0,_=E/1e3,C=b?(R-l.loaded)/b:8*R/A+_;if(C<=v)return;const P=b?8*b:A,k=!0===(null==(t=(null==e?void 0:e.details)||this.hls.latestLevelDetails)?void 0:t.live),M=this.hls.config.abrBandWidthUpFactor;let O,w=Number.POSITIVE_INFINITY;for(O=u-1;O>c;O--){const e=L[O].maxBitrate,t=!L[O].details||k;if(w=this.getTimeToLoadFrag(_,P,d*e,t),w<Math.min(v,d+_))break}if(w>=C)return;if(w>10*d)return;S?this.bwEstimator.sample(h-Math.min(E,T),l.loaded):this.bwEstimator.sampleTTFB(h);const F=L[O].maxBitrate;this.getBwEstimate()*M>F&&this.resetEstimator(F);const x=this.findBestLevel(F,c,O,0,v,1,1);x>-1&&(O=x),this.warn(`Fragment ${s.sn}${r?" part "+r.index:""} of level ${u} is loading too slowly;\n Fragment duration: ${s.duration.toFixed(3)}\n Time to underbuffer: ${v.toFixed(3)} s\n Estimated load time for current fragment: ${C.toFixed(3)} s\n Estimated load time for down switch fragment: ${w.toFixed(3)} s\n TTFB estimate: ${0|T} ms\n Current BW estimate: ${isFiniteNumber(A)?0|A:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${O} @ ${0|F} bps`),i.nextLoadLevel=i.nextAutoLevel=O,this.clearTimer();const N=()=>{if(this.clearTimer(),this.fragCurrent===s&&this.hls.loadLevel===O&&O>0){const e=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${O>0?"and switching down":""}\n Fragment duration: ${s.duration.toFixed(3)} s\n Time to underbuffer: ${e.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,O>c){let t=this.findBestLevel(this.hls.levels[c].bitrate,c,O,0,e,1,1);-1===t&&(t=c),this.hls.nextLoadLevel=this.hls.nextAutoLevel=t,this.resetEstimator(this.hls.levels[t].bitrate)}}};g||C>2*w?N():this.timer=self.setInterval(N,1e3*w),i.trigger(Events.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:r,stats:l})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new EwmaBandWidthEstimator(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.FRAG_LOADING,this.onFragLoading,this),e.on(Events.FRAG_LOADED,this.onFragLoaded,this),e.on(Events.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Events.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Events.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(Events.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.FRAG_LOADING,this.onFragLoading,this),e.off(Events.FRAG_LOADED,this.onFragLoaded,this),e.off(Events.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Events.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Events.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(Events.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const s=t.frag;if(!this.ignoreFragment(s)){var r;if(!s.bitrateTest)this.fragCurrent=s,this.partCurrent=null!=(r=t.part)?r:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case ErrorDetails.BUFFER_ADD_CODEC_ERROR:case ErrorDetails.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case ErrorDetails.FRAG_LOAD_TIMEOUT:{const e=t.frag,{fragCurrent:s,partCurrent:r}=this;if(e&&s&&e.sn===s.sn&&e.level===s.level){const t=performance.now(),s=r?r.stats:e.stats,i=t-s.loading.start,n=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&n>-1){const e=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(i-Math.min(e,n),s.loaded)}else this.bwEstimator.sampleTTFB(i)}break}}}getTimeToLoadFrag(e,t,s,r){return e+s/t+(r?e+this.lastLevelLoadSec:0)}onLevelLoaded(e,t){const s=this.hls.config,{loading:r}=t.stats,i=r.end-r.first;isFiniteNumber(i)&&(this.lastLevelLoadSec=i/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:s}){const r=s?s.stats:t.stats;if(t.type===PlaylistLevelType.MAIN&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const e=s?s.duration:t.duration,i=this.hls.levels[t.level],n=(i.loaded?i.loaded.bytes:0)+r.loaded,a=(i.loaded?i.loaded.duration:0)+e;i.loaded={bytes:n,duration:a},i.realBitrate=Math.round(8*n/a)}if(t.bitrateTest){const e={stats:r,frag:t,part:s,id:t.type};this.onFragBuffered(Events.FRAG_BUFFERED,e),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:s,part:r}=t,i=null!=r&&r.stats.loaded?r.stats:s.stats;if(i.aborted)return;if(this.ignoreFragment(s))return;const n=i.parsing.end-i.loading.start-Math.min(i.loading.first-i.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,i.loaded),i.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==PlaylistLevelType.MAIN||"initSegment"===e.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,s=this.getBwEstimate(),r=this.hls.config.maxStarvationDelay,i=this.findBestLevel(s,t,e,0,r,1,1);if(i>-1)return i;const n=this.hls.firstLevel,a=Math.min(Math.max(n,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&s&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;const r=t&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){const t=this.hls.levels;if(t.length>Math.max(e,r)&&t[e].loadError<=t[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:s}=this;if(s.levels.length<=1)return s.loadLevel;const{maxAutoLevel:r,config:i,minAutoLevel:n}=s,a=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let d=i.abrBandWidthFactor,h=i.abrBandWidthUpFactor;if(l){const e=this.findBestLevel(o,n,r,l,0,d,h);if(e>=0)return this.rebufferNotice=-1,e}let c=a?Math.min(a,i.maxStarvationDelay):i.maxStarvationDelay;if(!l){const e=this.bitrateTestDelay;if(e){c=(a?Math.min(a,i.maxLoadingDelay):i.maxLoadingDelay)-e,this.info(`bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*c)} ms`),d=h=1}}const u=this.findBestLevel(o,n,r,l,c,d,h);if(this.rebufferNotice!==u&&(this.rebufferNotice=u,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${u}`)),u>-1)return u;const f=s.levels[n],g=s.loadLevelObj;return g&&(null==f?void 0:f.bitrate)<g.bitrate?n:s.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const s=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,r=e.mainForwardBufferInfo;return(r?r.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,s,r,i,n,a){var o;const l=r+i,d=this.lastLoadedFragLevel,h=-1===d?this.hls.firstLevel:d,{fragCurrent:c,partCurrent:u}=this,{levels:f,allAudioTracks:g,loadLevel:m,config:p}=this.hls;if(1===f.length)return 0;const E=f[h],y=!(null==(o=this.hls.latestLevelDetails)||!o.live),v=-1===m||-1===d;let T,S="SDR",A=(null==E?void 0:E.frameRate)||0;const{audioPreference:L,videoPreference:I}=p,R=this.audioTracksByGroup||(this.audioTracksByGroup=getAudioTracksByGroup(g));let D=-1;if(v){if(-1!==this.firstSelection)return this.firstSelection;const r=getStartCodecTier(this.codecTiers||(this.codecTiers=getCodecTiers(f,R,t,s)),S,e,L,I),{codecSet:i,videoRanges:n,minFramerate:a,minBitrate:o,minIndex:l,preferHDR:d}=r;D=l,T=i,S=d?n[n.length-1]:n[0],A=a,e=Math.max(e,o),this.log(`picked start tier ${stringify(r)}`)}else T=null==E?void 0:E.codecSet,S=null==E?void 0:E.videoRange;const b=u?u.duration:c?c.duration:0,_=this.bwEstimator.getEstimateTTFB()/1e3,C=[];for(let o=s;o>=t;o--){var P;const t=f[o],c=o>h;if(!t)continue;if(p.useMediaCapabilities&&!t.supportedResult&&!t.supportedPromise){const s=navigator.mediaCapabilities;"function"==typeof(null==s?void 0:s.decodingInfo)&&requiresMediaCapabilitiesDecodingInfo(t,R,S,A,e,L)?(t.supportedPromise=getMediaDecodingInfoPromise(t,R,s,this.supportedCache),t.supportedPromise.then((e=>{if(!this.hls)return;t.supportedResult=e;const s=this.hls.levels,r=s.indexOf(t);e.error?this.warn(`MediaCapabilities decodingInfo error: "${e.error}" for level ${r} ${stringify(e)}`):e.supported?e.decodingInfoResults.some((e=>!1===e.smooth||!1===e.powerEfficient))&&this.log(`MediaCapabilities decodingInfo for level ${r} not smooth or powerEfficient: ${stringify(e)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${r} ${stringify(e)}`),r>-1&&s.length>1&&(this.log(`Removing unsupported level ${r}`),this.hls.removeLevel(r),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))})).catch((e=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${e}`)}))):t.supportedResult=SUPPORTED_INFO_DEFAULT}if((T&&t.codecSet!==T||S&&t.videoRange!==S||c&&A>t.frameRate||!c&&A>0&&A<t.frameRate||null!=(P=t.supportedResult)&&null!=(P=P.decodingInfoResults)&&P.some((e=>!1===e.smooth)))&&(!v||o!==D)){C.push(o);continue}const g=t.details,E=(u?null==g?void 0:g.partTarget:null==g?void 0:g.averagetargetduration)||b;let I;I=c?a*e:n*e;const k=b&&r>=2*b&&0===i?t.averageBitrate:t.maxBitrate,M=this.getTimeToLoadFrag(_,I,k*E,void 0===g);if(I>=k&&(o===d||0===t.loadError&&0===t.fragmentError)&&(M<=_||!isFiniteNumber(M)||y&&!this.bitrateTestDelay||M<l)){const e=this.forcedAutoLevel;return o===m||-1!==e&&e===m||(C.length&&this.trace(`Skipped level(s) ${C.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${f[C[0]].codecs}" ${f[C[0]].videoRange}; not compatible with "${T}" ${S}`),this.info(`switch candidate:${h}->${o} adjustedbw(${Math.round(I)})-bitrate=${Math.round(I-k)} ttfb:${_.toFixed(1)} avgDuration:${E.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${M.toFixed(1)} firstSelection:${v} codecSet:${t.codecSet} videoRange:${t.videoRange} hls.loadLevel:${m}`)),v&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:s}=this.hls;return Math.min(Math.max(e,s),t)}}const BinarySearch={search:function(e,t){let s=0,r=e.length-1,i=null,n=null;for(;s<=r;){i=(s+r)/2|0,n=e[i];const a=t(n);if(a>0)s=i+1;else{if(!(a<0))return n;r=i-1}}return null}};function findFragmentByPDT(e,t,s){if(null===t||!Array.isArray(e)||!e.length||!isFiniteNumber(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;for(let r=0;r<e.length;++r){const i=e[r];if(pdtWithinToleranceTest(t,s,i))return i}return null}function findFragmentByPTS(e,t,s=0,r=0,i=.005){let n=null;if(e){n=t[1+e.sn-t[0].sn]||null;const r=e.endDTS-s;r>0&&r<15e-7&&(s+=15e-7),n&&e.level!==n.level&&n.end<=e.end&&(n=t[2+e.sn-t[0].sn]||null)}else 0===s&&0===t[0].start&&(n=t[0]);if(n&&((!e||e.level===n.level)&&0===fragmentWithinToleranceTest(s,r,n)||fragmentWithinFastStartSwitch(n,e,Math.min(i,r))))return n;const a=BinarySearch.search(t,fragmentWithinToleranceTest.bind(null,s,r));return!a||a===e&&n?n:a}function fragmentWithinFastStartSwitch(e,t,s){if(t&&0===t.start&&t.level<e.level&&(t.endPTS||0)>0){const r=t.tagList.reduce(((e,t)=>("INF"===t[0]&&(e+=parseFloat(t[1])),e)),s);return e.start<=r}return!1}function fragmentWithinToleranceTest(e=0,t=0,s){if(s.start<=e&&s.start+s.duration>e)return 0;const r=Math.min(t,s.duration+(s.deltaPTS?s.deltaPTS:0));return s.start+s.duration-r<=e?1:s.start-r>e&&s.start?-1:0}function pdtWithinToleranceTest(e,t,s){const r=1e3*Math.min(t,s.duration+(s.deltaPTS?s.deltaPTS:0));return(s.endProgramDateTime||0)-r>e}function findNearestWithCC(e,t,s){if(e&&e.startCC<=t&&e.endCC>=t){let r=e.fragments;const{fragmentHint:i}=e;let n;return i&&(r=r.concat(i)),BinarySearch.search(r,(e=>e.cc<t?1:e.cc>t?-1:(n=e,e.end<=s?1:e.start>s?-1:0))),n||null}return null}function isTimeoutError(e){switch(e.details){case ErrorDetails.FRAG_LOAD_TIMEOUT:case ErrorDetails.KEY_LOAD_TIMEOUT:case ErrorDetails.LEVEL_LOAD_TIMEOUT:case ErrorDetails.MANIFEST_LOAD_TIMEOUT:case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:case ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:case ErrorDetails.ASSET_LIST_LOAD_TIMEOUT:return!0}return!1}function isKeyError(e){return e.details.startsWith("key")}function isUnusableKeyError(e){return isKeyError(e)&&!!e.frag&&!e.frag.decryptdata}function getRetryConfig(e,t){const s=isTimeoutError(t);return e.default[(s?"timeout":"error")+"Retry"]}function getRetryDelay(e,t){const s="linear"===e.backoff?1:Math.pow(2,t);return Math.min(s*e.retryDelayMs,e.maxRetryDelayMs)}function getLoaderConfigWithoutReties(e){return _objectSpread2(_objectSpread2({},e),{errorRetry:null,timeoutRetry:null})}function shouldRetry(e,t,s,r){if(!e)return!1;const i=null==r?void 0:r.code,n=t<e.maxNumRetry&&(retryForHttpStatus(i)||!!s);return e.shouldRetry?e.shouldRetry(e,t,s,r,n):n}function retryForHttpStatus(e){return offlineHttpStatus(e)||!!e&&(e<400||e>499)}function offlineHttpStatus(e){return 0===e&&!1===navigator.onLine}var NetworkErrorAction={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},ErrorActionFlags={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8};class ErrorController extends Logger{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(Events.ERROR,this.onError,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(Events.ERROR,this.onError,this),e.off(Events.ERROR,this.onErrorOut,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(null==e?void 0:e.type)===PlaylistLevelType.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,s=t.currentLevel;return null!=(e=t.loadLevelObj)&&e.details||-1===s?t.loadLevel:s}variantHasKey(e,t){if(e){var s;if(null!=(s=e.details)&&s.hasKey(t))return!0;const r=e.audioGroups;if(r){return this.hls.allAudioTracks.filter((e=>r.indexOf(e.groupId)>=0)).some((e=>{var s;return null==(s=e.details)?void 0:s.hasKey(t)}))}}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var s;if(t.fatal)return;const r=this.hls,i=t.context;switch(t.details){case ErrorDetails.FRAG_LOAD_ERROR:case ErrorDetails.FRAG_LOAD_TIMEOUT:case ErrorDetails.KEY_LOAD_ERROR:case ErrorDetails.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case ErrorDetails.FRAG_PARSING_ERROR:if(null!=(s=t.frag)&&s.gap)return void(t.errorAction=createDoNothingErrorAction());case ErrorDetails.FRAG_GAP:case ErrorDetails.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=NetworkErrorAction.SendAlternateToPenaltyBox);case ErrorDetails.LEVEL_EMPTY_ERROR:case ErrorDetails.LEVEL_PARSING_ERROR:{var n;const e=t.parent===PlaylistLevelType.MAIN?t.level:r.loadLevel;t.details===ErrorDetails.LEVEL_EMPTY_ERROR&&null!=(n=t.context)&&null!=(n=n.levelDetails)&&n.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case ErrorDetails.LEVEL_LOAD_ERROR:case ErrorDetails.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==i?void 0:i.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.level)));case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:case ErrorDetails.SUBTITLE_LOAD_ERROR:case ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){const e=r.loadLevelObj;if(e&&(i.type===PlaylistContextType.AUDIO_TRACK&&e.hasAudioGroup(i.groupId)||i.type===PlaylistContextType.SUBTITLE_TRACK&&e.hasSubtitleGroup(i.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=NetworkErrorAction.SendAlternateToPenaltyBox,void(t.errorAction.flags=ErrorActionFlags.MoveAllAlternatesMatchingHost)}return;case ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(t.errorAction={action:NetworkErrorAction.SendAlternateToPenaltyBox,flags:ErrorActionFlags.MoveAllAlternatesMatchingHDCP});case ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED:case ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case ErrorDetails.KEY_SYSTEM_NO_SESSION:return void(t.errorAction={action:NetworkErrorAction.SendAlternateToPenaltyBox,flags:ErrorActionFlags.MoveAllAlternatesMatchingKey});case ErrorDetails.BUFFER_ADD_CODEC_ERROR:case ErrorDetails.REMUX_ALLOC_ERROR:case ErrorDetails.BUFFER_APPEND_ERROR:var a;if(!t.errorAction)t.errorAction=this.getLevelSwitchAction(t,null!=(a=t.level)?a:r.loadLevel);return;case ErrorDetails.INTERNAL_EXCEPTION:case ErrorDetails.BUFFER_APPENDING_ERROR:case ErrorDetails.BUFFER_FULL_ERROR:case ErrorDetails.LEVEL_SWITCH_ERROR:case ErrorDetails.BUFFER_STALLED_ERROR:case ErrorDetails.BUFFER_SEEK_OVER_HOLE:case ErrorDetails.BUFFER_NUDGE_ON_STALL:return void(t.errorAction=createDoNothingErrorAction())}t.type===ErrorTypes.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=createDoNothingErrorAction())}getPlaylistRetryOrSwitchAction(e,t){const s=getRetryConfig(this.hls.config.playlistLoadPolicy,e),r=this.playlistError++;if(shouldRetry(s,r,isTimeoutError(e),e.response))return{action:NetworkErrorAction.RetryRequest,flags:ErrorActionFlags.None,retryConfig:s,retryCount:r};const i=this.getLevelSwitchAction(e,t);return s&&(i.retryConfig=s,i.retryCount=r),i}getFragRetryOrSwitchAction(e){const t=this.hls,s=this.getVariantLevelIndex(e.frag),r=t.levels[s],{fragLoadPolicy:i,keyLoadPolicy:n}=t.config,a=getRetryConfig(isKeyError(e)?n:i,e),o=t.levels.reduce(((e,t)=>e+t.fragmentError),0);if(r&&(e.details!==ErrorDetails.FRAG_GAP&&r.fragmentError++,!isUnusableKeyError(e))){if(shouldRetry(a,o,isTimeoutError(e),e.response))return{action:NetworkErrorAction.RetryRequest,flags:ErrorActionFlags.None,retryConfig:a,retryCount:o}}const l=this.getLevelSwitchAction(e,s);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(e,t){const s=this.hls;null==t&&(t=s.loadLevel);const r=this.hls.levels[t];if(r){var i,n;const t=e.details;r.loadError++,t===ErrorDetails.BUFFER_APPEND_ERROR&&r.fragmentError++;let l=-1;const{levels:d,loadLevel:h,minAutoLevel:c,maxAutoLevel:u}=s;s.autoLevelEnabled||s.config.preserveManualLevelOnError||(s.loadLevel=-1);const f=null==(i=e.frag)?void 0:i.type,g=(f===PlaylistLevelType.AUDIO&&t===ErrorDetails.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(t===ErrorDetails.BUFFER_ADD_CODEC_ERROR||t===ErrorDetails.BUFFER_APPEND_ERROR))&&d.some((({audioCodec:e})=>r.audioCodec!==e)),m="video"===e.sourceBufferName&&(t===ErrorDetails.BUFFER_ADD_CODEC_ERROR||t===ErrorDetails.BUFFER_APPEND_ERROR)&&d.some((({codecSet:e,audioCodec:t})=>r.codecSet!==e&&r.audioCodec===t)),{type:p,groupId:E}=null!=(n=e.context)?n:{};for(let s=d.length;s--;){const i=(s+h)%d.length;if(i!==h&&i>=c&&i<=u&&0===d[i].loadError){var a,o;const s=d[i];if(t===ErrorDetails.FRAG_GAP&&f===PlaylistLevelType.MAIN&&e.frag){const t=d[i].details;if(t){const s=findFragmentByPTS(e.frag,t.fragments,e.frag.start);if(null!=s&&s.gap)continue}}else{if(p===PlaylistContextType.AUDIO_TRACK&&s.hasAudioGroup(E)||p===PlaylistContextType.SUBTITLE_TRACK&&s.hasSubtitleGroup(E))continue;if(f===PlaylistLevelType.AUDIO&&null!=(a=r.audioGroups)&&a.some((e=>s.hasAudioGroup(e)))||f===PlaylistLevelType.SUBTITLE&&null!=(o=r.subtitleGroups)&&o.some((e=>s.hasSubtitleGroup(e)))||g&&r.audioCodec===s.audioCodec||m&&r.codecSet===s.codecSet||!g&&r.codecSet!==s.codecSet)continue}l=i;break}}if(l>-1&&s.loadLevel!==l)return e.levelRetry=!0,this.playlistError=0,{action:NetworkErrorAction.SendAlternateToPenaltyBox,flags:ErrorActionFlags.None,nextAutoLevel:l}}return{action:NetworkErrorAction.SendAlternateToPenaltyBox,flags:ErrorActionFlags.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s;switch(null==(s=t.errorAction)?void 0:s.action){case NetworkErrorAction.DoNothing:break;case NetworkErrorAction.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===ErrorDetails.FRAG_GAP?/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):t.fatal=!0}t.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(e){const t=this.hls,s=e.errorAction;if(!s)return;const{flags:r}=s,i=s.nextAutoLevel;switch(r){case ErrorActionFlags.None:this.switchLevel(e,i);break;case ErrorActionFlags.MoveAllAlternatesMatchingHDCP:{const r=this.getVariantLevelIndex(e.frag),i=t.levels[r],n=null==i?void 0:i.attrs["HDCP-LEVEL"];if(s.hdcpLevel=n,"NONE"===n)this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(n){t.maxHdcpLevel=HdcpLevels[HdcpLevels.indexOf(n)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case ErrorActionFlags.MoveAllAlternatesMatchingKey:{const t=e.decryptdata;if(t){const r=this.hls.levels,i=r.length;for(let s=i;s--;){var n,a;if(this.variantHasKey(r[s],t))this.log(`Banned key found in level ${s} (${r[s].bitrate}bps) or audio group "${null==(n=r[s].audioGroups)?void 0:n.join(",")}" (${null==(a=e.frag)?void 0:a.type} fragment) ${arrayToHex(t.keyId||[])}`),r[s].fragmentError++,r[s].loadError++,this.log(`Removing level ${s} with key error (${e.error})`),this.hls.removeLevel(s)}const o=e.frag;if(this.hls.levels.length<i)s.resolved=!0;else if(o&&o.type!==PlaylistLevelType.MAIN){const e=o.decryptdata;e&&!t.matches(e)&&(s.resolved=!0)}}break}}s.resolved||this.switchLevel(e,i)}switchLevel(e,t){if(void 0!==t&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===ErrorDetails.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&"audiovideo"!==e.sourceBufferName)){const t=getCodecsForMimeType(e.mimeType),s=this.hls.levels;for(let r=s.length;r--;)s[r][`${e.sourceBufferName}Codec`]===t&&(this.log(`Removing level ${r} for ${e.details} ("${t}" not supported)`),this.hls.removeLevel(r))}}}function createDoNothingErrorAction(e){const t={action:NetworkErrorAction.DoNothing,flags:ErrorActionFlags.None};return e&&(t.resolved=!0),t}var FragmentState={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class FragmentTracker{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.BUFFER_APPENDED,this.onBufferAppended,this),e.on(Events.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Events.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.BUFFER_APPENDED,this.onBufferAppended,this),e.off(Events.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Events.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const s=this.activePartLists[t];if(s)for(let t=s.length;t--;){const r=s[t];if(!r)break;if(r.start<=e&&e<=r.end&&r.loaded)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,s){const{fragments:r}=this,i=Object.keys(r);for(let n=i.length;n--;){const a=r[i[n]];if((null==a?void 0:a.body.type)===t&&(!s||a.buffered)){const t=a.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,s,r,i){this.timeRanges&&(this.timeRanges[e]=t);const n=(null==r?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach((r=>{const a=this.fragments[r];if(!a)return;if(n>=a.body.sn)return;if(!a.buffered&&(!a.loaded||i))return void(a.body.type===s&&this.removeFragment(a.body));const o=a.range[e];o&&(0!==o.time.length?o.time.some((e=>{const s=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return s&&this.removeFragment(a.body),s})):this.removeFragment(a.body))}))}detectPartialFragments(e){const t=this.timeRanges;if(!t||"initSegment"===e.frag.sn)return;const s=e.frag,r=getFragmentKey(s),i=this.fragments[r];if(!i||i.buffered&&s.gap)return;const n=!s.relurl;if(Object.keys(t).forEach((r=>{const a=s.elementaryStreams[r];if(!a)return;const o=t[r],l=n||!0===a.partial;i.range[r]=this.getBufferedTimes(s,e.part,l,o)})),i.loaded=null,Object.keys(i.range).length){i.buffered=!0;(i.body.endList=s.endList||i.body.endList)&&(this.endListFragments[i.body.type]=i),isPartial(i)||this.removeParts(s.sn-1,s.type)}else this.removeFragment(i.body)}removeParts(e,t){const s=this.activePartLists[t];s&&(this.activePartLists[t]=filterParts(s,(t=>t.fragment.sn>=e)))}fragBuffered(e,t){const s=getFragmentKey(e);let r=this.fragments[s];!r&&t&&(r=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,r.buffered=!0)}getBufferedTimes(e,t,s,r){const i={time:[],partial:s},n=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||n;for(let e=0;e<r.length;e++){const t=r.start(e)-this.bufferPadding,s=r.end(e)+this.bufferPadding;if(l>=t&&o<=s){i.time.push({startPTS:Math.max(n,r.start(e)),endPTS:Math.min(a,r.end(e))});break}if(n<s&&a>t){const t=Math.max(n,r.start(e)),s=Math.min(a,r.end(e));s>t&&(i.partial=!0,i.time.push({startPTS:t,endPTS:s}))}else if(a<=t)break}return i}getPartialFragment(e){let t,s,r,i=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach((l=>{const d=o[l];d&&isPartial(d)&&(s=d.body.start-a,r=d.body.end+a,e>=s&&e<=r&&(t=Math.min(e-s,r-e),n<=t&&(i=d.body,n=t)))})),i}isEndListAppended(e){const t=this.endListFragments[e];return void 0!==t&&(t.buffered||isPartial(t))}getState(e){const t=getFragmentKey(e),s=this.fragments[t];return s?s.buffered?isPartial(s)?FragmentState.PARTIAL:FragmentState.OK:FragmentState.APPENDING:FragmentState.NOT_LOADED}isTimeBuffered(e,t,s){let r,i;for(let n=0;n<s.length;n++){if(r=s.start(n)-this.bufferPadding,i=s.end(n)+this.bufferPadding,e>=r&&t<=i)return!0;if(t<=r)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if("initSegment"===t.frag.sn||t.frag.bitrateTest)return;const s=t.frag,r=t.part?null:t,i=getFragmentKey(s);this.fragments[i]={body:s,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:s,part:r,timeRanges:i,type:n}=t;if("initSegment"===s.sn)return;const a=s.type;if(r){let e=this.activePartLists[a];e||(this.activePartLists[a]=e=[]),e.push(r)}this.timeRanges=i;const o=i[n];this.detectEvictedFragments(n,o,a,r)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=getFragmentKey(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let r=s.length;r--;){const i=t[s[r]];if((null==i?void 0:i.body.type)===e)return!0}return!1}hasParts(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}removeFragmentsInRange(e,t,s,r,i){r&&!this.hasGaps||Object.keys(this.fragments).forEach((n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==s||r&&!o.gap||o.start<t&&o.end>e&&(a.buffered||i)&&this.removeFragment(o)}))}removeFragment(e){const t=getFragmentKey(e);e.clearElementaryStreamInfo();const s=this.activePartLists[e.type];if(s){const t=e.sn;this.activePartLists[e.type]=filterParts(s,(e=>e.fragment.sn!==t))}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=null==(e=this.hls)||null==(e=e.latestLevelDetails)?void 0:e.partList;t&&t.forEach((e=>e.clearElementaryStreamInfo()))}}function isPartial(e){var t,s,r;return e.buffered&&!!(e.body.gap||null!=(t=e.range.video)&&t.partial||null!=(s=e.range.audio)&&s.partial||null!=(r=e.range.audiovideo)&&r.partial)}function getFragmentKey(e){return`${e.type}_${e.level}_${e.sn}`}function filterParts(e,t){return e.filter((e=>{const s=t(e);return s||e.clearElementaryStreamInfo(),s}))}var DecrypterAesMode={cbc:0,ctr:1};class AESCrypto{constructor(e,t,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=s}decrypt(e,t){switch(this.aesMode){case DecrypterAesMode.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case DecrypterAesMode.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function removePadding(e){const t=e.byteLength,s=t&&new DataView(e.buffer).getUint8(t-1);return s?e.slice(0,t-s):e}class AESDecryptor{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),s=new Uint32Array(4);for(let e=0;e<4;e++)s[e]=t.getUint32(4*e);return s}initTable(){const e=this.sBox,t=this.invSBox,s=this.subMix,r=s[0],i=s[1],n=s[2],a=s[3],o=this.invSubMix,l=o[0],d=o[1],h=o[2],c=o[3],u=new Uint32Array(256);let f=0,g=0,m=0;for(m=0;m<256;m++)u[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){let s=g^g<<1^g<<2^g<<3^g<<4;s=s>>>8^255&s^99,e[f]=s,t[s]=f;const o=u[f],m=u[o],p=u[m];let E=257*u[s]^16843008*s;r[f]=E<<24|E>>>8,i[f]=E<<16|E>>>16,n[f]=E<<8|E>>>24,a[f]=E,E=16843009*p^65537*m^257*o^16843008*f,l[s]=E<<24|E>>>8,d[s]=E<<16|E>>>16,h[s]=E<<8|E>>>24,c[s]=E,f?(f=o^u[u[u[p^o]]],g^=u[u[g]]):f=g=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let s=!0,r=0;for(;r<t.length&&s;)s=t[r]===this.key[r],r++;if(s)return;this.key=t;const i=this.keySize=t.length;if(4!==i&&6!==i&&8!==i)throw new Error("Invalid aes key size="+i);const n=this.ksRows=4*(i+6+1);let a,o;const l=this.keySchedule=new Uint32Array(n),d=this.invKeySchedule=new Uint32Array(n),h=this.sBox,c=this.rcon,u=this.invSubMix,f=u[0],g=u[1],m=u[2],p=u[3];let E,y;for(a=0;a<n;a++)a<i?E=l[a]=t[a]:(y=E,a%i==0?(y=y<<8|y>>>24,y=h[y>>>24]<<24|h[y>>>16&255]<<16|h[y>>>8&255]<<8|h[255&y],y^=c[a/i|0]<<24):i>6&&a%i==4&&(y=h[y>>>24]<<24|h[y>>>16&255]<<16|h[y>>>8&255]<<8|h[255&y]),l[a]=E=(l[a-i]^y)>>>0);for(o=0;o<n;o++)a=n-o,y=3&o?l[a]:l[a-4],d[o]=o<4||a<=4?y:f[h[y>>>24]]^g[h[y>>>16&255]]^m[h[y>>>8&255]]^p[h[255&y]],d[o]=d[o]>>>0}networkToHostOrderSwap(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24}decrypt(e,t,s){const r=this.keySize+6,i=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],d=a[2],h=a[3],c=this.uint8ArrayToUint32Array_(s);let u=c[0],f=c[1],g=c[2],m=c[3];const p=new Int32Array(e),E=new Int32Array(p.length);let y,v,T,S,A,L,I,R,D,b,_,C,P,k;const M=this.networkToHostOrderSwap;for(;t<p.length;){for(D=M(p[t]),b=M(p[t+1]),_=M(p[t+2]),C=M(p[t+3]),A=D^i[0],L=C^i[1],I=_^i[2],R=b^i[3],P=4,k=1;k<r;k++)y=o[A>>>24]^l[L>>16&255]^d[I>>8&255]^h[255&R]^i[P],v=o[L>>>24]^l[I>>16&255]^d[R>>8&255]^h[255&A]^i[P+1],T=o[I>>>24]^l[R>>16&255]^d[A>>8&255]^h[255&L]^i[P+2],S=o[R>>>24]^l[A>>16&255]^d[L>>8&255]^h[255&I]^i[P+3],A=y,L=v,I=T,R=S,P+=4;y=n[A>>>24]<<24^n[L>>16&255]<<16^n[I>>8&255]<<8^n[255&R]^i[P],v=n[L>>>24]<<24^n[I>>16&255]<<16^n[R>>8&255]<<8^n[255&A]^i[P+1],T=n[I>>>24]<<24^n[R>>16&255]<<16^n[A>>8&255]<<8^n[255&L]^i[P+2],S=n[R>>>24]<<24^n[A>>16&255]<<16^n[L>>8&255]<<8^n[255&I]^i[P+3],E[t]=M(y^u),E[t+1]=M(S^f),E[t+2]=M(T^g),E[t+3]=M(v^m),u=D,f=b,g=_,m=C,t+=4}return E.buffer}}class FastAESKey{constructor(e,t,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=s}expandKey(){const e=getSubtleAlgoName(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function getSubtleAlgoName(e){switch(e){case DecrypterAesMode.cbc:return"AES-CBC";case DecrypterAesMode.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${e}`)}}const CHUNK_SIZE=16;class Decrypter{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const e=self.crypto;e&&(this.subtle=e.subtle||e.webkitSubtle)}catch(e){}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:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const s=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?removePadding(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,r){return this.useSoftware?new Promise(((i,n)=>{const a=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(a,t,s,r);const o=this.flush();o?i(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(e),t,s,r)}softwareDecrypt(e,t,s,r){const{currentIV:i,currentResult:n,remainderData:a}=this;if(r!==DecrypterAesMode.cbc||16!==t.byteLength)return logger.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=appendUint8Array(a,e),this.remainderData=null);const o=this.getValidChunk(e);if(!o.length)return null;i&&(s=i);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new AESDecryptor),l.expandKey(t);const d=n;return this.currentResult=l.decrypt(o.buffer,0,s),this.currentIV=o.slice(-16).buffer,d||null}webCryptoDecrypt(e,t,s,r){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,r));this.key=t,this.fastAesKey=new FastAESKey(this.subtle,t,r)}return this.fastAesKey.expandKey().then((t=>{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new AESCrypto(this.subtle,new Uint8Array(s),r).decrypt(e.buffer,t)})).catch((i=>(logger.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${i.name}: ${i.message}`),this.onWebCryptoError(e,t,s,r))))}onWebCryptoError(e,t,s,r){const i=this.enableSoftwareAES;if(i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,r);const i=this.flush();if(i)return i.buffer}throw new Error("WebCrypto"+(i?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const s=e.length-e.length%16;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&(logger.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const MIN_CHUNK_SIZE=Math.pow(2,17);class FragmentLoader{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const s=e.url;if(!s)return Promise.reject(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(s?"part list":"url")),networkDetails:null}));this.abort();const r=this.config,i=r.fLoader,n=r.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some((e=>"GAP"===e[0])))return void o(createGapLoadError(e));e.gap=!1}const l=this.loader=i?new i(r):new n(r),d=createLoaderContext(e);e.loader=l;const h=getLoaderConfigWithoutReties(r.fragLoadPolicy.default),c={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:MIN_CHUNK_SIZE};e.stats=l.stats;const u={onSuccess:(t,s,r,i)=>{this.resetLoader(e,l);let n=t.data;r.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),a({frag:e,part:null,payload:n,networkDetails:i})},onError:(t,r,i,n)=>{this.resetLoader(e,l),o(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:_objectSpread2({url:s,data:void 0},t),error:new Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:i,stats:n}))},onAbort:(t,s,r)=>{this.resetLoader(e,l),o(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:r,stats:t}))},onTimeout:(t,s,r)=>{this.resetLoader(e,l),o(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:r,stats:t}))}};t&&(u.onProgress=(s,r,i,n)=>t({frag:e,part:null,payload:i,networkDetails:n})),l.load(d,c,u)}))}loadPart(e,t,s){this.abort();const r=this.config,i=r.fLoader,n=r.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void o(createGapLoadError(e,t));const l=this.loader=i?new i(r):new n(r),d=createLoaderContext(e,t);e.loader=l;const h=getLoaderConfigWithoutReties(r.fragLoadPolicy.default),c={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:MIN_CHUNK_SIZE};t.stats=l.stats,l.load(d,c,{onSuccess:(r,i,n,o)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const d={frag:e,part:t,payload:r.data,networkDetails:o};s(d),a(d)},onError:(s,r,i,n)=>{this.resetLoader(e,l),o(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:_objectSpread2({url:d.url,data:void 0},s),error:new Error(`HTTP Error ${s.code} ${s.text}`),networkDetails:i,stats:n}))},onAbort:(s,r,i)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),o(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:i,stats:s}))},onTimeout:(s,r,i)=>{this.resetLoader(e,l),o(new LoadError({type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:i,stats:s}))}})}))}updateStatsFromPart(e,t){const s=e.stats,r=t.stats,i=r.total;if(s.loaded+=r.loaded,i){const r=Math.round(e.duration/t.duration),n=Math.min(Math.round(s.loaded/i),r),a=(r-n)*Math.round(s.loaded/n);s.total=s.loaded+a}else s.total=Math.max(s.loaded,s.total);const n=s.loading,a=r.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function createLoaderContext(e,t=null){const s=t||e,r={frag:e,part:t,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},i=s.byteRangeStartOffset,n=s.byteRangeEndOffset;if(isFiniteNumber(i)&&isFiniteNumber(n)){var a;let t=i,s=n;if("initSegment"===e.sn&&isMethodFullSegmentAesCbc(null==(a=e.decryptdata)?void 0:a.method)){const e=n-i;e%16&&(s=n+(16-e%16)),0!==i&&(r.resetIV=!0,t=i-16)}r.rangeStart=t,r.rangeEnd=s}return r}function createGapLoadError(e,t){const s=new Error(`GAP ${e.gap?"tag":"attribute"} found`),r={type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_GAP,fatal:!1,frag:e,error:s,networkDetails:null};return t&&(r.part=t),(t||e).stats.aborted=!0,new LoadError(r)}function isMethodFullSegmentAesCbc(e){return"AES-128"===e||"AES-256"===e}class LoadError extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class TaskLoop extends Logger{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class ChunkMetadata{constructor(e,t,s,r=0,i=-1,n=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=getNewPerformanceTiming(),this.buffering={audio:getNewPerformanceTiming(),video:getNewPerformanceTiming(),audiovideo:getNewPerformanceTiming()},this.level=e,this.sn=t,this.id=s,this.size=r,this.part=i,this.partial=n}}function getNewPerformanceTiming(){return{start:0,executeStart:0,executeEnd:0,end:0}}const noopBuffered={length:0,start:()=>0,end:()=>0};class BufferHelper{static isBuffered(e,t){if(e){const s=BufferHelper.getBuffered(e);for(let e=s.length;e--;)if(t>=s.start(e)&&t<=s.end(e))return!0}return!1}static bufferedRanges(e){if(e){const t=BufferHelper.getBuffered(e);return BufferHelper.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let s=0;s<e.length;s++)t.push({start:e.start(s),end:e.end(s)});return t}static bufferInfo(e,t,s){if(e){const r=BufferHelper.bufferedRanges(e);if(r.length)return BufferHelper.bufferedInfo(r,t,s)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.length>1&&e.sort(((e,t)=>e.start-t.start||t.end-e.end));let r=-1,i=[];if(s)for(let n=0;n<e.length;n++){t>=e[n].start&&t<=e[n].end&&(r=n);const a=i.length;if(a){const t=i[a-1].end;e[n].start-t<s?e[n].end>t&&(i[a-1].end=e[n].end):i.push(e[n])}else i.push(e[n])}else i=e;let n,a=0,o=t,l=t;for(let e=0;e<i.length;e++){const d=i[e].start,h=i[e].end;if(-1===r&&t>=d&&t<=h&&(r=e),t+s>=d&&t<h)o=d,l=h,a=l-t;else if(t+s<d){n=d;break}}return{len:a,start:o||0,end:l||0,nextStart:n,buffered:e,bufferedIndex:r}}static getBuffered(e){try{return e.buffered||noopBuffered}catch(e){return logger.log("failed to get media.buffered",e),noopBuffered}}}const VARIABLE_REPLACEMENT_REGEX=/\{\$([a-zA-Z0-9-_]+)\}/g;function hasVariableReferences(e){return VARIABLE_REPLACEMENT_REGEX.test(e)}function substituteVariables(e,t){if(null!==e.variableList||e.hasVariableRefs){const s=e.variableList;return t.replace(VARIABLE_REPLACEMENT_REGEX,(t=>{const r=t.substring(2,t.length-1),i=null==s?void 0:s[r];return void 0===i?(e.playlistParsingError||(e.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),t):i}))}return t}function addVariableDefinition(e,t,s){let r,i,n=e.variableList;if(n||(e.variableList=n={}),"QUERYPARAM"in t){r=t.QUERYPARAM;try{const e=new self.URL(s).searchParams;if(!e.has(r))throw new Error(`"${r}" does not match any query parameter in URI: "${s}"`);i=e.get(r)}catch(t){e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${t.message}`))}}else r=t.NAME,i=t.VALUE;r in n?e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):n[r]=i||""}function importVariableDefinition(e,t,s){const r=t.IMPORT;if(s&&r in s){let t=e.variableList;t||(e.variableList=t={}),t[r]=s[r]}else e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`))}const DECIMAL_RESOLUTION_REGEX=/^(\d+)x(\d+)$/,ATTR_LIST_REGEX=/(.+?)=(".*?"|.*?)(?:,|$)/g;class AttrList{constructor(e,t){"string"==typeof e&&(e=AttrList.parseAttrList(e,t)),_extends(this,e)}get clientAttrs(){return Object.keys(this).filter((e=>"X-"===e.substring(0,2)))}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;const s=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)s[e]=parseInt(t.slice(2*e,2*e+2),16);return s}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const s=this[e];return(s?s.split(/[ ,]+/):[]).reduce(((e,t)=>(e[t.toLowerCase()]=!0,e)),t)}bool(e){return"YES"===this[e]}decimalResolution(e){const t=DECIMAL_RESOLUTION_REGEX.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let s;const r={};for(ATTR_LIST_REGEX.lastIndex=0;null!==(s=ATTR_LIST_REGEX.exec(e));){const i=s[1].trim();let n=s[2];const a=0===n.indexOf('"')&&n.lastIndexOf('"')===n.length-1;let o=!1;if(a)n=n.slice(1,-1);else switch(i){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(t&&(a||o))n=substituteVariables(t,n);else if(!o&&!a)switch(i){case"CLOSED-CAPTIONS":if("NONE"===n)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":logger.warn(`${e}: attribute ${i} is missing quotes`)}r[i]=n}return r}}const CLASS_INTERSTITIAL="com.apple.hls.interstitial";function isDateRangeCueAttribute(e){return"ID"!==e&&"CLASS"!==e&&"CUE"!==e&&"START-DATE"!==e&&"DURATION"!==e&&"END-DATE"!==e&&"END-ON-NEXT"!==e}function isSCTE35Attribute(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}class DateRange{constructor(e,t,s=0){var r;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==t?void 0:t.tagAnchor)||null,this.tagOrder=null!=(r=null==t?void 0:t.tagOrder)?r:s,t){const s=t.attr;for(const t in s)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==s[t]){logger.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=_extends(new AttrList({}),s,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const e=(null==t?void 0:t.endDate)||new Date(this.attr["END-DATE"]);isFiniteNumber(e.getTime())&&(this._endDate=e)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return void 0===e?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return null===e||null===e.programDateTime?(logger.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return null!==t?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*t):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(isFiniteNumber(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===CLASS_INTERSTITIAL}get isValid(){return!!this.id&&!this._badValueForSameId&&isFiniteNumber(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)}}const DEFAULT_TARGET_DURATION=10;class LevelDetails{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e)return this.advanced=!0,void(this.updated=!0);const t=this.lastPartSn-e.lastPartSn,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&s>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some((t=>{let s=t.decryptdata;return s||(t.setKeyFormat(e.keyFormat),s=t.decryptdata),!!s&&e.matches(s)}))}get hasProgramDateTime(){return!!this.fragments.length&&isFiniteNumber(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const e=this.driftEndTime-this.driftStartTime;if(e>0){return 1e3*(this.driftEnd-this.driftStart)/e}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(-1!==t){for(let s=e.length;s--;)if(e[s].index>t)return e[s].index;return t}}return 0}get lastPartSn(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function arrayValuesMatch(e,t){return e.length===t.length&&!e.some(((e,s)=>e!==t[s]))}function optionalArrayValuesMatch(e,t){return!e&&!t||!(!e||!t)&&arrayValuesMatch(e,t)}function isFullSegmentEncryption(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function getAesModeFromFullSegmentMethod(e){switch(e){case"AES-128":case"AES-256":return DecrypterAesMode.cbc;case"AES-256-CTR":return DecrypterAesMode.ctr;default:throw new Error(`invalid full segment method ${e}`)}}function base64Decode(e){return Uint8Array.from(atob(e),(e=>e.charCodeAt(0)))}function strToUtf8array(e){return Uint8Array.from(unescape(encodeURIComponent(e)),(e=>e.charCodeAt(0)))}function getKeyIdBytes(e){const t=strToUtf8array(e).subarray(0,16),s=new Uint8Array(16);return s.set(t,16-t.length),s}function changeEndianness(e){const t=function(e,t,s){const r=e[t];e[t]=e[s],e[s]=r};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function convertDataUriToArrayBytes(e){const t=e.split(":");let s=null;if("data"===t[0]&&2===t.length){const e=t[1].split(";"),r=e[e.length-1].split(",");if(2===r.length){const t="base64"===r[0],i=r[1];t?(e.splice(-1,1),s=base64Decode(i)):s=getKeyIdBytes(i)}}return s}const optionalSelf="undefined"!=typeof self?self:void 0;var KeySystems={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},KeySystemFormats={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function keySystemFormatToKeySystemDomain(e){switch(e){case KeySystemFormats.FAIRPLAY:return KeySystems.FAIRPLAY;case KeySystemFormats.PLAYREADY:return KeySystems.PLAYREADY;case KeySystemFormats.WIDEVINE:return KeySystems.WIDEVINE;case KeySystemFormats.CLEARKEY:return KeySystems.CLEARKEY}}function keySystemDomainToKeySystemFormat(e){switch(e){case KeySystems.FAIRPLAY:return KeySystemFormats.FAIRPLAY;case KeySystems.PLAYREADY:return KeySystemFormats.PLAYREADY;case KeySystems.WIDEVINE:return KeySystemFormats.WIDEVINE;case KeySystems.CLEARKEY:return KeySystemFormats.CLEARKEY}}function getKeySystemsForConfig(e){const{drmSystems:t,widevineLicenseUrl:s}=e,r=t?[KeySystems.FAIRPLAY,KeySystems.WIDEVINE,KeySystems.PLAYREADY,KeySystems.CLEARKEY].filter((e=>!!t[e])):[];return!r[KeySystems.WIDEVINE]&&s&&r.push(KeySystems.WIDEVINE),r}const requestMediaKeySystemAccess=function(e){return null!=optionalSelf&&null!=(e=optionalSelf.navigator)&&e.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function getSupportedMediaKeySystemConfigurations(e,t,s,r){let i;switch(e){case KeySystems.FAIRPLAY:i=["cenc","sinf"];break;case KeySystems.WIDEVINE:case KeySystems.PLAYREADY:i=["cenc"];break;case KeySystems.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${e}`)}return createMediaKeySystemConfigurations(i,t,s,r)}function createMediaKeySystemConfigurations(e,t,s,r){return[{initDataTypes:e,persistentState:r.persistentState||"optional",distinctiveIdentifier:r.distinctiveIdentifier||"optional",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:t.map((e=>({contentType:`audio/mp4; codecs=${e}`,robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null}))),videoCapabilities:s.map((e=>({contentType:`video/mp4; codecs=${e}`,robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null})))}]}function isPersistentSessionType(e){var t;return!(!e||"persistent-license"!==e.sessionType&&(null==(t=e.sessionTypes)||!t.some((e=>"persistent-license"===e))))}function parsePlayReadyWRM(e){const t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),s=String.fromCharCode.apply(null,Array.from(t)),r=s.substring(s.indexOf("<"),s.length),i=(new DOMParser).parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(i){const e=i.childNodes[0]?i.childNodes[0].nodeValue:i.getAttribute("VALUE");if(e){const t=base64Decode(e).subarray(0,16);return changeEndianness(t),t}}return null}let keyUriToKeyIdMap={};class LevelKey{static clearKeyUriToKeyIdMap(){keyUriToKeyIdMap={}}static setKeyIdForUri(e,t){keyUriToKeyIdMap[e]=t}constructor(e,t,s,r=[1],i=null,n){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=s,this.keyFormatVersions=r,this.iv=i,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&!isFullSegmentEncryption(e),null!=n&&n.startsWith("0x")&&(this.keyId=new Uint8Array(hexToArrayBuffer(n)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&arrayValuesMatch(e.keyFormatVersions,this.keyFormatVersions)&&optionalArrayValuesMatch(e.iv,this.iv)&&optionalArrayValuesMatch(e.keyId,this.keyId)}isSupported(){if(this.method){if(isFullSegmentEncryption(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case KeySystemFormats.FAIRPLAY:case KeySystemFormats.WIDEVINE:case KeySystemFormats.PLAYREADY:case KeySystemFormats.CLEARKEY:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(isFullSegmentEncryption(this.method)){let t=this.iv;t||("number"!=typeof e&&(logger.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),t=createInitializationVector(e));return new LevelKey(this.method,this.uri,"identity",this.keyFormatVersions,t)}if(this.keyId){const e=keyUriToKeyIdMap[this.uri];if(e&&!arrayValuesMatch(this.keyId,e)&&LevelKey.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const s=convertDataUriToArrayBytes(this.uri);if(s)switch(this.keyFormat){case KeySystemFormats.WIDEVINE:if(this.pssh=s,!this.keyId){const e=parseMultiPssh(s.buffer);if(e.length){var r;const t=e[0];this.keyId=null!=(r=t.kids)&&r.length?t.kids[0]:null}}this.keyId||(this.keyId=getKeyIdFromPlayReadyKey(t));break;case KeySystemFormats.PLAYREADY:{const e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=mp4pssh(e,null,s),this.keyId=parsePlayReadyWRM(s);break}default:{let e=s.subarray(0,16);if(16!==e.length){const t=new Uint8Array(16);t.set(e,16-e.length),e=t}this.keyId=e;break}}if(!this.keyId||16!==this.keyId.byteLength){let e;e=getKeyIdFromWidevineKey(t),e||(e=getKeyIdFromPlayReadyKey(t),e||(e=keyUriToKeyIdMap[this.uri])),e&&(this.keyId=e,LevelKey.setKeyIdForUri(this.uri,e))}return this}}function getKeyIdFromWidevineKey(e){const t=null==e?void 0:e[KeySystemFormats.WIDEVINE];return t?t.keyId:null}function getKeyIdFromPlayReadyKey(e){const t=null==e?void 0:e[KeySystemFormats.PLAYREADY];if(t){const e=convertDataUriToArrayBytes(t.uri);if(e)return parsePlayReadyWRM(e)}return null}function createInitializationVector(e){const t=new Uint8Array(16);for(let s=12;s<16;s++)t[s]=e>>8*(15-s)&255;return t}const MASTER_PLAYLIST_REGEX=/#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,MASTER_PLAYLIST_MEDIA_REGEX=/#EXT-X-MEDIA:(.*)/g,IS_MEDIA_PLAYLIST=/^#EXT(?:INF|-X-TARGETDURATION):/m,LEVEL_PLAYLIST_REGEX_FAST=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),LEVEL_PLAYLIST_REGEX_SLOW=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 M3U8Parser{static findGroup(e,t){for(let s=0;s<e.length;s++){const r=e[s];if(r.id===t)return r}}static resolve(e,t){return urlToolkitExports.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return IS_MEDIA_PLAYLIST.test(e)}static parseMasterPlaylist(e,t){const s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:hasVariableReferences(e)},r=[];if(MASTER_PLAYLIST_REGEX.lastIndex=0,!e.startsWith("#EXTM3U"))return s.playlistParsingError=new Error("no EXTM3U delimiter"),s;let i;for(;null!=(i=MASTER_PLAYLIST_REGEX.exec(e));)if(i[1]){var n;const e=new AttrList(i[1],s),a=substituteVariables(s,i[2]),o={attrs:e,bitrate:e.decimalInteger("BANDWIDTH")||e.decimalInteger("AVERAGE-BANDWIDTH"),name:e.NAME,url:M3U8Parser.resolve(a,t)},l=e.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),setCodecs(e.CODECS,o);const d=e["SUPPLEMENTAL-CODECS"];d&&(o.supplemental={},setCodecs(d,o.supplemental)),null!=(n=o.unknownCodecs)&&n.length||r.push(o),s.levels.push(o)}else if(i[3]){const e=i[3],r=i[4];switch(e){case"SESSION-DATA":{const e=new AttrList(r,s),t=e["DATA-ID"];t&&(null===s.sessionData&&(s.sessionData={}),s.sessionData[t]=e);break}case"SESSION-KEY":{const e=parseKey(r,t,s);e.encrypted&&e.isSupported()?(null===s.sessionKeys&&(s.sessionKeys=[]),s.sessionKeys.push(e)):logger.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${r}"`);break}case"DEFINE":addVariableDefinition(s,new AttrList(r,s),t);break;case"CONTENT-STEERING":{const e=new AttrList(r,s);s.contentSteering={uri:M3U8Parser.resolve(e["SERVER-URI"],t),pathwayId:e["PATHWAY-ID"]||"."};break}case"START":s.startTimeOffset=parseStartTimeOffset(r)}}const a=r.length>0&&r.length<s.levels.length;return s.levels=a?r:s.levels,0===s.levels.length&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(e,t,s){let r;const i={},n=s.levels,a={AUDIO:n.map((e=>({id:e.attrs.AUDIO,audioCodec:e.audioCodec}))),SUBTITLES:n.map((e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec}))),"CLOSED-CAPTIONS":[]};let o=0;for(MASTER_PLAYLIST_MEDIA_REGEX.lastIndex=0;null!==(r=MASTER_PLAYLIST_MEDIA_REGEX.exec(e));){const e=new AttrList(r[1],s),n=e.TYPE;if(n){const s=a[n],r=i[n]||[];i[n]=r;const l=e.LANGUAGE,d=e["ASSOC-LANGUAGE"],h=e.CHANNELS,c=e.CHARACTERISTICS,u=e["INSTREAM-ID"],f={attrs:e,bitrate:0,id:o++,groupId:e["GROUP-ID"]||"",name:e.NAME||l||"",type:n,default:e.bool("DEFAULT"),autoselect:e.bool("AUTOSELECT"),forced:e.bool("FORCED"),lang:l,url:e.URI?M3U8Parser.resolve(e.URI,t):""};if(d&&(f.assocLang=d),h&&(f.channels=h),c&&(f.characteristics=c),u&&(f.instreamId=u),null!=s&&s.length){const e=M3U8Parser.findGroup(s,f.groupId)||s[0];assignCodec(f,e,"audioCodec"),assignCodec(f,e,"textCodec")}r.push(f)}}return i}static parseLevelPlaylist(e,t,s,r,i,n){var a;const o={url:t},l=new LevelDetails(t),d=l.fragments,h=[];let c,u,f,g,m=null,p=0,E=0,y=0,v=0,T=0,S=null,A=new Fragment(r,o),L=-1,I=!1,R=null;if(LEVEL_PLAYLIST_REGEX_FAST.lastIndex=0,l.m3u8=e,l.hasVariableRefs=hasVariableReferences(e),"#EXTM3U"!==(null==(a=LEVEL_PLAYLIST_REGEX_FAST.exec(e))?void 0:a[0]))return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;null!==(c=LEVEL_PLAYLIST_REGEX_FAST.exec(e));){I&&(I=!1,A=new Fragment(r,o),A.playlistOffset=y,A.setStart(y),A.sn=p,A.cc=v,T&&(A.bitrate=T),A.level=s,m&&(A.initSegment=m,m.rawProgramDateTime&&(A.rawProgramDateTime=m.rawProgramDateTime,m.rawProgramDateTime=null),R&&(A.setByteRange(R),R=null)));const e=c[1];if(e){A.duration=parseFloat(e);const t=(" "+c[2]).slice(1);A.title=t||null,A.tagList.push(t?["INF",e,t]:["INF",e])}else if(c[3]){if(isFiniteNumber(A.duration)){A.playlistOffset=y,A.setStart(y),f&&setFragLevelKeys(A,f,l),A.sn=p,A.level=s,A.cc=v,d.push(A);const e=(" "+c[3]).slice(1);A.relurl=substituteVariables(l,e),assignProgramDateTime(A,S,h),S=A,y+=A.duration,p++,E=0,I=!0}}else{if(c=c[0].match(LEVEL_PLAYLIST_REGEX_SLOW),!c){logger.warn("No matches on slow regex match for level playlist!");continue}for(u=1;u<c.length&&void 0===c[u];u++);const e=(" "+c[u]).slice(1),i=(" "+c[u+1]).slice(1),a=c[u+2]?(" "+c[u+2]).slice(1):null;switch(e){case"BYTERANGE":S?A.setByteRange(i,S):A.setByteRange(i);break;case"PROGRAM-DATE-TIME":A.rawProgramDateTime=i,A.tagList.push(["PROGRAM-DATE-TIME",i]),-1===L&&(L=d.length);break;case"PLAYLIST-TYPE":l.type&&assignMultipleMediaPlaylistTagOccuranceError(l,e,c),l.type=i.toUpperCase();break;case"MEDIA-SEQUENCE":0!==l.startSN?assignMultipleMediaPlaylistTagOccuranceError(l,e,c):d.length>0&&assignMustAppearBeforeSegmentsError(l,e,c),p=l.startSN=parseInt(i);break;case"SKIP":{l.skippedSegments&&assignMultipleMediaPlaylistTagOccuranceError(l,e,c);const t=new AttrList(i,l),s=t.decimalInteger("SKIPPED-SEGMENTS");if(isFiniteNumber(s)){l.skippedSegments+=s;for(let e=s;e--;)d.push(null);p+=s}const r=t.enumeratedString("RECENTLY-REMOVED-DATERANGES");r&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(r.split("\t")));break}case"TARGETDURATION":0!==l.targetduration&&assignMultipleMediaPlaylistTagOccuranceError(l,e,c),l.targetduration=Math.max(parseInt(i),1);break;case"VERSION":null!==l.version&&assignMultipleMediaPlaylistTagOccuranceError(l,e,c),l.version=parseInt(i);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||assignMultipleMediaPlaylistTagOccuranceError(l,e,c),l.live=!1;break;case"#":(i||a)&&A.tagList.push(a?[i,a]:[i]);break;case"DISCONTINUITY":v++,A.tagList.push(["DIS"]);break;case"GAP":A.gap=!0,A.tagList.push([e]);break;case"BITRATE":A.tagList.push([e,i]),T=1e3*parseInt(i),isFiniteNumber(T)?A.bitrate=T:T=0;break;case"DATERANGE":{const e=new AttrList(i,l),t=new DateRange(e,l.dateRanges[e.ID],l.dateRangeTagCount);l.dateRangeTagCount++,t.isValid||l.skippedSegments?l.dateRanges[t.id]=t:logger.warn(`Ignoring invalid DATERANGE tag: "${i}"`),A.tagList.push(["EXT-X-DATERANGE",i]);break}case"DEFINE":{const e=new AttrList(i,l);"IMPORT"in e?importVariableDefinition(l,e,n):addVariableDefinition(l,e,t)}break;case"DISCONTINUITY-SEQUENCE":0!==l.startCC?assignMultipleMediaPlaylistTagOccuranceError(l,e,c):d.length>0&&assignMustAppearBeforeSegmentsError(l,e,c),l.startCC=v=parseInt(i);break;case"KEY":{const e=parseKey(i,t,l);if(e.isSupported()){if("NONE"===e.method){f=void 0;break}f||(f={});const t=f[e.keyFormat];null!=t&&t.matches(e)||(t&&(f=_extends({},f)),f[e.keyFormat]=e)}else logger.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${i}"`);break}case"START":l.startTimeOffset=parseStartTimeOffset(i);break;case"MAP":{const e=new AttrList(i,l);if(A.duration){const t=new Fragment(r,o);setInitSegment(t,e,s,f),m=t,A.initSegment=m,m.rawProgramDateTime&&!A.rawProgramDateTime&&(A.rawProgramDateTime=m.rawProgramDateTime)}else{const t=A.byteRangeEndOffset;if(t){const e=A.byteRangeStartOffset;R=`${t-e}@${e}`}else R=null;setInitSegment(A,e,s,f),m=A,I=!0}m.cc=v;break}case"SERVER-CONTROL":g&&assignMultipleMediaPlaylistTagOccuranceError(l,e,c),g=new AttrList(i),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&&assignMultipleMediaPlaylistTagOccuranceError(l,e,c);const t=new AttrList(i);l.partTarget=t.decimalFloatingPoint("PART-TARGET");break}case"PART":{let e=l.partList;e||(e=l.partList=[]);const t=E>0?e[e.length-1]:void 0,s=E++,r=new AttrList(i,l),n=new Part(r,A,o,s,t);e.push(n),A.duration+=n.duration;break}case"PRELOAD-HINT":{const e=new AttrList(i,l);l.preloadHint=e;break}case"RENDITION-REPORT":{const e=new AttrList(i,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(e);break}default:logger.warn(`line parsed but not handled: ${c}`)}}}S&&!S.relurl?(d.pop(),y-=S.duration,l.partList&&(l.fragmentHint=S)):l.partList&&(assignProgramDateTime(A,S,h),A.cc=v,l.fragmentHint=A,f&&setFragLevelKeys(A,f,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const D=d.length,b=d[0],_=d[D-1];if(y+=l.skippedSegments*l.targetduration,y>0&&D&&_){l.averagetargetduration=y/D;const e=_.sn;l.endSN="initSegment"!==e?e:0,l.live||(_.endList=!0),L>0&&(backfillProgramDateTimes(d,L),b&&h.unshift(b))}return l.fragmentHint&&(y+=l.fragmentHint.duration),l.totalduration=y,h.length&&l.dateRangeTagCount&&b&&mapDateRanges(h,l),l.endCC=v,l}}function mapDateRanges(e,t){let s=e.length;if(!s){if(!t.hasProgramDateTime)return;{const r=t.fragments[t.fragments.length-1];e.push(r),s++}}const r=e[s-1],i=t.live?1/0:t.totalduration,n=Object.keys(t.dateRanges);for(let o=n.length;o--;){const l=t.dateRanges[n[o]],d=l.startDate.getTime();l.tagAnchor=r.ref;for(let r=s;r--;){var a;if((null==(a=e[r])?void 0:a.sn)<t.startSN)break;const s=findFragmentWithStartDate(t,d,e,r,i);if(-1!==s){l.tagAnchor=t.fragments[s].ref;break}}}}function findFragmentWithStartDate(e,t,s,r,i){const n=s[r];if(n){const o=n.programDateTime;if(t>=o||0===r){var a;if(t<=o+1e3*(((null==(a=s[r+1])?void 0:a.start)||i)-n.start)){const i=s[r].sn-e.startSN;if(i<0)return-1;const n=e.fragments;if(n.length>s.length){for(let a=(s[r+1]||n[n.length-1]).sn-e.startSN;a>i;a--){const e=n[a].programDateTime;if(t>=e&&t<e+1e3*n[a].duration)return a}}return i}}}return-1}function parseKey(e,t,s){var r,i;const n=new AttrList(e,s),a=null!=(r=n.METHOD)?r:"",o=n.URI,l=n.hexadecimalInteger("IV"),d=n.KEYFORMATVERSIONS,h=null!=(i=n.KEYFORMAT)?i:"identity";o&&n.IV&&!l&&logger.error(`Invalid IV: ${n.IV}`);const c=o?M3U8Parser.resolve(o,t):"",u=(d||"1").split("/").map(Number).filter(Number.isFinite);return new LevelKey(a,c,h,u,l,n.KEYID)}function parseStartTimeOffset(e){const t=new AttrList(e).decimalFloatingPoint("TIME-OFFSET");return isFiniteNumber(t)?t:null}function setCodecs(e,t){let s=(e||"").split(/[ ,]+/).filter((e=>e));["video","audio","text"].forEach((e=>{const r=s.filter((t=>isCodecType(t,e)));r.length&&(t[`${e}Codec`]=r.map((e=>e.split("/")[0])).join(","),s=s.filter((e=>-1===r.indexOf(e))))})),t.unknownCodecs=s}function assignCodec(e,t,s){const r=t[s];r&&(e[s]=r)}function backfillProgramDateTimes(e,t){let s=e[t];for(let r=t;r--;){const t=e[r];if(!t)return;t.programDateTime=s.programDateTime-1e3*t.duration,s=t}}function assignProgramDateTime(e,t,s){e.rawProgramDateTime?s.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function setInitSegment(e,t,s,r){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=s,e.sn="initSegment",r&&(e.levelkeys=r),e.initSegment=null}function setFragLevelKeys(e,t,s){e.levelkeys=t;const{encryptedFragments:r}=s;r.length&&r[r.length-1].levelkeys===t||!Object.keys(t).some((e=>t[e].isCommonEncryption))||r.push(e)}function assignMultipleMediaPlaylistTagOccuranceError(e,t,s){e.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${s[0]})`)}function assignMustAppearBeforeSegmentsError(e,t,s){e.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${s[0]})`)}function updateFromToPTS(e,t){const s=t.startPTS;if(isFiniteNumber(s)){let r,i=0;t.sn>e.sn?(i=s-e.start,r=e):(i=e.start-s,r=t),r.duration!==i&&r.setDuration(i)}else if(t.sn>e.sn){e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration)}else t.setStart(Math.max(e.start-t.duration,0))}function updateFragPTSDTS(e,t,s,r,i,n,a){r-s<=0&&(a.warn("Fragment should have a positive duration",t),r=s+t.duration,n=i+t.duration);let o=s,l=r;const d=t.startPTS,h=t.endPTS;if(isFiniteNumber(d)){const c=Math.abs(d-s);e&&c>e.totalduration?a.warn(`media timestamps and playlist times differ by ${c}s for level ${t.level} ${e.url}`):isFiniteNumber(t.deltaPTS)?t.deltaPTS=Math.max(c,t.deltaPTS):t.deltaPTS=c,o=Math.max(s,d),s=Math.min(s,d),i=void 0!==t.startDTS?Math.min(i,t.startDTS):i,l=Math.min(r,h),r=Math.max(r,h),n=void 0!==t.endDTS?Math.max(n,t.endDTS):n}const c=s-t.start;0!==t.start&&t.setStart(s),t.setDuration(r-t.start),t.startPTS=s,t.maxStartPTS=o,t.startDTS=i,t.endPTS=r,t.minEndPTS=l,t.endDTS=n;const u=t.sn;if(!e||u<e.startSN||u>e.endSN)return 0;let f;const g=u-e.startSN,m=e.fragments;for(m[g]=t,f=g;f>0;f--)updateFromToPTS(m[f],m[f-1]);for(f=g;f<m.length-1;f++)updateFromToPTS(m[f],m[f+1]);return e.fragmentHint&&updateFromToPTS(m[m.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,c}function mergeDetails(e,t,s){if(e===t)return;let r=null;const i=e.fragments;for(let e=i.length-1;e>=0;e--){const t=i[e].initSegment;if(t){r=t;break}}let n;e.fragmentHint&&delete e.fragmentHint.endPTS,mapFragmentIntersection(e,t,((e,s,i,a)=>{if((!t.startCC||t.skippedSegments)&&s.cc!==e.cc){const r=e.cc-s.cc;for(let e=i;e<a.length;e++)a[e].cc+=r;t.endCC=a[a.length-1].cc}isFiniteNumber(e.startPTS)&&isFiniteNumber(e.endPTS)&&(s.setStart(s.startPTS=e.startPTS),s.startDTS=e.startDTS,s.maxStartPTS=e.maxStartPTS,s.endPTS=e.endPTS,s.endDTS=e.endDTS,s.minEndPTS=e.minEndPTS,s.setDuration(e.endPTS-e.startPTS),s.duration&&(n=s),t.PTSKnown=t.alignedSliding=!0),e.hasStreams&&(s.elementaryStreams=e.elementaryStreams),s.loader=e.loader,e.hasStats&&(s.stats=e.stats),e.initSegment&&(s.initSegment=e.initSegment,r=e.initSegment)}));const a=t.fragments,o=t.fragmentHint?a.concat(t.fragmentHint):a;if(r&&o.forEach((e=>{var t;!e||e.initSegment&&e.initSegment.relurl!==(null==(t=r)?void 0:t.relurl)||(e.initSegment=r)})),t.skippedSegments){if(t.deltaUpdateFailed=a.some((e=>!e)),t.deltaUpdateFailed){s.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let e=t.skippedSegments;e--;)a.shift();t.startSN=a[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=mergeDateRanges(e.dateRanges,t,s));const r=e.fragments.filter((e=>e.rawProgramDateTime));if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(let e=1;e<o.length;e++)null===o[e].programDateTime&&assignProgramDateTime(o[e],o[e-1],r);mapDateRanges(r,t)}t.endCC=a[a.length-1].cc}if(!t.startCC){var l;const s=getFragmentWithSN(e,t.startSN-1);t.startCC=null!=(l=null==s?void 0:s.cc)?l:a[0].cc}mapPartIntersection(e.partList,t.partList,((e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats})),n?updateFragPTSDTS(t,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,s):adjustSliding(e,t),a.length&&(t.totalduration=t.edge-a[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;const d=t.advancedDateTime;if(t.advanced&&d){const e=t.edge;t.driftStart||(t.driftStartTime=d,t.driftStart=e),t.driftEndTime=d,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}function mergeDateRanges(e,t,s){const{dateRanges:r,recentlyRemovedDateranges:i}=t,n=_extends({},e);i&&i.forEach((e=>{delete n[e]}));const a=Object.keys(n).length;return a?(Object.keys(r).forEach((e=>{const t=n[e],i=new DateRange(r[e].attr,t);i.isValid?(n[e]=i,t||(i.tagOrder+=a)):s.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${stringify(r[e].attr)}"`)})),n):r}function mapPartIntersection(e,t,s){if(e&&t){let r=0;for(let i=0,n=e.length;i<=n;i++){const n=e[i],a=t[i+r];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?s(n,a):r--}}}function mapFragmentIntersection(e,t,s){const r=t.skippedSegments,i=Math.max(e.startSN,t.startSN)-t.startSN,n=(e.fragmentHint?1:0)+(r?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,a=t.startSN-e.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let d=i;d<=n;d++){const i=l[a+d];let n=o[d];if(r&&!n&&i&&(n=t.fragments[d]=i),i&&n){s(i,n,d,o);const r=i.relurl,a=n.relurl;if(r&¬EqualAfterStrippingQueries(r,a))return void(t.playlistParsingError=getSequenceError(`media sequence mismatch ${n.sn}:`,e,t,i,n));if(i.cc!==n.cc)return void(t.playlistParsingError=getSequenceError(`discontinuity sequence mismatch (${i.cc}!=${n.cc})`,e,t,i,n))}}}function getSequenceError(e,t,s,r,i){return new Error(`${e} ${i.url}\nPlaylist starting @${t.startSN}\n${t.m3u8}\n\nPlaylist starting @${s.startSN}\n${s.m3u8}`)}function adjustSliding(e,t,s=!0){const r=t.startSN+t.skippedSegments-e.startSN,i=e.fragments,n=r>=0;let a=0;if(n&&r<i.length)a=i[r].start;else if(n&&t.startSN===e.endSN+1)a=e.fragmentEnd;else if(n&&s)a=e.fragmentStart+r*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return;a=e.fragmentStart}addSliding(t,a)}function addSliding(e,t){if(t){const s=e.fragments;for(let r=e.skippedSegments;r<s.length;r++)s[r].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}function computeReloadInterval(e,t=1/0){let s=1e3*e.targetduration;if(e.updated){const r=e.fragments,i=4;if(r.length&&s*i>t){const e=1e3*r[r.length-1].duration;e<s&&(s=e)}}else s/=2;return Math.round(s)}function getFragmentWithSN(e,t,s){if(!e)return null;let r=e.fragments[t-e.startSN];return r||(r=e.fragmentHint,r&&r.sn===t?r:t<e.startSN&&s&&s.sn===t?s:null)}function getPartWith(e,t,s){return e?findPart(e.partList,t,s):null}function findPart(e,t,s){if(e)for(let r=e.length;r--;){const i=e[r];if(i.index===s&&i.fragment.sn===t)return i}return null}function reassignFragmentLevelIndexes(e){e.forEach(((e,t)=>{var s;null==(s=e.details)||s.fragments.forEach((e=>{e.level=t,e.initSegment&&(e.initSegment.level=t)}))}))}function notEqualAfterStrippingQueries(e,t){return!(e===t||!t)&&stripQuery(e)!==stripQuery(t)}function stripQuery(e){return e.replace(/\?[^?]*$/,"")}function findFirstFragWithCC(e,t){for(let r=0,i=e.length;r<i;r++){var s;if((null==(s=e[r])?void 0:s.cc)===t)return e[r]}return null}function shouldAlignOnDiscontinuities(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}function adjustFragmentStart(e,t){const s=e.start+t;e.startPTS=s,e.setStart(s),e.endPTS=s+e.duration}function adjustSlidingStart(e,t){const s=t.fragments;for(let t=0,r=s.length;t<r;t++)adjustFragmentStart(s[t],e);t.fragmentHint&&adjustFragmentStart(t.fragmentHint,e),t.alignedSliding=!0}function alignStream(e,t){e&&(alignDiscontinuities(t,e),t.alignedSliding||alignMediaPlaylistByPDT(t,e),t.alignedSliding||t.skippedSegments||adjustSliding(e,t,!1))}function alignDiscontinuities(e,t){if(!shouldAlignOnDiscontinuities(t,e))return;const s=Math.min(t.endCC,e.endCC),r=findFirstFragWithCC(t.fragments,s),i=findFirstFragWithCC(e.fragments,s);if(!r||!i)return;logger.log(`Aligning playlist at start of dicontinuity sequence ${s}`);adjustSlidingStart(r.start-i.start,e)}function alignMediaPlaylistByPDT(e,t){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;const s=e.fragments,r=t.fragments;if(!s.length||!r.length)return;let i,n;const a=Math.min(t.endCC,e.endCC);t.startCC<a&&e.startCC<a&&(i=findFirstFragWithCC(r,a),n=findFirstFragWithCC(s,a)),i&&n||(i=r[Math.floor(r.length/2)],n=findFirstFragWithCC(s,i.cc)||s[Math.floor(s.length/2)]);const o=i.programDateTime,l=n.programDateTime;if(!o||!l)return;adjustSlidingStart((l-o)/1e3-(n.start-i.start),e)}function addEventListener(e,t,s){removeEventListener(e,t,s),e.addEventListener(t,s)}function removeEventListener(e,t,s){e.removeEventListener(t,s)}const TimeRanges={toString:function(e){let t="";const s=e.length;for(let r=0;r<s;r++)t+=`[${e.start(r).toFixed(3)}-${e.end(r).toFixed(3)}]`;return t}},State={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class BaseStreamController extends TaskLoop{constructor(e,t,s,r,i){super(r,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=State.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.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:e,fragCurrent:t,media:s,mediaBuffer:r,state:i}=this,n=s?s.currentTime:0,a=BufferHelper.bufferInfo(r||s,n,e.maxBufferHole),o=!a.len;if(this.log(`Media seeking to ${isFiniteNumber(n)?n.toFixed(3):n}, state: ${i}, ${o?"out of":"in"} buffer`),this.state===State.ENDED)this.resetLoadingState();else if(t){const s=e.maxFragLookUpTolerance,r=t.start-s,i=t.start+t.duration+s;if(o||i<a.start||r>a.end){const e=n>i;(n<r||e)&&(e&&t.loader&&(this.log(`Cancelling fragment load for seek (sn: ${t.sn})`),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(s){this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0);if(n>this.lastCurrentTime&&(this.lastCurrentTime=n),!this.loadingParts){const e=Math.max(a.end,n),t=this.shouldLoadParts(this.getLevelDetails(),e);t&&(this.log(`LL-Part loading ON after seeking to ${n.toFixed(2)} with buffer @${e.toFixed(2)}`),this.loadingParts=t)}}this.hls.hasEnoughToStart||(this.log(`Setting ${o?"startPosition":"nextLoadPosition"} to ${n} for seek without enough to start`),this.nextLoadPosition=n,o&&(this.startPosition=n)),o&&this.state===State.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=i,this.hls=e,this.fragmentLoader=new FragmentLoader(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Decrypter(e.config)}registerListeners(){const{hls:e}=this;e.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Events.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Events.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===State.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=State.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return-1===t&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const s=e.end||0,r=this.config.timelineOffset||0;if(s<=r)return!1;const i=e.buffered;this.config.maxBufferHole&&i&&i.length>1&&(e=BufferHelper.bufferedInfo(i,e.start,0));const n=e.nextStart;if(n&&n>r&&n<t.edge)return!1;if(this.media.currentTime<e.start)return!1;const a=t.partList;if(null!=a&&a.length){const e=a[a.length-1];return BufferHelper.isBuffered(this.media,e.start+e.duration/2)}const o=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(o)}getLevelDetails(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;var t;return e?(null==(t=this.getLevelDetails())?void 0:t.appliedTimelineOffset)||e:0}onMediaAttached(e,t){const s=this.media=this.mediaBuffer=t.media;addEventListener(s,"seeking",this.onMediaSeeking),addEventListener(s,"ended",this.onMediaEnded);const r=this.config;this.levels&&r.autoStartLoad&&this.state===State.STOPPED&&this.startLoad(r.startPosition)}onMediaDetaching(e,t){const s=!!t.transferMedia,r=this.media;if(null!==r){if(r.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),removeEventListener(r,"seeking",this.onMediaSeeking),removeEventListener(r,"ended",this.onMediaEnded),this.keyLoader&&!s&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,s)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(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=State.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,s){this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){this._doFragLoad(e,t,s,(e=>{const t=e.frag;if(this.fragContextChanged(t))return this.warn(`${t.type} sn: ${t.sn}${e.part?" part: "+e.part.index:""} of ${this.fragInfo(t,!1,e.part)}) was dropped during download.`),void this.fragmentTracker.removeFragment(t);t.stats.chunkCount++,this._handleFragmentLoadProgress(e)})).then((e=>{if(!e)return;const t=this.state,s=e.frag;this.fragContextChanged(s)?(t===State.FRAG_LOADING||!this.fragCurrent&&t===State.PARSING)&&(this.fragmentTracker.removeFragment(s),this.state=State.IDLE):("payload"in e&&(this.log(`Loaded ${s.type} sn: ${s.sn} of ${this.playlistLabel()} ${s.level}`),this.hls.trigger(Events.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e))})).catch((t=>{this.state!==State.STOPPED&&this.state!==State.ERROR&&(this.warn(`Frag error: ${(null==t?void 0:t.message)||t}`),this.resetFragmentLoading(e))}))}clearTrackerIfNeeded(e){var t;const{fragmentTracker:s}=this;if(s.getState(e)===FragmentState.APPENDING){const t=e.type,r=this.getFwdBufferInfo(this.mediaBuffer,t),i=Math.max(e.duration,r?r.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?e.sn-n.sn:0)||this.reduceMaxBufferLength(i,e.duration))&&s.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===FragmentState.PARTIAL&&s.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,s=null){if(!(e-t))return;const r={startOffset:e,endOffset:t,type:s};this.hls.trigger(Events.BUFFER_FLUSHING,r)}_loadInitSegment(e,t){this._doFragLoad(e,t).then((e=>{const t=null==e?void 0:e.frag;if(!t||this.fragContextChanged(t)||!this.levels)throw new Error("init load aborted");return e})).then((e=>{const{hls:t}=this,{frag:s,payload:r}=e,i=s.decryptdata;if(r&&r.byteLength>0&&null!=i&&i.key&&i.iv&&isFullSegmentEncryption(i.method)){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),i.key.buffer,i.iv.buffer,getAesModeFromFullSegmentMethod(i.method)).catch((e=>{throw t.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:s}),e})).then((r=>{const i=self.performance.now();return t.trigger(Events.FRAG_DECRYPTED,{frag:s,payload:r,stats:{tstart:n,tdecrypt:i}}),e.payload=r,this.completeInitSegmentLoad(e)}))}return this.completeInitSegmentLoad(e)})).catch((t=>{this.state!==State.STOPPED&&this.state!==State.ERROR&&(this.warn(t),this.resetFragmentLoading(e))}))}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const s=e.frag.stats;this.state!==State.STOPPED&&(this.state=State.IDLE),e.frag.data=new Uint8Array(e.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var s,r;const i=e.tracks;if(i&&!t.encrypted&&(null!=(s=i.audio)&&s.encrypted||null!=(r=i.video)&&r.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const e=this.media,s=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${e?"attached mediaKeys: "+e.mediaKeys:"detached"})`);return this.warn(s.message),!e||e.mediaKeys?!1:(this.hls.trigger(Events.ERROR,{type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_NO_KEYS,fatal:!1,error:s,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${s?TimeRanges.toString(BufferHelper.getBuffered(s)):"(detached)"})`),isMediaFragment(e)){var r;if(e.type!==PlaylistLevelType.SUBTITLE){const t=e.elementaryStreams;if(!Object.keys(t).some((e=>!!t[e])))return void(this.state=State.IDLE)}const t=null==(r=this.levels)?void 0:r[e.level];null!=t&&t.fragmentError&&(this.log(`Resetting level fragment error count of ${t.fragmentError} on frag buffered`),t.fragmentError=0)}this.state=State.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:s,part:r,partsLoaded:i}=e,n=!i||0===i.length||i.some((e=>!e)),a=new ChunkMetadata(s.level,s.sn,s.stats.chunkCount+1,0,r?r.index:-1,!n);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,s=null,r){var i;this.fragCurrent=e;const n=t.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=null;if(!e.encrypted||null!=(i=e.decryptdata)&&i.key)e.encrypted||(a=this.keyLoader.loadClear(e,n.encryptedFragments,this.startFragRequested),a&&this.log("[eme] blocking frag load until media-keys acquired"));else if(this.log(`Loading key for ${e.sn} of [${n.startSN}-${n.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=State.KEY_LOADING,this.fragCurrent=e,a=this.keyLoader.load(e).then((e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(Events.KEY_LOADED,e),this.state===State.KEY_LOADING&&(this.state=State.IDLE),e})),this.hls.trigger(Events.KEY_LOADING,{frag:e}),null===this.fragCurrent)return this.log("context changed in KEY_LOADING"),Promise.resolve(null);const o=this.fragPrevious;if(isMediaFragment(e)&&(!o||e.sn!==o.sn)){const s=this.shouldLoadParts(t.details,e.end);s!==this.loadingParts&&(this.log(`LL-Part loading ${s?"ON":"OFF"} loading sn ${null==o?void 0:o.sn}->${e.sn}`),this.loadingParts=s)}if(s=Math.max(e.start,s||0),this.loadingParts&&isMediaFragment(e)){const i=n.partList;if(i&&r){s>n.fragmentEnd&&n.fragmentHint&&(e=n.fragmentHint);const o=this.getNextPart(i,e,s);if(o>-1){const l=i[o];let d;return e=this.fragCurrent=l.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${l.index} (${o}/${i.length-1}) of ${this.fragInfo(e,!1,l)}) cc: ${e.cc} [${n.startSN}-${n.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=State.FRAG_LOADING,d=a?a.then((s=>!s||this.fragContextChanged(s.frag)?null:this.doFragPartsLoad(e,l,t,r))).catch((e=>this.handleFragLoadError(e))):this.doFragPartsLoad(e,l,t,r).catch((e=>this.handleFragLoadError(e))),this.hls.trigger(Events.FRAG_LOADING,{frag:e,part:l,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):d}if(!e.url||this.loadedEndOfParts(i,s))return Promise.resolve(null)}}var l;if(isMediaFragment(e)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${null==(l=n.partList)?void 0:l.filter((e=>e.loaded)).map((e=>`[${e.start}-${e.end}]`))}`),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+n.startSN+"-"+n.endSN+"]"}, target: ${parseFloat(s.toFixed(3))}`),isFiniteNumber(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=State.FRAG_LOADING;const d=this.config.progressive;let h;return h=d&&a?a.then((t=>!t||this.fragContextChanged(t.frag)?null:this.fragmentLoader.load(e,r))).catch((e=>this.handleFragLoadError(e))):Promise.all([this.fragmentLoader.load(e,d?r:void 0),a]).then((([e])=>(!d&&r&&r(e),e))).catch((e=>this.handleFragLoadError(e))),this.hls.trigger(Events.FRAG_LOADING,{frag:e,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):h}doFragPartsLoad(e,t,s,r){return new Promise(((i,n)=>{var a;const o=[],l=null==(a=s.details)?void 0:a.partList,d=t=>{this.fragmentLoader.loadPart(e,t,r).then((r=>{o[t.index]=r;const n=r.part;this.hls.trigger(Events.FRAG_LOADED,r);const a=getPartWith(s.details,e.sn,t.index+1)||findPart(l,e.sn,t.index+1);if(!a)return i({frag:e,part:n,partsLoaded:o});d(a)})).catch(n)};d(t)}))}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===ErrorDetails.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===ErrorTypes.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(Events.ERROR,t)}else this.hls.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==State.PARSING)return void(this.fragCurrent||this.state===State.STOPPED||this.state===State.ERROR||(this.state=State.IDLE));const{frag:s,part:r,level:i}=t,n=self.performance.now();s.stats.parsing.end=n,r&&(r.stats.parsing.end=n);const a=this.getLevelDetails(),o=a&&s.sn>a.endSN||this.shouldLoadParts(a,s.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${s.end.toFixed(2)}`),this.loadingParts=o),this.updateLevelTiming(s,r,i,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var s;const i=e.partList[0];if(i.fragment.type===PlaylistLevelType.SUBTITLE)return!1;if(t>=i.end+((null==(s=e.fragmentHint)?void 0:s.duration)||0)){var r;if((this.hls.hasEnoughToStart?(null==(r=this.media)?void 0:r.currentTime)||this.lastCurrentTime:this.getLoadPosition())>i.start-i.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:s}=this,{level:r,sn:i,part:n}=e;if(null==t||!t[r])return this.warn(`Levels object was unset while buffering fragment ${i} of ${this.playlistLabel()} ${r}. The current chunk will not be buffered.`),null;const a=t[r],o=a.details,l=n>-1?getPartWith(o,i,n):null,d=l?l.fragment:getFragmentWithSN(o,i,s);return d?(s&&s!==d&&(d.stats=s.stats),{frag:d,part:l,level:a}):null}bufferFragmentData(e,t,s,r,i){if(this.state!==State.PARSING)return;const{data1:n,data2:a}=e;let o=n;if(a&&(o=appendUint8Array(n,a)),!o.length)return;const l=this.initPTS[t.cc],d=l?-l.baseTime/l.timescale:void 0,h={type:e.type,frag:t,part:s,chunkMeta:r,offset:d,parent:t.type,data:o};if(this.hls.trigger(Events.BUFFER_APPENDING,h),e.dropped&&e.independent&&!s){if(i)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!BufferHelper.isBuffered(t,t.currentTime))return void this.flushMainBuffer(0,e.start);const s=t.currentTime,r=BufferHelper.bufferInfo(t,s,0),i=e.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*i),a=Math.max(Math.min(e.start-n,r.end-n),s+n);e.start-a>n&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){var s;const r=this.getLoadPosition();if(!isFiniteNumber(r))return null;const i=this.lastCurrentTime>r||null!=(s=this.media)&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,r,t,i)}getFwdBufferInfoAtPos(e,t,s,r){const i=BufferHelper.bufferInfo(e,t,r);if(0===i.len&&void 0!==i.nextStart){const n=this.fragmentTracker.getBufferedFrag(t,s);if(n&&(i.nextStart<=n.end||n.gap)){const s=Math.max(Math.min(i.nextStart,n.end)-t,r);return BufferHelper.bufferInfo(e,t,s)}}return i}getMaxBufferLength(e){const{config:t}=this;let s;return s=e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const s=this.config,r=Math.max(Math.min(e-t,s.maxBufferLength),t),i=Math.max(e-3*t,s.maxMaxBufferLength/2,r);return i>=r&&(s.maxMaxBufferLength=i,this.warn(`Reduce max buffer length to ${i}s`),!0)}getAppendedFrag(e,t=PlaylistLevelType.MAIN){const s=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return s&&"fragment"in s?s.fragment:s}getNextFragment(e,t){const s=t.fragments,r=s.length;if(!r)return null;const{config:i}=this,n=s[0].start,a=i.lowLatencyMode&&!!t.partList;let o=null;if(t.live){const s=i.initialLiveManifestSize;if(r<s)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${s})`),null;if(!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<n){var l;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(t);const s=this.hls.startPosition,r=this.hls.liveSyncPosition,i=o?(-1!==s&&s>=n?s:r)||o.start:e;this.log(`Setting startPosition to ${i} to match start frag at live edge. mainStart: ${s} liveSyncPosition: ${r} frag.start: ${null==(l=o)?void 0:l.start}`),this.startPosition=this.nextLoadPosition=i}}else e<=n&&(o=s[0]);if(!o){const s=this.loadingParts?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,s,t)}let d=this.filterReplacedPrimary(o,t);if(!d&&o){const e=o.sn-t.startSN;d=this.filterReplacedPrimary(s[e+1]||null,t)}return this.mapToInitFragWhenRequired(d)}isLoopLoading(e,t){const s=this.fragmentTracker.getState(e);return(s===FragmentState.OK||s===FragmentState.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,s,r,i){let n=null;if(e.gap&&(n=this.getNextFragment(this.nextLoadPosition,t),n&&!n.gap&&s.nextStart)){const e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,r,0);if(null!==e&&s.len+e.len>=i){const e=n.sn;return this.loopSn!==e&&(this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${e}`),this.loopSn=e),null}}return this.loopSn=void 0,n}get primaryPrefetch(){if(interstitialsEnabled(this.config)){var e;if(null==(e=this.hls.interstitialsManager)||null==(e=e.playingItem)?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(interstitialsEnabled(this.config)&&e.type!==PlaylistLevelType.SUBTITLE){const s=this.hls.interstitialsManager,r=null==s?void 0:s.bufferingItem;if(r){const s=r.event;if(s){if(s.appendInPlace||Math.abs(e.start-r.start)>1||0===r.start)return null}else{if(e.end<=r.start&&!1===(null==t?void 0:t.live))return null;if(e.start>r.end&&r.nextEvent&&(r.nextEvent.appendInPlace||e.start-r.end>1))return null}}const i=null==s?void 0:s.playerQueue;if(i)for(let t=i.length;t--;){const s=i[t].interstitial;if(s.appendInPlace&&e.start>=s.startTime&&e.end<=s.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return null==e||!e.initSegment||e.initSegment.data||this.bitrateTest?e:e.initSegment}getNextPart(e,t,s){let r=-1,i=!1,n=!0;for(let a=0,o=e.length;a<o;a++){const o=e[a];if(n=n&&!o.independent,r>-1&&s<o.start)break;const l=o.loaded;l?r=-1:(i||(o.independent||n)&&o.fragment===t)&&(o.fragment!==t&&this.warn(`Need buffer at ${s} but next unloaded part starts at ${o.start}`),r=a),i=l}return r}loadedEndOfParts(e,t){let s;for(let r=e.length;r--;){if(s=e[r],!s.loaded)return!1;if(t>s.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,s=this.fragPrevious;let r=null;if(s){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),r=findFragmentByPDT(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){const i=s.sn+1;if(i>=e.startSN&&i<=e.endSN){const n=t[i-e.startSN];s.cc===n.cc&&(r=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=findNearestWithCC(e,s.cc,s.end),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{const t=this.hls.liveSyncPosition;null!==t&&(r=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r}getFragmentAtPosition(e,t,s){const{config:r}=this;let{fragPrevious:i}=this,{fragments:n,endSN:a}=s;const{fragmentHint:o}=s,{maxFragLookUpTolerance:l}=r,d=s.partList,h=!!(this.loadingParts&&null!=d&&d.length&&o);let c;if(h&&!this.bitrateTest&&d[d.length-1].fragment.sn===o.sn&&(n=n.concat(o),a=o.sn),e<t){var u;c=findFragmentByPTS(i,n,e,e<this.lastCurrentTime||e>t-l||null!=(u=this.media)&&u.paused||!this.startFragRequested?0:l)}else c=n[n.length-1];if(c){const e=c.sn-s.startSN,t=this.fragmentTracker.getState(c);if((t===FragmentState.OK||t===FragmentState.PARTIAL&&c.gap)&&(i=c),i&&c.sn===i.sn&&(!h||d[0].fragment.sn>c.sn||!s.live)){if(c.level===i.level){const t=n[e+1];c=c.sn<a&&this.fragmentTracker.getState(t)!==FragmentState.OK?t:null}}}return c}alignPlaylists(e,t,s){const r=e.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;const i=e.fragmentStart,n=!t,a=e.alignedSliding&&isFiniteNumber(i);if(n||!a&&!i){alignStream(s,e);const i=e.fragmentStart;return this.log(`Live playlist sliding: ${i.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${r}`),i}return i}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}setStartPosition(e,t){let s=this.startPosition;s<t&&(s=-1);const r=this.timelineOffset;if(-1===s){const i=null!==this.startTimeOffset,n=i?this.startTimeOffset:e.startTimeOffset;null!==n&&isFiniteNumber(n)?(s=t+n,n<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${n} found in ${i?"multivariant":"media"} playlist`),this.startPosition=s):e.live?(s=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${s}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+r}this.nextLoadPosition=s+r}getLoadPosition(){var e;const{media:t}=this;let s=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t?s=t.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&isMediaFragment(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===State.FRAG_LOADING_WAITING_RETRY)||(this.state=State.IDLE)}onFragmentOrKeyLoadError(e,t){var s;if(t.chunkMeta&&!t.frag){const e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}const r=t.frag;if(!r||r.type!==e||!this.levels)return;var i;if(this.fragContextChanged(r))return void this.warn(`Frag load error must match current frag to retry ${r.url} > ${null==(i=this.fragCurrent)?void 0:i.url}`);const n=t.details===ErrorDetails.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(r,!0);const a=t.errorAction;if(!a)return void(this.state=State.ERROR);const{action:o,flags:l,retryCount:d=0,retryConfig:h}=a,c=!!h,u=c&&o===NetworkErrorAction.RetryRequest,f=c&&!a.resolved&&l===ErrorActionFlags.MoveAllAlternatesMatchingHost,g=null==(s=this.hls.latestLevelDetails)?void 0:s.live;if(!u&&f&&isMediaFragment(r)&&!r.endList&&g&&!isUnusableKeyError(t))this.resetFragmentErrors(e),this.treatAsGap(r),a.resolved=!0;else if((u||f)&&d<h.maxNumRetry){var m;const s=offlineHttpStatus(null==(m=t.response)?void 0:m.code),i=getRetryDelay(h,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+i,this.state=State.FRAG_LOADING_WAITING_RETRY,a.resolved=!0,s)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(t.reason="offline");this.warn(`Fragment ${r.sn} of ${e} ${r.level} errored with ${t.details}, retrying loading ${d+1}/${h.maxNumRetry} in ${i}ms`)}else if(h){if(this.resetFragmentErrors(e),!(d<h.maxNumRetry))return void this.warn(`${t.details} reached or exceeded max retry (${d})`);n||o===NetworkErrorAction.RemoveAlternatePermanently||(a.resolved=!0)}else o===NetworkErrorAction.SendAlternateToPenaltyBox?this.state=State.WAITING_LEVEL:this.state=State.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,s=t===1/0;(!t||e>=t||s&&!offlineHttpStatus(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=State.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===State.PARSING||this.state===State.PARSED){const t=e.frag,s=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,s),i=r&&r.len>.5;i&&this.reduceMaxBufferLength(r.len,(null==t?void 0:t.duration)||10);const n=!i;return n&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${s} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(e){e===PlaylistLevelType.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==State.STOPPED&&(this.state=State.IDLE)}afterBufferFlushed(e,t,s){if(!e)return;const r=BufferHelper.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,s),this.state===State.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==State.STOPPED&&(this.state=State.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;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(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${-1===e.level?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,s,r){const i=s.details;if(!i)return void this.warn("level.details undefined");var n;if(!Object.keys(e.elementaryStreams).reduce(((t,n)=>{const a=e.elementaryStreams[n];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${e.sn} ${n} duration reliably (${o})`),t||!1;const l=r?0:updateFragPTSDTS(i,e,a.startPTS,a.endPTS,a.startDTS,a.endDTS,this);return this.hls.trigger(Events.LEVEL_PTS_UPDATED,{details:i,level:s,drift:l,type:n,frag:e,start:a.startPTS,end:a.endPTS}),!0}return t}),!1)&&(0===s.fragmentError&&this.treatAsGap(e,s),null===(null==(n=this.transmuxer)?void 0:n.error))){const t=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(t.message),this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,error:t,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=State.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(Events.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===PlaylistLevelType.MAIN?"level":"track"}fragInfo(e,t=!0,s){var r,i;return`${this.playlistLabel()} ${e.level} (${s?"part":"frag"}:[${(null!=(r=t&&!s?e.startPTS:(s||e).start)?r:NaN).toFixed(3)}-${(null!=(i=t&&!s?e.endPTS:(s||e).end)?i:NaN).toFixed(3)}]${s&&"main"===e.type?"INDEPENDENT="+(s.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;null==(e=this.transmuxer)||e.reset()}recoverWorkerError(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function interstitialsEnabled(e){return!!e.interstitialsController&&!1!==e.enableInterstitialPlayback}class ChunkCache{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let s;return e.length?(s=1===e.length?e[0]:concatUint8Arrays(e,t),this.reset(),s):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}function concatUint8Arrays(e,t){const s=new Uint8Array(t);let r=0;for(let t=0;t<e.length;t++){const i=e[t];s.set(i,r),r+=i.length}return s}var hasRequiredEventemitter3,eventemitter3={exports:{}};function requireEventemitter3(){return hasRequiredEventemitter3||(hasRequiredEventemitter3=1,function(e){var t=Object.prototype.hasOwnProperty,s="~";function r(){}function i(e,t,s){this.fn=e,this.context=t,this.once=s||!1}function n(e,t,r,n,a){if("function"!=typeof r)throw new TypeError("The listener must be a function");var o=new i(r,n||e,a),l=s?s+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function a(e,t){0==--e._eventsCount?e._events=new r:delete e._events[t]}function o(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(s=!1)),o.prototype.eventNames=function(){var e,r,i=[];if(0===this._eventsCount)return i;for(r in e=this._events)t.call(e,r)&&i.push(s?r.slice(1):r);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},o.prototype.listeners=function(e){var t=s?s+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var i=0,n=r.length,a=new Array(n);i<n;i++)a[i]=r[i].fn;return a},o.prototype.listenerCount=function(e){var t=s?s+e:e,r=this._events[t];return r?r.fn?1:r.length:0},o.prototype.emit=function(e,t,r,i,n,a){var o=s?s+e:e;if(!this._events[o])return!1;var l,d,h=this._events[o],c=arguments.length;if(h.fn){switch(h.once&&this.removeListener(e,h.fn,void 0,!0),c){case 1:return h.fn.call(h.context),!0;case 2:return h.fn.call(h.context,t),!0;case 3:return h.fn.call(h.context,t,r),!0;case 4:return h.fn.call(h.context,t,r,i),!0;case 5:return h.fn.call(h.context,t,r,i,n),!0;case 6:return h.fn.call(h.context,t,r,i,n,a),!0}for(d=1,l=new Array(c-1);d<c;d++)l[d-1]=arguments[d];h.fn.apply(h.context,l)}else{var u,f=h.length;for(d=0;d<f;d++)switch(h[d].once&&this.removeListener(e,h[d].fn,void 0,!0),c){case 1:h[d].fn.call(h[d].context);break;case 2:h[d].fn.call(h[d].context,t);break;case 3:h[d].fn.call(h[d].context,t,r);break;case 4:h[d].fn.call(h[d].context,t,r,i);break;default:if(!l)for(u=1,l=new Array(c-1);u<c;u++)l[u-1]=arguments[u];h[d].fn.apply(h[d].context,l)}}return!0},o.prototype.on=function(e,t,s){return n(this,e,t,s,!1)},o.prototype.once=function(e,t,s){return n(this,e,t,s,!0)},o.prototype.removeListener=function(e,t,r,i){var n=s?s+e:e;if(!this._events[n])return this;if(!t)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn!==t||i&&!o.once||r&&o.context!==r||a(this,n);else{for(var l=0,d=[],h=o.length;l<h;l++)(o[l].fn!==t||i&&!o[l].once||r&&o[l].context!==r)&&d.push(o[l]);d.length?this._events[n]=1===d.length?d[0]:d:a(this,n)}return this},o.prototype.removeAllListeners=function(e){var t;return e?(t=s?s+e:e,this._events[t]&&a(this,t)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=s,o.EventEmitter=o,e.exports=o}(eventemitter3)),eventemitter3.exports}var eventemitter3Exports=requireEventemitter3(),EventEmitter=getDefaultExportFromCjs(eventemitter3Exports);const version="1.6.13-beta.4",workerStore={};function hasUMDWorker(){return"function"==typeof __HLS_WORKER_BUNDLE__}function injectWorker(){const e=workerStore[version];if(e)return e.clientCount++,e;const t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),s=self.URL.createObjectURL(t),r={worker:new self.Worker(s),objectURL:s,clientCount:1};return workerStore[version]=r,r}function loadWorker(e){const t=workerStore[e];if(t)return t.clientCount++,t;const s=new self.URL(e,self.location.href).href,r={worker:new self.Worker(s),scriptURL:s,clientCount:1};return workerStore[e]=r,r}function removeWorkerFromStore(e){const t=workerStore[e||version];if(t){if(1===t.clientCount--){const{worker:s,objectURL:r}=t;delete workerStore[e||version],r&&self.URL.revokeObjectURL(r),s.terminate()}}}function isId3Footer(e,t){return t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function isId3Header(e,t){return t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function readId3Size(e,t){let s=0;return s=(127&e[t])<<21,s|=(127&e[t+1])<<14,s|=(127&e[t+2])<<7,s|=127&e[t+3],s}function getId3Data(e,t){const s=t;let r=0;for(;isId3Header(e,t);){r+=10;r+=readId3Size(e,t+6),isId3Footer(e,t+10)&&(r+=10),t+=r}if(r>0)return e.subarray(s,s+r)}function getAudioConfig(e,t,s,r){const i=t[s+2],n=i>>2&15;if(n>12){const t=new Error(`invalid ADTS sampling index:${n}`);return void e.emit(Events.ERROR,Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,fatal:!0,error:t,reason:t.message})}const a=1+(i>>6&3),o=t[s+3]>>6&3|(1&i)<<2,l=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][n];let d,h=n;5!==a&&29!==a||(h-=3);const c=(14&h)>>1,u=(1&h)<<7|o<<3;let f=0;if(1===a&&n>=6){f=5;const e=n-3;d=[f<<3|c,u|(14&e)>>1,(1&e)<<7|8,0]}else d=[a<<3|c,u];const g="mp4a.40."+(f||a);return logger.log(`manifest codec:${r}, parsed codec:${g}, channels:${o}, rate:${l} (ADTS object type:${a} sampling index:${n} esds config:[${d.join(",")}])`),{config:d,samplerate:l,channelCount:o,codec:g,parsedCodec:g,manifestCodec:r}}function isHeaderPattern$1(e,t){return 255===e[t]&&240==(246&e[t+1])}function getHeaderLength(e,t){return 1&e[t+1]?7:9}function getFullFrameLength(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function canGetFrameLength(e,t){return t+5<e.length}function isHeader$1(e,t){return t+1<e.length&&isHeaderPattern$1(e,t)}function canParse$1(e,t){return canGetFrameLength(e,t)&&isHeaderPattern$1(e,t)&&getFullFrameLength(e,t)<=e.length-t}function probe$1(e,t){if(isHeader$1(e,t)){const s=getHeaderLength(e,t);if(t+s>=e.length)return!1;const r=getFullFrameLength(e,t);if(r<=s)return!1;const i=t+r;return i===e.length||isHeader$1(e,i)}return!1}function initTrackConfig(e,t,s,r,i){if(!e.samplerate){const n=getAudioConfig(t,s,r,i);if(!n)return;_extends(e,n)}}function getFrameDuration(e){return 9216e4/e}function parseFrameHeader(e,t){const s=getHeaderLength(e,t);if(t+s<=e.length){const r=getFullFrameLength(e,t)-s;if(r>0)return{headerLength:s,frameLength:r}}}function appendFrame$2(e,t,s,r,i){const n=r+i*getFrameDuration(e.samplerate),a=parseFrameHeader(t,s);let o;if(a){const{frameLength:r,headerLength:i}=a,l=i+r,d=Math.max(0,s+l-t.length);d?(o=new Uint8Array(l-i),o.set(t.subarray(s+i,t.length),0)):o=t.subarray(s+i,s+l);const h={unit:o,pts:n};return d||e.samples.push(h),{sample:h,length:l,missing:d}}const l=t.length-s;o=new Uint8Array(l),o.set(t.subarray(s,t.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}function canParseId3(e,t){return isId3Header(e,t)&&readId3Size(e,t+6)+10<=e.length-t}function toArrayBuffer(e){return e instanceof ArrayBuffer?e:0==e.byteOffset&&e.byteLength==e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}function toUint8(e,t=0,s=1/0){return view(e,t,s,Uint8Array)}function view(e,t,s,r){const i=unsafeGetArrayBuffer(e);let n=1;"BYTES_PER_ELEMENT"in r&&(n=r.BYTES_PER_ELEMENT);const a=isArrayBufferView(e)?e.byteOffset:0,o=(a+e.byteLength)/n,l=(a+t)/n,d=Math.floor(Math.max(0,Math.min(l,o)));return new r(i,d,Math.floor(Math.min(d+Math.max(s,0),o))-d)}function unsafeGetArrayBuffer(e){return e instanceof ArrayBuffer?e:e.buffer}function isArrayBufferView(e){return e&&e.buffer instanceof ArrayBuffer&&void 0!==e.byteLength&&void 0!==e.byteOffset}function decodeId3ImageFrame(e){const t={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(e.size<2)return;if(3!==e.data[0])return void console.log("Ignore frame with unrecognized character encoding");const s=e.data.subarray(1).indexOf(0);if(-1===s)return;const r=utf8ArrayToStr(toUint8(e.data,1,s)),i=e.data[2+s],n=e.data.subarray(3+s).indexOf(0);if(-1===n)return;const a=utf8ArrayToStr(toUint8(e.data,3+s,n));let o;return o="--\x3e"===r?utf8ArrayToStr(toUint8(e.data,4+s+n)):toArrayBuffer(e.data.subarray(4+s+n)),t.mimeType=r,t.pictureType=i,t.description=a,t.data=o,t}function decodeId3PrivFrame(e){if(e.size<2)return;const t=utf8ArrayToStr(e.data,!0),s=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:s.buffer}}function decodeId3TextFrame(e){if(e.size<2)return;if("TXXX"===e.type){let t=1;const s=utf8ArrayToStr(e.data.subarray(t),!0);t+=s.length+1;const r=utf8ArrayToStr(e.data.subarray(t));return{key:e.type,info:s,data:r}}const t=utf8ArrayToStr(e.data.subarray(1));return{key:e.type,info:"",data:t}}function decodeId3UrlFrame(e){if("WXXX"===e.type){if(e.size<2)return;let t=1;const s=utf8ArrayToStr(e.data.subarray(t),!0);t+=s.length+1;const r=utf8ArrayToStr(e.data.subarray(t));return{key:e.type,info:s,data:r}}const t=utf8ArrayToStr(e.data);return{key:e.type,info:"",data:t}}function decodeId3Frame(e){return"PRIV"===e.type?decodeId3PrivFrame(e):"W"===e.type[0]?decodeId3UrlFrame(e):"APIC"===e.type?decodeId3ImageFrame(e):decodeId3TextFrame(e)}function getId3FrameData(e){const t=String.fromCharCode(e[0],e[1],e[2],e[3]),s=readId3Size(e,4);return{type:t,size:s,data:e.subarray(10,10+s)}}const HEADER_FOOTER_SIZE=10,FRAME_SIZE=10;function getId3Frames(e){let t=0;const s=[];for(;isId3Header(e,t);){const r=readId3Size(e,t+6);e[t+5]>>6&1&&(t+=HEADER_FOOTER_SIZE),t+=HEADER_FOOTER_SIZE;const i=t+r;for(;t+FRAME_SIZE<i;){const r=getId3FrameData(e.subarray(t)),i=decodeId3Frame(r);i&&s.push(i),t+=r.size+HEADER_FOOTER_SIZE}isId3Footer(e,t)&&(t+=HEADER_FOOTER_SIZE)}return s}function isId3TimestampFrame(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}function readId3Timestamp(e){if(8===e.data.byteLength){const t=new Uint8Array(e.data),s=1&t[3];let r=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return r/=45,s&&(r+=47721858.84),Math.round(r)}}function getId3Timestamp(e){const t=getId3Frames(e);for(let e=0;e<t.length;e++){const s=t[e];if(isId3TimestampFrame(s))return readId3Timestamp(s)}}let MetadataSchema=function(e){return e.audioId3="org.id3",e.dateRange="com.apple.quicktime.HLS",e.emsg="https://aomedia.org/emsg/ID3",e.misbklv="urn:misb:KLV:bin:1910.1",e}({});function dummyTrack(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class BaseAudioDemuxer{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,s,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,s){}demux(e,t){this.cachedData&&(e=appendUint8Array(this.cachedData,e),this.cachedData=null);let s,r=getId3Data(e,0),i=r?r.length:0;const n=this._audioTrack,a=this._id3Track,o=r?getId3Timestamp(r):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&isFiniteNumber(o))&&(this.basePTS=initPTSFn(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),r&&r.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:MetadataSchema.audioId3,duration:Number.POSITIVE_INFINITY});i<l;){if(this.canParse(e,i)){const t=this.appendFrame(n,e,i);t?(this.frameIndex++,this.lastPTS=t.sample.pts,i+=t.length,s=i):i=l}else canParseId3(e,i)?(r=getId3Data(e,i),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:MetadataSchema.audioId3,duration:Number.POSITIVE_INFINITY}),i+=r.length,s=i):i++;if(i===l&&s!==l){const t=e.slice(s);this.cachedData?this.cachedData=appendUint8Array(this.cachedData,t):this.cachedData=t}}return{audioTrack:n,videoTrack:dummyTrack(),id3Track:a,textTrack:dummyTrack()}}demuxSampleAes(e,t,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:dummyTrack(),id3Track:this._id3Track,textTrack:dummyTrack()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const initPTSFn=(e,t,s)=>{if(isFiniteNumber(e))return 90*e;return 9e4*t+(s?9e4*s.baseTime/s.timescale:0)};let chromeVersion$1=null;const BitratesMap=[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],SamplingRateMap=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],SamplesCoefficients=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],BytesInSlot=[0,1,1,4];function appendFrame$1(e,t,s,r,i){if(s+24>t.length)return;const n=parseHeader(t,s);if(n&&s+n.frameLength<=t.length){const a=r+i*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:t.subarray(s,s+n.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=n.channelCount,e.samplerate=n.sampleRate,e.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function parseHeader(e,t){const s=e[t+1]>>3&3,r=e[t+1]>>1&3,i=e[t+2]>>4&15,n=e[t+2]>>2&3;if(1!==s&&0!==i&&15!==i&&3!==n){const a=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*BitratesMap[14*(3===s?3-r:3===r?3:4)+i-1],d=SamplingRateMap[3*(3===s?0:2===s?1:2)+n],h=3===o?1:2,c=SamplesCoefficients[s][r],u=BytesInSlot[r],f=8*c*u,g=Math.floor(c*l/d+a)*u;if(null===chromeVersion$1){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);chromeVersion$1=e?parseInt(e[1]):0}return!!chromeVersion$1&&chromeVersion$1<=87&&2===r&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:d,channelCount:h,frameLength:g,samplesPerFrame:f}}}function isHeaderPattern(e,t){return 255===e[t]&&224==(224&e[t+1])&&0!=(6&e[t+1])}function isHeader(e,t){return t+1<e.length&&isHeaderPattern(e,t)}function canParse(e,t){return isHeaderPattern(e,t)&&4<=e.length-t}function probe(e,t){if(t+1<e.length&&isHeaderPattern(e,t)){const s=4,r=parseHeader(e,t);let i=s;null!=r&&r.frameLength&&(i=r.frameLength);const n=t+i;return n===e.length||isHeader(e,n)}return!1}class AACDemuxer extends BaseAudioDemuxer{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,s,r){super.resetInitSegment(e,t,s,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const s=getId3Data(e,0);let r=(null==s?void 0:s.length)||0;if(probe(e,r))return!1;for(let s=e.length;r<s;r++)if(probe$1(e,r))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return canParse$1(e,t)}appendFrame(e,t,s){initTrackConfig(e,this.observer,t,s,e.manifestCodec);const r=appendFrame$2(e,t,s,this.basePTS,this.frameIndex);if(r&&0===r.missing)return r}}const getAudioBSID=(e,t)=>{let s=0,r=5;t+=r;const i=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;r>0;){a[0]=e[t];const o=Math.min(r,8),l=8-o;n[0]=4278190080>>>24+l<<l,i[0]=(a[0]&n[0])>>l,s=s?s<<o|i[0]:i[0],t+=1,r-=o}return s};class AC3Demuxer extends BaseAudioDemuxer{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,r){super.resetInitSegment(e,t,s,r),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,s){const r=appendFrame(e,t,s,this.basePTS,this.frameIndex);if(-1!==r){return{sample:e.samples[e.samples.length-1],length:r,missing:0}}}static probe(e){if(!e)return!1;const t=getId3Data(e,0);if(!t)return!1;const s=t.length;return 11===e[s]&&119===e[s+1]&&void 0!==getId3Timestamp(t)&&getAudioBSID(e,s)<16}}function appendFrame(e,t,s,r,i){if(s+8>t.length)return-1;if(11!==t[s]||119!==t[s+1])return-1;const n=t[s+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&t[s+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+n];if(s+l>t.length)return-1;const d=t[s+6]>>5;let h=0;2===d?h+=2:(1&d&&1!==d&&(h+=2),4&d&&(h+=2));const c=(t[s+6]<<8|t[s+7])>>12-h&1,u=[2,1,2,3,3,4,4,5][d]+c,f=t[s+5]>>3,g=7&t[s+5],m=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|d<<3|c<<2|o>>4,o<<4&224]),p=r+i*(1536/a*9e4),E=t.subarray(s,s+l);return e.config=m,e.channelCount=u,e.samplerate=a,e.samples.push({unit:E,pts:p}),l}class MP3Demuxer extends BaseAudioDemuxer{resetInitSegment(e,t,s,r){super.resetInitSegment(e,t,s,r),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=getId3Data(e,0);let s=(null==t?void 0:t.length)||0;if(t&&11===e[s]&&119===e[s+1]&&void 0!==getId3Timestamp(t)&&getAudioBSID(e,s)<=16)return!1;for(let t=e.length;s<t;s++)if(probe(e,s))return logger.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return canParse(e,t)}appendFrame(e,t,s){if(null!==this.basePTS)return appendFrame$1(e,t,s,this.basePTS,this.frameIndex)}}const emsgSchemePattern=/\/emsg[-/]ID3/i;class MP4Demuxer{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,s,r){const i=this.videoTrack=dummyTrack("video",1),n=this.audioTrack=dummyTrack("audio",1),a=this.txtTrack=dummyTrack("text",1);if(this.id3Track=dummyTrack("id3",1),this.timeOffset=0,null==e||!e.byteLength)return;const o=parseInitSegment(e);if(o.video){const{id:e,timescale:t,codec:s,supplemental:r}=o.video;i.id=e,i.timescale=a.timescale=t,i.codec=s,i.supplemental=r}if(o.audio){const{id:e,timescale:t,codec:s}=o.audio;n.id=e,n.timescale=t,n.codec=s}a.id=RemuxerTrackIdConfig.text,i.sampleDuration=0,i.duration=n.duration=r}resetContiguity(){this.remainderData=null}static probe(e){return hasMoofData(e)}demux(e,t){this.timeOffset=t;let s=e;const r=this.videoTrack,i=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=appendUint8Array(this.remainderData,e));const t=segmentValidRange(s);this.remainderData=t.remainder,r.samples=t.valid||new Uint8Array}else r.samples=s;const n=this.extractID3Track(r,t);return i.samples=parseSamples(t,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,s=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const r=this.extractID3Track(t,this.timeOffset);return s.samples=parseSamples(e,t),{videoTrack:t,audioTrack:dummyTrack(),id3Track:r,textTrack:dummyTrack()}}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const r=findBox(e.samples,["emsg"]);r&&r.forEach((e=>{const r=parseEmsg(e);if(emsgSchemePattern.test(r.schemeIdUri)){const e=getEmsgStartTime(r,t);let i=4294967295===r.eventDuration?Number.POSITIVE_INFINITY:r.eventDuration/r.timeScale;i<=.001&&(i=Number.POSITIVE_INFINITY);const n=r.payload;s.samples.push({data:n,len:n.byteLength,dts:e,pts:e,type:MetadataSchema.emsg,duration:i})}else if(this.config.enableEmsgKLVMetadata&&r.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const e=getEmsgStartTime(r,t);s.samples.push({data:r.payload,len:r.payload.byteLength,dts:e,pts:e,type:MetadataSchema.misbklv,duration:Number.POSITIVE_INFINITY})}}))}return s}demuxSampleAes(e,t,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}}function getEmsgStartTime(e,t){return isFiniteNumber(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}class SampleAesDecrypter{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Decrypter(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,DecrypterAesMode.cbc)}decryptAacSample(e,t,s){const r=e[t].unit;if(r.length<=16)return;const i=r.subarray(16,r.length-r.length%16),n=i.buffer.slice(i.byteOffset,i.byteOffset+i.length);this.decryptBuffer(n).then((i=>{const n=new Uint8Array(i);r.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)})).catch(s)}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length)return void s();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=16*Math.floor((e.length-48)/160)+16,s=new Int8Array(t);let r=0;for(let t=32;t<e.length-16;t+=160,r+=16)s.set(e.subarray(t,t+16),r);return s}getAvcDecryptedUnit(e,t){const s=new Uint8Array(t);let r=0;for(let t=32;t<e.length-16;t+=160,r+=16)e.set(s.subarray(r,r+16),t);return e}decryptAvcSample(e,t,s,r,i){const n=discardEPB(i.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then((a=>{i.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,r)})).catch(r)}decryptAvcSamples(e,t,s,r){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length)return void r();const i=e[t].units;for(;!(s>=i.length);s++){const n=i[s];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(e,t,s,r,n),this.decrypter.isSync())))return}}}}class BaseVideoParser{constructor(){this.VideoSample=null}createVideoSample(e,t,s){return{key:e,frame:!1,pts:t,dts:s,units:[],length:0}}getLastNalUnit(e){var t;let s,r=this.VideoSample;if(r&&0!==r.units.length||(r=e[e.length-1]),null!=(t=r)&&t.units){const e=r.units;s=e[e.length-1]}return s}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){const s=t.samples,r=s.length;if(!r)return void t.dropped++;{const t=s[r-1];e.pts=t.pts,e.dts=t.dts}}t.samples.push(e)}}parseNALu(e,t,s){const r=t.byteLength;let i=e.naluState||0;const n=i,a=[];let o,l,d,h=0,c=-1,u=0;for(-1===i&&(c=0,u=this.getNALuType(t,0),i=0,h=1);h<r;)if(o=t[h++],i)if(1!==i)if(o)if(1===o){if(l=h-i-1,c>=0){const e={data:t.subarray(c,l),type:u};a.push(e)}else{const s=this.getLastNalUnit(e.samples);s&&(n&&h<=4-n&&s.state&&(s.data=s.data.subarray(0,s.data.byteLength-n)),l>0&&(s.data=appendUint8Array(s.data,t.subarray(0,l)),s.state=0))}h<r?(d=this.getNALuType(t,h),c=h,u=d,i=0):i=-1}else i=0;else i=3;else i=o?0:2;else i=o?0:1;if(c>=0&&i>=0){const e={data:t.subarray(c,r),type:u,state:i};a.push(e)}if(0===a.length){const s=this.getLastNalUnit(e.samples);s&&(s.data=appendUint8Array(s.data,t))}return e.naluState=i,a}}class ExpGolomb{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,s=e.byteLength-t,r=new Uint8Array(4),i=Math.min(4,t);if(0===i)throw new Error("no bytes available");r.set(e.subarray(s,s+i)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=8*i,this.bytesAvailable-=i}skipBits(e){let t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(t=(e-=this.bitsAvailable)>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const s=this.word>>>32-t;if(e>32&&logger.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return t=e-t,t>0&&this.bitsAvailable?s<<t|this.readBits(t):s}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(0!=(this.word&2147483648>>>e))return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class AvcVideoParser extends BaseVideoParser{parsePES(e,t,s,r){const i=this.parseNALu(e,s.data,r);let n,a=this.VideoSample,o=!1;s.data=null,a&&i.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),i.forEach((r=>{var i,l;switch(r.type){case 1:{let t=!1;n=!0;const i=r.data;if(o&&i.length>4){const e=this.readSliceType(i);2!==e&&4!==e&&7!==e&&9!==e||(t=!0)}var d;if(t)null!=(d=a)&&d.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.frame=!0,a.key=t;break}case 5:n=!0,null!=(i=a)&&i.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 6:n=!0,parseSEIMessageFromNALu(r.data,1,s.pts,t.samples);break;case 7:{var h,c;n=!0,o=!0;const t=r.data,s=this.readSPS(t);if(!e.sps||e.width!==s.width||e.height!==s.height||(null==(h=e.pixelRatio)?void 0:h[0])!==s.pixelRatio[0]||(null==(c=e.pixelRatio)?void 0:c[1])!==s.pixelRatio[1]){e.width=s.width,e.height=s.height,e.pixelRatio=s.pixelRatio,e.sps=[t];const r=t.subarray(1,4);let i="avc1.";for(let e=0;e<3;e++){let t=r[e].toString(16);t.length<2&&(t="0"+t),i+=t}e.codec=i}break}case 8:n=!0,e.pps=[r.data];break;case 9:n=!0,e.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:n=!0;break;default:n=!1}if(a&&n){a.units.push(r)}})),r&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return 31&e[t]}readSliceType(e){const t=new ExpGolomb(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s,r=8,i=8;for(let n=0;n<e;n++)0!==i&&(s=t.readEG(),i=(r+s+256)%256),r=0===i?r:i}readSPS(e){const t=new ExpGolomb(e);let s,r,i,n=0,a=0,o=0,l=0;const d=t.readUByte.bind(t),h=t.readBits.bind(t),c=t.readUEG.bind(t),u=t.readBoolean.bind(t),f=t.skipBits.bind(t),g=t.skipEG.bind(t),m=t.skipUEG.bind(t),p=this.skipScalingList.bind(this);d();const E=d();if(h(5),f(3),d(),m(),100===E||110===E||122===E||244===E||44===E||83===E||86===E||118===E||128===E){const e=c();if(3===e&&f(1),m(),m(),f(1),u())for(r=3!==e?8:12,i=0;i<r;i++)u()&&p(i<6?16:64,t)}m();const y=c();if(0===y)c();else if(1===y)for(f(1),g(),g(),s=c(),i=0;i<s;i++)g();m(),f(1);const v=c(),T=c(),S=h(1);0===S&&f(1),f(1),u()&&(n=c(),a=c(),o=c(),l=c());let A=[1,1];if(u()&&u()){switch(d()){case 1:A=[1,1];break;case 2:A=[12,11];break;case 3:A=[10,11];break;case 4:A=[16,11];break;case 5:A=[40,33];break;case 6:A=[24,11];break;case 7:A=[20,11];break;case 8:A=[32,11];break;case 9:A=[80,33];break;case 10:A=[18,11];break;case 11:A=[15,11];break;case 12:A=[64,33];break;case 13:A=[160,99];break;case 14:A=[4,3];break;case 15:A=[3,2];break;case 16:A=[2,1];break;case 255:A=[d()<<8|d(),d()<<8|d()]}}return{width:Math.ceil(16*(v+1)-2*n-2*a),height:(2-S)*(T+1)*16-(S?2:4)*(o+l),pixelRatio:A}}}class HevcVideoParser extends BaseVideoParser{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,s,r){const i=this.parseNALu(e,s.data,r);let n,a=this.VideoSample,o=!1;s.data=null;const l=e=>(a=this.VideoSample=this.createVideoSample(e,s.pts,s.dts),a);i.forEach(((r,i)=>{var d,h;if(this.startsNewAccessUnit(a,e,r,i)){this.pushAccessUnit(a,e);const t=r.type>=16&&r.type<=23;a=l(t),o=!1}switch(r.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,n=!0;break;case 16:case 17:case 18:case 21:case 22:case 23:var c;if(n=!0,o)null!=(c=a)&&c.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null);a||(a=l(!0)),a.key=!0,a.frame=!0;break;case 19:case 20:n=!0,null!=(d=a)&&d.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=l(!0)),a.key=!0,a.frame=!0;break;case 39:n=!0,parseSEIMessageFromNALu(r.data,2,s.pts,t.samples);break;case 32:n=!0,e.vps||("object"!=typeof e.params&&(e.params={}),e.params=_extends(e.params,this.readVPS(r.data)),this.initVPS=r.data),e.vps=[r.data];break;case 33:if(n=!0,o=!0,void 0===e.vps||e.vps[0]===this.initVPS||void 0===e.sps||this.matchSPS(e.sps[0],r.data)||(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const t=this.readSPS(r.data);e.width=t.width,e.height=t.height,e.pixelRatio=t.pixelRatio,e.codec=t.codecString,e.sps=[],"object"!=typeof e.params&&(e.params={});for(const s in t.params)e.params[s]=t.params[s]}this.pushParameterSet(e.sps,r.data,e.vps),a||(a=l(!1));break;case 34:if(n=!0,"object"==typeof e.params){if(!e.pps){e.pps=[];const t=this.readPPS(r.data);for(const s in t)e.params[s]=t[s]}this.pushParameterSet(e.pps,r.data,e.vps)}break;case 35:n=!0,e.audFound=!0,null!=(h=a)&&h.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=l(!1));break;default:n=!1}if(a&&n){a.units.push(r)}})),r&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,s){(s&&s[0]===this.initVPS||!s&&!e.length)&&e.push(t)}startsNewAccessUnit(e,t,s,r){if(!e)return!1;if(!t.audFound&&0===r)return!0;if(!e.frame)return!1;const{type:i,data:n}=s;return!!(i>=32&&i<=35||39===i||i>=41&&i<=44||i>=48&&i<=55)||i<=31&&n.length>2&&0!=(128&n[2])}getNALuType(e,t){return(126&e[t])>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let s=0;for(let r=0;r<e.byteLength;r++)r>=2&&3===e[r]&&0===e[r-1]&&0===e[r-2]||(t[s]=e[r],s++);return new Uint8Array(t.buffer,0,s)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new ExpGolomb(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);return{numTemporalLayers:t.readBits(3)+1,temporalIdNested:t.readBoolean()}}readSPS(e){const t=new ExpGolomb(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const s=t.readBits(3);t.readBoolean();const r=t.readBits(2),i=t.readBoolean(),n=t.readBits(5),a=t.readUByte(),o=t.readUByte(),l=t.readUByte(),d=t.readUByte(),h=t.readUByte(),c=t.readUByte(),u=t.readUByte(),f=t.readUByte(),g=t.readUByte(),m=t.readUByte(),p=t.readUByte(),E=[],y=[];for(let e=0;e<s;e++)E.push(t.readBoolean()),y.push(t.readBoolean());if(s>0)for(let e=s;e<8;e++)t.readBits(2);for(let e=0;e<s;e++)E[e]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),y[e]&&t.readUByte();t.readUEG();const v=t.readUEG();3==v&&t.skipBits(1);const T=t.readUEG(),S=t.readUEG(),A=t.readBoolean();let L=0,I=0,R=0,D=0;A&&(L+=t.readUEG(),I+=t.readUEG(),R+=t.readUEG(),D+=t.readUEG());const b=t.readUEG(),_=t.readUEG(),C=t.readUEG();for(let e=t.readBoolean()?0:s;e<=s;e++)t.skipUEG(),t.skipUEG(),t.skipUEG();t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.readBoolean()){if(t.readBoolean())for(let e=0;e<4;e++)for(let s=0;s<(3===e?2:6);s++){if(t.readBoolean()){const s=Math.min(64,1<<4+(e<<1));e>1&&t.readEG();for(let e=0;e<s;e++)t.readEG()}else t.readUEG()}}t.readBoolean(),t.readBoolean();t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const P=t.readUEG();let k=0;for(let e=0;e<P;e++){let s=!1;if(0!==e&&(s=t.readBoolean()),s){e===P&&t.readUEG(),t.readBoolean(),t.readUEG();let s=0;for(let e=0;e<=k;e++){const e=t.readBoolean();let r=!1;e||(r=t.readBoolean()),(e||r)&&s++}k=s}else{const e=t.readUEG(),s=t.readUEG();k=e+s;for(let s=0;s<e;s++)t.readUEG(),t.readBoolean();for(let e=0;e<s;e++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const e=t.readUEG();for(let s=0;s<e;s++){for(let e=0;e<C+4;e++)t.readBits(1);t.readBits(1)}}let M=0,O=1,w=1,F=!0,x=1,N=0;t.readBoolean(),t.readBoolean();let U=!1;if(t.readBoolean()){if(t.readBoolean()){const e=t.readUByte();e>0&&e<16?(O=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][e-1],w=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][e-1]):255===e&&(O=t.readBits(16),w=t.readBits(16))}t.readBoolean()&&t.readBoolean();if(t.readBoolean()){t.readBits(3),t.readBoolean();t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())}t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),U=t.readBoolean(),U&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG());if(t.readBoolean()){x=t.readBits(32),N=t.readBits(32);t.readBoolean()&&t.readUEG();if(t.readBoolean()){const e=t.readBoolean(),r=t.readBoolean();let i=!1;(e||r)&&(i=t.readBoolean(),i&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),i&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let n=0;n<=s;n++){F=t.readBoolean();let s=!1;F||t.readBoolean()?t.readEG():s=t.readBoolean();const n=s?1:t.readUEG()+1;if(e)for(let e=0;e<n;e++)t.readUEG(),t.readUEG(),i&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(r)for(let e=0;e<n;e++)t.readUEG(),t.readUEG(),i&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),M=t.readUEG())}let B=T,$=S;if(A){let e=1,t=1;1===v?e=t=2:2==v&&(e=2),B=T-e*I-e*L,$=S-t*D-t*R}const G=r?["A","B","C"][r]:"",K=a<<24|o<<16|l<<8|d;let H=0;for(let e=0;e<32;e++)H=(H|(K>>e&1)<<31-e)>>>0;let V=H.toString(16);1===n&&"2"===V&&(V="6");return{codecString:`hvc1.${G}${n}.${V}.${i?"H":"L"}${p}.B0`,params:{general_tier_flag:i,general_profile_idc:n,general_profile_space:r,general_profile_compatibility_flags:[a,o,l,d],general_constraint_indicator_flags:[h,c,u,f,g,m],general_level_idc:p,bit_depth:b+8,bit_depth_luma_minus8:b,bit_depth_chroma_minus8:_,min_spatial_segmentation_idc:M,chroma_format_idc:v,frame_rate:{fixed:F,fps:N/x}},width:B,height:$,pixelRatio:[O,w]}}readPPS(e){const t=new ExpGolomb(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2);t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const s=t.readBoolean(),r=t.readBoolean();let i=1;return r&&s?i=0:r?i=3:s&&(i=2),{parallelismType:i}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const PACKET_LENGTH=188;class TSDemuxer{constructor(e,t,s,r){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.logger=r,this.videoParser=null}static probe(e,t){const s=TSDemuxer.syncOffset(e);return s>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),-1!==s}static syncOffset(e){const t=e.length;let s=Math.min(940,t-188)+1,r=0;for(;r<s;){let i=!1,n=-1,a=0;for(let o=r;o<t;o+=188){if(71!==e[o]||t-o!=188&&71!==e[o+188]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(s=Math.min(n+18612,e.length-188)+1)),i||(i=0===parsePID(e,o)),i&&a>1&&(0===n&&a>2||o+188>s))return n}r++}return-1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:RemuxerTrackIdConfig[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}resetInitSegment(e,t,s,r){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=TSDemuxer.createTrack("video"),this._videoTrack.duration=r,this._audioTrack=TSDemuxer.createTrack("audio",r),this._id3Track=TSDemuxer.createTrack("id3"),this._txtTrack=TSDemuxer.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s=!1,r=!1){let i;s||(this.sampleAes=null);const n=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let d=n.pid,h=n.pesData,c=a.pid,u=o.pid,f=a.pesData,g=o.pesData,m=null,p=this.pmtParsed,E=this._pmtId,y=e.length;if(this.remainderData&&(y=(e=appendUint8Array(this.remainderData,e)).length,this.remainderData=null),y<188&&!r)return this.remainderData=e,{audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};const v=Math.max(0,TSDemuxer.syncOffset(e));y-=(y-v)%188,y<e.byteLength&&!r&&(this.remainderData=new Uint8Array(e.buffer,y,e.buffer.byteLength-y));let T=0;for(let t=v;t<y;t+=188)if(71===e[t]){const r=!!(64&e[t+1]),y=parsePID(e,t);let T;if((48&e[t+3])>>4>1){if(T=t+5+e[t+4],T===t+188)continue}else T=t+4;switch(y){case d:r&&(h&&(i=parsePES(h,this.logger))&&(this.readyVideoParser(n.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(n,l,i,!1)),h={data:[],size:0}),h&&(h.data.push(e.subarray(T,t+188)),h.size+=t+188-T);break;case c:if(r){if(f&&(i=parsePES(f,this.logger)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,i);break;case"mp3":this.parseMPEGPES(a,i);break;case"ac3":this.parseAC3PES(a,i)}f={data:[],size:0}}f&&(f.data.push(e.subarray(T,t+188)),f.size+=t+188-T);break;case u:r&&(g&&(i=parsePES(g,this.logger))&&this.parseID3PES(o,i),g={data:[],size:0}),g&&(g.data.push(e.subarray(T,t+188)),g.size+=t+188-T);break;case 0:r&&(T+=e[T]+1),E=this._pmtId=parsePAT(e,T);break;case E:{r&&(T+=e[T]+1);const i=parsePMT(e,T,this.typeSupported,s,this.observer,this.logger);d=i.videoPid,d>0&&(n.pid=d,n.segmentCodec=i.segmentVideoCodec),c=i.audioPid,c>0&&(a.pid=c,a.segmentCodec=i.segmentAudioCodec),u=i.id3Pid,u>0&&(o.pid=u),null===m||p||(this.logger.warn(`MPEG-TS PMT found at ${t} after unknown PID '${m}'. Backtracking to sync byte @${v} to parse all TS packets.`),m=null,t=v-188),p=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=y}}else T++;T>0&&emitParsingError(this.observer,new Error(`Found ${T} TS packet/s that do not start with 0x47`),void 0,this.logger),n.pesData=h,a.pesData=f,o.pesData=g;const S={audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};return r&&this.extractRemainingSamples(S),S}flush(){const{remainderData:e}=this;let t;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:s,id3Track:r,textTrack:i}=e,n=s.pesData,a=t.pesData,o=r.pesData;let l;if(n&&(l=parsePES(n,this.logger))?(this.readyVideoParser(s.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(s,i,l,!0),s.pesData=null)):s.pesData=n,a&&(l=parsePES(a,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l)}t.pesData=null}else null!=a&&a.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=a;o&&(l=parsePES(o,this.logger))?(this.parseID3PES(r,l),r.pesData=null):r.pesData=o}demuxSampleAes(e,t,s){const r=this.demux(e,s,!0,!this.config.progressive),i=this.sampleAes=new SampleAesDecrypter(this.observer,this.config,t);return this.decrypt(r,i)}readyVideoParser(e){null===this.videoParser&&("avc"===e?this.videoParser=new AvcVideoParser:"hevc"===e&&(this.videoParser=new HevcVideoParser))}decrypt(e,t){return new Promise((s=>{const{audioTrack:r,videoTrack:i}=e;r.samples&&"aac"===r.segmentCodec?t.decryptAacSamples(r.samples,0,(()=>{i.samples?t.decryptAvcSamples(i.samples,0,0,(()=>{s(e)})):s(e)})):i.samples&&t.decryptAvcSamples(i.samples,0,0,(()=>{s(e)}))}))}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let s=0;const r=this.aacOverFlow;let i,n,a,o=t.data;if(r){this.aacOverFlow=null;const t=r.missing,i=r.sample.unit.byteLength;if(-1===t)o=appendUint8Array(r.sample.unit,o);else{const n=i-t;r.sample.unit.set(o.subarray(0,t),n),e.samples.push(r.sample),s=r.missing}}for(i=s,n=o.length;i<n-1&&!isHeader$1(o,i);i++);if(i!==s){let e;const t=i<n-1;if(e=t?`AAC PES did not start with ADTS header,offset:${i}`:"No ADTS header found in AAC PES",emitParsingError(this.observer,new Error(e),t,this.logger),!t)return}if(initTrackConfig(e,this.observer,o,i,this.audioCodec),void 0!==t.pts)a=t.pts;else{if(!r)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const t=getFrameDuration(e.samplerate);a=r.sample.pts+t}}let l,d=0;for(;i<n;){if(l=appendFrame$2(e,o,i,a,d),i+=l.length,l.missing){this.aacOverFlow=l;break}for(d++;i<n-1&&!isHeader$1(o,i);i++);}}parseMPEGPES(e,t){const s=t.data,r=s.length;let i=0,n=0;const a=t.pts;if(void 0!==a)for(;n<r;)if(isHeader(s,n)){const t=appendFrame$1(e,s,n,a,i);if(!t)break;n+=t.length,i++}else n++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(e,t){{const s=t.data,r=t.pts;if(void 0===r)return void this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");const i=s.length;let n,a=0,o=0;for(;o<i&&(n=appendFrame(e,s,o,r,a++))>0;)o+=n}}parseID3PES(e,t){if(void 0===t.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const s=_extends({},t,{type:this._videoTrack?MetadataSchema.emsg:MetadataSchema.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}}function parsePID(e,t){return((31&e[t+1])<<8)+e[t+2]}function parsePAT(e,t){return(31&e[t+10])<<8|e[t+11]}function parsePMT(e,t,s,r,i,n){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t<o;){const o=parsePID(e,t),l=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!r){logEncryptedSamplesFoundInUnencryptedStream("ADTS AAC",n);break}case 15:-1===a.audioPid&&(a.audioPid=o);break;case 21:-1===a.id3Pid&&(a.id3Pid=o);break;case 219:if(!r){logEncryptedSamplesFoundInUnencryptedStream("H.264",n);break}case 27:-1===a.videoPid&&(a.videoPid=o);break;case 3:case 4:s.mpeg||s.mp3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="mp3"):n.log("MPEG audio found, not supported in this browser");break;case 193:if(!r){logEncryptedSamplesFoundInUnencryptedStream("AC-3",n);break}case 129:s.ac3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===a.audioPid&&l>0){let r=t+5,i=l;for(;i>2;){if(106===e[r])!0!==s.ac3?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=o,a.segmentAudioCodec="ac3");const t=e[r+1]+2;r+=t,i-=t}}break;case 194:case 135:return emitParsingError(i,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:-1===a.videoPid&&(a.videoPid=o,a.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"))}t+=l+5}return a}function emitParsingError(e,t,s,r){r.warn(`parsing error: ${t.message}`),e.emit(Events.ERROR,Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,levelRetry:s,error:t,reason:t.message})}function logEncryptedSamplesFoundInUnencryptedStream(e,t){t.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function parsePES(e,t){let s,r,i,n,a,o=0;const l=e.data;if(!e||0===e.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=appendUint8Array(l[0],l[1]),l.splice(1,1);s=l[0];if(1===(s[0]<<16)+(s[1]<<8)+s[2]){if(r=(s[4]<<8)+s[5],r&&r>e.size-6)return null;const d=s[7];192&d&&(n=536870912*(14&s[9])+4194304*(255&s[10])+16384*(254&s[11])+128*(255&s[12])+(254&s[13])/2,64&d?(a=536870912*(14&s[14])+4194304*(255&s[15])+16384*(254&s[16])+128*(255&s[17])+(254&s[18])/2,n-a>54e5&&(t.warn(`${Math.round((n-a)/9e4)}s delta between PTS and DTS, align them`),n=a)):a=n),i=s[8];let h=i+9;if(e.size<=h)return null;e.size-=h;const c=new Uint8Array(e.size);for(let e=0,t=l.length;e<t;e++){s=l[e];let t=s.byteLength;if(h){if(h>t){h-=t;continue}s=s.subarray(h),t-=h,h=0}c.set(s,o),o+=t}return r&&(r-=i+3),{data:c,pts:n,dts:a,len:r}}return null}class AAC{static getSilentFrame(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}const UINT32_MAX=Math.pow(2,32)-1;class MP4{static init(){let e;for(e in MP4.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:[]},MP4.types)MP4.types.hasOwnProperty(e)&&(MP4.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),s=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);MP4.HDLR_TYPES={video:t,audio:s};const r=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),i=new Uint8Array([0,0,0,0,0,0,0,0]);MP4.STTS=MP4.STSC=MP4.STCO=i,MP4.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),MP4.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),MP4.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),MP4.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);MP4.FTYP=MP4.box(MP4.types.ftyp,n,o,n,a),MP4.DINF=MP4.box(MP4.types.dinf,MP4.box(MP4.types.dref,r))}static box(e,...t){let s=8,r=t.length;const i=r;for(;r--;)s+=t[r].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=255&s,n.set(e,4),r=0,s=8;r<i;r++)n.set(t[r],s),s+=t[r].byteLength;return n}static hdlr(e){return MP4.box(MP4.types.hdlr,MP4.HDLR_TYPES[e])}static mdat(e){return MP4.box(MP4.types.mdat,e)}static mdhd(e,t){t*=e;const s=Math.floor(t/(UINT32_MAX+1)),r=Math.floor(t%(UINT32_MAX+1));return MP4.box(MP4.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,s>>24,s>>16&255,s>>8&255,255&s,r>>24,r>>16&255,r>>8&255,255&r,85,196,0,0]))}static mdia(e){return MP4.box(MP4.types.mdia,MP4.mdhd(e.timescale||0,e.duration||0),MP4.hdlr(e.type),MP4.minf(e))}static mfhd(e){return MP4.box(MP4.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))}static minf(e){return"audio"===e.type?MP4.box(MP4.types.minf,MP4.box(MP4.types.smhd,MP4.SMHD),MP4.DINF,MP4.stbl(e)):MP4.box(MP4.types.minf,MP4.box(MP4.types.vmhd,MP4.VMHD),MP4.DINF,MP4.stbl(e))}static moof(e,t,s){return MP4.box(MP4.types.moof,MP4.mfhd(e),MP4.traf(s,t))}static moov(e){let t=e.length;const s=[];for(;t--;)s[t]=MP4.trak(e[t]);return MP4.box.apply(null,[MP4.types.moov,MP4.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(MP4.mvex(e)))}static mvex(e){let t=e.length;const s=[];for(;t--;)s[t]=MP4.trex(e[t]);return MP4.box.apply(null,[MP4.types.mvex,...s])}static mvhd(e,t){t*=e;const s=Math.floor(t/(UINT32_MAX+1)),r=Math.floor(t%(UINT32_MAX+1)),i=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,s>>24,s>>16&255,s>>8&255,255&s,r>>24,r>>16&255,r>>8&255,255&r,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return MP4.box(MP4.types.mvhd,i)}static sdtp(e){const t=e.samples||[],s=new Uint8Array(4+t.length);let r,i;for(r=0;r<t.length;r++)i=t[r].flags,s[r+4]=i.dependsOn<<4|i.isDependedOn<<2|i.hasRedundancy;return MP4.box(MP4.types.sdtp,s)}static stbl(e){return MP4.box(MP4.types.stbl,MP4.stsd(e),MP4.box(MP4.types.stts,MP4.STTS),MP4.box(MP4.types.stsc,MP4.STSC),MP4.box(MP4.types.stsz,MP4.STSZ),MP4.box(MP4.types.stco,MP4.STCO))}static avc1(e){let t,s,r,i=[],n=[];for(t=0;t<e.sps.length;t++)s=e.sps[t],r=s.byteLength,i.push(r>>>8&255),i.push(255&r),i=i.concat(Array.prototype.slice.call(s));for(t=0;t<e.pps.length;t++)s=e.pps[t],r=s.byteLength,n.push(r>>>8&255),n.push(255&r),n=n.concat(Array.prototype.slice.call(s));const a=MP4.box(MP4.types.avcC,new Uint8Array([1,i[3],i[4],i[5],255,224|e.sps.length].concat(i).concat([e.pps.length]).concat(n))),o=e.width,l=e.height,d=e.pixelRatio[0],h=e.pixelRatio[1];return MP4.box(MP4.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,MP4.box(MP4.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),MP4.box(MP4.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,h>>24,h>>16&255,h>>8&255,255&h])))}static esds(e){const t=e.config,s=t.length;return new Uint8Array([0,0,0,0,3,23+s,0,1,0,4,15+s,64,21,0,0,0,0,0,0,0,0,0,0,0,5,s,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,255&t,0,0])}static mp4a(e){return MP4.box(MP4.types.mp4a,MP4.audioStsd(e),MP4.box(MP4.types.esds,MP4.esds(e)))}static mp3(e){return MP4.box(MP4.types[".mp3"],MP4.audioStsd(e))}static ac3(e){return MP4.box(MP4.types["ac-3"],MP4.audioStsd(e),MP4.box(MP4.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if("audio"===e.type){if("aac"===t)return MP4.box(MP4.types.stsd,MP4.STSD,MP4.mp4a(e));if("ac3"===t&&e.config)return MP4.box(MP4.types.stsd,MP4.STSD,MP4.ac3(e));if("mp3"===t&&"mp3"===e.codec)return MP4.box(MP4.types.stsd,MP4.STSD,MP4.mp3(e))}else{if(!e.pps||!e.sps)throw new Error("video track missing pps or sps");if("avc"===t)return MP4.box(MP4.types.stsd,MP4.STSD,MP4.avc1(e));if("hevc"===t&&e.vps)return MP4.box(MP4.types.stsd,MP4.STSD,MP4.hvc1(e))}throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,s=(e.duration||0)*(e.timescale||0),r=e.width||0,i=e.height||0,n=Math.floor(s/(UINT32_MAX+1)),a=Math.floor(s%(UINT32_MAX+1));return MP4.box(MP4.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,r>>8&255,255&r,0,0,i>>8&255,255&i,0,0]))}static traf(e,t){const s=MP4.sdtp(e),r=e.id,i=Math.floor(t/(UINT32_MAX+1)),n=Math.floor(t%(UINT32_MAX+1));return MP4.box(MP4.types.traf,MP4.box(MP4.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r])),MP4.box(MP4.types.tfdt,new Uint8Array([1,0,0,0,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n])),MP4.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,MP4.box(MP4.types.trak,MP4.tkhd(e),MP4.mdia(e))}static trex(e){const t=e.id;return MP4.box(MP4.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const s=e.samples||[],r=s.length,i=12+16*r,n=new Uint8Array(i);let a,o,l,d,h,c;for(t+=8+i,n.set(["video"===e.type?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,255&r,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0),a=0;a<r;a++)o=s[a],l=o.duration,d=o.size,h=o.flags,c=o.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,d>>>24&255,d>>>16&255,d>>>8&255,255&d,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,61440&h.degradPrio,15&h.degradPrio,c>>>24&255,c>>>16&255,c>>>8&255,255&c],12+16*a);return MP4.box(MP4.types.trun,n)}static initSegment(e){MP4.types||MP4.init();const t=MP4.moov(e);return appendUint8Array(MP4.FTYP,t)}static hvc1(e){const t=e.params,s=[e.vps,e.sps,e.pps],r=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),3|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),s.length]);let i=r.length;for(let e=0;e<s.length;e+=1){i+=3;for(let t=0;t<s[e].length;t+=1)i+=2+s[e][t].length}const n=new Uint8Array(i);n.set(r,0),i=r.length;const a=s.length-1;for(let e=0;e<s.length;e+=1){n.set(new Uint8Array([32+e|(e===a?128:0),0,s[e].length]),i),i+=3;for(let t=0;t<s[e].length;t+=1)n.set(new Uint8Array([s[e][t].length>>8,255&s[e][t].length]),i),i+=2,n.set(s[e][t],i),i+=s[e][t].length}const o=MP4.box(MP4.types.hvcC,n),l=e.width,d=e.height,h=e.pixelRatio[0],c=e.pixelRatio[1];return MP4.box(MP4.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,d>>8&255,255&d,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,MP4.box(MP4.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),MP4.box(MP4.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,c>>24,c>>16&255,c>>8&255,255&c])))}}MP4.types=void 0,MP4.HDLR_TYPES=void 0,MP4.STTS=void 0,MP4.STSC=void 0,MP4.STCO=void 0,MP4.STSZ=void 0,MP4.VMHD=void 0,MP4.SMHD=void 0,MP4.STSD=void 0,MP4.FTYP=void 0,MP4.DINF=void 0;const MPEG_TS_CLOCK_FREQ_HZ=9e4;function toTimescaleFromBase(e,t,s=1,r=!1){const i=e*t*s;return r?Math.round(i):i}function toTimescaleFromScale(e,t,s=1,r=!1){return toTimescaleFromBase(e,t,1/s,r)}function toMsFromMpegTsClock(e,t=!1){return toTimescaleFromBase(e,1e3,1/MPEG_TS_CLOCK_FREQ_HZ,t)}function toMpegTsClockFromTimescale(e,t=1){return toTimescaleFromBase(e,MPEG_TS_CLOCK_FREQ_HZ,1/t)}function timestampToString(e){const{baseTime:t,timescale:s,trackId:r}=e;return`${t/s} (${t}/${s}) trackId: ${r}`}const MAX_SILENT_FRAME_DURATION=1e4,AAC_SAMPLES_PER_FRAME=1024,MPEG_AUDIO_SAMPLE_PER_FRAME=1152,AC3_SAMPLES_PER_FRAME=1536;let now,chromeVersion=null,safariWebkitVersion=null;function createMp4Sample(e,t,s,r){return{duration:t,size:s,cts:r,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}class MP4Remuxer extends Logger{constructor(e,t,s,r){if(super("mp4-remuxer",r),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.ISGenerated=!1,null===chromeVersion){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);chromeVersion=e?parseInt(e[1]):0}if(null===safariWebkitVersion){const e=navigator.userAgent.match(/Safari\/(\d+)/i);safariWebkitVersion=e?parseInt(e[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;t&&e&&e.trackId===t.trackId&&e.baseTime===t.baseTime&&e.timescale===t.timescale||this.log(`Reset initPTS: ${t?timestampToString(t):t} > ${e?timestampToString(e):e}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const s=e[0].pts,r=e.reduce(((e,r)=>{let i=r.pts,n=i-e;return n<-4294967296&&(t=!0,i=normalizePts(i,s),n=i-e),n>0?e:i}),s);return t&&this.debug("PTS rollover detected"),r}remux(e,t,s,r,i,n,a,o){let l,d,h,c,u,f,g=i,m=i;const p=e.pid>-1,E=t.pid>-1,y=t.samples.length,v=e.samples.length>0,T=a&&y>0||y>1;if((!p||v)&&(!E||T)||this.ISGenerated||a){if(this.ISGenerated){var S,A,L,I;const e=this.videoTrackConfig;(e&&(t.width!==e.width||t.height!==e.height||(null==(S=t.pixelRatio)?void 0:S[0])!==(null==(A=e.pixelRatio)?void 0:A[0])||(null==(L=t.pixelRatio)?void 0:L[1])!==(null==(I=e.pixelRatio)?void 0:I[1]))||!e&&T||null===this.nextAudioTs&&v)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(e,t,i,n));const s=this.isVideoContiguous;let r,a=-1;if(T&&(a=findKeyframeIndex(t.samples),!s&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,a>0){this.warn(`Dropped ${a} out of ${y} video samples due to a missing keyframe`);const e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(a),t.dropped+=a,m+=(t.samples[0].pts-e)/t.inputTimeScale,r=m}else-1===a&&(this.warn(`No keyframe found out of ${y} video samples`),f=!1);if(this.ISGenerated){if(v&&T){const s=this.getVideoStartPts(t.samples),r=(normalizePts(e.samples[0].pts,s)-s)/t.inputTimeScale;g+=Math.max(0,r),m+=Math.max(0,-r)}if(v){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),h=this.generateIS(e,t,i,n)),d=this.remuxAudio(e,g,this.isAudioContiguous,n,E||T||o===PlaylistLevelType.AUDIO?m:void 0),T){const r=d?d.endPTS-d.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),h=this.generateIS(e,t,i,n)),l=this.remuxVideo(t,m,s,r)}}else T&&(l=this.remuxVideo(t,m,s,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=r)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(u=flushTextTrackMetadataCueSamples(s,i,this._initPTS,this._initDTS)),r.samples.length&&(c=flushTextTrackUserdataCueSamples(r,i,this._initPTS))),{audio:d,video:l,initSegment:h,independent:f,text:c,id3:u}}computeInitPts(e,t,s,r){const i=Math.round(s*t);let n=normalizePts(e,i);if(n<i+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(i-n)/t} ${r}`);n<i+t;)n+=8589934592;return n-i}generateIS(e,t,s,r){const i=e.samples,n=t.samples,a=this.typeSupported,o={},l=this._initPTS;let d,h,c,u=!l||r,f="audio/mp4",g=-1;if(u&&(d=h=1/0),e.config&&i.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}o.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&a.mpeg?new Uint8Array(0):MP4.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(g=e.id,c=e.inputTimeScale,l&&c===l.timescale?u=!1:d=h=this.computeInitPts(i[0].pts,c,s,"audio"))}if(t.sps&&t.pps&&n.length){if(t.timescale=t.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:MP4.initSegment([t]),metadata:{width:t.width,height:t.height}},u)if(g=t.id,c=t.inputTimeScale,l&&c===l.timescale)u=!1;else{const e=this.getVideoStartPts(n),t=normalizePts(n[0].dts,e),r=this.computeInitPts(t,c,s,"video"),i=this.computeInitPts(e,c,s,"video");h=Math.min(h,r),d=Math.min(d,i)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,u?(l&&this.warn(`Timestamps at playlist time: ${r?"":"~"}${s} ${d/c} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${d/c} (${d}/${c}) trackId: ${g}`),this._initPTS={baseTime:d,timescale:c,trackId:g},this._initDTS={baseTime:h,timescale:c,trackId:g}):d=c=void 0,{tracks:o,initPTS:d,timescale:c,trackId:g}}remuxVideo(e,t,s,r){const i=e.inputTimeScale,n=e.samples,a=[],o=n.length,l=this._initPTS,d=l.baseTime*i/l.timescale;let h,c,u=this.nextVideoTs,f=8,g=this.videoSampleDuration,m=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,E=!1;if(!s||null===u){const e=d+t*i,r=n[0].pts-normalizePts(n[0].dts,n[0].pts);chromeVersion&&null!==u&&Math.abs(e-r-(u+d))<15e3?s=!0:u=e-r-d}const y=u+d;for(let e=0;e<o;e++){const t=n[e];t.pts=normalizePts(t.pts,y),t.dts=normalizePts(t.dts,y),t.dts<n[e>0?e-1:e].dts&&(E=!0)}E&&n.sort((function(e,t){const s=e.dts-t.dts,r=e.pts-t.pts;return s||r})),h=n[0].dts,c=n[n.length-1].dts;const v=c-h,T=v?Math.round(v/(o-1)):g||e.inputTimeScale/30;if(s){const s=h-y,r=s>T,i=s<-1;if((r||i)&&(r?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${toMsFromMpegTsClock(s,!0)} ms (${s}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${toMsFromMpegTsClock(-s,!0)} ms (${s}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!i||y>=n[0].pts||chromeVersion)){h=y;const e=n[0].pts-s;if(r)n[0].dts=h,n[0].pts=e;else{let t=!0;for(let r=0;r<n.length&&!(n[r].dts>e&&t);r++){const e=n[r].pts;if(n[r].dts-=s,n[r].pts-=s,r<n.length-1){const s=n[r+1].pts;t=s<=n[r].pts==s<=e}}}this.log(`Video: Initial PTS/DTS adjusted: ${toMsFromMpegTsClock(e,!0)}/${toMsFromMpegTsClock(h,!0)}, delta: ${toMsFromMpegTsClock(s,!0)} ms`)}}h=Math.max(0,h);let S=0,A=0,L=h;for(let e=0;e<o;e++){const t=n[e],s=t.units,r=s.length;let i=0;for(let e=0;e<r;e++)i+=s[e].data.length;A+=i,S+=r,t.length=i,t.dts<L?(t.dts=L,L+=T/4|0||1):L=t.dts,m=Math.min(t.pts,m),p=Math.max(t.pts,p)}c=n[o-1].dts;const I=A+4*S+8;let R;try{R=new Uint8Array(I)}catch(e){return void this.observer.emit(Events.ERROR,Events.ERROR,{type:ErrorTypes.MUX_ERROR,details:ErrorDetails.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:I,reason:`fail allocating video mdat ${I}`})}const D=new DataView(R.buffer);D.setUint32(0,I),R.set(MP4.types.mdat,4);let b=!1,_=Number.POSITIVE_INFINITY,C=Number.POSITIVE_INFINITY,P=Number.NEGATIVE_INFINITY,k=Number.NEGATIVE_INFINITY;for(let e=0;e<o;e++){const t=n[e],s=t.units;let l,h=0;for(let e=0,t=s.length;e<t;e++){const t=s[e],r=t.data,i=t.data.byteLength;D.setUint32(f,i),f+=4,R.set(r,f),f+=i,h+=4+i}if(e<o-1)g=n[e+1].dts-t.dts,l=n[e+1].pts-t.pts;else{const s=this.config,a=e>0?t.dts-n[e-1].dts:T;if(l=e>0?t.pts-n[e-1].pts:T,s.stretchShortVideoTrack&&null!==this.nextAudioTs){const e=Math.floor(s.maxBufferHole*i),n=(r?m+r*i:this.nextAudioTs+d)-t.pts;n>e?(g=n-a,g<0?g=a:b=!0,this.log(`It is approximately ${n/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)):g=a}else g=a}const c=Math.round(t.pts-t.dts);_=Math.min(_,g),P=Math.max(P,g),C=Math.min(C,l),k=Math.max(k,l),a.push(createMp4Sample(t.key,g,h,c))}if(a.length)if(chromeVersion){if(chromeVersion<70){const e=a[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(safariWebkitVersion&&k-C<P-_&&T/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 e=h;for(let t=0,s=a.length;t<s;t++){const r=e+a[t].duration,i=e+a[t].cts;if(t<s-1){const e=r+a[t+1].cts;a[t].duration=e-i}else a[t].duration=t?a[t-1].duration:T;a[t].cts=0,e=r}}g=b||!g?T:g;const M=c+g;this.nextVideoTs=u=M-d,this.videoSampleDuration=g,this.isVideoContiguous=!0;const O={data1:MP4.moof(e.sequenceNumber++,h,_extends(e,{samples:a})),data2:R,startPTS:(m-d)/i,endPTS:(p+g-d)/i,startDTS:(h-d)/i,endDTS:u/i,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:e.dropped};return e.samples=[],e.dropped=0,O}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(e,t,s,r,i){const n=e.inputTimeScale,a=n/(e.samplerate?e.samplerate:n),o=this.getSamplesPerFrame(e),l=o*a,d=this._initPTS,h="mp3"===e.segmentCodec&&this.typeSupported.mpeg,c=[],u=void 0!==i;let f=e.samples,g=h?0:8,m=this.nextAudioTs||-1;const p=d.baseTime*n/d.timescale,E=p+t*n;if(this.isAudioContiguous=s=s||f.length&&m>0&&(r&&Math.abs(E-(m+p))<9e3||Math.abs(normalizePts(f[0].pts,E)-(m+p))<20*l),f.forEach((function(e){e.pts=normalizePts(e.pts,E)})),!s||m<0){const e=f.length;if(f=f.filter((e=>e.pts>=0)),e!==f.length&&this.warn(`Removed ${f.length-e} of ${e} samples (initPTS ${p} / ${n})`),!f.length)return;m=0===i?0:r&&!u?Math.max(0,E-p):f[0].pts-p}if("aac"===e.segmentCodec){const t=this.config.maxAudioFramesDrift;for(let s=0,r=m+p;s<f.length;s++){const i=f[s],a=i.pts,o=a-r,d=Math.abs(1e3*o/n);if(o<=-t*l&&u)0===s&&(this.warn(`Audio frame @ ${(a/n).toFixed(3)}s overlaps marker by ${Math.round(1e3*o/n)} ms.`),this.nextAudioTs=m=a-p,r=a);else if(o>=t*l&&d<1e4&&u){let t=Math.round(o/l);for(r=a-t*l;r<0&&t&&l;)t--,r+=l;0===s&&(this.nextAudioTs=m=r-p),this.warn(`Injecting ${t} audio frames @ ${((r-p)/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n<t;n++){let t=AAC.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);t||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),t=i.unit.subarray()),f.splice(s,0,{unit:t,pts:r}),r+=l,s++}}i.pts=r,r+=l}}let y,v=null,T=null,S=0,A=f.length;for(;A--;)S+=f[A].unit.byteLength;for(let t=0,r=f.length;t<r;t++){const r=f[t],i=r.unit;let n=r.pts;if(null!==T){c[t-1].duration=Math.round((n-T)/a)}else{if(s&&"aac"===e.segmentCodec&&(n=m+p),v=n,!(S>0))return;S+=g;try{y=new Uint8Array(S)}catch(e){return void this.observer.emit(Events.ERROR,Events.ERROR,{type:ErrorTypes.MUX_ERROR,details:ErrorDetails.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:S,reason:`fail allocating audio mdat ${S}`})}if(!h){new DataView(y.buffer).setUint32(0,S),y.set(MP4.types.mdat,4)}}y.set(i,g);const l=i.byteLength;g+=l,c.push(createMp4Sample(!0,o,l,0)),T=n}const L=c.length;if(!L)return;const I=c[c.length-1];m=T-p,this.nextAudioTs=m+a*I.duration;const R=h?new Uint8Array(0):MP4.moof(e.sequenceNumber++,v/a,_extends({},e,{samples:c}));e.samples=[];const D=(v-p)/n,b=m/n,_={data1:R,data2:y,startPTS:D,endPTS:b,startDTS:D,endDTS:b,type:"audio",hasAudio:!0,hasVideo:!1,nb:L};return this.isAudioContiguous=!0,_}}function normalizePts(e,t){let s;if(null===t)return e;for(s=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=s;return e}function findKeyframeIndex(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return-1}function flushTextTrackMetadataCueSamples(e,t,s,r){const i=e.samples.length;if(!i)return;const n=e.inputTimeScale;for(let a=0;a<i;a++){const i=e.samples[a];i.pts=normalizePts(i.pts-s.baseTime*n/s.timescale,t*n)/n,i.dts=normalizePts(i.dts-r.baseTime*n/r.timescale,t*n)/n}const a=e.samples;return e.samples=[],{samples:a}}function flushTextTrackUserdataCueSamples(e,t,s){const r=e.samples.length;if(!r)return;const i=e.inputTimeScale;for(let n=0;n<r;n++){const r=e.samples[n];r.pts=normalizePts(r.pts-s.baseTime*i/s.timescale,t*i)/i}e.samples.sort(((e,t)=>e.pts-t.pts));const n=e.samples;return e.samples=[],{samples:n}}class PassThroughRemuxer extends Logger{constructor(e,t,s,r){super("passthrough-remuxer",r),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,s,r){this.audioCodec=t,this.videoCodec=s,this.generateInitSegment(e,r),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:s,videoCodec:r}=this;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const{audio:i,video:n}=this.initData=parseInitSegment(e);if(t)patchEncyptionData(e,t);else{const e=i||n;null!=e&&e.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${e.codec}")!`)}i&&(s=getParsedTrackCodec(i,ElementaryStreamTypes.AUDIO,this)),n&&(r=getParsedTrackCodec(n,ElementaryStreamTypes.VIDEO,this));const a={};i&&n?a.audiovideo={container:"video/mp4",codec:s+","+r,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:i?a.audio={container:"audio/mp4",codec:s,encrypted:i.encrypted,initSegment:e,id:"audio"}:n?a.video={container:"video/mp4",codec:r,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=a}remux(e,t,s,r,i,n){var a,o;let{initPTS:l,lastEndTime:d}=this;const h={audio:void 0,video:void 0,text:r,id3:s,initSegment:void 0};isFiniteNumber(d)||(d=this.lastEndTime=i||0);const c=t.samples;if(!c.length)return h;const u={initPTS:void 0,timescale:void 0,trackId:void 0};let f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(c),f=this.initData),null==(o=f)||!o.length)return this.warn("Failed to generate initSegment."),h;this.emitInitSegment&&(u.tracks=this.initTracks,this.emitInitSegment=!1);const g=getSampleData(c,f,this),m=f.audio?g[f.audio.id]:null,p=f.video?g[f.video.id]:null,E=toStartEndOrDefault(p,1/0),y=toStartEndOrDefault(m,1/0),v=toStartEndOrDefault(p,0,!0),T=toStartEndOrDefault(m,0,!0);let S=i,A=0;const L=m&&(!p||!l&&y<E||l&&l.trackId===f.audio.id),I=L?m:p;if(I){const e=I.timescale,t=I.start-i*e,s=L?f.audio.id:f.video.id;S=I.start/e,A=L?T-y:v-E,!n&&l||!isInvalidInitPts(l,S,i,A)&&e===l.timescale||(l&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${i} ${t/e} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${S-i} (${t}/${e}) trackId: ${s}`),l=null,u.initPTS=t,u.timescale=e,u.trackId=s)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${i}`);l?(u.initPTS=l.baseTime,u.timescale=l.timescale,u.trackId=l.trackId):(u.timescale&&void 0!==u.trackId&&void 0!==u.initPTS||(this.warn("Could not set initPTS"),u.initPTS=S,u.timescale=1,u.trackId=-1),this.initPTS=l={baseTime:u.initPTS,timescale:u.timescale,trackId:u.trackId});const R=S-l.baseTime/l.timescale,D=R+A;A>0?this.lastEndTime=D:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const b=!!f.audio,_=!!f.video;let C="";b&&(C+="audio"),_&&(C+="video");const P={data1:c,startPTS:R,startDTS:R,endPTS:D,endDTS:D,type:C,hasAudio:b,hasVideo:_,nb:1,dropped:0,encrypted:!!f.audio&&f.audio.encrypted||!!f.video&&f.video.encrypted};h.audio=b&&!_?P:void 0,h.video=_?P:void 0;const k=null==p?void 0:p.sampleCount;if(k){const e=p.keyFrameIndex,t=-1!==e;P.nb=k,P.dropped=0===e||this.isVideoContiguous?0:t?e:k,P.independent=t,P.firstKeyFrame=e,t&&p.keyFrameStart&&(P.firstKeyFramePTS=(p.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(h.independent=t),this.isVideoContiguous||(this.isVideoContiguous=t),P.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${e}/${k} dropped: ${P.dropped} start: ${P.firstKeyFramePTS||"NA"}`)}return h.initSegment=u,h.id3=flushTextTrackMetadataCueSamples(s,i,l,l),r.samples.length&&(h.text=flushTextTrackUserdataCueSamples(r,i,l)),h}}function toStartEndOrDefault(e,t,s=!1){return void 0!==(null==e?void 0:e.start)?(e.start+(s?e.duration:0))/e.timescale:t}function isInvalidInitPts(e,t,s,r){if(null===e)return!0;const i=Math.max(r,1),n=t-e.baseTime/e.timescale;return Math.abs(n-s)>i}function getParsedTrackCodec(e,t,s){const r=e.codec;if(r&&r.length>4)return r;if(t===ElementaryStreamTypes.AUDIO){if("ec-3"===r||"ac-3"===r||"alac"===r)return r;if("fLaC"===r||"Opus"===r){return getCodecCompatibleName(r,!1)}return s.warn(`Unhandled audio codec "${r}" in mp4 MAP`),r||"mp4a"}return s.warn(`Unhandled video codec "${r}" in mp4 MAP`),r||"avc1"}try{now=self.performance.now.bind(self.performance)}catch(e){now=Date.now}const muxConfig=[{demux:MP4Demuxer,remux:PassThroughRemuxer},{demux:TSDemuxer,remux:MP4Remuxer},{demux:AACDemuxer,remux:MP4Remuxer},{demux:MP3Demuxer,remux:MP4Remuxer}];muxConfig.splice(2,0,{demux:AC3Demuxer,remux:MP4Remuxer});class Transmuxer{constructor(e,t,s,r,i,n){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=s,this.id=i,this.logger=n}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,r){const i=s.transmuxing;i.executeStart=now();let n=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:o}=this;r&&(this.currentTransmuxState=r);const{contiguous:l,discontinuity:d,trackSwitch:h,accurateTimeOffset:c,timeOffset:u,initSegmentChange:f}=r||a,{audioCodec:g,videoCodec:m,defaultInitPts:p,duration:E,initSegmentData:y}=o,v=getEncryptionType(n,t);if(v&&isFullSegmentEncryption(v.method)){const e=this.getDecrypter(),t=getAesModeFromFullSegmentMethod(v.method);if(!e.isSync())return this.asyncResult=!0,this.decryptionPromise=e.webCryptoDecrypt(n,v.key.buffer,v.iv.buffer,t).then((e=>{const t=this.push(e,null,s);return this.decryptionPromise=null,t})),this.decryptionPromise;{let r=e.softwareDecrypt(n,v.key.buffer,v.iv.buffer,t);if(s.part>-1){const t=e.flush();r=t?t.buffer:t}if(!r)return i.executeEnd=now(),emptyResult(s);n=new Uint8Array(r)}}const T=this.needsProbing(d,h);if(T){const e=this.configureTransmuxer(n);if(e)return this.logger.warn(`[transmuxer] ${e.message}`),this.observer.emit(Events.ERROR,Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),i.executeEnd=now(),emptyResult(s)}(d||h||f||T)&&this.resetInitSegment(y,g,m,E,t),(d||f||T)&&this.resetInitialTimestamp(p),l||this.resetContiguity();const S=this.transmux(n,v,u,c,s);this.asyncResult=isPromise(S);const A=this.currentTransmuxState;return A.contiguous=!0,A.discontinuity=!1,A.trackSwitch=!1,i.executeEnd=now(),S}flush(e){const t=e.transmuxing;t.executeStart=now();const{decrypter:s,currentTransmuxState:r,decryptionPromise:i}=this;if(i)return this.asyncResult=!0,i.then((()=>this.flush(e)));const n=[],{timeOffset:a}=r;if(s){const t=s.flush();t&&n.push(this.push(t.buffer,null,e))}const{demuxer:o,remuxer:l}=this;if(!o||!l){t.executeEnd=now();const s=[emptyResult(e)];return this.asyncResult?Promise.resolve(s):s}const d=o.flush(a);return isPromise(d)?(this.asyncResult=!0,d.then((t=>(this.flushRemux(n,t,e),n)))):(this.flushRemux(n,d,e),this.asyncResult?Promise.resolve(n):n)}flushRemux(e,t,s){const{audioTrack:r,videoTrack:i,id3Track:n,textTrack:a}=t,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===PlaylistLevelType.MAIN?"level":"track"} ${s.level}`);const d=this.remuxer.remux(r,i,n,a,l,o,!0,this.id);e.push({remuxResult:d,chunkMeta:s}),s.transmuxing.executeEnd=now()}resetInitialTimestamp(e){const{demuxer:t,remuxer:s}=this;t&&s&&(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,r,i){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(e,t,s,r),a.resetInitSegment(e,t,s,i))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,s,r,i){let n;return n=t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,s,r,i):this.transmuxUnencrypted(e,s,r,i),n}transmuxUnencrypted(e,t,s,r){const{audioTrack:i,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(i,n,a,o,t,s,!1,this.id),chunkMeta:r}}transmuxSampleAes(e,t,s,r,i){return this.demuxer.demuxSampleAes(e,t,s).then((e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,s,r,!1,this.id),chunkMeta:i})))}configureTransmuxer(e){const{config:t,observer:s,typeSupported:r}=this;let i;for(let t=0,s=muxConfig.length;t<s;t++){var n;if(null!=(n=muxConfig[t].demux)&&n.probe(e,this.logger)){i=muxConfig[t];break}}if(!i)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=i.remux,d=i.demux;o&&o instanceof l||(this.remuxer=new l(s,t,r,this.logger)),a&&a instanceof d||(this.demuxer=new d(s,t,r,this.logger),this.probe=d.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Decrypter(this.config)),e}}function getEncryptionType(e,t){let s=null;return e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(s=t),s}const emptyResult=e=>({remuxResult:{},chunkMeta:e});function isPromise(e){return"then"in e&&e.then instanceof Function}class TransmuxConfig{constructor(e,t,s,r,i){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=s,this.duration=r,this.defaultInitPts=i||null}}class TransmuxState{constructor(e,t,s,r,i,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=s,this.trackSwitch=r,this.timeOffset=i,this.initSegmentChange=n}}let transmuxerInstanceCount=0;class TransmuxerInterface{constructor(e,t,s,r){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=transmuxerInstanceCount++,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=e=>{const t=e.data,s=this.hls;if(s&&null!=t&&t.event&&t.instanceNo===this.instanceNo)switch(t.event){case"init":{var r;const e=null==(r=this.workerContext)?void 0:r.objectURL;e&&self.URL.revokeObjectURL(e);break}case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":s.logger[t.data.logType]&&s.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.part=this.part,t.data.id=this.id,s.trigger(t.event,t.data)}},this.onWorkerError=e=>{if(!this.hls)return;const t=new Error(`${e.message} (${e.filename}:${e.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})};const i=e.config;this.hls=e,this.id=t,this.useWorker=!!i.enableWorker,this.onTransmuxComplete=s,this.onFlush=r;const n=(e,t)=>{(t=t||{}).frag=this.frag||void 0,e===Events.ERROR&&(t.parent=this.id,t.part=this.part,this.error=t.error),this.hls.trigger(e,t)};this.observer=new EventEmitter,this.observer.on(Events.FRAG_DECRYPTED,n),this.observer.on(Events.ERROR,n);const a=getM2TSSupportedAudioTypes(i.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const s=this.hls.logger;if(i.workerPath||hasUMDWorker()){try{i.workerPath?(s.log(`loading Web Worker ${i.workerPath} for "${t}"`),this.workerContext=loadWorker(i.workerPath)):(s.log(`injecting Web Worker for "${t}"`),this.workerContext=injectWorker());const{worker:e}=this.workerContext;e.addEventListener("message",this.onWorkerMessage),e.addEventListener("error",this.onWorkerError),e.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:t,config:stringify(i)})}catch(r){s.warn(`Error setting up "${t}" Web Worker, fallback to inline`,r),this.terminateWorker(),this.error=null,this.transmuxer=new Transmuxer(this.observer,a,i,"",t,e.logger)}return}}this.transmuxer=new Transmuxer(this.observer,a,i,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=transmuxerInstanceCount++;const t=this.hls.config,s=getM2TSSupportedAudioTypes(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:stringify(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),removeWorkerFromStore(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,s,r,i,n,a,o,l,d){var h,c;l.transmuxing.start=self.performance.now();const{instanceNo:u,transmuxer:f}=this,g=n?n.start:i.start,m=i.decryptdata,p=this.frag,E=!(p&&i.cc===p.cc),y=!(p&&l.level===p.level),v=p?l.sn-p.sn:-1,T=this.part?l.part-this.part.index:-1,S=0===v&&l.id>1&&l.id===(null==p?void 0:p.stats.chunkCount),A=!y&&(1===v||0===v&&(1===T||S&&T<=0)),L=self.performance.now();(y||v||0===i.stats.parsing.start)&&(i.stats.parsing.start=L),!n||!T&&A||(n.stats.parsing.start=L);const I=!(p&&(null==(h=i.initSegment)?void 0:h.url)===(null==(c=p.initSegment)?void 0:c.url)),R=new TransmuxState(E,A,o,y,g,I);if(!A||E||I){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${i.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===PlaylistLevelType.MAIN?"level":"track"}: ${l.level} id: ${l.id}\n discontinuity: ${E}\n trackSwitch: ${y}\n contiguous: ${A}\n accurateTimeOffset: ${o}\n timeOffset: ${g}\n initSegmentChange: ${I}`);const e=new TransmuxConfig(s,r,t,a,d);this.configureTransmuxer(e)}if(this.frag=i,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:u,cmd:"demux",data:e,decryptdata:m,chunkMeta:l,state:R},e instanceof ArrayBuffer?[e]:[]);else if(f){const t=f.push(e,m,l,R);isPromise(t)?t.then((e=>{this.handleTransmuxComplete(e)})).catch((e=>{this.transmuxerError(e,l,"transmuxer-interface push error")})):this.handleTransmuxComplete(t)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(s){const t=s.flush(e);isPromise(t)?t.then((t=>{this.handleFlushResult(t,e)})).catch((t=>{this.transmuxerError(t,e,"transmuxer-interface flush error")})):this.handleFlushResult(t,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach((e=>{this.handleTransmuxComplete(e)})),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):s&&s.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const TICK_INTERVAL$3=100;class AudioStreamController extends BaseStreamController{constructor(e,t,s){super(e,t,s,"audio-stream-controller",PlaylistLevelType.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Events.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Events.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(Events.BUFFER_RESET,this.onBufferReset,this),e.on(Events.BUFFER_CREATED,this.onBufferCreated,this),e.on(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Events.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Events.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Events.FRAG_LOADING,this.onFragLoading,this),e.on(Events.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Events.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Events.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(Events.BUFFER_RESET,this.onBufferReset,this),e.off(Events.BUFFER_CREATED,this.onBufferCreated,this),e.off(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Events.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Events.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Events.FRAG_LOADING,this.onFragLoading,this),e.off(Events.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:s,initPTS:r,timescale:i,trackId:n}){if(s===PlaylistLevelType.MAIN){const e=t.cc,s=this.fragCurrent;if(this.initPTS[e]={baseTime:r,timescale:i,trackId:n},this.log(`InitPTS for cc: ${e} found from main: ${r/i} (${r}/${i}) trackId: ${n}`),this.mainAnchor=t,this.state===State.WAITING_INIT_PTS){const s=this.waitingData;(!s&&!this.loadingParts||s&&s.frag.cc!==e)&&this.syncWithAnchor(t,null==s?void 0:s.frag)}else!this.hls.hasEnoughToStart&&s&&s.cc!==e?(s.abortRequests(),this.syncWithAnchor(t,s)):this.state===State.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var s;const r=(null==(s=this.mainFragLoading)?void 0:s.frag)||null;if(t&&(null==r?void 0:r.cc)===t.cc)return;const i=(r||e).cc,n=findNearestWithCC(this.getLevelDetails(),i,this.getLoadPosition());n&&(this.log(`Syncing with main frag at ${n.start} cc ${n.cc}`),this.startFragRequested=!1,this.nextLoadPosition=n.start,this.resetLoadingState(),this.state===State.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels)return this.startPosition=e,void(this.state=State.STOPPED);const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),s>0&&-1===e?(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s,this.state=State.IDLE):this.state=State.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case State.IDLE:this.doTickIdle();break;case State.WAITING_TRACK:{const{levels:e,trackId:t}=this,s=null==e?void 0:e[t],r=null==s?void 0:s.details;if(r&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(r))break;this.state=State.WAITING_INIT_PTS}break}case State.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break;case State.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:s,cache:r,complete:i}=e,n=this.mainAnchor;if(void 0!==this.initPTS[t.cc]){this.waitingData=null,this.state=State.FRAG_LOADING;const e={frag:t,part:s,payload:r.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(e),i&&super._handleFragmentLoadComplete(e)}else n&&n.cc!==e.frag.cc&&this.syncWithAnchor(n,e.frag)}else this.state=State.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:s,media:r,trackId:i}=this,n=t.config;if(!this.buffering||!r&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||null==s||!s[i])return;const a=s[i],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o))return this.state=State.WAITING_TRACK,void(this.startFragRequested=!1);const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,ElementaryStreamTypes.AUDIO,PlaylistLevelType.AUDIO));const d=this.getFwdBufferInfo(l,PlaylistLevelType.AUDIO);if(null===d)return;if(!this.switchingTrack&&this._streamEnded(d,o))return t.trigger(Events.BUFFER_EOS,{type:"audio"}),void(this.state=State.ENDED);const h=d.len,c=t.maxBufferLength,u=o.fragments,f=u[0].start,g=this.getLoadPosition(),m=this.flushing?g:d.end;if(this.switchingTrack&&r){const e=g;o.PTSKnown&&e<f&&(d.end>f||d.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),r.currentTime=f+.05)}if(h>=c&&!this.switchingTrack&&m<u[u.length-1].start)return;let p=this.getNextFragment(m,o);if(p&&this.isLoopLoading(p,m)&&(p=this.getNextFragmentLoopLoading(p,o,d,PlaylistLevelType.MAIN,c)),!p)return void(this.bufferFlushed=!0);let E=(null==(e=this.mainFragLoading)?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&E&&isMediaFragment(p)&&!p.endList&&(!o.live||!this.loadingParts&&m<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(E)===FragmentState.OK&&(this.mainFragLoading=E=null),E&&isMediaFragment(E))){if(p.start>E.end){const e=this.fragmentTracker.getFragAtPos(m,PlaylistLevelType.MAIN);e&&e.end>E.end&&(E=e,this.mainFragLoading={frag:e,targetBufferTime:null})}if(p.start>E.end)return}this.loadFragment(p,a,m)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map((e=>new Level(e)))}onAudioTrackSwitching(e,t){const s=!!t.url;this.trackId=t.id;const{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),s?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==State.STOPPED&&(this.setInterval(100),this.state=State.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(Events.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(e,t){var s;const{levels:r}=this,{details:i,id:n,groupId:a,track:o}=t;if(!r)return void this.warn(`Audio tracks reset while loading track ${n} "${o.name}" of "${a}"`);const l=this.mainDetails;if(!l||i.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=t,void(this.state!==State.STOPPED&&(this.state=State.WAITING_TRACK));this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${o.name}" of "${a}" loaded [${i.startSN},${i.endSN}]${i.lastPartSn?`[part-${i.lastPartSn}-${i.lastPartIndex}]`:""},duration:${i.totalduration}`);const d=r[n];let h=0;if(i.live||null!=(s=d.details)&&s.live){if(this.checkLiveUpdate(i),i.deltaUpdateFailed)return;var c;if(d.details)h=this.alignPlaylists(i,d.details,null==(c=this.levelLastLoaded)?void 0:c.details);i.alignedSliding||(alignDiscontinuities(i,l),i.alignedSliding||alignMediaPlaylistByPDT(i,l),h=i.fragmentStart)}d.details=i,this.levelLastLoaded=d,this.startFragRequested||this.setStartPosition(l,h),this.hls.trigger(Events.AUDIO_TRACK_UPDATED,{details:i,id:n,groupId:t.groupId}),this.state!==State.WAITING_TRACK||this.waitForCdnTuneIn(i)||(this.state=State.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:r,payload:i}=e,{config:n,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const d=l.details;if(!d)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(s.start);const h=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let c=this.transmuxer;c||(c=this.transmuxer=new TransmuxerInterface(this.hls,PlaylistLevelType.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const u=this.initPTS[s.cc],f=null==(t=s.initSegment)?void 0:t.data;if(void 0!==u){const e=!1,t=r?r.index:-1,n=-1!==t,a=new ChunkMetadata(s.level,s.sn,s.stats.chunkCount,i.byteLength,t,n);c.push(i,f,h,"",s,r,d.totalduration,e,a,u)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${d.startSN} ,${d.endSN}],track ${a}`);const{cache:e}=this.waitingData=this.waitingData||{frag:s,part:r,cache:new ChunkCache,complete:!1};e.push(new Uint8Array(i)),this.state!==State.STOPPED&&(this.state=State.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===PlaylistLevelType.MAIN&&isMediaFragment(t.frag)&&(this.mainFragLoading=t,this.state===State.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:s,part:r}=t;if(s.type===PlaylistLevelType.AUDIO)if(this.fragContextChanged(s))this.warn(`Fragment ${s.sn}${r?" p: "+r.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if(isMediaFragment(s)){this.fragPrevious=s;const e=this.switchingTrack;e&&(this.bufferedTrack=e,this.switchingTrack=null,this.hls.trigger(Events.AUDIO_TRACK_SWITCHED,_objectSpread2({},e)))}this.fragBufferedComplete(s,r),this.media&&this.tick()}else this.audioOnly||s.type!==PlaylistLevelType.MAIN||s.elementaryStreams.video||s.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}onError(e,t){var s;if(t.fatal)this.state=State.ERROR;else switch(t.details){case ErrorDetails.FRAG_GAP:case ErrorDetails.FRAG_PARSING_ERROR:case ErrorDetails.FRAG_DECRYPT_ERROR:case ErrorDetails.FRAG_LOAD_ERROR:case ErrorDetails.FRAG_LOAD_TIMEOUT:case ErrorDetails.KEY_LOAD_ERROR:case ErrorDetails.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(PlaylistLevelType.AUDIO,t);break;case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:case ErrorDetails.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==State.WAITING_TRACK||(null==(s=t.context)?void 0:s.type)!==PlaylistContextType.AUDIO_TRACK||(this.state=State.IDLE);break;case ErrorDetails.BUFFER_ADD_CODEC_ERROR:case ErrorDetails.BUFFER_APPEND_ERROR:if("audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case ErrorDetails.BUFFER_FULL_ERROR:if("audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case ErrorDetails.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushing(e,{type:t}){t!==ElementaryStreamTypes.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==ElementaryStreamTypes.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===State.ENDED&&(this.state=State.IDLE);const e=this.mediaBuffer||this.media;e&&(this.afterBufferFlushed(e,t,PlaylistLevelType.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const s="audio",{hls:r}=this,{remuxResult:i,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:d}=a,{details:h}=d,{audio:c,text:u,id3:f,initSegment:g}=i;if(!this.fragContextChanged(o)&&h){if(this.state=State.PARSING,this.switchingTrack&&c&&this.completeAudioSwitch(this.switchingTrack),null!=g&&g.tracks){const e=o.initSegment||o;if(this.unhandledEncryptionError(g,o))return;this._bufferInitSegment(d,g.tracks,e,n),r.trigger(Events.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:s,tracks:g.tracks})}if(c){const{startPTS:e,endPTS:t,startDTS:s,endDTS:r}=c;l&&(l.elementaryStreams[ElementaryStreamTypes.AUDIO]={startPTS:e,endPTS:t,startDTS:s,endDTS:r}),o.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO,e,t,s,r),this.bufferFragmentData(c,o,l,n)}if(null!=f&&null!=(t=f.samples)&&t.length){const e=_extends({id:s,frag:o,details:h},f);r.trigger(Events.FRAG_PARSING_METADATA,e)}if(u){const e=_extends({id:s,frag:o,details:h},u);r.trigger(Events.FRAG_PARSING_USERDATA,e)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(e,t,s,r){if(this.state!==State.PARSING)return;if(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio)return;const i=t.audio;i.id=PlaylistLevelType.AUDIO;const n=e.audioCodec;this.log(`Init audio buffer, container:${i.container}, codecs[level/parsed]=[${n}/${i.codec}]`),n&&1===n.split(",").length&&(i.levelCodec=n),this.hls.trigger(Events.BUFFER_CODECS,t);const a=i.initSegment;if(null!=a&&a.byteLength){const e={type:"audio",frag:s,part:null,chunkMeta:r,parent:s.type,data:a};this.hls.trigger(Events.BUFFER_APPENDING,e)}this.tickImmediate()}loadFragment(e,t,s){const r=this.fragmentTracker.getState(e);var i;if(this.switchingTrack||r===FragmentState.NOT_LOADED||r===FragmentState.PARTIAL)if(isMediaFragment(e))if(null!=(i=t.details)&&i.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=State.WAITING_INIT_PTS;const s=this.mainDetails;s&&s.fragmentStart!==t.details.fragmentStart&&alignMediaPlaylistByPDT(t.details,s)}else super.loadFragment(e,t,s);else this._loadInitSegment(e,t);else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:s,assocLang:r,characteristics:i,audioCodec:n,channels:a}=this.bufferedTrack;matchesOption({name:t,lang:s,assocLang:r,characteristics:i,audioCodec:n,channels:a},e,audioMatchPredicate)||(useAlternateAudio(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(Events.AUDIO_TRACK_SWITCHED,_objectSpread2({},e))}}class BasePlaylistController extends Logger{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,s){const r=null==t?void 0:t.renditionReports;if(r){let i=-1;for(let s=0;s<r.length;s++){const n=r[s];let a;try{a=new self.URL(n.URI,t.url).href}catch(e){this.warn(`Could not construct new URL for Rendition Report: ${e}`),a=n.URI||""}if(a===e){i=s;break}a===e.substring(0,a.length)&&(i=s)}if(-1!==i){const e=r[i],n=parseInt(e["LAST-MSN"])||t.lastPartSn;let a=parseInt(e["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const e=Math.min(t.age-t.partTarget,t.targetduration);a>=0&&e>t.partTarget&&(a+=1)}const o=s&&getSkipValue(s);return new HlsUrlParameters(n,a>=0?a:void 0,o)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}return e}playlistLoaded(e,t,s){const{details:r,stats:i}=t,n=self.performance.now(),a=i.loading.first?Math.max(0,n-i.loading.first):0;r.advancedDateTime=Date.now()-a;const o=this.hls.config.timelineOffset;if(o!==r.appliedTimelineOffset){const e=Math.max(o||0,0);r.appliedTimelineOffset=e,r.fragments.forEach((t=>{t.setStart(t.playlistOffset+e)}))}if(r.live||null!=s&&s.live){const o="levelInfo"in t?t.levelInfo:t.track;if(r.reloaded(s),s&&r.fragments.length>0){mergeDetails(s,r,this);const e=r.playlistParsingError;if(e){this.warn(e);const s=this.hls;if(!s.config.ignorePlaylistParsingErrors){var l;const{networkDetails:n}=t;return void s.trigger(Events.ERROR,{type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.LEVEL_PARSING_ERROR,fatal:!1,url:r.url,error:e,reason:e.message,level:t.level||void 0,parent:null==(l=r.fragments[0])?void 0:l.type,networkDetails:n,stats:i})}r.playlistParsingError=null}}-1===r.requestScheduled&&(r.requestScheduled=i.loading.start);const d=this.hls.mainForwardBufferInfo,h=d?d.end-d.len:0,c=computeReloadInterval(r,1e3*(r.edge-h));if(r.requestScheduled+c<n?r.requestScheduled=n:r.requestScheduled+=c,this.log(`live playlist ${e} ${r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED"}`),!this.canLoad||!r.live)return;let u,f,g;if(r.canBlockReload&&r.endSN&&r.advanced){const e=this.hls.config.lowLatencyMode,i=r.lastPartSn,a=r.endSN,l=r.lastPartIndex,d=i===a;-1!==l?d?(f=a+1,g=e?0:l):(f=i,g=e?l+1:r.maxPartIndex):f=a+1;const h=r.age,c=h+r.ageHeader;let m=Math.min(c-r.partTarget,1.5*r.targetduration);if(m>0){if(c>3*r.targetduration)this.log(`Playlist last advanced ${h.toFixed(2)}s ago. Omitting segment and part directives.`),f=void 0,g=void 0;else if(null!=s&&s.tuneInGoal&&c-r.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${m} with playlist age: ${r.age}`),m=0;else{const e=Math.floor(m/r.targetduration);if(f+=e,void 0!==g){g+=Math.round(m%r.targetduration/r.partTarget)}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${h.toFixed(2)}s goal: ${m} skip sn ${e} to part ${g}`)}r.tuneInGoal=m}if(u=this.getDeliveryDirectives(r,t.deliveryDirectives,f,g),e||!d)return r.requestScheduled=n,void this.loadingPlaylist(o,u)}else(r.canBlockReload||r.canSkipUntil)&&(u=this.getDeliveryDirectives(r,t.deliveryDirectives,f,g));u&&void 0!==f&&r.canBlockReload&&(r.requestScheduled=i.loading.first+Math.max(c-2*a,c/2)),this.scheduleLoading(o,u,r)}else this.clearTimer()}scheduleLoading(e,t,s){const r=s||e.details;if(!r)return void this.loadingPlaylist(e,t);const i=self.performance.now(),n=r.requestScheduled;if(i>=n)return void this.loadingPlaylist(e,t);const a=n-i;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout((()=>this.loadingPlaylist(e,t)),a)}getDeliveryDirectives(e,t,s,r){let i=getSkipValue(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,r=t.part,i=HlsSkip.No),new HlsUrlParameters(s,r,i)}checkRetry(e){const t=e.details,s=isTimeoutError(e),r=e.errorAction,{action:i,retryCount:n=0,retryConfig:a}=r||{},o=!!r&&!!a&&(i===NetworkErrorAction.RetryRequest||!r.resolved&&i===NetworkErrorAction.SendAlternateToPenaltyBox);if(o){var l;if(n>=a.maxNumRetry)return!1;if(s&&null!=(l=e.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const e=getRetryDelay(a,n);this.clearTimer(),this.timer=self.setTimeout((()=>this.loadPlaylist()),e),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,r.resolved=!0}return o}}function subtitleOptionsIdentical(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s++)if(!mediaAttributesIdentical(e[s].attrs,t[s].attrs))return!1;return!0}function mediaAttributesIdentical(e,t,s){const r=e["STABLE-RENDITION-ID"];return r&&!s?r===t["STABLE-RENDITION-ID"]:!(s||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some((s=>e[s]!==t[s]))}class AudioTrackController extends BasePlaylistController{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Events.LEVEL_LOADING,this.onLevelLoading,this),e.on(Events.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Events.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(Events.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Events.LEVEL_LOADING,this.onLevelLoading,this),e.off(Events.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Events.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(Events.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:s,groupId:r,details:i}=t,n=this.tracksInGroup[s];if(!n||n.groupId!==r)return void this.warn(`Audio track with id:${s} and group:${r} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=t.details,this.log(`Audio track ${s} "${n.name}" lang:${n.lang} group:${r} loaded [${i.startSN}-${i.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.audioGroups||null,r=this.groupIds;let i=this.currentTrack;if(!s||(null==r?void 0:r.length)!==(null==s?void 0:s.length)||null!=s&&s.some((e=>-1===(null==r?void 0:r.indexOf(e))))){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const e=this.tracks.filter((e=>!s||-1!==s.indexOf(e.groupId)));if(e.length)this.selectDefaultTrack&&!e.some((e=>e.default))&&(this.selectDefaultTrack=!1),e.forEach(((e,t)=>{e.id=t}));else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=e;const t=this.hls.config.audioPreference;if(!i&&t){const s=findMatchingOption(t,e,audioMatchPredicate);if(s>-1)i=e[s];else{const e=findMatchingOption(t,this.tracks);i=this.tracks[e]}}let r=this.findTrackId(i);-1===r&&i&&(r=this.findTrackId(null));const a={audioTracks:e};this.log(`Updating audio tracks, ${e.length} track(s) found in group(s): ${null==s?void 0:s.join(",")}`),this.hls.trigger(Events.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==r&&-1===o)this.setAudioTrack(r);else if(e.length&&-1===o){var n;const t=new Error(`No audio track selected for current audio group-ID(s): ${null==(n=this.groupIds)?void 0:n.join(",")} track count: ${e.length}`);this.warn(t.message),this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}}onError(e,t){!t.fatal&&t.context&&(t.context.type!==PlaylistContextType.AUDIO_TRACK||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const r=this.currentTrack;if(r&&matchesOption(e,r,audioMatchPredicate))return r;const i=findMatchingOption(e,this.tracksInGroup,audioMatchPredicate);if(i>-1){const e=this.tracksInGroup[i];return this.setAudioTrack(i),e}if(r){let r=t.loadLevel;-1===r&&(r=t.firstAutoLevel);const i=findClosestLevelWithAudioGroup(e,t.levels,s,r,audioMatchPredicate);if(-1===i)return null;t.nextLoadLevel=i}if(e.channels||e.audioCodec){const t=findMatchingOption(e,s);if(t>-1)return s[t]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length)return void this.warn(`Invalid audio track id: ${e}`);this.selectDefaultTrack=!1;const s=this.currentTrack,r=t[e],i=r.details&&!r.details.live;if(e===this.trackId&&r===s&&i)return;if(this.log(`Switching to audio-track ${e} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=e,this.currentTrack=r,this.hls.trigger(Events.AUDIO_TRACK_SWITCHING,_objectSpread2({},r)),i)return;const n=this.switchParams(r.url,null==s?void 0:s.details,r.details);this.loadPlaylist(n)}findTrackId(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const r=t[s];if((!this.selectDefaultTrack||r.default)&&(!e||matchesOption(e,r,audioMatchPredicate)))return s}if(e){const{name:s,lang:r,assocLang:i,characteristics:n,audioCodec:a,channels:o}=e;for(let e=0;e<t.length;e++){if(matchesOption({name:s,lang:r,assocLang:i,characteristics:n,audioCodec:a,channels:o},t[e],audioMatchPredicate))return e}for(let s=0;s<t.length;s++){const r=t[s];if(mediaAttributesIdentical(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<t.length;s++){const r=t[s];if(mediaAttributesIdentical(e.attrs,r.attrs,["LANGUAGE"]))return s}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&useAlternateAudio(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,r=e.groupId,i=this.getUrlWithDirectives(e.url,t),n=e.details,a=null==n?void 0:n.age;this.log(`Loading audio-track ${s} "${e.name}" lang:${e.lang} group:${r}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${i}`),this.hls.trigger(Events.AUDIO_TRACK_LOADING,{url:i,id:s,groupId:r,deliveryDirectives:t||null,track:e})}}class BufferOperationQueue{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,s){if(null===this.queues||null===this.tracks)return;const r=this.queues[t];r.push(e),1!==r.length||s||this.executeNext(t)}appendBlocker(e){return new Promise((t=>{const s={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,e)}))}prependBlocker(e){return new Promise((t=>{if(this.queues){const s={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(s)}}))}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach((e=>{var t;const s=null==(t=e[0])?void 0:t.label;"async-blocker"!==s&&"async-blocker-prepend"!==s||(e[0].execute(),e.splice(0,1))}))}unblockAudio(e){if(null===this.queues)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(null===this.queues||null===this.tracks)return;const t=this.queues[e];if(t.length){const r=t[0];try{r.execute()}catch(t){var s;if(r.onError(t),null===this.queues||null===this.tracks)return;const i=null==(s=this.tracks[e])?void 0:s.buffer;null!=i&&i.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){null!==this.queues&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return(null==(t=this.queues)?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return null===e||null===t?"<destroyed>":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(e){var t,s;return null!=(t=this.queues)&&t[e]||null!=(s=this.tracks)&&s[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const s=null==(t=this.tracks)?void 0:t[e],r=null==s?void 0:s.buffer;return r?`SourceBuffer${r.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(e){var t;return(null==(t=this.queues)?void 0:t[e].map((e=>e.label)).join(", "))||""}}const VIDEO_CODEC_PROFILE_REPLACE=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,TRACK_REMOVED_ERROR_NAME="HlsJsTrackRemovedError";class HlsJsTrackRemovedError extends Error{constructor(e){super(e),this.name="HlsJsTrackRemovedError"}}class BufferController extends Logger{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=e=>{var t;this.hls&&"open"===(null==(t=this.mediaSource)?void 0:t.readyState)&&this.hls.pauseBuffering()},this._onStartStreaming=e=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=e=>{const{media:t,mediaSource:s}=this;e&&this.log("Media source opened"),t&&s&&(s.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(Events.MEDIA_ATTACHED,{media:t,mediaSource:s}),null!==this.mediaSource&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:e,_objectUrl:t}=this;e!==t&&this.error(`Media element src was set while attaching MediaSource (${t} > ${e})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=isManagedMediaSource(getMediaSource(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Events.BUFFER_RESET,this.onBufferReset,this),e.on(Events.BUFFER_APPENDING,this.onBufferAppending,this),e.on(Events.BUFFER_CODECS,this.onBufferCodecs,this),e.on(Events.BUFFER_EOS,this.onBufferEos,this),e.on(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Events.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Events.FRAG_PARSED,this.onFragParsed,this),e.on(Events.FRAG_CHANGED,this.onFragChanged,this),e.on(Events.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Events.BUFFER_RESET,this.onBufferReset,this),e.off(Events.BUFFER_APPENDING,this.onBufferAppending,this),e.off(Events.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Events.BUFFER_EOS,this.onBufferEos,this),e.off(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Events.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Events.FRAG_PARSED,this.onFragParsed,this),e.off(Events.FRAG_CHANGED,this.onFragChanged,this),e.off(Events.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const s={};if(this.operationQueue){const e=this.isUpdating();e||this.operationQueue.removeBlockers();const t=this.isQueued();(e||t)&&this.warn(`Transfering MediaSource with${t?" operations in queue":""}${e?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const r=this.transferData;return!this.sourceBufferCount&&r&&r.mediaSource===t?_extends(s,r.tracks):this.sourceBuffers.forEach((e=>{const[t]=e;t&&(s[t]=_extends({},this.tracks[t]),this.removeBuffer(t)),e[0]=e[1]=null})),{media:e,mediaSource:t,tracks:s}}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(e,t){var s;let r=2;(t.audio&&!t.video||!t.altAudio)&&(r=1),this.bufferCodecEventsTotal=r,this.log(`${r} bufferCodec event(s) expected.`),null!=(s=this.transferData)&&s.mediaSource&&this.sourceBufferCount&&r&&this.bufferCreated()}onMediaAttaching(e,t){const s=this.media=t.media;this.transferData=this.overrides=void 0;const r=getMediaSource(this.appendSource);if(r){const e=!!t.mediaSource;(e||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const i=this.mediaSource=t.mediaSource||new r;if(this.assignMediaSource(i),e)this._objectUrl=s.src,this.attachTransferred();else{const e=this._objectUrl=self.URL.createObjectURL(i);if(this.appendSource)try{s.removeAttribute("src");const t=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||t&&i instanceof t,removeSourceChildren(s),addSource(s,e),s.load()}catch(t){s.src=e}else s.src=e}s.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,s;this.log(`${(null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${null==(s=e.constructor)?void 0:s.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const s=this.tracks,r=t.tracks,i=r?Object.keys(r):null,n=i?i.length:0,a=()=>{Promise.resolve().then((()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()}))};if(r&&i&&n){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: ${stringify(s,((e,t)=>"initSegment"===e?void 0:t))};\ntransfer tracks: ${stringify(r,((e,t)=>"initSegment"===e?void 0:t))}}`),!isCompatibleTrackChange(r,s)){t.mediaSource=null,t.tracks=void 0;const i=e.currentTime,n=this.details,a=Math.max(i,(null==n?void 0:n.fragments[0].start)||0);return a-i>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${i} -> ${a}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(r)}"->"${Object.keys(s)}") start time: ${a} currentTime: ${i}`),this.onMediaDetaching(Events.MEDIA_DETACHING,{}),this.onMediaAttaching(Events.MEDIA_ATTACHING,t),void(e.currentTime=a))}this.transferData=void 0,i.forEach((e=>{const t=e,s=r[t];if(s){const e=s.buffer;if(e){const r=this.fragmentTracker,i=s.id;if(r.hasFragments(i)||r.hasParts(i)){const s=BufferHelper.getBuffered(e);r.detectEvictedFragments(t,s,i,null,!0)}const n=sourceBufferNameToIndex(t),a=[t,e];this.sourceBuffers[n]=a,e.updating&&this.operationQueue&&this.operationQueue.prependBlocker(t),this.trackSourceBuffer(t,s)}}})),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var e;const t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}onMediaDetaching(e,t){const s=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:r,mediaSource:i,_objectUrl:n}=this;if(i){if(this.log("media source "+(s?"transferring":"detaching")),s)this.sourceBuffers.forEach((([e])=>{e&&this.removeBuffer(e)})),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const e="open"===i.readyState;try{const t=i.sourceBuffers;for(let s=t.length;s--;)e&&t[s].abort(),i.removeSourceBuffer(t[s]);e&&i.endOfStream()}catch(e){this.warn(`onMediaDetaching: ${e.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}i.removeEventListener("sourceopen",this._onMediaSourceOpen),i.removeEventListener("sourceended",this._onMediaSourceEnded),i.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(i.removeEventListener("startstreaming",this._onStartStreaming),i.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}r&&(r.removeEventListener("emptied",this._onMediaEmptied),s||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(r.removeAttribute("src"),this.appendSource&&removeSourceChildren(r),r.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null)}onBufferReset(){this.sourceBuffers.forEach((([e])=>{e&&this.resetBuffer(e)})),this.initTracks()}resetBuffer(e){var t;const s=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),s)try{var r;null!=(r=this.mediaSource)&&r.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(t){this.warn(`onBufferReset ${e}`,t)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[sourceBufferNameToIndex(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new BufferOperationQueue(this.tracks)}onBufferCodecs(e,t){var s;const r=this.tracks,i=Object.keys(t);this.log(`BUFFER_CODECS: "${i}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in t&&(r.audio||r.video)||r.audiovideo&&("audio"in t||"video"in t),a=!n&&this.sourceBufferCount&&this.media&&i.some((e=>!r[e]));n||a?this.warn(`Unsupported transition between "${Object.keys(r)}" and "${i}" SourceBuffers`):(i.forEach((e=>{var s,i;const n=t[e],{id:a,codec:o,levelCodec:l,container:d,metadata:h,supplemental:c}=n;let u=r[e];const f=null==(s=this.transferData)||null==(s=s.tracks)?void 0:s[e],g=null!=f&&f.buffer?f:u,m=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),p=null==g?void 0:g.levelCodec;u||(u=r[e]={buffer:void 0,listeners:[],codec:o,supplemental:c,container:d,levelCodec:l,metadata:h,id:a});const E=pickMostCompleteCodecName(m,p),y=null==E?void 0:E.replace(VIDEO_CODEC_PROFILE_REPLACE,"$1");let v=pickMostCompleteCodecName(o,l);const T=null==(i=v)?void 0:i.replace(VIDEO_CODEC_PROFILE_REPLACE,"$1");v&&E&&y!==T&&("audio"===e.slice(0,5)&&(v=getCodecCompatibleName(v,this.appendSource)),this.log(`switching codec ${m} to ${v}`),v!==(u.pendingCodec||u.codec)&&(u.pendingCodec=v),u.container=d,this.appendChangeType(e,d,v))})),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&"main"===(null==(s=t.audio)?void 0:s.id)&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))}get sourceBufferTracks(){return Object.keys(this.tracks).reduce(((e,t)=>{const s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e}),{})}appendChangeType(e,t,s){const r=`${t};codecs=${s}`,i={label:`change-type=${r}`,execute:()=>{const i=this.tracks[e];if(i){const n=i.buffer;null!=n&&n.changeType&&(this.log(`changing ${e} sourceBuffer type to ${r}`),n.changeType(r),i.codec=s,i.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn(`Failed to change ${e} SourceBuffer type`,t)}};this.append(i,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const s=e.start,r=s+.05*e.duration;if(!0===(null==(t=this.fragmentTracker.getAppendedFrag(s,PlaylistLevelType.MAIN))?void 0:t.gap))return;const i={label:"block-audio",execute:()=>{var e;const t=this.tracks.video;(this.lastVideoAppendEnd>r||null!=t&&t.buffer&&BufferHelper.isBuffered(t.buffer,r)||!0===(null==(e=this.fragmentTracker.getAppendedFrag(r,PlaylistLevelType.MAIN))?void 0:e.gap))&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn("Error executing block-audio operation",e)}};this.blockedAudioAppend={op:i,frag:e},this.append(i,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:s}=this,{data:r,type:i,parent:n,frag:a,part:o,chunkMeta:l,offset:d}=t,h=l.buffering[i],{sn:c,cc:u}=a,f=self.performance.now();h.start=f;const g=a.stats.buffering,m=o?o.stats.buffering:null;0===g.start&&(g.start=f),m&&0===m.start&&(m.start=f);const p=s.audio;let E=!1;"audio"===i&&"audio/mpeg"===(null==p?void 0:p.container)&&(E=!this.lastMpegAudioChunk||1===l.id||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const y=s.video,v=null==y?void 0:y.buffer;if(v&&"initSegment"!==c){const e=o||a,t=this.blockedAudioAppend;if("audio"!==i||"main"===n||this.blockedAudioAppend||y.ending||y.ended){if("video"===i){const s=e.end;if(t){const e=t.frag.start;(s>e||s<this.lastVideoAppendEnd||BufferHelper.isBuffered(v,e))&&this.unblockAudio()}this.lastVideoAppendEnd=s}}else{const t=e.start+.05*e.duration,s=v.buffered,r=this.currentOp("video");s.length||r?!r&&!BufferHelper.isBuffered(v,t)&&this.lastVideoAppendEnd<t&&this.blockAudio(e):this.blockAudio(e)}}const T=(o||a).start,S={label:`append-${i}`,execute:()=>{var e;h.executeStart=self.performance.now();const t=null==(e=this.tracks[i])?void 0:e.buffer;t&&(E?this.updateTimestampOffset(t,T,.1,i,c,u):void 0!==d&&isFiniteNumber(d)&&this.updateTimestampOffset(t,d,1e-6,i,c,u)),this.appendExecutor(r,i)},onStart:()=>{},onComplete:()=>{const e=self.performance.now();h.executeEnd=h.end=e,0===g.first&&(g.first=e),m&&0===m.first&&(m.first=e);const t={};this.sourceBuffers.forEach((([e,s])=>{e&&(t[e]=BufferHelper.getBuffered(s))})),this.appendErrors[i]=0,"audio"===i||"video"===i?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(Events.BUFFER_APPENDED,{type:i,frag:a,part:o,chunkMeta:l,parent:a.type,timeRanges:t})},onError:e=>{var t;const s={type:ErrorTypes.MEDIA_ERROR,parent:a.type,details:ErrorDetails.BUFFER_APPEND_ERROR,sourceBufferName:i,frag:a,part:o,chunkMeta:l,error:e,err:e,fatal:!1},r=null==(t=this.media)?void 0:t.error;if(e.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==e.name||"quota"in e)s.details=ErrorDetails.BUFFER_FULL_ERROR;else if(e.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!r)s.errorAction=createDoNothingErrorAction(!0);else if("HlsJsTrackRemovedError"===e.name&&0===this.sourceBufferCount)s.errorAction=createDoNothingErrorAction(!0);else{const e=++this.appendErrors[i];this.warn(`Failed ${e}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${i}" sourceBuffer (${r||"no media error"})`),(e>=this.hls.config.appendErrorMaxRetry||r)&&(s.fatal=!0)}this.hls.trigger(Events.ERROR,s)}};this.log(`queuing "${i}" append sn: ${c}${o?" p: "+o.index:""} of ${a.type===PlaylistLevelType.MAIN?"level":"track"} ${a.level} cc: ${u}`),this.append(S,i,this.isPending(this.tracks[i]))}getFlushOp(e,t,s){return this.log(`queuing "${e}" remove ${t}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{this.hls.trigger(Events.BUFFER_FLUSHED,{type:e})},onError:r=>{this.warn(`Failed to remove ${t}-${s} from "${e}" SourceBuffer`,r)}}}onBufferFlushing(e,t){const{type:s,startOffset:r,endOffset:i}=t;s?this.append(this.getFlushOp(s,r,i),s):this.sourceBuffers.forEach((([e])=>{e&&this.append(this.getFlushOp(e,r,i),e)}))}onFragParsed(e,t){const{frag:s,part:r}=t,i=[],n=r?r.elementaryStreams:s.elementaryStreams;n[ElementaryStreamTypes.AUDIOVIDEO]?i.push("audiovideo"):(n[ElementaryStreamTypes.AUDIO]&&i.push("audio"),n[ElementaryStreamTypes.VIDEO]&&i.push("video"));0===i.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers((()=>{const e=self.performance.now();s.stats.buffering.end=e,r&&(r.stats.buffering.end=e);const t=r?r.stats:s.stats;this.hls.trigger(Events.FRAG_BUFFERED,{frag:s,part:r,stats:t,id:s.type})}),i).catch((e=>{this.warn(`Fragment buffered callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)}))}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some((([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1}))}onBufferEos(e,t){var s;this.sourceBuffers.forEach((([e])=>{if(e){const s=this.tracks[e];t.type&&t.type!==e||(s.ending=!0,s.ended||(s.ended=!0,this.log(`${e} buffer reached EOS`)))}}));const r=!1!==(null==(s=this.overrides)?void 0:s.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some((([e])=>{var t;return e&&!(null!=(t=this.tracks[e])&&t.ended)}))?r?(this.log("Queueing EOS"),this.blockUntilOpen((()=>{this.tracksEnded();const{mediaSource:e}=this;e&&"open"===e.readyState?(this.log("Calling mediaSource.endOfStream()"),e.endOfStream(),this.hls.trigger(Events.BUFFERED_TO_END,void 0)):e&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`)}))):(this.tracksEnded(),this.hls.trigger(Events.BUFFERED_TO_END,void 0)):"video"===t.type&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach((([e])=>{if(null!==e){const t=this.tracks[e];t&&(t.ending=!1)}}))}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen((()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)}))}onError(e,t){if(t.details===ErrorDetails.BUFFER_APPEND_ERROR&&t.frag){var s;const e=null==(s=t.errorAction)?void 0:s.nextAutoLevel;isFiniteNumber(e)&&e!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:s}=this;if(!s||null===t)return;if(!this.sourceBufferCount)return;const r=e.config,i=s.currentTime,n=t.levelTargetDuration,a=t.live&&null!==r.liveBackBufferLength?r.liveBackBufferLength:r.backBufferLength;if(isFiniteNumber(a)&&a>=0){const e=Math.max(a,n),t=Math.floor(i/n)*n-e;this.flushBackBuffer(i,n,t)}const o=r.frontBufferFlushThreshold;if(isFiniteNumber(o)&&o>0){const e=Math.max(r.maxBufferLength,o),t=Math.max(e,n),s=Math.floor(i/n)*n+t;this.flushFrontBuffer(i,n,s)}}flushBackBuffer(e,t,s){this.sourceBuffers.forEach((([e,t])=>{if(t){const i=BufferHelper.getBuffered(t);if(i.length>0&&s>i.start(0)){var r;this.hls.trigger(Events.BACK_BUFFER_REACHED,{bufferEnd:s});const t=this.tracks[e];if(null!=(r=this.details)&&r.live)this.hls.trigger(Events.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(null!=t&&t.ended)return void this.log(`Cannot flush ${e} back buffer while SourceBuffer is in ended state`);this.hls.trigger(Events.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:e})}}}))}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach((([t,r])=>{if(r){const i=BufferHelper.getBuffered(r),n=i.length;if(n<2)return;const a=i.start(n-1),o=i.end(n-1);if(s>a||e>=a&&e<=o)return;this.hls.trigger(Events.BUFFER_FLUSHING,{startOffset:a,endOffset:1/0,type:t})}}))}getDurationAndRange(){var e;const{details:t,mediaSource:s}=this;if(!t||!this.media||"open"!==(null==s?void 0:s.readyState))return null;const r=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&s.setLiveSeekableRange){const e=Math.max(0,t.fragmentStart);return{duration:1/0,start:e,end:Math.max(e,r)}}return{duration:1/0}}const i=null==(e=this.overrides)?void 0:e.duration;if(i)return isFiniteNumber(i)?{duration:i}:null;const n=this.media.duration;return r>(isFiniteNumber(s.duration)?s.duration:0)&&r>n||!isFiniteNumber(n)?{duration:r}:null}updateMediaSource({duration:e,start:t,end:s}){const r=this.mediaSource;this.media&&r&&"open"===r.readyState&&(r.duration!==e&&(isFiniteNumber(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),r.duration=e),void 0!==t&&void 0!==s&&(this.log(`MediaSource duration is set to ${r.duration}. Setting seekable range to ${t}-${s}.`),r.setLiveSeekableRange(t,s)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${stringify(s)}`),this.tracksReady){var r;const e=null==(r=this.transferData)?void 0:r.tracks;e&&Object.keys(e).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach((([t,s])=>{if(t){const r=this.tracks[t];e[t]={buffer:s,container:r.container,codec:r.codec,supplemental:r.supplemental,levelCodec:r.levelCodec,id:r.id,metadata:r.metadata}}})),this.hls.trigger(Events.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach((([e])=>{this.executeNext(e)}))}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const i in e){const n=i,a=e[n];if(this.isPending(a)){const e=this.getTrackCodec(a,n),i=`${a.container};codecs=${e}`;a.codec=e,this.log(`creating sourceBuffer(${i})${this.currentOp(n)?" Queued":""} ${stringify(a)}`);try{const e=s.addSourceBuffer(i),r=sourceBufferNameToIndex(n),o=[n,e];t[r]=o,a.buffer=e}catch(e){var r;return this.error(`error while trying to add sourceBuffer: ${e.message}`),this.shiftAndExecuteNext(n),null==(r=this.operationQueue)||r.removeBlockers(),delete this.tracks[n],void this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:n,mimeType:i,parent:a.id})}this.trackSourceBuffer(n,a)}}this.bufferCreated()}getTrackCodec(e,t){const s=e.supplemental;let r=e.codec;s&&("video"===t||"audiovideo"===t)&&areCodecsMediaSourceSupported(s,"video")&&(r=replaceVideoCodec(r,s));const i=pickMostCompleteCodecName(r,e.levelCodec);return i?"audio"===t.slice(0,5)?getCodecCompatibleName(i,this.appendSource):i:""}trackSourceBuffer(e,t){const s=t.buffer;if(!s)return;const r=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,codec:r,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",((e,t)=>{const s=t.removedRanges;null!=s&&s.length&&this.hls.trigger(Events.BUFFER_FLUSHED,{type:e})}))}get mediaSrc(){var e,t;const s=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==s?void 0:s.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if("closed"===(null==(t=this.mediaSource)?void 0:t.readyState))return void this.resetBuffer(e);const s=this.currentOp(e);s&&(s.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var s;const r=new Error(`${e} SourceBuffer error. MediaSource readyState: ${null==(s=this.mediaSource)?void 0:s.readyState}`);this.error(`${r}`,t),this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});const i=this.currentOp(e);i&&i.onError(r)}updateTimestampOffset(e,t,s,r,i,n){const a=t-e.timestampOffset;Math.abs(a)>=s&&(this.log(`Updating ${r} SourceBuffer timestampOffset to ${t} (sn: ${i} cc: ${n})`),e.timestampOffset=t)}removeExecutor(e,t,s){const{media:r,mediaSource:i}=this,n=this.tracks[e],a=null==n?void 0:n.buffer;if(!r||!i||!a)return this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),void this.shiftAndExecuteNext(e);const o=isFiniteNumber(r.duration)?r.duration:1/0,l=isFiniteNumber(i.duration)?i.duration:1/0,d=Math.max(0,t),h=Math.min(s,o,l);h>d&&(!n.ending||n.ended)?(n.ended=!1,this.log(`Removing [${d},${h}] from the ${e} SourceBuffer`),a.remove(d,h)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const s=this.tracks[t],r=null==s?void 0:s.buffer;if(!r)throw new HlsJsTrackRemovedError(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);s.ending=!1,s.ended=!1,r.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch((e=>{this.warn(`SourceBuffer blocked callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)}));else try{e()}catch(e){this.warn(`Callback run without blocking ${this.operationQueue} ${e}`)}}isUpdating(){return this.sourceBuffers.some((([e,t])=>e&&t.updating))}isQueued(){return this.sourceBuffers.some((([e])=>e&&!!this.currentOp(e)))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:s}=this,r=t.map((e=>this.appendBlocker(e)));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(r).then((t=>{s===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))}))}stepOperationQueue(e){e.forEach((e=>{var t;const s=null==(t=this.tracks[e])?void 0:t.buffer;s&&!s.updating&&this.shiftAndExecuteNext(e)}))}append(e,t,s){this.operationQueue&&this.operationQueue.append(e,t,s)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce(((e,t)=>e+(this.isPending(this.tracks[t])?1:0)),0)}get sourceBufferCount(){return this.sourceBuffers.reduce(((e,[t])=>e+(t?1:0)),0)}get sourceBufferTypes(){return this.sourceBuffers.map((([e])=>e)).filter((e=>!!e))}addBufferListener(e,t,s){const r=this.tracks[e];if(!r)return;const i=r.buffer;if(!i)return;const n=s.bind(this,e);r.listeners.push({event:t,listener:n}),i.addEventListener(t,n)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const s=t.buffer;s&&(t.listeners.forEach((e=>{s.removeEventListener(e.event,e.listener)})),t.listeners.length=0)}}function removeSourceChildren(e){const t=e.querySelectorAll("source");[].slice.call(t).forEach((t=>{e.removeChild(t)}))}function addSource(e,t){const s=self.document.createElement("source");s.type="video/mp4",s.src=t,e.appendChild(s)}function sourceBufferNameToIndex(e){return"audio"===e?1:0}class CapLevelController{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(Events.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Events.BUFFER_CODECS,this.onBufferCodecs,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(Events.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Events.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const s=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,s.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&isFiniteNumber(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const e=this.hls.levels;if(e.length){const t=this.hls,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const s=t.filter(((t,s)=>this.isLevelAllowed(t)&&s<=e));return this.clientRect=null,CapLevelController.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,t.width||t.height||(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(e){}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some((t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height))}static getMaxLevelByMediaSize(e,t,s){if(null==e||!e.length)return-1;let r=e.length-1;const i=Math.max(t,s);for(let t=0;t<e.length;t+=1){const s=e[t];if((s.width>=i||s.height>=i)&&(n=s,!(a=e[t+1])||n.width!==a.width||n.height!==a.height)){r=t;break}}var n,a;return r}}const CmObjectType={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},CmcdObjectType=CmObjectType,CmStreamingFormat={HLS:"h"},CmcdStreamingFormat=CmStreamingFormat;class SfItem{constructor(e,t){Array.isArray(e)&&(e=e.map((e=>e instanceof SfItem?e:new SfItem(e)))),this.value=e,this.params=t}}const DICT="Dict";function format(e){return Array.isArray(e)?JSON.stringify(e):e instanceof Map?"Map{}":e instanceof Set?"Set{}":"object"==typeof e?JSON.stringify(e):String(e)}function throwError(e,t,s,r){return new Error(`failed to ${e} "${format(t)}" as ${s}`,{cause:r})}function serializeError(e,t,s){return throwError("serialize",e,t,s)}class SfToken{constructor(e){this.description=e}}const BARE_ITEM="Bare Item",BOOLEAN="Boolean";function serializeBoolean(e){if("boolean"!=typeof e)throw serializeError(e,BOOLEAN);return e?"?1":"?0"}function encodeBase64(e){return btoa(String.fromCharCode(...e))}const BYTES="Byte Sequence";function serializeByteSequence(e){if(!1===ArrayBuffer.isView(e))throw serializeError(e,BYTES);return`:${encodeBase64(e)}:`}const INTEGER="Integer";function isInvalidInt(e){return e<-999999999999999||999999999999999<e}function serializeInteger(e){if(isInvalidInt(e))throw serializeError(e,INTEGER);return e.toString()}function serializeDate(e){return`@${serializeInteger(e.getTime()/1e3)}`}function roundToEven(e,t){if(e<0)return-roundToEven(-e,t);const s=Math.pow(10,t);if(Math.abs(e*s%1-.5)<Number.EPSILON){const t=Math.floor(e*s);return(t%2==0?t:t+1)/s}return Math.round(e*s)/s}const DECIMAL="Decimal";function serializeDecimal(e){const t=roundToEven(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw serializeError(e,DECIMAL);const s=t.toString();return s.includes(".")?s:`${s}.0`}const STRING="String",STRING_REGEX=/[\x00-\x1f\x7f]+/;function serializeString(e){if(STRING_REGEX.test(e))throw serializeError(e,STRING);return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function symbolToStr(e){return e.description||e.toString().slice(7,-1)}const TOKEN="Token";function serializeToken(e){const t=symbolToStr(e);if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t))throw serializeError(t,TOKEN);return t}function serializeBareItem(e){switch(typeof e){case"number":if(!isFiniteNumber(e))throw serializeError(e,BARE_ITEM);return Number.isInteger(e)?serializeInteger(e):serializeDecimal(e);case"string":return serializeString(e);case"symbol":return serializeToken(e);case"boolean":return serializeBoolean(e);case"object":if(e instanceof Date)return serializeDate(e);if(e instanceof Uint8Array)return serializeByteSequence(e);if(e instanceof SfToken)return serializeToken(e);default:throw serializeError(e,BARE_ITEM)}}const KEY="Key";function serializeKey(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw serializeError(e,KEY);return e}function serializeParams(e){return null==e?"":Object.entries(e).map((([e,t])=>!0===t?`;${serializeKey(e)}`:`;${serializeKey(e)}=${serializeBareItem(t)}`)).join("")}function serializeItem(e){return e instanceof SfItem?`${serializeBareItem(e.value)}${serializeParams(e.params)}`:serializeBareItem(e)}function serializeInnerList(e){return`(${e.value.map(serializeItem).join(" ")})${serializeParams(e.params)}`}function serializeDict(e,t={whitespace:!0}){if("object"!=typeof e||null==e)throw serializeError(e,DICT);const s=e instanceof Map?e.entries():Object.entries(e),r=(null==t?void 0:t.whitespace)?" ":"";return Array.from(s).map((([e,t])=>{t instanceof SfItem==!1&&(t=new SfItem(t));let s=serializeKey(e);return!0===t.value?s+=serializeParams(t.params):(s+="=",Array.isArray(t.value)?s+=serializeInnerList(t):s+=serializeItem(t)),s})).join(`,${r}`)}function encodeSfDict(e,t){return serializeDict(e,t)}const CMCD_OBJECT="CMCD-Object",CMCD_REQUEST="CMCD-Request",CMCD_SESSION="CMCD-Session",CMCD_STATUS="CMCD-Status",CMCD_HEADER_MAP={br:CMCD_OBJECT,ab:CMCD_OBJECT,d:CMCD_OBJECT,ot:CMCD_OBJECT,tb:CMCD_OBJECT,tpb:CMCD_OBJECT,lb:CMCD_OBJECT,tab:CMCD_OBJECT,lab:CMCD_OBJECT,url:CMCD_OBJECT,pb:CMCD_REQUEST,bl:CMCD_REQUEST,tbl:CMCD_REQUEST,dl:CMCD_REQUEST,ltc:CMCD_REQUEST,mtp:CMCD_REQUEST,nor:CMCD_REQUEST,nrr:CMCD_REQUEST,rc:CMCD_REQUEST,sn:CMCD_REQUEST,sta:CMCD_REQUEST,su:CMCD_REQUEST,ttfb:CMCD_REQUEST,ttfbb:CMCD_REQUEST,ttlb:CMCD_REQUEST,cmsdd:CMCD_REQUEST,cmsds:CMCD_REQUEST,smrt:CMCD_REQUEST,df:CMCD_REQUEST,cs:CMCD_REQUEST,ts:CMCD_REQUEST,cid:CMCD_SESSION,pr:CMCD_SESSION,sf:CMCD_SESSION,sid:CMCD_SESSION,st:CMCD_SESSION,v:CMCD_SESSION,msd:CMCD_SESSION,bs:CMCD_STATUS,bsd:CMCD_STATUS,cdn:CMCD_STATUS,rtp:CMCD_STATUS,bg:CMCD_STATUS,pt:CMCD_STATUS,ec:CMCD_STATUS,e:CMCD_STATUS},CmcdHeaderField={REQUEST:CMCD_REQUEST};function createHeaderMap(e){return Object.keys(e).reduce(((t,s)=>{var r;return null===(r=e[s])||void 0===r||r.forEach((e=>t[e]=s)),t}),{})}function groupCmcdHeaders(e,t){const s={};if(!e)return s;const r=Object.keys(e),i=t?createHeaderMap(t):{};return r.reduce(((t,s)=>{var r;const n=CMCD_HEADER_MAP[s]||i[s]||CmcdHeaderField.REQUEST;return(null!==(r=t[n])&&void 0!==r?r:t[n]={})[s]=e[s],t}),s)}function isTokenField(e){return["ot","sf","st","e","sta"].includes(e)}function isValid(e){return"number"==typeof e?isFiniteNumber(e):null!=e&&""!==e&&!1!==e}const CMCD_EVENT_MODE="event";function urlToRelativePath(e,t){const s=new URL(e),r=new URL(t);if(s.origin!==r.origin)return e;const i=s.pathname.split("/").slice(1),n=r.pathname.split("/").slice(1,-1);for(;i[0]===n[0];)i.shift(),n.shift();for(;n.length;)n.shift(),i.unshift("..");return i.join("/")+s.search+s.hash}const toRounded=e=>Math.round(e),toUrlSafe=(e,t)=>Array.isArray(e)?e.map((e=>toUrlSafe(e,t))):e instanceof SfItem&&"string"==typeof e.value?new SfItem(toUrlSafe(e.value,t),e.params):(t.baseUrl&&(e=urlToRelativePath(e,t.baseUrl)),1===t.version?encodeURIComponent(e):e),toHundred=e=>100*toRounded(e/100),nor=(e,t)=>{let s=e;return t.version>=2&&(e instanceof SfItem&&"string"==typeof e.value?s=new SfItem([e]):"string"==typeof e&&(s=[e])),toUrlSafe(s,t)},CMCD_FORMATTER_MAP={br:toRounded,d:toRounded,bl:toHundred,dl:toHundred,mtp:toHundred,nor:nor,rtp:toHundred,tb:toRounded},CMCD_REQUEST_MODE="request",CMCD_RESPONSE_MODE="response",CMCD_COMMON_KEYS=["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"],CMCD_EVENT_KEYS=["e"],CUSTOM_KEY_REGEX=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function isCmcdCustomKey(e){return CUSTOM_KEY_REGEX.test(e)}function isCmcdEventKey(e){return CMCD_COMMON_KEYS.includes(e)||CMCD_EVENT_KEYS.includes(e)||isCmcdCustomKey(e)}const CMCD_REQUEST_KEYS=["d","dl","nor","ot","rtp","su"];function isCmcdRequestKey(e){return CMCD_COMMON_KEYS.includes(e)||CMCD_REQUEST_KEYS.includes(e)||isCmcdCustomKey(e)}const CMCD_RESPONSE_KEYS=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function isCmcdResponseKey(e){return CMCD_COMMON_KEYS.includes(e)||CMCD_REQUEST_KEYS.includes(e)||CMCD_RESPONSE_KEYS.includes(e)||isCmcdCustomKey(e)}const CMCD_V1_KEYS=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function isCmcdV1Key(e){return CMCD_V1_KEYS.includes(e)||isCmcdCustomKey(e)}const filterMap={[CMCD_RESPONSE_MODE]:isCmcdResponseKey,[CMCD_EVENT_MODE]:isCmcdEventKey,[CMCD_REQUEST_MODE]:isCmcdRequestKey};function prepareCmcdData(e,t={}){const s={};if(null==e||"object"!=typeof e)return s;const r=t.version||e.v||1,i=t.reportingMode||CMCD_REQUEST_MODE,n=1===r?isCmcdV1Key:filterMap[i];let a=Object.keys(e).filter(n);const o=t.filter;"function"==typeof o&&(a=a.filter(o));const l=i===CMCD_RESPONSE_MODE||i===CMCD_EVENT_MODE;l&&!a.includes("ts")&&a.push("ts"),r>1&&!a.includes("v")&&a.push("v");const d=_extends({},CMCD_FORMATTER_MAP,t.formatters),h={version:r,reportingMode:i,baseUrl:t.baseUrl};return a.sort().forEach((t=>{let i=e[t];const n=d[t];if("function"==typeof n&&(i=n(i,h)),"v"===t){if(1===r)return;i=r}"pr"==t&&1===i||(l&&"ts"===t&&!isFiniteNumber(i)&&(i=Date.now()),isValid(i)&&(isTokenField(t)&&"string"==typeof i&&(i=new SfToken(i)),s[t]=i))})),s}function toCmcdHeaders(e,t={}){const s={};if(!e)return s;const r=groupCmcdHeaders(prepareCmcdData(e,t),null==t?void 0:t.customHeaderMap);return Object.entries(r).reduce(((e,[t,s])=>{const r=encodeSfDict(s,{whitespace:!1});return r&&(e[t]=r),e}),s)}function appendCmcdHeaders(e,t,s){return _extends(e,toCmcdHeaders(t,s))}const CMCD_PARAM="CMCD";function encodeCmcd(e,t={}){return e?encodeSfDict(prepareCmcdData(e,t),{whitespace:!1}):""}function toCmcdUrl(e,t={}){if(!e)return"";const s=encodeCmcd(e,t);return encodeURIComponent(s)}function toCmcdQuery(e,t={}){if(!e)return"";const s=toCmcdUrl(e,t);return`${CMCD_PARAM}=${s}`}const REGEX=/CMCD=[^&#]+/;function appendCmcdQuery(e,t,s){const r=toCmcdQuery(t,s);if(!r)return e;if(REGEX.test(e))return e.replace(REGEX,r);const i=e.includes("?")?"&":"?";return`${e}${i}${r}`}class CMCDController{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=e=>{try{this.apply(e,{ot:CmcdObjectType.MANIFEST,su:!this.initialized})}catch(e){this.hls.logger.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=e=>{try{const{frag:t,part:s}=e,r=this.hls.levels[t.level],i=this.getObjectType(t),n={d:1e3*(s||t).duration,ot:i};i!==CmcdObjectType.VIDEO&&i!==CmcdObjectType.AUDIO&&i!=CmcdObjectType.MUXED||(n.br=r.bitrate/1e3,n.tb=this.getTopBandwidth(i)/1e3,n.bl=this.getBufferLength(i));const a=s?this.getNextPart(s):this.getNextFrag(t);null!=a&&a.url&&a.url!==t.url&&(n.nor=a.url),this.apply(e,n)}catch(e){this.hls.logger.warn("Could not generate segment CMCD data.",e)}},this.hls=e;const t=this.config=e.config,{cmcd:s}=t;null!=s&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||e.sessionId,this.cid=s.contentId,this.useHeaders=!0===s.useHeaders,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events.MEDIA_DETACHED,this.onMediaDetached,this),e.on(Events.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events.MEDIA_DETACHED,this.onMediaDetached,this),e.off(Events.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var s,r;this.audioBuffer=null==(s=t.tracks.audio)?void 0:s.buffer,this.videoBuffer=null==(r=t.tracks.video)?void 0:r.buffer}createData(){var e;return{v:1,sf:CmcdStreamingFormat.HLS,sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){_extends(t,this.createData());const s=t.ot===CmcdObjectType.INIT||t.ot===CmcdObjectType.VIDEO||t.ot===CmcdObjectType.MUXED;this.starved&&s&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);const{includeKeys:r}=this;r&&(t=Object.keys(t).reduce(((e,s)=>(r.includes(s)&&(e[s]=t[s]),e)),{}));const i={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),appendCmcdHeaders(e.headers,t,i)):e.url=appendCmcdQuery(e.url,t,i)}getNextFrag(e){var t;const s=null==(t=this.hls.levels[e.level])?void 0:t.details;if(s){const t=e.sn-s.startSN;return s.fragments[t+1]}}getNextPart(e){var t;const{index:s,fragment:r}=e,i=null==(t=this.hls.levels[r.level])||null==(t=t.details)?void 0:t.partList;if(i){const{sn:e}=r;for(let t=i.length-1;t>=0;t--){const r=i[t];if(r.index===s&&r.fragment.sn===e)return i[t+1]}}}getObjectType(e){const{type:t}=e;return"subtitle"===t?CmcdObjectType.TIMED_TEXT:"initSegment"===e.sn?CmcdObjectType.INIT:"audio"===t?CmcdObjectType.AUDIO:"main"===t?this.hls.audioTracks.length?CmcdObjectType.VIDEO:CmcdObjectType.MUXED:void 0}getTopBandwidth(e){let t,s=0;const r=this.hls;if(e===CmcdObjectType.AUDIO)t=r.audioTracks;else{const e=r.maxAutoLevel,s=e>-1?e+1:r.levels.length;t=r.levels.slice(0,s)}return t.forEach((e=>{e.bitrate>s&&(s=e.bitrate)})),s>0?s:NaN}getBufferLength(e){const t=this.media,s=e===CmcdObjectType.AUDIO?this.audioBuffer:this.videoBuffer;if(!s||!t)return NaN;return 1e3*BufferHelper.bufferInfo(s,t.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new s(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,s,r){t(e),this.loader.load(e,s,r)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,s=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new s(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,s,r){t(e),this.loader.load(e,s,r)}}}}const PATHWAY_PENALTY_DURATION_MS=3e5;class ContentSteeringController extends Logger{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Events.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Events.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce(((e,t)=>(-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e)),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter((t=>t!==e)))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:s}=t;null!==s&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:s}=t;if((null==s?void 0:s.action)===NetworkErrorAction.SendAlternateToPenaltyBox&&s.flags===ErrorActionFlags.MoveAllAlternatesMatchingHost){const e=this.levels;let r=this._pathwayPriority,i=this.pathwayId;if(t.context){const{groupId:s,pathwayId:r,type:n}=t.context;s&&e?i=this.getPathwayForGroupId(s,n,i):r&&(i=r)}i in this.penalizedPathways||(this.penalizedPathways[i]=performance.now()),!r&&e&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),s.resolved=this.pathwayId!==i),t.details!==ErrorDetails.BUFFER_APPEND_ERROR||t.fatal?s.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${i} levels: ${e?e.length:e} priorities: ${stringify(r)} penalized: ${stringify(this.penalizedPathways)}`):s.resolved=!0}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){const s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return null===this.levels?[]:this.levels.filter((t=>e===t.pathwayId))}updatePathwayPriority(e){let t;this._pathwayPriority=e;const s=this.penalizedPathways,r=performance.now();Object.keys(s).forEach((e=>{r-s[e]>3e5&&delete s[e]}));for(let r=0;r<e.length;r++){const i=e[r];if(i in s)continue;if(i===this.pathwayId)return;const n=this.hls.nextLoadLevel,a=this.hls.levels[n];if(t=this.getLevelsForPathway(i),t.length>0){this.log(`Setting Pathway to "${i}"`),this.pathwayId=i,reassignFragmentLevelIndexes(t),this.hls.trigger(Events.LEVELS_UPDATED,{levels:t});const e=this.hls.levels[n];a&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(e,t,s){const r=this.getLevelsForPathway(s).concat(this.levels||[]);for(let s=0;s<r.length;s++)if(t===PlaylistContextType.AUDIO_TRACK&&r[s].hasAudioGroup(e)||t===PlaylistContextType.SUBTITLE_TRACK&&r[s].hasSubtitleGroup(e))return r[s].pathwayId;return s}clonePathways(e){const t=this.levels;if(!t)return;const s={},r={};e.forEach((e=>{const{ID:i,"BASE-ID":n,"URI-REPLACEMENT":a}=e;if(t.some((e=>e.pathwayId===i)))return;const o=this.getLevelsForPathway(n).map((e=>{const t=new AttrList(e.attrs);t["PATHWAY-ID"]=i;const n=t.AUDIO&&`${t.AUDIO}_clone_${i}`,o=t.SUBTITLES&&`${t.SUBTITLES}_clone_${i}`;n&&(s[t.AUDIO]=n,t.AUDIO=n),o&&(r[t.SUBTITLES]=o,t.SUBTITLES=o);const l=performUriReplacement(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),d=new Level({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:l,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(let t=1;t<e.audioGroups.length;t++)d.addGroupId("audio",`${e.audioGroups[t]}_clone_${i}`);if(e.subtitleGroups)for(let t=1;t<e.subtitleGroups.length;t++)d.addGroupId("text",`${e.subtitleGroups[t]}_clone_${i}`);return d}));t.push(...o),cloneRenditionGroups(this.audioTracks,s,a,i),cloneRenditionGroups(this.subtitleTracks,r,a,i)}))}loadSteeringManifest(e){const t=this.hls.config,s=t.loader;let r;this.loader&&this.loader.destroy(),this.loader=new s(t);try{r=new self.URL(e)}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${e}`)}if("data:"!==r.protocol){const e=0|(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate);r.searchParams.set("_HLS_pathway",this.pathwayId),r.searchParams.set("_HLS_throughput",""+e)}const i={responseType:"json",url:r.href},n=t.steeringManifestLoadPolicy.default,a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(e,t,s,i)=>{this.log(`Loaded steering manifest: "${r}"`);const n=e.data;if(1!==(null==n?void 0:n.VERSION))return void this.log(`Steering VERSION ${n.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=n.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=n;if(a)try{this.uri=new self.URL(a,r).href}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||s.url),o&&this.clonePathways(o);const d={steeringManifest:n,url:r.toString()};this.hls.trigger(Events.STEERING_MANIFEST_LOADED,d),l&&this.updatePathwayPriority(l)},onError:(e,t,s,r)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),410===e.code)return this.enabled=!1,void this.log(`Steering manifest ${t.url} no longer available`);let i=1e3*this.timeToLoad;if(429!==e.code)this.scheduleRefresh(this.uri||t.url,i);else{const e=this.loader;if("function"==typeof(null==e?void 0:e.getResponseHeader)){const t=e.getResponseHeader("Retry-After");t&&(i=1e3*parseFloat(t))}this.log(`Steering manifest ${t.url} rate limited`)}},onTimeout:(e,t,s)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}};this.log(`Requesting steering manifest: ${r}`),this.loader.load(i,o,l)}scheduleRefresh(e,t=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout((()=>{var t;const s=null==(t=this.hls)?void 0:t.media;!s||s.ended?this.scheduleRefresh(e,1e3*this.timeToLoad):this.loadSteeringManifest(e)}),t)}}function cloneRenditionGroups(e,t,s,r){e&&Object.keys(t).forEach((i=>{const n=e.filter((e=>e.groupId===i)).map((e=>{const n=_extends({},e);return n.details=void 0,n.attrs=new AttrList(n.attrs),n.url=n.attrs.URI=performUriReplacement(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",s),n.groupId=n.attrs["GROUP-ID"]=t[i],n.attrs["PATHWAY-ID"]=r,n}));e.push(...n)}))}function performUriReplacement(e,t,s,r){const{HOST:i,PARAMS:n,[s]:a}=r;let o;t&&(o=null==a?void 0:a[t],o&&(e=o));const l=new self.URL(e);return i&&!o&&(l.host=i),n&&Object.keys(n).sort().forEach((e=>{e&&l.searchParams.set(e,n[e])})),l.href}class EMEController extends Logger{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=EMEController.CDMCleanupPromise?[EMEController.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=e=>{const{initDataType:t,initData:s}=e,r=`"${e.type}" event: init data type: "${t}"`;if(this.debug(r),null!==s){if(!this.keyFormatPromise){let e=Object.keys(this.keySystemAccessPromises);e.length||(e=getKeySystemsForConfig(this.config));const t=e.map(keySystemDomainToKeySystemFormat).filter((e=>!!e));this.keyFormatPromise=this.getKeyFormatPromise(t)}this.keyFormatPromise.then((i=>{const n=keySystemFormatToKeySystemDomain(i);if("sinf"!==t||n!==KeySystems.FAIRPLAY)return void this.log(`Ignoring "${e.type}" event with init data type: "${t}" for selected key-system ${n}`);let a;try{const e=bin2str(new Uint8Array(s)),t=parseSinf(base64Decode(JSON.parse(e).sinf));if(!t)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");a=new Uint8Array(t.subarray(8,24))}catch(e){return void this.warn(`${r} Failed to parse sinf: ${e}`)}const o=arrayToHex(a),{keyIdToKeySessionPromise:l,mediaKeySessions:d}=this;let h=l[o];for(let e=0;e<d.length;e++){const r=d[e],i=r.decryptdata;if(!i.keyId)continue;const n=arrayToHex(i.keyId);if(arrayValuesMatch(a,i.keyId)||-1!==i.uri.replace(/-/g,"").indexOf(o)){if(h=l[n],!h)continue;if(i.pssh)break;delete l[n],i.pssh=new Uint8Array(s),i.keyId=a,h=l[o]=h.then((()=>this.generateRequestWithPreferredKeySession(r,t,s,"encrypted-event-key-match"))),h.catch((e=>this.handleError(e)));break}}h||this.handleError(new Error(`Key ID ${o} not encountered in playlist. Key-system sessions ${d.length}.`))})).catch((e=>this.handleError(e)))}},this.onWaitingForKey=e=>{this.log(`"${e.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(Events.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(Events.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(Events.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(Events.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(Events.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(Events.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:s}=this.config,r=null==t?void 0:t[e];return r?r.licenseUrl:e===KeySystems.WIDEVINE&&s?s:void 0}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(void 0===t)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,s=null==t?void 0:t[e];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,s=(e,t,s)=>!!e&&s.indexOf(e)===t,r=t.map((e=>e.audioCodec)).filter(s),i=t.map((e=>e.videoCodec)).filter(s);return r.length+i.length===0&&i.push("avc1.42e01e"),new Promise(((t,s)=>{const n=e=>{const a=e.shift();this.getMediaKeysPromise(a,r,i).then((e=>t({keySystem:a,mediaKeys:e}))).catch((t=>{e.length?n(e):s(t instanceof EMEKeyError?t:new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))}))};n(e)}))}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:s}=this.config;if("function"!=typeof s){let e=`Configured requestMediaKeySystemAccess is not a function ${s}`;return null===requestMediaKeySystemAccess&&"http:"===self.location.protocol&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(e))}return s(e,t)}getMediaKeysPromise(e,t,s){var r;const i=getSupportedMediaKeySystemConfigurations(e,t,s,this.config.drmSystemOptions||{});let n=this.keySystemAccessPromises[e],a=null==(r=n)?void 0:r.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${stringify(i)}`),a=this.requestMediaKeySystemAccess(e,i);const t=n=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch((t=>{this.log(`Failed to obtain access to key-system "${e}": ${t}`)})),a.then((s=>{this.log(`Access for key-system "${s.keySystem}" obtained`);const r=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const i=t.mediaKeys=s.createMediaKeys().then((s=>(this.log(`Media-keys created for "${e}"`),t.hasMediaKeys=!0,r.then((t=>t?this.setMediaKeysServerCertificate(s,e,t):s)))));return i.catch((t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)})),i}))}return a.then((()=>n.mediaKeys))}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:s}){this.log(`Creating key-system session "${t}" keyId: ${arrayToHex(e.keyId||[])} keyUri: ${e.uri}`);const r=s.createSession(),i={decryptdata:e,keySystem:t,mediaKeys:s,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(i),i}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const s=this.createMediaKeySessionContext(e),r=getKeyIdString(t),i="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(s,i,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){const s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyId ${arrayToHex(e.decryptdata.keyId||[])}\n } (data length: ${t.byteLength})`),s.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map((e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys}))).filter((({hasMediaKeys:e})=>!!e)).map((({keySystem:e})=>keySystemDomainToKeySystemFormat(e))).filter((e=>!!e))}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then((({keySystem:e,mediaKeys:t})=>this.attemptSetMediaKeys(e,t)))}selectKeySystem(e){return new Promise(((t,s)=>{this.getKeySystemSelectionPromise(e).then((({keySystem:e})=>{const r=keySystemDomainToKeySystemFormat(e);r?t(r):s(new Error(`Unable to find format for key-system "${e}"`))})).catch(s)}))}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){const t=getKeySystemsForConfig(this.config),s=e.map(keySystemFormatToKeySystemDomain).filter((e=>!!e&&-1!==t.indexOf(e)));return this.selectKeySystem(s)}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let s=0;s<t.length;s++){const r=getKeyStatus(e,t[s]);if(r)return r}}loadKey(e){const t=e.keyInfo.decryptdata,s=getKeyIdString(t),r=this.bannedKeyIds[s];if(r||"internal-error"===this.getKeyStatus(t)){const s=getKeyStatusError(r||"internal-error",t);return this.handleError(s,e.frag),Promise.reject(s)}const i=`(keyId: ${s} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${i}`);const n=this.keyIdToKeySessionPromise[s];if(!n){const r=this.getKeySystemForKeyPromise(t).then((({keySystem:s,mediaKeys:r})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${i}`),this.attemptSetMediaKeys(s,r).then((()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:s,mediaKeys:r,decryptdata:t}))))))).then((e=>{const s=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(e,"cenc",s,"playlist-key")}));return r.catch((t=>this.handleError(t,e.frag))),this.keyIdToKeySessionPromise[s]=r,r}return n.catch((s=>{if(s instanceof EMEKeyError){const r=_objectSpread2({},s.data);"internal-error"===this.getKeyStatus(t)&&(r.decryptdata=t);const i=new EMEKeyError(r,s.message);this.handleError(i,e.frag)}})),n}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof EMEKeyError){t&&(e.data.frag=t);const s=e.data.decryptdata;this.error(`${e.message}${s?` (${arrayToHex(s.keyId||[])})`:""}`),this.hls.trigger(Events.ERROR,e.data)}else this.error(e.message),this.hls.trigger(Events.ERROR,{type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=getKeyIdString(e),s=this.keyIdToKeySessionPromise[t];if(!s){const t=keySystemFormatToKeySystemDomain(e.keyFormat),s=t?[t]:getKeySystemsForConfig(this.config);return this.attemptKeySystemAccess(s)}return s}getKeySystemSelectionPromise(e){if(e.length||(e=getKeySystemsForConfig(this.config)),0===e.length)throw new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaKeys===t)return Promise.resolve();const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const r=Promise.all(s).then((()=>{if(!this.media)throw this.mediaKeys=null,new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)}));return this.mediaKeys=t,this.setMediaKeysQueue.push(r),r.then((()=>{this.log(`Media-keys set for "${e}"`),s.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter((e=>-1===s.indexOf(e)))}))}generateRequestWithPreferredKeySession(e,t,s,r){var i;const n=null==(i=this.config.drmSystems)||null==(i=i[e.keySystem])?void 0:i.generateRequest;if(n)try{const r=n.call(this.hls,t,s,e);if(!r)throw new Error("Invalid response from configured generateRequest filter");t=r.initDataType,s=r.initData?r.initData:null,e.decryptdata.pssh=s?new Uint8Array(s):null}catch(e){if(this.warn(e.message),this.hls&&this.hls.config.debug)throw e}if(null===s)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);const a=getKeyIdString(e.decryptdata),o=e.decryptdata.uri;this.log(`Generating key-session request for "${r}" keyId: ${a} URI: ${o} (init data type: ${t} length: ${s.byteLength})`);const l=new EventEmitter,d=e._onmessage=t=>{const s=e.mediaKeysSession;if(!s)return void l.emit("error",new Error("invalid state"));const{messageType:r,message:i}=t;this.log(`"${r}" message event for session "${s.sessionId}" message size: ${i.byteLength}`),"license-request"===r||"license-renewal"===r?this.renewLicense(e,i).catch((e=>{l.eventNames().length?l.emit("error",e):this.handleError(e)})):"license-release"===r?e.keySystem===KeySystems.FAIRPLAY&&this.updateKeySession(e,strToUtf8array("acknowledged")).then((()=>this.removeSession(e))).catch((e=>this.handleError(e))):this.warn(`unhandled media key message type "${r}"`)},h=(e,t)=>{let s;t.keyStatus=e,e.startsWith("usable")?l.emit("resolved"):"internal-error"===e||"output-restricted"===e||"output-downscaled"===e?s=getKeyStatusError(e,t.decryptdata):"expired"===e?s=new Error(`key expired (keyId: ${a})`):"released"===e?s=new Error("key released"):"status-pending"===e||this.warn(`unhandled key status change "${e}" (keyId: ${a})`),s&&(l.eventNames().length?l.emit("error",s):this.handleError(s))},c=e._onkeystatuseschange=t=>{if(!e.mediaKeysSession)return void l.emit("error",new Error("invalid state"));const s=this.getKeyStatuses(e);if(!Object.keys(s).some((e=>"status-pending"!==s[e])))return;if("expired"===s[a])return this.log(`Expired key ${stringify(s)} in key-session "${e.mediaKeysSession.sessionId}"`),void this.renewKeySession(e);let r=s[a];if(r)h(r,e);else{var i;const t=1e3;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(i=e.keyStatusTimeouts)[a]||(i[a]=self.setTimeout((()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const s=this.getKeyStatus(e.decryptdata);if(s&&"status-pending"!==s)return this.log(`No status for keyId ${a} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${s} from other session.`),h(s,e);this.log(`key status for ${a} in key-session "${e.mediaKeysSession.sessionId}" timed out after ${t}ms`),r="internal-error",h(r,e)}),t)),this.log(`No status for keyId ${a} (${stringify(s)}).`)}};addEventListener(e.mediaKeysSession,"message",d),addEventListener(e.mediaKeysSession,"keystatuseschange",c);const u=new Promise(((e,t)=>{l.on("error",t),l.on("resolved",e)}));return e.mediaKeysSession.generateRequest(t,s).then((()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${a} URI: ${o}`)})).catch((t=>{throw new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_NO_SESSION,error:t,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${t}`)})).then((()=>u)).catch((t=>(l.removeAllListeners(),this.removeSession(e).then((()=>{throw t}))))).then((()=>(l.removeAllListeners(),e)))}getKeyStatuses(e){const t={};return e.mediaKeysSession.keyStatuses.forEach(((s,r)=>{if("string"==typeof r&&"object"==typeof s){const e=r;r=s,s=e}const i="buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);e.keySystem===KeySystems.PLAYREADY&&16===i.length&&changeEndianness(i);const n=arrayToHex(i);"internal-error"===s&&(this.bannedKeyIds[n]=s),this.log(`key status change "${s}" for keyStatuses keyId: ${n} key-session "${e.mediaKeysSession.sessionId}"`),t[n]=s})),t}fetchServerCertificate(e){const t=this.config,s=new(0,t.loader)(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise(((i,n)=>{const a={responseType:"arraybuffer",url:r},o=t.certLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(e,t,s,r)=>{i(e.data)},onError:(t,s,i,o)=>{n(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:i,response:_objectSpread2({url:a.url,data:void 0},t)},`"${e}" certificate request failed (${r}). Status: ${t.code} (${t.text})`))},onTimeout:(t,s,i)=>{n(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:i,response:{url:a.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(e,t,s)=>{n(new Error("aborted"))}};s.load(a,l,d)}))):Promise.resolve()}setMediaKeysServerCertificate(e,t,s){return new Promise(((r,i)=>{e.setServerCertificate(s).then((i=>{this.log(`setServerCertificate ${i?"success":"not supported by CDM"} (${s.byteLength}) on "${t}"`),r(e)})).catch((e=>{i(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))}))}))}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then((t=>this.updateKeySession(e,new Uint8Array(t)).catch((t=>{throw new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:t,fatal:!1},t.message)}))))}unpackPlayReadyKeyMessage(e,t){const s=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!s.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const r=(new DOMParser).parseFromString(s,"application/xml"),i=r.querySelectorAll("HttpHeader");if(i.length>0){let t;for(let s=0,r=i.length;s<r;s++){var n,a;t=i[s];const r=null==(n=t.querySelector("name"))?void 0:n.textContent,o=null==(a=t.querySelector("value"))?void 0:a.textContent;r&&o&&e.setRequestHeader(r,o)}}const o=r.querySelector("Challenge"),l=null==o?void 0:o.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return strToUtf8array(atob(l))}setupLicenseXHR(e,t,s,r){const i=this.config.licenseXhrSetup;return i?Promise.resolve().then((()=>{if(!s.decryptdata)throw new Error("Key removed");return i.call(this.hls,e,t,s,r)})).catch((n=>{if(!s.decryptdata)throw n;return e.open("POST",t,!0),i.call(this.hls,e,t,s,r)})).then((s=>{e.readyState||e.open("POST",t,!0);return{xhr:e,licenseChallenge:s||r}})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){const s=this.config.keyLoadPolicy.default;return new Promise(((r,i)=>{const n=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${n}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return i(new Error("invalid state"));if(4===a.readyState)if(200===a.status){this._requestLicenseFailureCount=0;let t=a.response;this.log(`License received ${t instanceof ArrayBuffer?t.byteLength:t}`);const s=this.config.licenseResponseCallback;if(s)try{t=s.call(this.hls,a,n,e)}catch(e){this.error(e)}r(t)}else{const o=s.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)i(new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:a,response:{url:n,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${n}). Status: ${a.status} (${a.statusText})`));else{const s=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${s} attempts left`),this.requestLicense(e,t).then(r,i)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=a,this.setupLicenseXHR(a,n,e,t).then((({xhr:t,licenseChallenge:s})=>{e.keySystem==KeySystems.PLAYREADY&&(s=this.unpackPlayReadyKeyMessage(t,s)),t.send(s)})).catch(i)}))}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const s=t.media;this.media=s,addEventListener(s,"encrypted",this.onMediaEncrypted),addEventListener(s,"waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media;e&&(removeEventListener(e,"encrypted",this.onMediaEncrypted),removeEventListener(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;if(this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={},!this.mediaKeys&&!this.mediaKeySessions.length)return;const t=this.media,s=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,LevelKey.clearKeyUriToKeyIdMap();const r=s.length;EMEController.CDMCleanupPromise=Promise.all(s.map((e=>this.removeSession(e))).concat((null==t||null==(e=t.setMediaKeys(null))?void 0:e.catch((e=>{this.log(`Could not clear media keys: ${e}`),this.hls&&this.hls.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${e}`)})})))||Promise.resolve())).catch((e=>{this.log(`Could not close sessions and clear media keys: ${e}`),this.hls&&this.hls.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${e}`)})})).then((()=>{r&&this.log("finished closing key sessions and clearing media keys")}))}onManifestLoading(){this.keyFormatPromise=null,this.bannedKeyIds={}}onManifestLoaded(e,{sessionKeys:t}){if(t&&this.config.emeEnabled&&!this.keyFormatPromise){const e=t.reduce(((e,t)=>(-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e)),[]);this.log(`Selecting key-system from session-keys ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:s,decryptdata:r}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${arrayToHex((null==r?void 0:r.keyId)||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const i=this.mediaKeySessions.indexOf(e);i>-1&&this.mediaKeySessions.splice(i,1);const{keyStatusTimeouts:n}=e;n&&Object.keys(n).forEach((e=>self.clearTimeout(n[e])));const{drmSystemOptions:a}=this.config;return(isPersistentSessionType(a)?new Promise(((e,s)=>{self.setTimeout((()=>s(new Error("MediaKeySession.remove() timeout"))),8e3),t.remove().then(e).catch(s)})):Promise.resolve()).catch((e=>{this.log(`Could not remove session: ${e}`),this.hls&&this.hls.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${e}`)})})).then((()=>t.close())).catch((e=>{this.log(`Could not close session: ${e}`),this.hls&&this.hls.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${e}`)})}))}return Promise.resolve()}}function getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw new Error("keyId is null");return arrayToHex(e.keyId)}function getKeyStatus(e,t){return e.keyId&&t.mediaKeysSession.keyStatuses.has(e.keyId)?t.mediaKeysSession.keyStatuses.get(e.keyId):e.matches(t.decryptdata)?t.keyStatus:void 0}EMEController.CDMCleanupPromise=void 0;class EMEKeyError extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}function getKeyStatusError(e,t){const s="output-restricted"===e,r=s?ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new EMEKeyError({type:ErrorTypes.KEY_SYSTEM_ERROR,details:r,fatal:!1,decryptdata:t},s?"HDCP level output restricted":`key status changed to "${e}"`)}class FPSController{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const s=this.hls.config;if(s.capLevelOnFPSDrop){const e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&"function"==typeof e.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){const r=performance.now();if(t){if(this.lastTime){const e=r-this.lastTime,i=s-this.lastDroppedFrames,n=t-this.lastDecodedFrames,a=1e3*i/e,o=this.hls;if(o.trigger(Events.FPS_DROP,{currentDropped:i,currentDecoded:n,totalDroppedFrames:s}),a>0&&i>o.config.fpsDroppedMonitoringThreshold*n){let e=o.currentLevel;o.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=e)&&(e-=1,o.trigger(Events.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:o.currentLevel}),o.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=s,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}var VTTCue=function(){if(null!=optionalSelf&&optionalSelf.VTTCue)return self.VTTCue;const e=["","lr","rl"],t=["start","middle","end","left","right"];function s(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;const s=t.toLowerCase();return!!~e.indexOf(s)&&s}function r(e){return s(t,e)}function i(e,...t){let s=1;for(;s<arguments.length;s++){const t=arguments[s];for(const s in t)e[s]=t[s]}return e}function n(t,n,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let d="",h=!1,c=t,u=n,f=a,g=null,m="",p=!0,E="auto",y="start",v=50,T="middle",S=50,A="middle";Object.defineProperty(o,"id",i({},l,{get:function(){return d},set:function(e){d=""+e}})),Object.defineProperty(o,"pauseOnExit",i({},l,{get:function(){return h},set:function(e){h=!!e}})),Object.defineProperty(o,"startTime",i({},l,{get:function(){return c},set:function(e){if("number"!=typeof e)throw new TypeError("Start time must be set to a number.");c=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",i({},l,{get:function(){return u},set:function(e){if("number"!=typeof e)throw new TypeError("End time must be set to a number.");u=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",i({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",i({},l,{get:function(){return g},set:function(e){g=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",i({},l,{get:function(){return m},set:function(t){const r=function(t){return s(e,t)}(t);if(!1===r)throw new SyntaxError("An invalid or illegal string was specified.");m=r,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",i({},l,{get:function(){return p},set:function(e){p=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",i({},l,{get:function(){return E},set:function(e){if("number"!=typeof e&&"auto"!==e)throw new SyntaxError("An invalid number or illegal string was specified.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",i({},l,{get:function(){return y},set:function(e){const t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");y=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",i({},l,{get:function(){return v},set:function(e){if(e<0||e>100)throw new Error("Position must be between 0 and 100.");v=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",i({},l,{get:function(){return T},set:function(e){const t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");T=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",i({},l,{get:function(){return S},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");S=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",i({},l,{get:function(){return A},set:function(e){const t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");A=t,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class StringDecoder{decode(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function parseTimeStamp(e){function t(e,t,s,r){return 3600*(0|e)+60*(0|t)+(0|s)+parseFloat(r||0)}const s=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return s?parseFloat(s[2])>59?t(s[2],s[3],0,s[4]):t(s[1],s[2],s[3],s[4]):null}class Settings{constructor(){this.values=Object.create(null)}set(e,t){this.get(e)||""===t||(this.values[e]=t)}get(e,t,s){return s?this.has(e)?this.values[e]:t[s]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,s){for(let r=0;r<s.length;++r)if(t===s[r]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}}function parseOptions(e,t,s,r){const i=r?e.split(r):[e];for(const e in i){if("string"!=typeof i[e])continue;const r=i[e].split(s);if(2!==r.length)continue;t(r[0],r[1])}}const defaults=new VTTCue(0,0,""),center="middle"===defaults.align?"middle":"center";function parseCue(e,t,s){const r=e;function i(){const t=parseTimeStamp(e);if(null===t)throw new Error("Malformed timestamp: "+r);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function n(){e=e.replace(/^\s+/,"")}if(n(),t.startTime=i(),n(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+r);e=e.slice(3),n(),t.endTime=i(),n(),function(e,t){const r=new Settings;parseOptions(e,(function(e,t){let i;switch(e){case"region":for(let i=s.length-1;i>=0;i--)if(s[i].id===t){r.set(e,s[i].region);break}break;case"vertical":r.alt(e,t,["rl","lr"]);break;case"line":i=t.split(","),r.integer(e,i[0]),r.percent(e,i[0])&&r.set("snapToLines",!1),r.alt(e,i[0],["auto"]),2===i.length&&r.alt("lineAlign",i[1],["start",center,"end"]);break;case"position":i=t.split(","),r.percent(e,i[0]),2===i.length&&r.alt("positionAlign",i[1],["start",center,"end","line-left","line-right","auto"]);break;case"size":r.percent(e,t);break;case"align":r.alt(e,t,["start",center,"end","left","right"])}}),/:/,/\s/),t.region=r.get("region",null),t.vertical=r.get("vertical","");let i=r.get("line","auto");"auto"===i&&-1===defaults.line&&(i=-1),t.line=i,t.lineAlign=r.get("lineAlign","start"),t.snapToLines=r.get("snapToLines",!0),t.size=r.get("size",100),t.align=r.get("align",center);let n=r.get("position","auto");"auto"===n&&50===defaults.position&&(n="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=n}(e,t)}function fixLineBreaks(e){return e.replace(/<br(?: \/)?>/gi,"\n")}class VTTParser{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new StringDecoder,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;function s(){let e=t.buffer,s=0;for(e=fixLineBreaks(e);s<e.length&&"\r"!==e[s]&&"\n"!==e[s];)++s;const r=e.slice(0,s);return"\r"===e[s]&&++s,"\n"===e[s]&&++s,t.buffer=e.slice(s),r}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{let e="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;e=s();const r=e.match(/^()?WEBVTT([ \t].*)?$/);if(null==r||!r[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let r=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(r?r=!1:e=s(),t.state){case"HEADER":/:/.test(e)?parseOptions(e,(function(e,t){}),/:/):e||(t.state="ID");continue;case"NOTE":e||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(e)){t.state="NOTE";break}if(!e)continue;if(t.cue=new VTTCue(0,0,""),t.state="CUE",-1===e.indexOf("--\x3e")){t.cue.id=e;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{parseCue(e,t.cue,t.regionList)}catch(e){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const s=-1!==e.indexOf("--\x3e");if(!e||s&&(r=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=e}continue;case"BADCUE":e||(t.state="ID")}}}catch(e){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||"HEADER"===e.state)&&(e.buffer+="\n\n",e.parse()),"INITIAL"===e.state||"BADWEBVTT"===e.state)throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}function hash(e){let t=5381,s=e.length;for(;s;)t=33*t^e.charCodeAt(--s);return(t>>>0).toString()}const LINEBREAKS=/\r\n|\n\r|\n|\r/g,startsWith=function(e,t,s=0){return e.slice(s,s+t.length)===t},cueString2millis=function(e){let t=parseInt(e.slice(-3));const s=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),i=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(isFiniteNumber(t)&&isFiniteNumber(s)&&isFiniteNumber(r)&&isFiniteNumber(i)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*s,t+=6e4*r,t+=36e5*i,t};function generateCueId(e,t,s){return hash(e.toString())+hash(t.toString())+hash(s)}const calculateOffset=function(e,t,s){let r=e[t],i=e[r.prevCC];if(!i||!i.new&&r.new)return e.ccOffset=e.presentationOffset=r.start,void(r.new=!1);for(;null!=(n=i)&&n.new;){var n;e.ccOffset+=r.start-i.start,r.new=!1,r=i,i=e[r.prevCC]}e.presentationOffset=s};function parseWebVTT(e,t,s,r,i,n,a){const o=new VTTParser,l=utf8ArrayToStr(new Uint8Array(e)).trim().replace(LINEBREAKS,"\n").split("\n"),d=[],h=t?toMpegTsClockFromTimescale(t.baseTime,t.timescale):0;let c,u="00:00.000",f=0,g=0,m=!0;o.oncue=function(e){const n=s[r];let a=s.ccOffset;const o=(f-h)/9e4;if(null!=n&&n.new&&(void 0!==g?a=s.ccOffset=n.start:calculateOffset(s,r,o)),o){if(!t)return void(c=new Error("Missing initPTS for VTT MPEGTS"));a=o-s.presentationOffset}const l=e.endTime-e.startTime,u=normalizePts(9e4*(e.startTime+a-g),9e4*i)/9e4;e.startTime=Math.max(u,0),e.endTime=Math.max(u+l,0);const m=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(m)),e.id||(e.id=generateCueId(e.startTime,e.endTime,m)),e.endTime>0&&d.push(e)},o.onparsingerror=function(e){c=e},o.onflush=function(){c?a(c):n(d)},l.forEach((e=>{if(m){if(startsWith(e,"X-TIMESTAMP-MAP=")){m=!1,e.slice(16).split(",").forEach((e=>{startsWith(e,"LOCAL:")?u=e.slice(6):startsWith(e,"MPEGTS:")&&(f=parseInt(e.slice(7)))}));try{g=cueString2millis(u)/1e3}catch(e){c=e}return}""===e&&(m=!1)}o.parse(e+"\n")})),o.flush()}const IMSC1_CODEC="stpp.ttml.im1t",HMSF_REGEX=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,TIME_UNIT_REGEX=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,textAlignToLineAlign={left:"start",center:"center",right:"end",start:"start",end:"end"};function parseIMSC1(e,t,s,r){const i=findBox(new Uint8Array(e),["mdat"]);if(0===i.length)return void r(new Error("Could not parse IMSC1 mdat"));const n=i.map((e=>utf8ArrayToStr(e))),a=toTimescaleFromScale(t.baseTime,1,t.timescale);try{n.forEach((e=>s(parseTTML(e,a))))}catch(e){r(e)}}function parseTTML(e,t){const s=(new DOMParser).parseFromString(e,"text/xml").getElementsByTagName("tt")[0];if(!s)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},i=Object.keys(r).reduce(((e,t)=>(e[t]=s.getAttribute(`ttp:${t}`)||r[t],e)),{}),n="preserve"!==s.getAttribute("xml:space"),a=collectionToDictionary(getElementCollection(s,"styling","style")),o=collectionToDictionary(getElementCollection(s,"layout","region")),l=getElementCollection(s,"body","[begin]");return[].map.call(l,(e=>{const s=getTextContent(e,n);if(!s||!e.hasAttribute("begin"))return null;const r=parseTtmlTime(e.getAttribute("begin"),i),l=parseTtmlTime(e.getAttribute("dur"),i);let d=parseTtmlTime(e.getAttribute("end"),i);if(null===r)throw timestampParsingError(e);if(null===d){if(null===l)throw timestampParsingError(e);d=r+l}const h=new VTTCue(r-t,d-t,s);h.id=generateCueId(h.startTime,h.endTime,h.text);const c=getTtmlStyles(o[e.getAttribute("region")],a[e.getAttribute("style")],a),{textAlign:u}=c;if(u){const e=textAlignToLineAlign[u];e&&(h.lineAlign=e),h.align=u}return _extends(h,c),h})).filter((e=>null!==e))}function getElementCollection(e,t,s){const r=e.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(s)):[]}function collectionToDictionary(e){return e.reduce(((e,t)=>{const s=t.getAttribute("xml:id");return s&&(e[s]=t),e}),{})}function getTextContent(e,t){return[].slice.call(e.childNodes).reduce(((e,s,r)=>{var i;return"br"===s.nodeName&&r?e+"\n":null!=(i=s.childNodes)&&i.length?getTextContent(s,t):t?e+s.textContent.trim().replace(/\s+/g," "):e+s.textContent}),"")}function getTtmlStyles(e,t,s){const r="http://www.w3.org/ns/ttml#styling";let i=null;const n=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;return n&&s.hasOwnProperty(n)&&(i=s[n]),["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"].reduce(((s,n)=>{const a=getAttributeNS(t,r,n)||getAttributeNS(e,r,n)||getAttributeNS(i,r,n);return a&&(s[n]=a),s}),{})}function getAttributeNS(e,t,s){return e&&e.hasAttributeNS(t,s)?e.getAttributeNS(t,s):null}function timestampParsingError(e){return new Error(`Could not parse ttml timestamp ${e}`)}function parseTtmlTime(e,t){if(!e)return null;let s=parseTimeStamp(e);return null===s&&(HMSF_REGEX.test(e)?s=parseHoursMinutesSecondsFrames(e,t):TIME_UNIT_REGEX.test(e)&&(s=parseTimeUnits(e,t))),s}function parseHoursMinutesSecondsFrames(e,t){const s=HMSF_REGEX.exec(e),r=(0|s[4])+(0|s[5])/t.subFrameRate;return 3600*(0|s[1])+60*(0|s[2])+(0|s[3])+r/t.frameRate}function parseTimeUnits(e,t){const s=TIME_UNIT_REGEX.exec(e),r=Number(s[1]);switch(s[2]){case"h":return 3600*r;case"m":return 60*r;case"ms":return 1e3*r;case"f":return r/t.frameRate;case"t":return r/t.tickRate}return r}function createTrackNode(e,t,s,r="",i="disabled"){const n=e.ownerDocument.createElement("track");return n.kind=t,n.label=s,r&&(n.srclang=r),n.src="data:,WEBVTT",n.track.mode=i,e.appendChild(n),n}function getTrackKind(e){return e.forced&&(navigator.vendor.includes("Apple")||/iPhone|iPad|iPod/.test(navigator.userAgent))?"forced":e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function addCueToTrack(e,t){const s=e.mode;if("disabled"===s&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(s){logger.debug(`[texttrack-utils]: ${s}`);try{const s=new self.TextTrackCue(t.startTime,t.endTime,t.text);s.id=t.id,e.addCue(s)}catch(e){logger.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}"disabled"===s&&(e.mode=s)}function removeCuesInRange(e,t,s,r){const i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues&&e.cues.length>0){const i=getCuesInRange(e.cues,t,s);for(let t=0;t<i.length;t++)r&&!r(i[t])||e.removeCue(i[t])}"disabled"===i&&(e.mode=i)}function getFirstCueIndexFromTime(e,t){if(t<=e[0].startTime)return 0;const s=e.length-1;if(t>e[s].endTime)return-1;let r,i=0,n=s;for(;i<=n;)if(r=Math.floor((n+i)/2),t<e[r].startTime)n=r-1;else{if(!(t>e[r].startTime&&i<s))return r;i=r+1}return e[i].startTime-t<t-e[n].startTime?i:n}function getCuesInRange(e,t,s){const r=[],i=getFirstCueIndexFromTime(e,t);if(i>-1)for(let n=i,a=e.length;n<a;n++){const i=e[n];if(i.startTime>=t&&i.endTime<=s)r.push(i);else if(i.startTime>s)return r}return r}class SubtitleTrackController extends BasePlaylistController{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=-1,t=!1;if(this.currentTrack){var s;const r=null==(s=this.currentTrack.trackNode)?void 0:s.track.mode;"showing"===r?(e=this.trackId,t=!0):"hidden"===r&&(e=this.trackId)}if(!t)for(let t=0;t<this.tracksInGroup.length;t++){var r;const s=null==(r=this.tracksInGroup[t].trackNode)?void 0:r.track.mode;if("showing"===s){e=t;break}e<0&&"hidden"===s&&(e=t)}var i;e>-1&&(this._subtitleDisplay="showing"===(null==(i=this.tracksInGroup[e].trackNode)?void 0:i.track.mode));this.setSubtitleTrack(e,!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(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Events.LEVEL_LOADING,this.onLevelLoading,this),e.on(Events.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Events.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(Events.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Events.LEVEL_LOADING,this.onLevelLoading,this),e.off(Events.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Events.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(Events.ERROR,this.onError,this)}createTracksInGroup(){var e;if(!this.media||!this.hls.config.renderTextTracksNatively)return;this.tracksInGroup.forEach((e=>{e.trackNode||(e.trackNode=createTrackNode(this.media,getTrackKind(e),e.name,e.lang))}));const t=null==(e=this.currentTrack)||null==(e=e.trackNode)?void 0:e.track;"disabled"===(null==t?void 0:t.mode)&&(t.mode=this._subtitleDisplay?"showing":"hidden")}onMediaAttached(e,t){const s=t.media;this.media=s;let r=this.trackId;this.queuedDefaultTrack>-1&&(r=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.setSubtitleTrack(r),this.createTracksInGroup(),this.useTextTrackPolling=!(s.textTracks&&"onchange"in s.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):s.textTracks.addEventListener("change",this.asyncPollTrackChange)}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const s=this.media;if(!s)return;const r=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId,this.setSubtitleTrack(-1)),this.media=null,r||this.hls.config.renderTextTracksNatively&&this.tracksInGroup.forEach((e=>{e.trackNode&&(e.trackNode.remove(),e.trackNode=void 0)}))}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:s,groupId:r,details:i}=t,n=this.tracksInGroup[s];if(!n||n.groupId!==r)return void this.warn(`Subtitle track with id:${s} and group:${r} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=t.details,this.log(`Subtitle track ${s} "${n.name}" lang:${n.lang} group:${r} loaded [${i.startSN}-${i.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.subtitleGroups||null,r=this.groupIds;let i=this.currentTrack;if(!s||(null==r?void 0:r.length)!==(null==s?void 0:s.length)||null!=s&&s.some((e=>-1===(null==r?void 0:r.indexOf(e))))){this.groupIds=s;const e=[];if(this.tracks.forEach((t=>{(t.textCodec===IMSC1_CODEC?this.hls.config.enableIMSC1:this.hls.config.enableWebVTT)&&(!s||s.includes(t.groupId)?(t.id=e.length,e.push(t)):t.trackNode&&(t.trackNode.remove(),t.trackNode=void 0))})),e.length===this.tracksInGroup.length){let t=!1;for(let s=0;s<e.length;s++)if(e[s]!==this.tracksInGroup[s]){t=!0;break}if(!t)return}e.length&&this.selectDefaultTrack&&!e.some((e=>e.default))&&(this.selectDefaultTrack=!1),this.tracksInGroup=e,this.trackId=-1,this.currentTrack=null;const t=this.hls.config.subtitlePreference;if(!i&&t){this.selectDefaultTrack=!1;const s=findMatchingOption(t,e);if(s>-1)i=e[s];else{const e=findMatchingOption(t,this.tracks);i=this.tracks[e]}}let r=this.findTrackId(i);-1===r&&i&&(r=this.findTrackId(null));const n={subtitleTracks:e};this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${null==s?void 0:s.join(",")}" group-id`),this.hls.trigger(Events.SUBTITLE_TRACKS_UPDATED,n),this.setSubtitleTrack(r),this.createTracksInGroup()}}findTrackId(e){const t=this.tracksInGroup,s=this.selectDefaultTrack;for(let r=0;r<t.length;r++){const i=t[r];if((!s||i.default)&&(s||e)&&(!e||matchesOption(i,e)))return r}if(e){for(let s=0;s<t.length;s++){const r=t[s];if(mediaAttributesIdentical(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<t.length;s++){const r=t[s];if(mediaAttributesIdentical(e.attrs,r.attrs,["LANGUAGE"]))return s}}return-1}onError(e,t){!t.fatal&&t.context&&(t.context.type!==PlaylistContextType.SUBTITLE_TRACK||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t))}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e,!0)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(-1===e.id)return this.setSubtitleTrack(-1,!0),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const s=this.currentTrack;if(s&&matchesOption(e,s))return s;const r=findMatchingOption(e,this.tracksInGroup);if(r>-1){const e=this.tracksInGroup[r];return this.setSubtitleTrack(r,!0),e}if(s)return null;{const s=findMatchingOption(e,t);if(s>-1)return t[s]}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,r=e.groupId,i=this.getUrlWithDirectives(e.url,t),n=e.details,a=null==n?void 0:n.age;this.log(`Loading subtitle ${s} "${e.name}" lang:${e.lang} group:${r}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${i}`),this.hls.trigger(Events.SUBTITLE_TRACK_LOADING,{url:i,id:s,groupId:r,deliveryDirectives:t||null,track:e})}toggleTrackModes(){if(!this.media||!this.hls.config.renderTextTracksNatively)return;const e=this.currentTrack;this.tracksInGroup.forEach((t=>{if(t.trackNode){const s=t===e?this._subtitleDisplay?"showing":"hidden":"disabled",r=t.trackNode.track;r.mode!==s&&(r.mode=s)}}))}setSubtitleTrack(e,t=!1){const s=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=e);if(e<-1||e>=s.length||!isFiniteNumber(e))return void this.warn(`Invalid subtitle track id: ${e}`);const r=this.currentTrack,i=s[e]||null;if(this.trackId=e,this.currentTrack=i,t&&this.toggleTrackModes(),!i)return void(r&&this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH,{id:e}));const n=!!i.details&&!i.details.live;if(i===r&&n)return;this.log(`Switching to subtitle-track ${e}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));const{id:a,groupId:o="",name:l,type:d,url:h}=i;this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:d,url:h});const c=this.switchParams(i.url,null==r?void 0:r.details,i.details);this.loadPlaylist(c)}}function uuid(){try{return crypto.randomUUID()}catch(e){try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){let t=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const s=(t+16*Math.random())%16|0;return t=Math.floor(t/16),("x"==e?s:3&s|8).toString(16)}))}}}const ALIGNED_END_THRESHOLD_SECONDS=.025;let TimelineOccupancy=function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e}({});function generateAssetIdentifier(e,t,s){return`${e.identifier}-${s+1}-${hash(t)}`}class InterstitialEvent{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,null==(e=this.assetListLoader)||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const s=this.playoutLimit;if(e<=0||isNaN(s))return!1;if(0===s)return!0;return((null==(t=this.assetList[e])?void 0:t.startOffset)||0)>s}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return getSnapToFragmentTime(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(0===this.startTime||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime;return t-getSnapToFragmentTime(t,e)<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=isFiniteNumber(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return getSnapToFragmentTime(e,t)}return e}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)<.025))}set appendInPlace(e){this.appendInPlaceStarted?this.resetOnResume=!e:this.appendInPlaceDisabled=!e}get timelineStart(){return null!==this._timelineStart?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return t=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?TimelineOccupancy.Range:TimelineOccupancy.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 eventToString(this)}}function getSnapToFragmentTime(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<.025)?t.start:t.start+t.duration}function getInterstitialUrl(e,t,s){const r=new self.URL(e,s);return"data:"!==r.protocol&&r.searchParams.set("_HLS_primary_id",t),r}function getNextAssetIndex(e,t){for(;null!=(s=e.assetList[++t])&&s.error;)var s;return t}function eventToString(e){return`["${e.identifier}" ${e.cue.pre?"<pre>":e.cue.post?"<post>":""}${e.timelineStart.toFixed(2)}-${e.resumeTime.toFixed(2)}]`}function eventAssetToString(e){const t=e.timelineStart,s=e.duration||0;return`["${e.identifier}" ${t.toFixed(2)}-${(t+s).toFixed(2)}]`}class HlsAssetPlayer{constructor(e,t,s,r){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(Events.PLAYOUT_LIMIT_REACHED,{})};const i=this.hls=new e(t);this.interstitial=s,this.assetItem=r;const n=()=>{this.hasDetails=!0};i.once(Events.LEVEL_LOADED,n),i.once(Events.AUDIO_TRACK_LOADED,n),i.once(Events.SUBTITLE_TRACK_LOADED,n),i.on(Events.MEDIA_ATTACHING,((e,{media:t})=>{this.removeMediaListeners(),this.mediaAttached=t;this.interstitial.playoutLimit&&(t.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&i.on(Events.BUFFER_APPENDED,(()=>{const e=this.bufferedEnd;this.reachedPlayout(e)&&(this._bufferedEosTime=e,i.trigger(Events.BUFFERED_TO_END,void 0))})))}))}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=getInterstitialUrl(t,e.config.primarySessionId||"").href}catch(e){}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if(null!=(t=this.hls)&&t.bufferedToEnd)return!0;if(!e)return!1;const s=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset,i=BufferHelper.bufferInfo(e,r,0);return this.getAssetTime(i.end)>=s-.02}reachedPlayout(e){const t=this.interstitial.playoutLimit;return this.startOffset+e>=t}get destroyed(){var e;return!(null!=(e=this.hls)&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return(null==(e=this.hls)?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=BufferHelper.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;if(!e)return 0;const t=this.interstitial.playoutLimit;if(t){const s=t-this.startOffset;if(s>0&&s<e)return s}return e}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return(null==(e=this.hls)?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const s=e-t;if(Math.abs(s)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,s=this.duration;return Math.min(Math.max(0,e-t),s)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){var e;this.mediaAttached&&(null!=(e=this.hls)&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd))}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),null==(t=this.hls)||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,null==(e=this.hls)||e.detachMedia()}resumeBuffering(){var e;null==(e=this.hls)||e.resumeBuffering()}pauseBuffering(){var e;null==(e=this.hls)||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),(null==(e=this.hls)?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=e=>delete e.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,s){var r;null==(r=this.hls)||r.on(e,t)}once(e,t,s){var r;null==(r=this.hls)||r.once(e,t)}off(e,t,s){var r;null==(r=this.hls)||r.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${eventAssetToString(this.assetItem)} ${null==(e=this.hls)?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const ABUTTING_THRESHOLD_SECONDS=.033;class InterstitialsSchedule extends Logger{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach((e=>e.reset())),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce(((s,r)=>e<=r.startOffset&&t>r.startOffset?(delete r.error,s+1):s),0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let s=-1;e.nextEvent?s=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(s=this.findEventIndex(e.previousEvent.identifier)+1);const r=this.items;if(r)for(r[s]||(void 0===t&&(t=e.start),s=this.findItemIndexAtTime(t));s>=0&&null!=(i=r[s])&&i.event;){var i;s--}return s}findItemIndexAtTime(e,t){const s=this.items;if(s)for(let r=0;r<s.length;r++){let i=s[r];if(t&&"primary"!==t&&(i=i[t]),e===i.start||e>i.start&&e<i.end)return r}return-1}findJumpRestrictedIndex(e,t){const s=this.items;if(s)for(let r=e;r<=t&&s[r];r++){const e=s[r].event;if(null!=e&&e.restrictions.jump&&!e.appendInPlace)return r}return-1}findEventIndex(e){const t=this.items;if(t)for(let r=t.length;r--;){var s;if((null==(s=t[r].event)?void 0:s.identifier)===e)return r}return-1}findAssetIndex(e,t){const s=e.assetList,r=s.length;if(r>1)for(let e=0;e<r;e++){const i=s[e];if(!i.error){const s=i.timelineStart;if(t===s||t>s&&(t<s+(i.duration||0)||e===r-1))return e}}return 0}get assetIdAtEnd(){var e;const t=null==(e=this.items)||null==(e=e[this.length-1])?void 0:e.event;if(t){const e=t.assetList,s=e[e.length-1];if(s)return s.identifier}return null}parseInterstitialDateRanges(e,t){const s=e.main.details,{dateRanges:r}=s,i=this.events,n=this.parseDateRanges(r,{url:s.url},t),a=Object.keys(r),o=i?i.filter((e=>!a.includes(e.identifier))):[];n.length&&n.sort(((e,t)=>{const s=e.cue.pre,r=e.cue.post,i=t.cue.pre,n=t.cue.post;if(s&&!i)return-1;if(i&&!s)return 1;if(r&&!n)return 1;if(n&&!r)return-1;if(!(s||i||r||n)){const s=e.startTime,r=t.startTime;if(s!==r)return s-r}return e.dateRange.tagOrder-t.dateRange.tagOrder})),this.events=n,o.forEach((e=>{this.removeEvent(e)})),this.updateSchedule(e,o)}updateSchedule(e,t=[],s=!1){const r=this.events||[];if(r.length||t.length||this.length<2){const i=this.items,n=this.parseSchedule(r,e);(s||t.length||(null==i?void 0:i.length)!==n.length||n.some(((e,t)=>Math.abs(e.playout.start-i[t].playout.start)>.005||Math.abs(e.playout.end-i[t].playout.end)>.005)))&&(this.items=n,this.onScheduleUpdate(t,i))}}parseDateRanges(e,t,s){const r=[],i=Object.keys(e);for(let n=0;n<i.length;n++){const a=i[n],o=e[a];if(o.isInterstitial){let e=this.eventMap[a];e?e.setDateRange(o):(e=new InterstitialEvent(o,t),this.eventMap[a]=e,!1===s&&(e.appendInPlace=s)),r.push(e)}}return r}parseSchedule(e,t){const s=[],r=t.main.details,i=r.live?1/0:r.edge;let n=0;if((e=e.filter((e=>!(e.error||e.cue.once&&e.hasPlayed)))).length){this.resolveOffsets(e,t);let r=0,o=0;if(e.forEach(((t,a)=>{const l=t.cue.pre,d=t.cue.post,h=e[a-1]||null,c=t.appendInPlace,u=d?i:t.startOffset,f=t.duration,g=t.timelineOccupancy===TimelineOccupancy.Range?f:0,m=t.resumptionOffset,p=(null==h?void 0:h.startTime)===u,E=u+t.cumulativeDuration;let y=c?E+f:u+m;if(l||!d&&u<=0){const e=o;o+=g,t.timelineStart=E;const r=n;n+=f,s.push({event:t,start:E,end:y,playout:{start:r,end:n},integrated:{start:e,end:o}})}else{if(!(u<=i))return;{if(!p){const i=u-r;if(i>.033){const l=r,d=o;o+=i;const h=n;n+=i;const c={previousEvent:e[a-1]||null,nextEvent:t,start:l,end:l+i,playout:{start:h,end:n},integrated:{start:d,end:o}};s.push(c)}else i>0&&h&&(h.cumulativeDuration+=i,s[s.length-1].end=u)}d&&(y=E),t.timelineStart=E;const i=o;o+=g;const l=n;n+=f,s.push({event:t,start:E,end:y,playout:{start:l,end:n},integrated:{start:i,end:o}})}}const v=t.resumeTime;r=d||v>i?i:v})),r<i){var a;const e=r,t=o,l=i-r;o+=l;const d=n;n+=l,s.push({previousEvent:(null==(a=s[s.length-1])?void 0:a.event)||null,nextEvent:null,start:r,end:e+l,playout:{start:d,end:n},integrated:{start:t,end:o}})}this.setDurations(i,n,o)}else{const e=0;s.push({previousEvent:null,nextEvent:null,start:e,end:i,playout:{start:e,end:i},integrated:{start:e,end:i}}),this.setDurations(i,i,i)}return s}setDurations(e,t,s){this.durations={primary:e,playout:t,integrated:s}}resolveOffsets(e,t){const s=t.main.details,r=s.live?1/0:s.edge;let i=0,n=-1;e.forEach(((a,o)=>{const l=a.cue.pre,d=a.cue.post,h=l?0:d?r:a.startTime;this.updateAssetDurations(a);if(n===h?a.cumulativeDuration=i:(i=0,n=h),!d&&a.snapOptions.in&&(a.resumeAnchor=findFragmentByPTS(null,s.fragments,a.startOffset+a.resumptionOffset,0,0)||void 0),a.appendInPlace&&!a.appendInPlaceStarted){this.primaryCanResumeInPlaceAt(a,t)||(a.appendInPlace=!1)}if(!a.appendInPlace&&o+1<e.length){e[o+1].startTime-e[o].resumeTime<.033&&(e[o+1].appendInPlace=!1,e[o+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${a}`))}const c=isFiniteNumber(a.resumeOffset)?a.resumeOffset:a.duration;i+=c}))}primaryCanResumeInPlaceAt(e,t){const s=e.resumeTime,r=e.startTime+e.resumptionOffset;if(Math.abs(s-r)>.025)return this.log(`"${e.identifier}" resumption ${s} not aligned with estimated timeline end ${r}`),!1;return!Object.keys(t).some((r=>{const i=t[r].details,n=i.edge;if(s>=n)return this.log(`"${e.identifier}" resumption ${s} past ${r} playlist end ${n}`),!1;const a=findFragmentByPTS(null,i.fragments,s);if(!a)return this.log(`"${e.identifier}" resumption ${s} does not align with any fragments in ${r} playlist (${i.fragStart}-${i.fragmentEnd})`),!0;const o="audio"===r?.175:0;return!(Math.abs(a.start-s)<.025+o||Math.abs(a.end-s)<.025+o)&&(this.log(`"${e.identifier}" resumption ${s} not aligned with ${r} fragment bounds (${a.start}-${a.end} sn: ${a.sn} cc: ${a.cc})`),!0)}))}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let s=0,r=!1,i=!1;for(let n=0;n<e.assetList.length;n++){const a=e.assetList[n],o=t+s;a.startOffset=s,a.timelineStart=o,r||(r=null===a.duration),i||(i=!!a.error);s+=a.error?0:a.duration||0}e.duration=r&&!i?Math.max(s,e.duration):s}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function segmentToString(e){return`[${e.event?'"'+e.event.identifier+'"':"primary"}: ${e.start.toFixed(2)}-${e.end.toFixed(2)}]`}class AssetListLoader{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const s=e.assetListUrl;let r;try{r=getInterstitialUrl(s,this.hls.sessionId,e.baseUrl)}catch(t){const r=this.assignAssetListError(e,ErrorDetails.ASSET_LIST_LOAD_ERROR,t,s);return void this.hls.trigger(Events.ERROR,r)}t&&"data:"!==r.protocol&&r.searchParams.set("_HLS_start_offset",""+t);const i=this.hls.config,n=new(0,i.loader)(i),a={responseType:"json",url:r.href},o=i.interstitialAssetListLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(t,s,r,i)=>{const n=t.data,a=null==n?void 0:n.ASSETS;if(Array.isArray(a))e.assetListResponse=n,this.hls.trigger(Events.ASSET_LIST_LOADED,{event:e,assetListResponse:n,networkDetails:i});else{const t=this.assignAssetListError(e,ErrorDetails.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),r.url,s,i);this.hls.trigger(Events.ERROR,t)}},onError:(t,s,r,i)=>{const n=this.assignAssetListError(e,ErrorDetails.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${t.code} ${t.text} (${s.url})`),s.url,i,r);this.hls.trigger(Events.ERROR,n)},onTimeout:(t,s,r)=>{const i=this.assignAssetListError(e,ErrorDetails.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${s.url})`),s.url,t,r);this.hls.trigger(Events.ERROR,i)}};return n.load(a,l,d),this.hls.trigger(Events.ASSET_LIST_LOADING,{event:e}),n}assignAssetListError(e,t,s,r,i,n){return e.error=s,{type:ErrorTypes.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:r,error:s,networkDetails:n,stats:i}}}function playWithCatch(e){null==e||e.play().catch((()=>{}))}function timelineMessage(e,t){return`[${e}] Advancing timeline position to ${t}`}class InterstitialsController extends Logger{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const e=this.currentTime;if(void 0===e||this.playbackDisabled||!this.schedule)return;const t=e-this.timelinePos;if(Math.abs(t)<1/7056e5)return;const s=t<=-.01;this.timelinePos=e,this.bufferedPos=e;const r=this.playingItem;if(!r)return void this.checkBuffer();if(s){this.schedule.resetErrorsInRange(e,e-t)&&this.updateSchedule(!0)}if(this.checkBuffer(),s&&e<r.start||e>=r.end){var i;const t=this.findItemIndex(r);let n=this.schedule.findItemIndexAtTime(e);if(-1===n&&(n=t+(s?-1:1),this.log(`seeked ${s?"back ":""}to position not covered by schedule ${e} (resolving from ${t} to ${n})`)),!this.isInterstitial(r)&&null!=(i=this.media)&&i.paused&&(this.shouldPlay=!1),!s&&n>t){const e=this.schedule.findJumpRestrictedIndex(t+1,n);if(e>t)return void this.setSchedulePosition(e)}return void this.setSchedulePosition(n)}const n=this.playingAsset;if(!n){if(this.playingLastItem&&this.isInterstitial(r)){const t=r.event.assetList[0];t&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(e,t))}return}const a=n.timelineStart,o=n.duration||0;var l;(s&&e<a||e>=a+o)&&(null!=(l=r.event)&&l.appendInPlace&&(this.clearInterstitial(r.event,r),this.flushFrontBuffer(e)),this.setScheduleToAssetAtTime(e,n))},this.onTimeupdate=()=>{const e=this.currentTime;if(void 0===e||this.playbackDisabled)return;if(!(e>this.timelinePos))return;this.timelinePos=e,e>this.bufferedPos&&this.checkBuffer();const t=this.playingItem;if(!t||this.playingLastItem)return;if(e>=t.end){this.timelinePos=t.end;const e=this.findItemIndex(t);this.setSchedulePosition(e+1)}const s=this.playingAsset;if(!s)return;e>=s.timelineStart+(s.duration||0)&&this.setScheduleToAssetAtTime(e,s)},this.onScheduleUpdate=(e,t)=>{const s=this.schedule;if(!s)return;const r=this.playingItem,i=s.events||[],n=s.items||[],a=s.durations,o=e.map((e=>e.identifier)),l=!(!i.length&&!o.length);(l||t)&&this.log(`INTERSTITIALS_UPDATED (${i.length}): ${i}\nSchedule: ${n.map((e=>segmentToString(e)))} pos: ${this.timelinePos}`),o.length&&this.log(`Removed events ${o}`);let d=null,h=null;r&&(d=this.updateItem(r,this.timelinePos),this.itemsMatch(r,d)?this.playingItem=d:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const c=this.bufferingItem;if(c&&(h=this.updateItem(c,this.bufferedPos),this.itemsMatch(c,h)?this.bufferingItem=h:c.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(c.event,null))),e.forEach((e=>{e.assetList.forEach((e=>{this.clearAssetPlayer(e.identifier,null)}))})),this.playerQueue.forEach((e=>{if(e.interstitial.appendInPlace){const t=e.assetItem.timelineStart,s=e.timelineOffset-t;if(s)try{e.timelineOffset=t}catch(r){Math.abs(s)>.025&&this.warn(`${r} ("${e.assetId}" ${e.timelineOffset}->${t})`)}}})),l||t){if(this.hls.trigger(Events.INTERSTITIALS_UPDATED,{events:i.slice(0),schedule:n.slice(0),durations:a,removedIds:o}),this.isInterstitial(r)&&o.includes(r.event.identifier))return this.warn(`Interstitial "${r.event.identifier}" removed while playing`),void this.primaryFallback(r.event);r&&this.trimInPlace(d,r),c&&h!==d&&this.trimInPlace(h,c),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new AssetListLoader(e),this.schedule=new InterstitialsSchedule(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Events.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(Events.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(Events.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(Events.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(Events.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(Events.BUFFER_APPENDED,this.onBufferAppended,this),e.on(Events.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Events.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(Events.MEDIA_ENDED,this.onMediaEnded,this),e.on(Events.ERROR,this.onError,this),e.on(Events.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Events.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(Events.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(Events.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(Events.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(Events.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(Events.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Events.BUFFER_APPENDED,this.onBufferAppended,this),e.off(Events.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Events.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(Events.MEDIA_ENDED,this.onMediaEnded,this),e.off(Events.ERROR,this.onError,this),e.off(Events.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;null==(e=this.getBufferingPlayer())||e.resumeBuffering()}pauseBuffering(){var e;null==(e=this.getBufferingPlayer())||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){removeEventListener(e,"play",this.onPlay),removeEventListener(e,"pause",this.onPause),removeEventListener(e,"seeking",this.onSeeking),removeEventListener(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const s=this.media=t.media;addEventListener(s,"seeking",this.onSeeking),addEventListener(s,"timeupdate",this.onTimeupdate),addEventListener(s,"play",this.onPlay),addEventListener(s,"pause",this.onPause)}onMediaAttached(e,t){const s=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,null===s)this.checkStart();else if(!r){this.clearScheduleState();const e=this.findItemIndex(s);this.setSchedulePosition(e)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const s=!!t.transferMedia,r=this.media;if(this.media=null,!s&&(r&&this.removeMediaListeners(r),this.detachedData)){const e=this.getBufferingPlayer();e&&(this.log(`Removing schedule state for detachedData and ${e}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,e.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,s=t=>t?e.getAssetPlayer(t.identifier):t,r=(t,r,n,a,o)=>{if(t){let l=t[r].start;const d=t.event;if(d){if("playout"===r||d.timelineOccupancy!==TimelineOccupancy.Point){const e=s(n);(null==e?void 0:e.interstitial)===d&&(l+=e.assetItem.startOffset+e[o])}}else{l+=("bufferedPos"===a?i():e[a])-t.start}return l}return 0},i=()=>{const t=e.bufferedPos;return t===Number.MAX_VALUE?n("primary"):Math.max(t,0)},n=t=>{var s,r;return null!=(s=e.primaryDetails)&&s.live?e.primaryDetails.edge:(null==(r=e.schedule)?void 0:r.durations[t])||0},a=(t,i)=>{var n,a;const o=e.effectivePlayingItem;if(null!=o&&null!=(n=o.event)&&n.restrictions.skip||!e.schedule)return;e.log(`seek to ${t} "${i}"`);const l=e.effectivePlayingItem,d=e.schedule.findItemIndexAtTime(t,i),h=null==(a=e.schedule.items)?void 0:a[d],c=e.getBufferingPlayer(),u=null==c?void 0:c.interstitial,f=null==u?void 0:u.appendInPlace,g=l&&e.itemsMatch(l,h);if(l&&(f||g)){const n=s(e.playingAsset),a=(null==n?void 0:n.media)||e.primaryMedia;if(a){const s="primary"===i?a.currentTime:r(l,i,e.playingAsset,"timelinePos","currentTime"),o=t-s,d=(f?s:a.currentTime)+o;if(d>=0&&(!n||f||d<=n.duration))return void(a.currentTime=d)}}if(h){let s=t;if("primary"!==i){const e=t-h[i].start;s=h.start+e}const r=!e.isInterstitial(h);if(e.isInterstitial(l)&&!l.event.appendInPlace||!r&&!h.event.appendInPlace){if(l){const n=e.findItemIndex(l);if(d>n){const t=e.schedule.findJumpRestrictedIndex(n+1,d);if(t>n)return void e.setSchedulePosition(t)}let a=0;if(r)e.timelinePos=s,e.checkBuffer();else{const e=h.event.assetList,s=t-(h[i]||h).start;for(let t=e.length;t--;){const r=e[t];if(r.duration&&s>=r.startOffset&&s<r.startOffset+r.duration){a=t;break}}}e.setSchedulePosition(d,a)}}else{const t=e.media||(f?null==c?void 0:c.media:null);t&&(t.currentTime=s)}}},o=()=>{const s=e.effectivePlayingItem;if(e.isInterstitial(s))return s;const r=t();return e.isInterstitial(r)?r:null},l={get bufferedEnd(){const s=t(),i=e.bufferingItem;var n;return i&&i===s&&(r(i,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-i.playout.start||(null==(n=e.bufferingAsset)?void 0:n.startOffset))||0},get currentTime(){const t=o(),s=e.effectivePlayingItem;return s&&s===t?r(s,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-s.playout.start:0},set currentTime(t){const s=o(),r=e.effectivePlayingItem;r&&r===s&&a(t+r.playout.start,"playout")},get duration(){const e=o();return e?e.playout.end-e.playout.start:0},get assetPlayers(){var t;const s=null==(t=o())?void 0:t.event.assetList;return s?s.map((t=>e.getAssetPlayer(t.identifier))):[]},get playingIndex(){var t;const s=null==(t=o())?void 0:t.event;return s&&e.effectivePlayingAsset?s.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return o()}};return this.manager={get events(){var t;return(null==(t=e.schedule)||null==(t=t.events)?void 0:t.slice(0))||[]},get schedule(){var t;return(null==(t=e.schedule)||null==(t=t.items)?void 0:t.slice(0))||[]},get interstitialPlayer(){return o()?l:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const s=t();return e.findItemIndex(s)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return i()},get currentTime(){const t=e.timelinePos;return t>0?t:0},set currentTime(e){a(e,"primary")},get duration(){return n("primary")},get seekableStart(){var t;return(null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0}},integrated:{get bufferedEnd(){return r(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return r(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(e){a(e,"integrated")},get duration(){return n("integrated")},get seekableStart(){var t;return((t,s)=>{var r;if(0!==t&&"primary"!==s&&null!=(r=e.schedule)&&r.length){var i;const r=e.schedule.findItemIndexAtTime(t),n=null==(i=e.schedule.items)?void 0:i[r];if(n)return t+(n[s].start-n.start)}return t})((null==(t=e.primaryDetails)?void 0:t.fragmentStart)||0,"integrated")}},skip:()=>{const t=e.effectivePlayingItem,s=null==t?void 0:t.event;if(s&&!s.restrictions.skip){const r=e.findItemIndex(t);if(s.appendInPlace){const e=t.playout.start+t.event.duration;a(e+.001,"playout")}else e.advanceAfterAssetEnded(s,r,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,s=null==(e=this.schedule)?void 0:e.items;return!!(this.playbackStarted&&t&&s)&&this.findItemIndex(t)===s.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var e,t;if(null===this.mediaSelection)return;const s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let r=this.media;!r&&null!=(e=this.bufferingItem)&&null!=(e=e.event)&&e.appendInPlace&&(r=this.primaryMedia);const i=null==(t=r)?void 0:t.currentTime;return void 0!==i&&isFiniteNumber(i)?i:void 0}get primaryMedia(){var e;return this.media||(null==(e=this.detachedData)?void 0:e.media)||null}isInterstitial(e){return!(null==e||!e.event)}retreiveMediaSource(e,t){const s=this.getAssetPlayer(e);s&&this.transferMediaFromPlayer(s,t)}transferMediaFromPlayer(e,t){const s=e.interstitial.appendInPlace,r=e.media;if(s&&r===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&r)return void(this.detachedData={media:r});const s=e.transferMedia();this.log(`transfer MediaSource from ${e} ${stringify(s)}`),this.detachedData=s}else t&&r&&(this.shouldPlay||(this.shouldPlay=!r.paused))}transferMediaTo(e,t){var s,r;if(e.media===t)return;let i=null;const n=this.hls,a=e!==n,o=a&&e.interstitial.appendInPlace,l=null==(s=this.detachedData)?void 0:s.mediaSource;let d;if(n.media)o&&(i=n.transferMedia(),this.detachedData=i),d="Primary";else if(l){const e=this.getBufferingPlayer();e?(i=e.transferMedia(),d=`${e}`):d="detached MediaSource"}else d="detached media";if(!i)if(l)i=this.detachedData,this.log(`using detachedData: MediaSource ${stringify(i)}`);else if(!this.detachedData||n.media===t){const e=this.playerQueue;e.length>1&&e.forEach((e=>{if(a&&e.interstitial.appendInPlace!==o){const t=e.interstitial;this.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${t}`)}})),this.hls.detachMedia(),this.detachedData={media:t}}const h=i&&"mediaSource"in i&&"closed"!==(null==(r=i.mediaSource)?void 0:r.readyState),c=h&&i?i:t;this.log(`${h?"transfering MediaSource":"attaching media"} to ${a?e:"Primary"} from ${d} (media.currentTime: ${t.currentTime})`);const u=this.schedule;if(c===i&&u){const t=a&&e.assetId===u.assetIdAtEnd;c.overrides={duration:u.duration,endOfStream:!a||t}}e.attachMedia(c)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=null==e?void 0:e.events;if(!t||this.playbackDisabled||!this.media)return;-1===this.bufferedPos&&(this.bufferedPos=0);const s=this.timelinePos,r=this.effectivePlayingItem;if(-1===s){const s=this.hls.startPosition;if(this.log(timelineMessage("checkStart",s)),this.timelinePos=s,t.length&&t[0].cue.pre){const s=e.findEventIndex(t[0].identifier);this.setSchedulePosition(s)}else if(s>=0||!this.primaryLive){const t=this.timelinePos=s>0?s:0,r=e.findItemIndexAtTime(t);this.setSchedulePosition(r)}}else if(r&&!this.playingItem){const t=e.findItemIndex(r);this.setSchedulePosition(t)}}advanceAssetBuffering(e,t){const s=e.event,r=s.findAssetIndex(t),i=getNextAssetIndex(s,r);if(s.isAssetPastPlayoutLimit(i)){if(this.schedule){var n;const t=null==(n=this.schedule.items)?void 0:n[this.findItemIndex(e)+1];t&&this.bufferedToItem(t)}}else this.bufferedToEvent(e,i)}advanceAfterAssetEnded(e,t,s){const r=getNextAssetIndex(e,s);if(e.isAssetPastPlayoutLimit(r)){if(this.schedule){const s=this.schedule.items;if(s){const r=t+1;if(r>=s.length)return void this.setSchedulePosition(-1);const i=e.resumeTime;this.timelinePos<i&&(this.log(timelineMessage("advanceAfterAssetEnded",i)),this.timelinePos=i,e.appendInPlace&&this.advanceInPlace(i),this.checkBuffer(this.bufferedPos<i)),this.setSchedulePosition(r)}}}else{if(e.appendInPlace){const t=e.assetList[r];t&&this.advanceInPlace(t.timelineStart)}this.setSchedulePosition(t,r)}}setScheduleToAssetAtTime(e,t){const s=this.schedule;if(!s)return;const r=t.parentIdentifier,i=s.getEvent(r);if(i){const t=s.findEventIndex(r),n=s.findAssetIndex(i,e);this.advanceAfterAssetEnded(i,t,n-1)}}setSchedulePosition(e,t){var s;const r=null==(s=this.schedule)?void 0:s.items;if(!r||this.playbackDisabled)return;const i=e>=0?r[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${i?segmentToString(i):i}) pos: ${this.timelinePos}`);const n=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(n)){const s=n.event,d=this.playingAsset,h=null==d?void 0:d.identifier,c=h?this.getAssetPlayer(h):null;if(c&&h&&(!this.eventItemsMatch(n,i)||void 0!==t&&h!==s.assetList[t].identifier)){var o;const t=s.findAssetIndex(d);if(this.log(`INTERSTITIAL_ASSET_ENDED ${t+1}/${s.assetList.length} ${eventAssetToString(d)}`),this.endedAsset=d,this.playingAsset=null,this.hls.trigger(Events.INTERSTITIAL_ASSET_ENDED,{asset:d,assetListIndex:t,event:s,schedule:r.slice(0),scheduleIndex:e,player:c}),n!==this.playingItem)return void(this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(s,this.findItemIndex(this.playingItem),t));this.retreiveMediaSource(h,i),!c.media||null!=(o=this.detachedData)&&o.mediaSource||c.detachMedia()}if(!this.eventItemsMatch(n,i)&&(this.endedItem=n,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${s} ${segmentToString(n)}`),s.hasPlayed=!0,this.hls.trigger(Events.INTERSTITIAL_ENDED,{event:s,schedule:r.slice(0),scheduleIndex:e}),s.cue.once)){var l;this.updateSchedule();const e=null==(l=this.schedule)?void 0:l.items;if(i&&e){const s=this.findItemIndex(i);this.advanceSchedule(s,e,t,n,a)}return}}this.advanceSchedule(e,r,t,n,a)}advanceSchedule(e,t,s,r,i){const n=this.schedule;if(!n)return;const a=t[e]||null,o=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach((t=>{const s=t.interstitial,r=n.findEventIndex(s.identifier);(r<e||r>e+1)&&this.clearInterstitial(s,a)})),this.isInterstitial(a)){this.timelinePos=Math.min(Math.max(this.timelinePos,a.start),a.end);const i=a.event;if(void 0===s){const t=getNextAssetIndex(i,(s=n.findAssetIndex(i,this.timelinePos))-1);if(i.isAssetPastPlayoutLimit(t)||i.appendInPlace&&this.timelinePos===a.end)return void this.advanceAfterAssetEnded(i,e,s);s=t}const l=this.waitingItem;this.assetsBuffered(a,o)||this.setBufferingItem(a);let d=this.preloadAssets(i,s);if(this.eventItemsMatch(a,l||r)||(this.waitingItem=a,this.log(`INTERSTITIAL_STARTED ${segmentToString(a)} ${i.appendInPlace?"append in place":""}`),this.hls.trigger(Events.INTERSTITIAL_STARTED,{event:i,schedule:t.slice(0),scheduleIndex:e})),!i.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${i}`);if(i.assetListLoader&&(i.assetListLoader.destroy(),i.assetListLoader=void 0),!o)return void this.log(`Waiting for attachMedia to start Interstitial ${i}`);this.waitingItem=this.endedItem=null,this.playingItem=a;const h=i.assetList[s];if(!h)return void this.advanceAfterAssetEnded(i,e,s||0);if(d||(d=this.getAssetPlayer(h.identifier)),null===d||d.destroyed){const e=i.assetList.length;this.warn(`asset ${s+1}/${e} player destroyed ${i}`),d=this.createAssetPlayer(i,h,s),d.loadSource()}if(!this.eventItemsMatch(a,this.bufferingItem)&&i.appendInPlace&&this.isAssetBuffered(h))return;this.startAssetPlayer(d,s,t,e,o),this.shouldPlay&&playWithCatch(d.media)}else a?(this.resumePrimary(a,e,r),this.shouldPlay&&playWithCatch(this.hls.media)):i&&this.isInterstitial(r)&&(this.endedItem=null,this.playingItem=r,r.event.appendInPlace||this.attachPrimary(n.durations.primary,null))}get playbackDisabled(){return!1===this.hls.config.enableInterstitialPlayback}get primaryDetails(){var e;return null==(e=this.mediaSelection)?void 0:e.main.details}get primaryLive(){var e;return!(null==(e=this.primaryDetails)||!e.live)}resumePrimary(e,t,s){var r,i;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${segmentToString(e)}`),null==(r=this.detachedData)||!r.mediaSource){let s=this.timelinePos;(s<e.start||s>=e.end)&&(s=this.getPrimaryResumption(e,t),this.log(timelineMessage("resumePrimary",s)),this.timelinePos=s),this.attachPrimary(s,e)}if(!s)return;const n=null==(i=this.schedule)?void 0:i.items;n&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${segmentToString(e)}`),this.hls.trigger(Events.INTERSTITIALS_PRIMARY_RESUMED,{schedule:n.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const s=e.start;if(this.primaryLive){const e=this.primaryDetails;if(0===t)return this.hls.startPosition;if(e&&(s<e.fragmentStart||s>e.edge))return this.hls.liveSyncPosition||-1}return s}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);if(null!=t&&t.hls)return t.hls.bufferedToEnd;return BufferHelper.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,s){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const r=this.primaryMedia;if(!r)return;const i=this.hls;i.media?this.checkBuffer():(this.transferMediaTo(i,r),s&&this.startLoadingPrimaryAt(e,s)),s||(this.log(timelineMessage("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,s))}startLoadingPrimaryAt(e,t){var s;const r=this.hls;!r.loadingEnabled||!r.media||Math.abs(((null==(s=r.mainForwardBufferInfo)?void 0:s.start)||r.media.currentTime)-e)>.5?r.startLoad(e,t):r.bufferingEnabled||r.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),null==(e=this.schedule)||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(Events.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(Events.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(-1===t.level||!this.schedule)return;const s=this.hls.levels[t.level];if(!s.details)return;const r=_objectSpread2(_objectSpread2({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=r,this.schedule.parseInterstitialDateRanges(r,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const s=this.hls.audioTracks[t.id],r=this.mediaSelection;if(!r)return void(this.altSelection=_objectSpread2(_objectSpread2({},this.altSelection),{},{audio:s}));const i=_objectSpread2(_objectSpread2({},r),{},{audio:s});this.mediaSelection=i}onSubtitleTrackUpdated(e,t){const s=this.hls.subtitleTracks[t.id],r=this.mediaSelection;if(!r)return void(this.altSelection=_objectSpread2(_objectSpread2({},this.altSelection),{},{subtitles:s}));const i=_objectSpread2(_objectSpread2({},r),{},{subtitles:s});this.mediaSelection=i}onAudioTrackSwitching(e,t){const s=getBasicSelectionOption(t);this.playerQueue.forEach((({hls:e})=>e&&(e.setAudioOption(t)||e.setAudioOption(s))))}onSubtitleTrackSwitch(e,t){const s=getBasicSelectionOption(t);this.playerQueue.forEach((({hls:e})=>e&&(e.setSubtitleOption(t)||-1!==t.id&&e.setSubtitleOption(s))))}onBufferCodecs(e,t){const s=t.tracks;s&&(this.requiredTracks=s)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const s=this.playingItem;if(s&&!this.itemsMatch(s,this.bufferingItem)&&!this.isInterstitial(s)){const e=this.timelinePos;this.bufferedPos=e,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let e=0;e<t.length;e++){const r=t[e];if(r.cue.post){var s;const e=this.schedule.findEventIndex(r.identifier),t=null==(s=this.schedule.items)?void 0:s[e];this.isInterstitial(t)&&this.eventItemsMatch(t,this.bufferingItem)&&this.bufferedToItem(t,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const e=this.findItemIndex(t);this.setSchedulePosition(e+1)}else this.shouldPlay=!1}updateItem(e,t){var s;const r=null==(s=this.schedule)?void 0:s.items;if(e&&r){return r[this.findItemIndex(e,t)]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach(((t,s)=>{e.event.isAssetPastPlayoutLimit(s)&&this.clearAssetPlayer(t.identifier,null)}));const s=e.end+.25,r=BufferHelper.bufferInfo(this.primaryMedia,s,0);if(r.end>s||(r.nextStart||0)>s){this.log(`trim buffered interstitial ${segmentToString(e)} (was ${segmentToString(t)})`);const r=!0;this.attachPrimary(s,null,r),this.flushFrontBuffer(s)}}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var s;return!!t&&(e===t||e.event.identifier===(null==(s=t.event)?void 0:s.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const s=this.mediaSelection;s&&(null==(t=this.schedule)||t.updateSchedule(s,[],e))}checkBuffer(e){var t;const s=null==(t=this.schedule)?void 0:t.items;if(!s)return;const r=BufferHelper.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=r.len<1),this.updateBufferedPos(r.end,s,e)}updateBufferedPos(e,t,s){const r=this.schedule,i=this.bufferingItem;if(this.bufferedPos>e||!r)return;if(1===t.length&&this.itemsMatch(t[0],i))return void(this.bufferedPos=e);const n=this.playingItem,a=this.findItemIndex(n);let o=r.findItemIndexAtTime(e);if(this.bufferedPos<e){var l;const s=this.findItemIndex(i),r=Math.min(s+1,t.length-1),n=t[r];if((-1===o&&i&&e>=i.end||null!=(l=n.event)&&l.appendInPlace&&e+.01>=n.start)&&(o=r),this.isInterstitial(i)){const e=i.event;if(r-a>1&&!1===e.appendInPlace)return;if(0===e.assetList.length&&e.assetListLoader)return}if(this.bufferedPos=e,o>s&&o>a)this.bufferedToItem(n);else{const t=this.primaryDetails;this.primaryLive&&t&&e>t.edge-t.targetduration&&n.start<t.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(n)&&this.preloadAssets(n.event,0)}}else s&&n&&!this.itemsMatch(n,i)&&(o===a?this.bufferedToItem(n):o===a+1&&this.bufferedToItem(t[o]))}assetsBuffered(e,t){return 0!==e.event.assetList.length&&!e.event.assetList.some((e=>{const s=this.getAssetPlayer(e.identifier);return!(null!=s&&s.bufferedInPlaceToEnd(t))}))}setBufferingItem(e){const t=this.bufferingItem,s=this.schedule;if(!this.itemsMatch(e,t)&&s){const{items:r,events:i}=s;if(!r||!i)return t;const n=this.isInterstitial(e),a=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const o=a?a.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${segmentToString(e)}`+(t?` (${o.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(n){const t=s.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach(((e,s)=>{const r=this.getAssetPlayer(e.identifier);r&&(s===t&&r.loadSource(),r.resumeBuffering())}))}else this.hls.resumeBuffering(),this.playerQueue.forEach((e=>e.pauseBuffering()));this.hls.trigger(Events.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:i.slice(0),schedule:r.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const s=this.setBufferingItem(e);if(!this.playbackDisabled)if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(null!==s){this.bufferingAsset=null;const t=this.detachedData;if(t)if(t.mediaSource){const t=!0;this.attachPrimary(e.start,e,t)}else this.preloadPrimary(e);else this.preloadPrimary(e)}}preloadPrimary(e){const t=this.findItemIndex(e),s=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(s)}bufferedToEvent(e,t){const s=e.event,r=0===s.assetList.length&&!s.assetListLoader,i=s.cue.once;if(r||!i){const e=this.preloadAssets(s,t);if(null!=e&&e.interstitial.appendInPlace){const t=this.primaryMedia;t&&this.bufferAssetPlayer(e,t)}}}preloadAssets(e,t){const s=e.assetUrl,r=e.assetList.length,i=0===r&&!e.assetListLoader,n=e.cue.once;if(i){const i=e.timelineStart;if(e.appendInPlace){var a;const t=this.playingItem;this.isInterstitial(t)||(null==t||null==(a=t.nextEvent)?void 0:a.identifier)!==e.identifier||this.flushFrontBuffer(i+.25)}let n,o=0;if(!this.playingItem&&this.primaryLive&&(o=this.hls.startPosition,-1===o&&(o=this.hls.liveSyncPosition||0)),o&&!e.cue.pre&&!e.cue.post){const e=o-i;e>0&&(n=Math.round(1e3*e)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${s?1:r} ${e}${n?` live-start: ${o} start-offset: ${n}`:""}`),s)return this.createAsset(e,0,0,i,e.duration,s);const l=this.assetListLoader.loadAssetList(e,n);l&&(e.assetListLoader=l)}else if(!n&&r){for(let s=t;s<r;s++){const t=e.assetList[s],r=this.getAssetPlayerQueueIndex(t.identifier);-1!==r&&!this.playerQueue[r].destroyed||t.error||this.createAssetPlayer(e,t,s)}const s=e.assetList[t];if(s){const e=this.getAssetPlayer(s.identifier);return e&&e.loadSource(),e}}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`);Object.keys(t).forEach((t=>{this.hls.trigger(Events.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:t})}))}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let s=0;s<t.length;s++)if(e===t[s].assetId)return s;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t)for(let s=0;s<e.length;s++)if(e[s].media===t)return e[s];return null}createAsset(e,t,s,r,i,n){const a={parentIdentifier:e.identifier,identifier:generateAssetIdentifier(e,n,t),duration:i,startOffset:s,timelineStart:r,uri:n};return this.createAssetPlayer(e,a,t)}createAssetPlayer(e,t,s){const r=this.hls,i=r.userConfig;let n=i.videoPreference;const a=r.loadLevelObj||r.levels[r.currentLevel];(n||a)&&(n=_extends({},n),a.videoCodec&&(n.videoCodec=a.videoCodec),a.videoRange&&(n.allowedVideoRanges=[a.videoRange]));const o=r.audioTracks[r.audioTrack],l=r.subtitleTracks[r.subtitleTrack];let d=0;if(this.primaryLive||e.appendInPlace){const e=this.timelinePos-t.timelineStart;if(e>1){const s=t.duration;s&&e<s&&(d=e)}}const h=t.identifier,c=_objectSpread2(_objectSpread2({},i),{},{maxMaxBufferLength:Math.min(180,r.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:r.sessionId,assetPlayerId:h,abrEwmaDefaultEstimate:r.bandwidthEstimate,interstitialsController:void 0,startPosition:d,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:n,audioPreference:o||i.audioPreference,subtitlePreference:l||i.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(c.timelineOffset=t.timelineStart));const u=c.cmcd;null!=u&&u.sessionId&&u.contentId&&(c.cmcd=_extends({},u,{contentId:hash(t.uri)})),this.getAssetPlayer(h)&&this.warn(`Duplicate date range identifier ${e} and asset ${h}`);const f=new HlsAssetPlayer(this.HlsPlayerClass,c,e,t);this.playerQueue.push(f),e.assetList[s]=t;let g=!0;const m=r=>{if(r.live){var i;const t=new Error(`Interstitials MUST be VOD assets ${e}`),r={fatal:!0,type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},n=(null==(i=this.schedule)?void 0:i.findEventIndex(e.identifier))||-1;return void this.handleAssetItemError(r,e,n,s,t.message)}const n=r.edge-r.fragmentStart,a=t.duration;(g||null===a||n>a)&&(g=!1,this.log(`Interstitial asset "${h}" duration change ${a} > ${n}`),t.duration=n,this.updateSchedule())};f.on(Events.LEVEL_UPDATED,((e,{details:t})=>m(t))),f.on(Events.LEVEL_PTS_UPDATED,((e,{details:t})=>m(t))),f.on(Events.EVENT_CUE_ENTER,(()=>this.onInterstitialCueEnter()));const p=(e,t)=>{const s=this.getAssetPlayer(h);if(s&&t.tracks){s.off(Events.BUFFER_CODECS,p),s.tracks=t.tracks;const e=this.primaryMedia;this.bufferingAsset===s.assetItem&&e&&!s.media&&this.bufferAssetPlayer(s,e)}};f.on(Events.BUFFER_CODECS,p);f.on(Events.BUFFERED_TO_END,(()=>{var s;const r=this.getAssetPlayer(h);if(this.log(`buffered to end of asset ${r}`),!r||!this.schedule)return;const i=this.schedule.findEventIndex(e.identifier),n=null==(s=this.schedule.items)?void 0:s[i];this.isInterstitial(n)&&this.advanceAssetBuffering(n,t)}));const E=t=>()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;this.shouldPlay=!0;const s=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,s,t)};return f.once(Events.MEDIA_ENDED,E(s)),f.once(Events.PLAYOUT_LIMIT_REACHED,E(1/0)),f.on(Events.ERROR,((t,r)=>{if(!this.schedule)return;const i=this.getAssetPlayer(h);if(r.details===ErrorDetails.BUFFER_STALLED_ERROR)return null!=i&&i.appendInPlace?void this.handleInPlaceStall(e):(this.onTimeupdate(),void this.checkBuffer(!0));this.handleAssetItemError(r,e,this.schedule.findEventIndex(e.identifier),s,`Asset player error ${r.error} ${e}`)})),f.on(Events.DESTROYING,(()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;const t=new Error(`Asset player destroyed unexpectedly ${h}`),r={fatal:!0,type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};this.handleAssetItemError(r,e,this.schedule.findEventIndex(e.identifier),s,t.message)})),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${eventAssetToString(t)}`),this.hls.trigger(Events.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:f}),f}clearInterstitial(e,t){e.assetList.forEach((e=>{this.clearAssetPlayer(e.identifier,t)})),e.reset()}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(-1!==t){this.log(`reset asset player "${e}" after error`);const s=this.playerQueue[t];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(e,t){const s=this.getAssetPlayerQueueIndex(e);if(-1!==s){const e=this.playerQueue[s];this.log(`clear ${e} toSegment: ${t?segmentToString(t):t}`),this.transferMediaFromPlayer(e,t),this.playerQueue.splice(s,1),e.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,s,r,i){const{interstitial:n,assetItem:a,assetId:o}=e,l=n.assetList.length,d=this.playingAsset;this.endedAsset=null,this.playingAsset=a,d&&d.identifier===o||(d&&(this.clearAssetPlayer(d.identifier,s[r]),delete d.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${eventAssetToString(a)}`),this.hls.trigger(Events.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:t,event:n,schedule:s.slice(0),scheduleIndex:r,player:e})),this.bufferAssetPlayer(e,i)}bufferAssetPlayer(e,t){var s,r;if(!this.schedule)return;const{interstitial:i,assetItem:n}=e,a=this.schedule.findEventIndex(i.identifier),o=null==(s=this.schedule.items)?void 0:s[a];if(!o)return;e.loadSource(),this.setBufferingItem(o),this.bufferingAsset=n;const l=this.getBufferingPlayer();if(l===e)return;const d=i.appendInPlace;if(d&&!1===(null==l?void 0:l.interstitial.appendInPlace))return;const h=(null==l?void 0:l.tracks)||(null==(r=this.detachedData)?void 0:r.tracks)||this.requiredTracks;if(d&&n!==this.playingAsset){if(!e.tracks)return void this.log(`Waiting for track info before buffering ${e}`);if(h&&!isCompatibleTrackChange(h,e.tracks)){const t=new Error(`Asset ${eventAssetToString(n)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(h)}')`),s={fatal:!0,type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},r=i.findAssetIndex(n);return void this.handleAssetItemError(s,i,a,r,t.message)}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,s=this.primaryMedia;if(!t||!s)return;const r=s.currentTime,i=t.findAssetIndex(e,r),n=e.assetList[i];if(n){const a=this.getAssetPlayer(n.identifier);if(a){const o=a.currentTime||r-n.timelineStart,l=a.duration-o;if(this.warn(`Stalled at ${o} of ${o+l} in ${a} ${e} (media.currentTime: ${r})`),o&&(l/s.playbackRate<.5||a.bufferedInPlaceToEnd(s))&&a.hls){const s=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,s,i)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,s,r,i){if(e.details===ErrorDetails.BUFFER_STALLED_ERROR)return;const n=t.assetList[r]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${n?eventAssetToString(n):n} ${e.error}`),!this.schedule)return;const a=(null==n?void 0:n.identifier)||"",o=this.getAssetPlayerQueueIndex(a),l=this.playerQueue[o]||null,d=this.schedule.items,h=_extends({},e,{fatal:!1,errorAction:createDoNothingErrorAction(!0),asset:n,assetListIndex:r,event:t,schedule:d,scheduleIndex:s,player:l});if(this.hls.trigger(Events.INTERSTITIAL_ASSET_ERROR,h),!e.fatal)return;const c=this.playingAsset,u=this.bufferingAsset,f=new Error(i);if(n&&(this.clearAssetPlayer(a,null),n.error=f),t.assetList.some((e=>!e.error)))for(let e=r;e<t.assetList.length;e++)this.resetAssetPlayer(t.assetList[e].identifier);else t.error=f;this.updateSchedule(!0),t.error?this.primaryFallback(t):c&&c.identifier===a?this.advanceAfterAssetEnded(t,s,r):u&&u.identifier===a&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,u)}primaryFallback(e){const t=e.timelineStart,s=this.effectivePlayingItem;if(s){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${this.timelinePos} playing: ${segmentToString(s)} error: ${e.error}`);let r=this.timelinePos;-1===r&&(r=this.hls.startPosition);const i=this.updateItem(s,r);if(this.itemsMatch(s,i)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t)),!this.schedule)return;const n=this.schedule.findItemIndexAtTime(r);this.setSchedulePosition(n)}else this.checkStart()}onAssetListLoaded(e,t){var s,r;const i=t.event,n=i.identifier,a=t.assetListResponse.ASSETS;if(null==(s=this.schedule)||!s.hasEvent(n))return;const o=i.timelineStart,l=i.duration;let d=0;a.forEach(((e,t)=>{const s=parseFloat(e.DURATION);this.createAsset(i,t,d,o+d,s,e.URI),d+=s})),i.duration=d,this.log(`Loaded asset-list with duration: ${d} (was: ${l}) ${i}`);const h=this.waitingItem,c=(null==h?void 0:h.event.identifier)===n;this.updateSchedule();const u=null==(r=this.bufferingItem)?void 0:r.event;if(c){var f;const e=this.schedule.findEventIndex(n),t=null==(f=this.schedule.items)?void 0:f[e];if(t){if(!this.playingItem&&this.timelinePos>t.end){if(this.schedule.findItemIndexAtTime(this.timelinePos)!==e)return i.error=new Error(`Interstitial no longer within playback range ${this.timelinePos} ${i}`),this.updateSchedule(!0),void this.primaryFallback(i)}this.setBufferingItem(t)}this.setSchedulePosition(e)}else if((null==u?void 0:u.identifier)===n){const e=i.assetList[0];if(e){const t=this.getAssetPlayer(e.identifier);if(u.appendInPlace){const e=this.primaryMedia;t&&e&&this.bufferAssetPlayer(t,e)}else t&&t.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case ErrorDetails.ASSET_LIST_PARSING_ERROR:case ErrorDetails.ASSET_LIST_LOAD_ERROR:case ErrorDetails.ASSET_LIST_LOAD_TIMEOUT:{const e=t.interstitial;e&&(this.updateSchedule(!0),this.primaryFallback(e));break}case ErrorDetails.BUFFER_STALLED_ERROR:{const e=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(e)&&e.event.appendInPlace)return void this.handleInPlaceStall(e.event);this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}const TICK_INTERVAL$2=500;class SubtitleStreamController extends BaseStreamController{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",PlaylistLevelType.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Events.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(Events.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(Events.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(Events.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(Events.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Events.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(Events.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(Events.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(Events.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(Events.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=State.IDLE,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:s,success:r}=t;if(this.fragContextChanged(s)||(isMediaFragment(s)&&(this.fragPrevious=s),this.state=State.IDLE),!r)return;const i=this.tracksBuffered[this.currentTrackId];if(!i)return;let n;const a=s.start;for(let e=0;e<i.length;e++)if(a>=i[e].start&&a<=i[e].end){n=i[e];break}const o=s.start+s.duration;n?n.end=o:(n={start:a,end:o},i.push(n)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:s,endOffset:r}=t;if(0===s&&r!==Number.POSITIVE_INFINITY){const e=r-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach((t=>{for(let s=0;s<t.length;)if(t[s].end<=e)t.shift();else{if(!(t[s].start<e))break;t[s].start=e,s++}})),this.fragmentTracker.removeFragmentsInRange(s,e,PlaylistLevelType.SUBTITLE)}}onError(e,t){const s=t.frag;(null==s?void 0:s.type)===PlaylistLevelType.SUBTITLE&&(t.details===ErrorDetails.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==State.STOPPED&&(this.state=State.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){this.levels&&subtitleOptionsIdentical(this.levels,t)?this.levels=t.map((e=>new Level(e))):(this.tracksBuffered=[],this.levels=t.map((e=>{const t=new Level(e);return this.tracksBuffered[t.id]=[],t})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,PlaylistLevelType.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,null==(s=this.levels)||!s.length||-1===this.currentTrackId)return void this.clearInterval();const r=this.levels[this.currentTrackId];null!=r&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.state!==State.STOPPED&&this.setInterval(500)}onSubtitleTrackLoaded(e,t){var s;const{currentTrackId:r,levels:i}=this,{details:n,id:a}=t;if(!i)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=i[a];if(a>=i.length||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||null!=(s=o.details)&&s.live){if(n.deltaUpdateFailed)return;const e=this.mainDetails;if(!e)return void(this.startFragRequested=!1);const t=e.fragments[0];var d;if(o.details)l=this.alignPlaylists(n,o.details,null==(d=this.levelLastLoaded)?void 0:d.details),0===l&&t&&(l=t.start,addSliding(n,l));else n.hasProgramDateTime&&e.hasProgramDateTime?(alignMediaPlaylistByPDT(n,e),l=n.fragmentStart):t&&(l=t.start,addSliding(n,l));e&&!this.startFragRequested&&this.setStartPosition(e,l)}if(o.details=n,this.levelLastLoaded=o,a===r&&(this.hls.trigger(Events.SUBTITLE_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===State.IDLE)){findFragmentByPTS(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}_handleFragmentLoadComplete(e){const{frag:t,payload:s}=e,r=t.decryptdata,i=this.hls;if(!this.fragContextChanged(t)&&s&&s.byteLength>0&&null!=r&&r.key&&r.iv&&isFullSegmentEncryption(r.method)){const e=performance.now();this.decrypter.decrypt(new Uint8Array(s),r.key.buffer,r.iv.buffer,getAesModeFromFullSegmentMethod(r.method)).catch((e=>{throw i.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e})).then((s=>{const r=performance.now();i.trigger(Events.FRAG_DECRYPTED,{frag:t,payload:s,stats:{tstart:e,tdecrypt:r}})})).catch((e=>{this.warn(`${e.name}: ${e.message}`),this.state=State.IDLE}))}}doTick(){if(this.media){if(this.state===State.IDLE){const{currentTrackId:e,levels:t}=this,s=null==t?void 0:t[e];if(!s||!t.length||!s.details)return;if(this.waitForLive(s))return;const{config:r}=this,i=this.getLoadPosition(),n=BufferHelper.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],i,r.maxBufferHole),{end:a,len:o}=n,l=s.details;if(o>this.hls.maxBufferLength+l.levelTargetDuration)return;const d=l.fragments,h=d.length,c=l.edge;let u=null;const f=this.fragPrevious;if(a<c){const e=r.maxFragLookUpTolerance,t=a>c-e?0:e;u=findFragmentByPTS(f,d,Math.max(d[0].start,a),t),!u&&f&&f.start<d[0].start&&(u=d[0])}else u=d[h-1];if(u=this.filterReplacedPrimary(u,s.details),!u)return;const g=d[u.sn-l.startSN-1];if(g&&g.cc===u.cc&&this.fragmentTracker.getState(g)===FragmentState.NOT_LOADED&&(u=g),this.fragmentTracker.getState(u)===FragmentState.NOT_LOADED){const e=this.mapToInitFragWhenRequired(u);e&&this.loadFragment(e,s,a)}}}else this.state=State.IDLE}loadFragment(e,t,s){isMediaFragment(e)?super.loadFragment(e,t,s):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new BufferableInstance(this.tracksBuffered[this.currentTrackId]||[])}}class BufferableInstance{constructor(e){this.buffered=void 0;const t=(t,s,r)=>{if((s>>>=0)>r-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${r})`);return e[s][t]};this.buffered={get length(){return e.length},end:s=>t("end",s,e.length),start:s=>t("start",s,e.length)}}}const specialCea608CharsCodes={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},getCharForByte=e=>String.fromCharCode(specialCea608CharsCodes[e]||e),NR_ROWS=15,NR_COLS=100,rowsLowCh1={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},rowsHighCh1={17:2,18:4,21:6,22:8,23:10,19:13,20:15},rowsLowCh2={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},rowsHighCh2={25:2,26:4,29:6,30:8,31:10,27:13,28:15},backgroundColors=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class CaptionsLogger{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const s="function"==typeof t?t():t;logger.log(`${this.time} [${e}] ${s}`)}}}const numArrayToHexArray=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t};class PenState{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let s=0;s<t.length;s++){const r=t[s];e.hasOwnProperty(r)&&(this[r]=e[r])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class StyledUnicodeChar{constructor(){this.uchar=" ",this.penState=new PenState}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}}class Row{constructor(e){this.chars=[],this.pos=0,this.currPenState=new PenState,this.cueStartTime=null,this.logger=void 0;for(let e=0;e<100;e++)this.chars.push(new StyledUnicodeChar);this.logger=e}equals(e){for(let t=0;t<100;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<100;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<100;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>100&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=100)}moveCursor(e){const t=this.pos+e;if(e>1)for(let e=this.pos+1;e<t+1;e++)this.chars[e].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=getCharForByte(e);this.pos>=100?this.logger.log(0,(()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!")):(this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1))}clearFromPos(e){let t;for(t=e;t<100;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let s=0;s<100;s++){const r=this.chars[s].uchar;" "!==r&&(t=!1),e.push(r)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e);this.chars[this.pos].setPenState(this.currPenState)}}class CaptionScreen{constructor(e){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<15;t++)this.rows.push(new Row(e));this.logger=e}reset(){for(let e=0;e<15;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let s=0;s<15;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<15;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<15;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e);this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,(()=>"pacData = "+stringify(e)));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let e=0;e<15;e++)this.rows[e].clear();const e=this.currRow+1-this.nrRollUpRows,s=this.lastOutputScreen;if(s){const r=s.rows[e].cueStartTime,i=this.logger.time;if(null!==r&&null!==i&&r<i)for(let r=0;r<this.nrRollUpRows;r++)this.rows[t-this.nrRollUpRows+r+1].copy(s.rows[e+r])}}this.currRow=t;const s=this.rows[this.currRow];if(null!==e.indent){const t=e.indent,r=Math.max(t-1,0);s.setCursor(e.indent),e.color=s.chars[r].penState.foreground}const r={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(r)}setBkgData(e){this.logger.log(2,(()=>"bkgData = "+stringify(e))),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,(()=>this.getDisplayText()));const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let s="",r=-1;for(let s=0;s<15;s++){const i=this.rows[s].getTextString();i&&(r=s+1,e?t.push("Row "+r+": '"+i+"'"):t.push(i.trim()))}return t.length>0&&(s=e?"["+t.join(" | ")+"]":t.join("\n")),s}getTextAndFormat(){return this.rows}}class Cea608Channel{constructor(e,t,s){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new CaptionScreen(s),this.nonDisplayedMemory=new CaptionScreen(s),this.lastOutputScreen=new CaptionScreen(s),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,(()=>"MODE="+e)),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let t=0;t<e.length;t++)this.writeScreen.insertChar(e[t]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,(()=>t+": "+this.writeScreen.getDisplayText(!0))),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,(()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0))),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,(()=>"DISP: "+this.displayedMemory.getDisplayText()))}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{const s=Math.floor(e/2)-16,r=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=r[s]}this.logger.log(2,"MIDROW: "+stringify(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class Cea608Parser{constructor(e,t,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory=createCmdHistory(),this.logger=void 0;const r=this.logger=new CaptionsLogger;this.channels=[null,new Cea608Channel(e,t,r),new Cea608Channel(e+1,s,r)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let e=0;e<t.length;e+=2){const s=127&t[e],r=127&t[e+1];let i=!1,n=null;if(0===s&&0===r)continue;this.logger.log(3,(()=>"["+numArrayToHexArray([t[e],t[e+1]])+"] -> ("+numArrayToHexArray([s,r])+")"));const a=this.cmdHistory;if(s>=16&&s<=31){if(hasCmdRepeated(s,r,a)){setLastCmd(null,null,a),this.logger.log(3,(()=>"Repeated command ("+numArrayToHexArray([s,r])+") is dropped"));continue}setLastCmd(s,r,this.cmdHistory),i=this.parseCmd(s,r),i||(i=this.parseMidrow(s,r)),i||(i=this.parsePAC(s,r)),i||(i=this.parseBackgroundAttributes(s,r))}else setLastCmd(null,null,a);if(!i&&(n=this.parseChars(s,r),n)){const e=this.currentChannel;if(e&&e>0){this.channels[e].insertChars(n)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}i||n||this.logger.log(2,(()=>"Couldn't parse cleaned data "+numArrayToHexArray([s,r])+" orig: "+numArrayToHexArray([t[e],t[e+1]])))}}parseCmd(e,t){if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=33&&t<=35))return!1;const s=20===e||21===e||23===e?1:2,r=this.channels[s];return 20===e||21===e||28===e||29===e?32===t?r.ccRCL():33===t?r.ccBS():34===t?r.ccAOF():35===t?r.ccAON():36===t?r.ccDER():37===t?r.ccRU(2):38===t?r.ccRU(3):39===t?r.ccRU(4):40===t?r.ccFON():41===t?r.ccRDC():42===t?r.ccTR():43===t?r.ccRTD():44===t?r.ccEDM():45===t?r.ccCR():46===t?r.ccENM():47===t&&r.ccEOC():r.ccTO(t-32),this.currentChannel=s,!0}parseMidrow(e,t){let s=0;if((17===e||25===e)&&t>=32&&t<=47){if(s=17===e?1:2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const r=this.channels[s];return!!r&&(r.ccMIDROW(t),this.logger.log(3,(()=>"MIDROW ("+numArrayToHexArray([e,t])+")")),!0)}return!1}parsePAC(e,t){let s;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127)&&!((16===e||24===e)&&t>=64&&t<=95))return!1;const r=e<=23?1:2;s=t>=64&&t<=95?1===r?rowsLowCh1[e]:rowsLowCh2[e]:1===r?rowsHighCh1[e]:rowsHighCh2[e];const i=this.channels[r];return!!i&&(i.setPAC(this.interpretPAC(s,t)),this.currentChannel=r,!0)}interpretPAC(e,t){let s;const r={color:null,italics:!1,indent:null,underline:!1,row:e};return s=t>95?t-96:t-64,r.underline=1==(1&s),s<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(r.italics=!0,r.color="white"):r.indent=4*Math.floor((s-16)/2),r}parseChars(e,t){let s,r=null,i=null;if(e>=25?(s=2,i=e-8):(s=1,i=e),i>=17&&i<=19){let e;e=17===i?t+80:18===i?t+112:t+144,this.logger.log(2,(()=>"Special char '"+getCharForByte(e)+"' in channel "+s)),r=[e]}else e>=32&&e<=127&&(r=0===t?[e]:[e,t]);return r&&this.logger.log(3,(()=>"Char codes = "+numArrayToHexArray(r).join(","))),r}parseBackgroundAttributes(e,t){if(!((16===e||24===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=45&&t<=47))return!1;let s;const r={};16===e||24===e?(s=Math.floor((t-32)/2),r.background=backgroundColors[s],t%2==1&&(r.background=r.background+"_semi")):45===t?r.background="transparent":(r.foreground="black",47===t&&(r.underline=!0));const i=e<=23?1:2;return this.channels[i].setBkgData(r),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}setLastCmd(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const s=this.channels[t];s&&s.cueSplitAtTime(e)}}}function setLastCmd(e,t,s){s.a=e,s.b=t}function hasCmdRepeated(e,t,s){return s.a===e&&s.b===t}function createCmdHistory(){return{a:null,b:null}}class OutputFilter{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,s){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class TimelineController{constructor(e){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.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=newVTTCCs(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Events.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(Events.FRAG_LOADING,this.onFragLoading,this),e.on(Events.FRAG_LOADED,this.onFragLoaded,this),e.on(Events.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(Events.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(Events.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Events.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(Events.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Events.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(Events.FRAG_LOADING,this.onFragLoading,this),e.off(Events.FRAG_LOADED,this.onFragLoaded,this),e.off(Events.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(Events.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(Events.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Events.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new OutputFilter(this,"textTrack1"),t=new OutputFilter(this,"textTrack2"),s=new OutputFilter(this,"textTrack3"),r=new OutputFilter(this,"textTrack4");this.cea608Parser1=new Cea608Parser(1,e,t),this.cea608Parser2=new Cea608Parser(3,s,r)}addCues(e,t,s,r,i){let n=!1;for(let e=i.length;e--;){const r=i[e],a=intersection(r[0],r[1],t,s);if(a>=0&&(r[0]=Math.min(r[0],t),r[1]=Math.max(r[1],s),n=!0,a/(s-t)>.5))return}if(n||i.push([t,s]),this.config.renderTextTracksNatively){const i=this.captionsTracks[e].track;this.Cues.newCue(i,t,s,r)}else{const i=this.Cues.newCue(null,t,s,r);this.hls.trigger(Events.CUES_PARSED,{type:"captions",cues:i,track:e})}}onInitPtsFound(e,{frag:t,id:s,initPTS:r,timescale:i,trackId:n}){const{unparsedVttFrags:a}=this;s===PlaylistLevelType.MAIN&&(this.initPTS[t.cc]={baseTime:r,timescale:i,trackId:n}),a.length&&(this.unparsedVttFrags=[],a.forEach((e=>{this.initPTS[e.frag.cc]?this.onFragLoaded(Events.FRAG_LOADED,e):this.hls.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e.frag,error:new Error("Subtitle discontinuity domain does not match main")})})))}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:s,media:r}=this,{label:i,languageCode:n}=t[e];r&&(s[e]=createTrackNode(r,"captions",i,n))}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const s={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=s,this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}onMediaAttaching(e,t){this.media=t.media}onMediaDetaching(e,t){const s=!!t.transferMedia;if(this.media=null,!s){if(this.config.renderTextTracksNatively){const{captionsTracks:e}=this;for(const t in e)e[t].remove()}this.captionsTracks={},this.nonNativeCaptionsTracks={}}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=newVTTCCs(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}onSubtitleTracksUpdated(e,t){const s=t.subtitleTracks||[];if(s.length&&!this.config.renderTextTracksNatively&&!subtitleOptionsIdentical(this.tracks,s)){const e=s.map((e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e})));this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}this.tracks=s}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach((e=>{const t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;const s=`textTrack${t[1]}`,r=this.captionsProperties[s];r&&(r.label=e.name,e.lang&&(r.languageCode=e.lang),r.media=e)}))}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===PlaylistLevelType.MAIN){var s,r;const{cea608Parser1:e,cea608Parser2:i,lastSn:n}=this,{cc:a,sn:o}=t.frag,l=null!=(s=null==(r=t.part)?void 0:r.index)?s:-1;e&&i&&(o!==n+1||o===n&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(e.reset(),i.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(e,t){const{frag:s,payload:r}=t;if(s.level<this.tracks.length&&s.type===PlaylistLevelType.SUBTITLE)if(r.byteLength){const e=s.decryptdata,i="stats"in t;if(null==e||!e.encrypted||i){const e=this.tracks[s.level],i=this.vttCCs;i[s.cc]||(i[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),e.textCodec===IMSC1_CODEC?this._parseIMSC1(s,r):this._parseVTTs(t)}}else this.hls.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const s=this.hls;parseIMSC1(t,this.initPTS[e.cc],(t=>{this._appendCues(t,e.level),s.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})}),(t=>{s.logger.log(`Failed to parse IMSC1: ${t}`),s.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})}))}_parseVTTs(e){var t;const{frag:s,payload:r}=e,{initPTS:i,unparsedVttFrags:n}=this,a=i.length-1;if(!i[s.cc]&&-1===a)return void n.push(e);const o=this.hls;parseWebVTT(null!=(t=s.initSegment)&&t.data?appendUint8Array(s.initSegment.data,new Uint8Array(r)).buffer:r,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,(e=>{this._appendCues(e,s.level),o.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})}),(t=>{const i="Missing initPTS for VTT MPEGTS"===t.message;i?n.push(e):this.config.enableIMSC1&&this._fallbackToIMSC1(s,r),o.logger.log(`Failed to parse VTT cue: ${t}`),i&&a>s.cc||o.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:t})}))}_fallbackToIMSC1(e,t){const s=this.tracks[e.level];s.textCodec||parseIMSC1(t,this.initPTS[e.cc],(()=>{s.textCodec=IMSC1_CODEC,this._parseIMSC1(e,t)}),(()=>{s.textCodec="wvtt"}))}_appendCues(e,t){const s=this.hls;if(this.config.renderTextTracksNatively){var r;const s=null==(r=this.tracks[t].trackNode)?void 0:r.track;if(!s||"disabled"===s.mode)return;e.forEach((e=>addCueToTrack(s,e)))}else{const r=this.tracks[t];if(!r)return;const i=r.default?"default":"subtitles"+t;s.trigger(Events.CUES_PARSED,{type:"subtitles",cues:e,track:i})}}onFragDecrypted(e,t){const{frag:s}=t;s.type===PlaylistLevelType.SUBTITLE&&this.onFragLoaded(Events.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:r}=t;if(s.type!==PlaylistLevelType.MAIN||"NONE"!==this.closedCaptionsForLevel(s))for(let e=0;e<r.length;e++){const t=r[e].bytes;if(t){this.cea608Parser1||this.initCea608Parsers();const s=this.extractCea608Data(t);this.cea608Parser1.addData(r[e].pts,s[0]),this.cea608Parser2.addData(r[e].pts,s[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:s,endOffsetSubtitles:r,type:i}){const{media:n}=this;if(n&&!(n.currentTime<s)){if(!i||"video"===i){const{captionsTracks:e}=this;Object.keys(e).forEach((r=>removeCuesInRange(e[r].track,t,s)))}this.config.renderTextTracksNatively&&0===t&&void 0!==r&&this.tracks.forEach((e=>{var s;const i=null==(s=e.trackNode)?void 0:s.track;i&&removeCuesInRange(i,t,r)}))}}extractCea608Data(e){const t=[[],[]],s=31&e[0];let r=2;for(let i=0;i<s;i++){const s=e[r++],i=127&e[r++],n=127&e[r++];if(0===i&&0===n)continue;if(0!=(4&s)){const e=3&s;0!==e&&1!==e||(t[e].push(i),t[e].push(n))}}return t}}function intersection(e,t,s,r){return Math.min(t,r)-Math.max(e,s)}function newVTTCCs(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const WHITESPACE_CHAR=/\s/,Cues={newCue(e,t,s,r){const i=[];let n,a,o,l,d;const h=self.VTTCue||self.TextTrackCue;for(let u=0;u<r.rows.length;u++)if(n=r.rows[u],o=!0,l=0,d="",!n.isEmpty()){var c;for(let e=0;e<n.chars.length;e++)WHITESPACE_CHAR.test(n.chars[e].uchar)&&o?l++:(d+=n.chars[e].uchar,o=!1);n.cueStartTime=t,t===s&&(s+=1e-4),l>=16?l--:l++;const r=fixLineBreaks(d.trim()),f=generateCueId(t,s,r);null!=e&&null!=(c=e.cues)&&c.getCueById(f)||(a=new h(t,s,r),a.id=f,a.line=u+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),i.push(a))}return e&&i.length&&(i.sort(((e,t)=>"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line)),i.forEach((t=>addCueToTrack(e,t)))),i}};function fetchSupported(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}const BYTERANGE=/(\d+)-(\d+)\/(\d+)/;class FetchLoader{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||getRequest,this.controller=new self.AbortController,this.stats=new LoadStats}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,s){const r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();const i=getRequestParameters(e,this.controller.signal),n="arraybuffer"===e.responseType,a=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=s,this.request=this.fetchSetup(e,i),self.clearTimeout(this.requestTimeout),t.timeout=o&&isFiniteNumber(o)?o:l,this.requestTimeout=self.setTimeout((()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response))}),t.timeout);(isPromise(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then((s=>{var i;this.response=this.loader=s;const a=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout((()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response))}),l-(a-r.loading.start)),!s.ok){const{status:e,statusText:t}=s;throw new FetchError(t||"fetch, bad network response",e,s)}r.loading.first=a,r.total=getContentLength(s.headers)||r.total;const o=null==(i=this.callbacks)?void 0:i.onProgress;return o&&isFiniteNumber(t.highWaterMark)?this.loadProgressively(s,r,e,t.highWaterMark,o):n?s.arrayBuffer():"json"===e.responseType?s.json():s.text()})).then((s=>{var i,n;const o=this.response;if(!o)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);const l=s[a];l&&(r.loaded=r.total=l);const d={url:o.url,data:s,code:o.status},h=null==(i=this.callbacks)?void 0:i.onProgress;h&&!isFiniteNumber(t.highWaterMark)&&h(r,e,s,o),null==(n=this.callbacks)||n.onSuccess(d,r,e,o)})).catch((t=>{var s;if(self.clearTimeout(this.requestTimeout),r.aborted)return;const i=t&&t.code||0,n=t?t.message:null;null==(s=this.callbacks)||s.onError({code:i,text:n},e,t?t.details:null,r)}))}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,s,r=0,i){const n=new ChunkCache,a=e.body.getReader(),o=()=>a.read().then((a=>{if(a.done)return n.dataLength&&i(t,s,n.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const l=a.value,d=l.length;return t.loaded+=d,d<r||n.dataLength?(n.push(l),n.dataLength>=r&&i(t,s,n.flush().buffer,e)):i(t,s,l.buffer,e),o()})).catch((()=>Promise.reject()));return o()}}function getRequestParameters(e,t){const s={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(_extends({},e.headers))};return e.rangeEnd&&s.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1)),s}function getByteRangeLength(e){const t=BYTERANGE.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}function getContentLength(e){const t=e.get("Content-Range");if(t){const e=getByteRangeLength(t);if(isFiniteNumber(e))return e}const s=e.get("Content-Length");if(s)return parseInt(s)}function getRequest(e,t){return new self.Request(e.url,t)}class FetchError extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const AGE_HEADER_LINE_REGEX=/^age:\s*[\d.]+\s*$/im;class XhrLoader{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new LoadStats,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const s=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;const i=this.xhrSetup;i?Promise.resolve().then((()=>{if(this.loader===s&&!this.stats.aborted)return i(s,t.url)})).catch((e=>{if(this.loader===s&&!this.stats.aborted)return s.open("GET",t.url,!0),i(s,t.url)})).then((()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)})).catch((e=>{var i;null==(i=this.callbacks)||i.onError({code:s.status,text:e.message},t,s,r)})):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const r=t.headers,{maxTimeToFirstByteMs:i,maxLoadTimeMs:n}=s.loadPolicy;if(r)for(const t in r)e.setRequestHeader(t,r[t]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),s.timeout=i&&isFiniteNumber(i)?i:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:s}=this;if(!e||!t)return;const r=t.readyState,i=this.config;if(!s.aborted&&r>=2&&(0===s.loading.first&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),i.timeout!==i.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),i.timeout=i.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),4===r)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const r=t.status,l="text"===t.responseType?t.responseText:null;if(r>=200&&r<300){const i=null!=l?l:t.response;if(null!=i){var n,a;s.loading.end=Math.max(self.performance.now(),s.loading.first);const o="arraybuffer"===t.responseType?i.byteLength:i.length;s.loaded=s.total=o,s.bwEstimate=8e3*s.total/(s.loading.end-s.loading.first);const l=null==(n=this.callbacks)?void 0:n.onProgress;l&&l(s,e,i,t);const d={url:t.responseURL,data:i,code:r};return void(null==(a=this.callbacks)||a.onSuccess(d,s,e,t))}}const d=i.loadPolicy.errorRetry;var o;if(shouldRetry(d,s.retry,!1,{url:e.url,data:void 0,code:r}))this.retry(d);else logger.error(`${r} while loading ${e.url}`),null==(o=this.callbacks)||o.onError({code:r,text:t.statusText},e,t,s)}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry;if(shouldRetry(e,this.stats.retry,!0))this.retry(e);else{var t;logger.warn(`timeout while loading ${null==(t=this.context)?void 0:t.url}`);const e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=getRetryDelay(e,s.retry),s.retry++,logger.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==t?void 0:t.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const defaultLoadPolicy={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},hlsDefaultConfig=_objectSpread2(_objectSpread2({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:XhrLoader,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:AbrController,bufferController:BufferController,capLevelController:CapLevelController,errorController:ErrorController,fpsController:FPSController,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:requestMediaKeySystemAccess,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:defaultLoadPolicy},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},timelineConfig()),{},{subtitleStreamController:SubtitleStreamController,subtitleTrackController:SubtitleTrackController,timelineController:TimelineController,audioStreamController:AudioStreamController,audioTrackController:AudioTrackController,emeController:EMEController,cmcdController:CMCDController,contentSteeringController:ContentSteeringController,interstitialsController:InterstitialsController});function timelineConfig(){return{cueHandler:Cues,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function mergeConfig(e,t,s){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const r=deepCpy(e),i=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((e=>{const n=`${"level"===e?"playlist":e}LoadPolicy`,a=void 0===t[n],o=[];i.forEach((s=>{const i=`${e}Loading${s}`,l=t[i];if(void 0!==l&&a){o.push(i);const e=r[n].default;switch(t[n]={default:e},s){case"TimeOut":e.maxLoadTimeMs=l,e.maxTimeToFirstByteMs=l;break;case"MaxRetry":e.errorRetry.maxNumRetry=l,e.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":e.errorRetry.retryDelayMs=l,e.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":e.errorRetry.maxRetryDelayMs=l,e.timeoutRetry.maxRetryDelayMs=l}}})),o.length&&s.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${n}": ${stringify(t[n])}`)})),_objectSpread2(_objectSpread2({},r),t)}function deepCpy(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(deepCpy):Object.keys(e).reduce(((t,s)=>(t[s]=deepCpy(e[s]),t)),{}):e}function enableStreamingMode(e,t){const s=e.loader;if(s!==FetchLoader&&s!==XhrLoader)t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1;else{fetchSupported()&&(e.loader=FetchLoader,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}}const MAX_START_GAP_JUMP=2,SKIP_BUFFER_HOLE_STEP_SECONDS=.1,SKIP_BUFFER_RANGE_START=.05,TICK_INTERVAL$1=100;class GapController extends TaskLoop{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var e;null!=(e=this.media)&&e.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var e;this.hls&&(this.ended=(null==(e=this.media)?void 0:e.currentTime)||1,this.hls.trigger(Events.MEDIA_ENDED,{stalled:!1}))},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(100),this.mediaSource=t.mediaSource;const s=this.media=t.media;addEventListener(s,"playing",this.onMediaPlaying),addEventListener(s,"waiting",this.onMediaWaiting),addEventListener(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:s}=this;s&&(removeEventListener(s,"playing",this.onMediaPlaying),removeEventListener(s,"waiting",this.onMediaWaiting),removeEventListener(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(null==(e=this.media)||!e.readyState||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var s,r;const i=null==(s=this.hls)?void 0:s.config;if(!i)return;const n=this.media;if(!n)return;const{seeking:a}=n,o=this.seeking&&!a,l=!this.seeking&&a,d=n.paused&&!a||n.ended||0===n.playbackRate;if(this.seeking=a,e!==t)return t&&(this.ended=0),this.moved=!0,a||(this.nudgeRetry=0,i.nudgeOnVideoHole&&!d&&e>t&&this.nudgeOnVideoHole(e,t)),void(0===this.waiting&&this.stallResolved(e));if(l||o)return void(o&&this.stallResolved(e));if(d)return this.nudgeRetry=0,this.stallResolved(e),void(!this.ended&&n.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(Events.MEDIA_ENDED,{stalled:!1})));if(!BufferHelper.getBuffered(n).length)return void(this.nudgeRetry=0);const h=BufferHelper.bufferInfo(n,e,0),c=h.nextStart||0,u=this.fragmentTracker;if(a&&u&&this.hls){const t=getInFlightDependency(this.hls.inFlightFragments,e),s=h.len>2,r=!c||t||c-e>2&&!u.getPartialFragment(e);if(s||r)return;this.moved=!1}const f=null==(r=this.hls)?void 0:r.latestLevelDetails;if(!this.moved&&null!==this.stalled&&u){if(!(h.len>0)&&!c)return;const t=Math.max(c,h.start||0)-e,s=!(null==f||!f.live)?2*f.targetduration:2,r=appendedFragAtPosition(e,u);if(t>0&&(t<=s||r))return void(n.paused||this._trySkipBufferHole(r))}const g=i.detectStallWithCurrentTimeMs,m=self.performance.now(),p=this.waiting;let E=this.stalled;if(null===E){if(!(p>0&&m-p<g))return void(this.stalled=m);E=this.stalled=p}const y=m-E;if(!a&&(y>=g||p)&&this.hls){var v;if("ended"===(null==(v=this.mediaSource)?void 0:v.readyState)&&(null==f||!f.live)&&Math.abs(e-((null==f?void 0:f.edge)||0))<1){if(this.ended)return;return this.ended=e||1,void this.hls.trigger(Events.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(h),!this.media||!this.hls)return}const T=BufferHelper.bufferInfo(n,e,i.maxBufferHole);this._tryFixBufferStall(T,y,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(Events.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;const r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(s=this.buffered.audio)&&s.length&&r&&r.length>1&&e>r.end(0)){const s=BufferHelper.bufferedInfo(BufferHelper.timeRangesToArray(this.buffered.audio),e,0);if(s.len>1&&t>=s.start){const s=BufferHelper.timeRangesToArray(r),i=BufferHelper.bufferedInfo(s,t,0).bufferedIndex;if(i>-1&&i<s.length-1){const t=BufferHelper.bufferedInfo(s,e,0).bufferedIndex,r=s[i].end,n=s[i+1].start;if((-1===t||t>i)&&n-r<1&&e-r<2){const s=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${r} -> ${n} buffered index: ${t}`);this.warn(s.message),this.media.currentTime+=1e-6;let i=appendedFragAtPosition(e,this.fragmentTracker);i&&"fragment"in i?i=i.fragment:i||(i=void 0);const a=BufferHelper.bufferInfo(this.media,e,0);this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:s,reason:s.message,frag:i,buffer:a.len,bufferInfo:a})}}}}}_tryFixBufferStall(e,t,s){var r,i;const{fragmentTracker:n,media:a}=this,o=null==(r=this.hls)?void 0:r.config;if(!a||!n||!o)return;const l=null==(i=this.hls)?void 0:i.latestLevelDetails,d=appendedFragAtPosition(s,n);if(d||null!=l&&l.live&&s<l.fragmentStart){if(this._trySkipBufferHole(d)||!this.media)return}const h=e.buffered,c=this.adjacentTraversal(e,s);(h&&h.length>1&&e.len>o.maxBufferHole||e.nextStart&&(e.nextStart-s<o.maxBufferHole||c))&&(t>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const s=this.fragmentTracker,r=e.nextStart;if(s&&r){const e=s.getFragAtPos(t,PlaylistLevelType.MAIN),i=s.getFragAtPos(r,PlaylistLevelType.MAIN);if(e&&i)return i.sn-e.sn<2}return!1}_reportStall(e){const{hls:t,media:s,stallReported:r,stalled:i}=this;if(!r&&null!==i&&s&&t){this.stallReported=!0;const r=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${stringify(e)})`);this.warn(r.message),t.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:e.len,bufferInfo:e,stalled:{start:i}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:s,media:r}=this,i=null==(t=this.hls)?void 0:t.config;if(!r||!s||!i)return 0;const n=r.currentTime,a=BufferHelper.bufferInfo(r,n,0),o=n<a.start?a.start:a.nextStart;if(o&&this.hls){const t=a.len<=i.maxBufferHole,d=a.len>0&&a.len<1&&r.readyState<3,h=o-n;if(h>0&&(t||d)){if(h>i.maxBufferHole){let t=!1;if(0===n){const e=s.getAppendedFrag(0,PlaylistLevelType.MAIN);e&&o<e.end&&(t=!0)}if(!t&&e){var l;if(null==(l=this.hls.loadLevelObj)||!l.details)return 0;if(getInFlightDependency(this.hls.inFlightFragments,o))return 0;let t=!1,r=e.end;for(;r<o;){const e=appendedFragAtPosition(r,s);if(!e){t=!0;break}r+=e.duration}if(t)return 0}}const t=Math.max(o+.05,n+.1);if(this.warn(`skipping hole, adjusting currentTime from ${n} to ${t}`),this.moved=!0,r.currentTime=t,null==e||!e.gap){const s=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${t}`),r={type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:s,reason:s.message,buffer:a.len,bufferInfo:a};e&&("fragment"in e?r.part=e:r.frag=e),this.hls.trigger(Events.ERROR,r)}return t}}return 0}_tryNudgeBuffer(e){const{hls:t,media:s,nudgeRetry:r}=this,i=null==t?void 0:t.config;if(!s||!i)return 0;const n=s.currentTime;if(this.nudgeRetry++,r<i.nudgeMaxRetry){const a=n+(r+1)*i.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);this.warn(o.message),s.currentTime=a,t.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:e.len,bufferInfo:e})}else{const s=new Error(`Playhead still not moving while enough data buffered @${n} after ${i.nudgeMaxRetry} nudges`);this.error(s.message),t.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_STALLED_ERROR,error:s,fatal:!0,buffer:e.len,bufferInfo:e})}}}function getInFlightDependency(e,t){const s=inFlight(e.main);if(s&&s.start<=t)return s;const r=inFlight(e.audio);return r&&r.start<=t?r:null}function inFlight(e){if(!e)return null;switch(e.state){case State.IDLE:case State.STOPPED:case State.ENDED:case State.ERROR:return null}return e.frag}function appendedFragAtPosition(e,t){return t.getAppendedFrag(e,PlaylistLevelType.MAIN)||t.getPartialFragment(e)}const MIN_CUE_DURATION=.25;function getCueClass(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function createCueWithDataFields(e,t,s,r,i){let n=new e(t,s,"");try{n.value=r,i&&(n.type=i)}catch(a){n=new e(t,s,stringify(i?_objectSpread2({type:i},r):r))}return n}const MAX_CUE_ENDTIME=(()=>{const e=getCueClass();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class ID3TrackController{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(Events.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Events.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Events.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Events.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Events.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){this.media=t.media}onMediaAttached(){var e;const t=null==(e=this.hls)?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null;!!t.transferMedia||(this.id3Track&&(this.id3Track.remove(),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){return createTrackNode(e,"metadata","id3","","hidden")}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:s,enableID3MetadataCues:r}=this.hls.config;if(!s&&!r)return;const{samples:i}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=getCueClass();if(n)for(let e=0;e<i.length;e++){const t=i[e].type;if(t===MetadataSchema.emsg&&!s||!r)continue;const a=getId3Frames(i[e].data),o=i[e].pts;let l=o+i[e].duration;l>MAX_CUE_ENDTIME&&(l=MAX_CUE_ENDTIME);l-o<=0&&(l=o+.25);for(let e=0;e<a.length;e++){const s=a[e];if(!isId3TimestampFrame(s)){this.updateId3CueEnds(o,t);const e=createCueWithDataFields(n,o,l,s,t);e&&this.id3Track.track.addCue(e)}}}}updateId3CueEnds(e,t){var s;const r=null==(s=this.id3Track)?void 0:s.track.cues;if(r)for(let s=r.length;s--;){const i=r[s];i.type===t&&i.startTime<e&&i.endTime===MAX_CUE_ENDTIME&&(i.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:r}){const{id3Track:i,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(i&&(a||o)){let e;e="audio"===r?e=>e.type===MetadataSchema.audioId3&&o:"video"===r?e=>e.type===MetadataSchema.emsg&&a:e=>e.type===MetadataSchema.audioId3&&o||e.type===MetadataSchema.emsg&&a,removeCuesInRange(i.track,t,s,e)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:s,timelineOffset:r,enableDateRangeMetadataCues:i,interstitialsController:n}=this.hls.config;if(!i)return;const a=getCueClass();if(s&&r&&!n){const{fragmentStart:t,fragmentEnd:r}=e;let i=this.assetCue;i?(i.startTime=t,i.endTime=r):a&&(i=this.assetCue=createCueWithDataFields(a,t,r,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),i&&(i.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.track.addCue(i),i.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:o}=this,{dateRanges:l}=e,d=Object.keys(l);let h=this.dateRangeCuesAppended;var c;if(o&&t)if(null!=(c=o.track.cues)&&c.length){const e=Object.keys(h).filter((e=>!d.includes(e)));for(let t=e.length;t--;){var u;const s=e[t],r=null==(u=h[s])?void 0:u.cues;delete h[s],r&&Object.keys(r).forEach((e=>{const t=r[e];if(t){t.removeEventListener("enter",this.onEventCueEnter);try{o.track.removeCue(t)}catch(e){}}}))}}else h=this.dateRangeCuesAppended={};const f=e.fragments[e.fragments.length-1];if(0!==d.length&&isFiniteNumber(null==f?void 0:f.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let e=0;e<d.length;e++){const t=d[e],s=l[t],r=s.startTime,i=h[t],o=(null==i?void 0:i.cues)||{};let c=(null==i?void 0:i.durationKnown)||!1,u=MAX_CUE_ENDTIME;const{duration:f,endDate:g}=s;if(g&&null!==f)u=r+f,c=!0;else if(s.endOnNext&&!c){const e=d.reduce(((e,t)=>{if(t!==s.id){const r=l[t];if(r.class===s.class&&r.startDate>s.startDate&&(!e||s.startDate<e.startDate))return r}return e}),null);e&&(u=e.startTime,c=!0)}const m=Object.keys(s.attr);for(let e=0;e<m.length;e++){const l=m[e];if(!isDateRangeCueAttribute(l))continue;const d=o[l];if(d)!c||null!=i&&i.durationKnown?Math.abs(d.startTime-r)>.01&&(d.startTime=r,d.endTime=u):d.endTime=u;else if(a){let e=s.attr[l];isSCTE35Attribute(l)&&(e=hexToArrayBuffer(e));const i=createCueWithDataFields(a,r,u,{key:l,data:e},MetadataSchema.dateRange);i&&(i.id=t,this.id3Track.track.addCue(i),o[l]=i,n&&("X-ASSET-LIST"!==l&&"X-ASSET-URL"!==l||i.addEventListener("enter",this.onEventCueEnter)))}}h[t]={cues:o,dateRange:s,durationKnown:c}}}}}class LatencyController{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:e}=this,t=this.levelDetails;if(!e||!t)return;this.currentTime=e.currentTime;const s=this.computeLatency();if(null===s)return;this._latency=s;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:i}=this.config;if(!r||1===i||!t.live)return;const n=this.targetLatency;if(null===n)return;const a=s-n;if(a<Math.min(this.maxLatency,n+t.targetduration)&&a>.05&&this.forwardBufferLength>1){const t=Math.min(2,Math.max(1,i)),s=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20,r=Math.min(t,Math.max(1,s));this.changeMediaPlaybackRate(e,r)}else 1!==e.playbackRate&&0!==e.playbackRate&&this.changeMediaPlaybackRate(e,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return(null==(e=this.hls)?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(null===e||null===this.hls)return null;const{holdBack:t,partHoldBack:s,targetduration:r}=e,{liveSyncDuration:i,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&s||t;(this._targetLatencyUpdated||o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==i?i:n*r);const d=r;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,d)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t)return null;const s=this.levelDetails;if(null===s)return null;const r=s.edge,i=e-t-this.edgeStalled,n=r-s.totalduration,a=r-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(n,i),a)}get drift(){const e=this.levelDetails;return null===e?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(null===e)return 0;const t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const s=e.buffered.length;return(s?e.buffered.end(s-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Events.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Events.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var s;t.details===ErrorDetails.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(s=this.levelDetails)&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var s,r;e.playbackRate!==t&&(null==(s=this.hls)||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(r=this.targetLatency)?void 0:r.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return null===e?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}class LevelController extends BasePlaylistController{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Events.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Events.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Events.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Events.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach((e=>{e.loadError=0,e.fragmentError=0})),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const s=this.hls.config.preferManagedMediaSource,r=[],i={},n={};let a=!1,o=!1,l=!1;t.levels.forEach((e=>{const t=e.attrs;let{audioCodec:d,videoCodec:h}=e;d&&(e.audioCodec=d=getCodecCompatibleName(d,s)||void 0),h&&(h=e.videoCodec=convertAVC1ToAVCOTI(h));const{width:c,height:u,unknownCodecs:f}=e,g=(null==f?void 0:f.length)||0;if(a||(a=!(!c||!u)),o||(o=!!h),l||(l=!!d),g||d&&!this.isAudioSupported(d)||h&&!this.isVideoSupported(h))return void this.log(`Some or all CODECS not supported "${t.CODECS}"`);const{CODECS:m,"FRAME-RATE":p,"HDCP-LEVEL":E,"PATHWAY-ID":y,RESOLUTION:v,"VIDEO-RANGE":T}=t,S=`${`${y||"."}-`}${e.bitrate}-${v}-${p}-${m}-${T}-${E}`;if(i[S])if(i[S].uri===e.url||e.attrs["PATHWAY-ID"])i[S].addGroupId("audio",t.AUDIO),i[S].addGroupId("text",t.SUBTITLES);else{const t=n[S]+=1;e.attrs["PATHWAY-ID"]=new Array(t+1).join(".");const s=this.createLevel(e);i[S]=s,r.push(s)}else{const t=this.createLevel(e);i[S]=t,n[S]=1,r.push(t)}})),this.filterAndSortMediaOptions(r,t,a,o,l)}createLevel(e){const t=new Level(e),s=e.supplemental;if(null!=s&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){const e=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(e.message),t.supportedResult=getUnsupportedResult(e,[])}return t}isAudioSupported(e){return areCodecsMediaSourceSupported(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return areCodecsMediaSourceSupported(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,s,r,i){var n;let a=[],o=[],l=e;const d=(null==(n=t.stats)?void 0:n.parsing)||{};if((s||r)&&i&&(l=l.filter((({videoCodec:e,videoRange:t,width:s,height:r})=>(!!e||!(!s||!r))&&isVideoRange(t)))),0===l.length)return Promise.resolve().then((()=>{if(this.hls){let e="no level with compatible codecs found in manifest",s=e;t.levels.length&&(s=`one or more CODECS in variant not supported: ${stringify(t.levels.map((e=>e.attrs.CODECS)).filter(((e,t,s)=>s.indexOf(e)===t)))}`,this.warn(s),e+=` (${s})`);const r=new Error(e);this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:r,reason:s})}})),void(d.end=performance.now());t.audioTracks&&(a=t.audioTracks.filter((e=>!e.audioCodec||this.isAudioSupported(e.audioCodec))),assignTrackIdsByGroup(a)),t.subtitles&&(o=t.subtitles,assignTrackIdsByGroup(o));const h=l.slice(0);l.sort(((e,t)=>{if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return VideoRangeValues.indexOf(e.videoRange)-VideoRangeValues.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){const s=videoCodecPreferenceValue(e.videoCodec),r=videoCodecPreferenceValue(t.videoCodec);if(s!==r)return r-s}if(e.uri===t.uri&&e.codecSet!==t.codecSet){const s=codecsSetSelectionPreferenceValue(e.codecSet),r=codecsSetSelectionPreferenceValue(t.codecSet);if(s!==r)return r-s}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0}));let c=h[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==h.length))for(let e=0;e<h.length;e++)if(h[e].pathwayId===l[0].pathwayId){c=h[e];break}this._levels=l;for(let e=0;e<l.length;e++)if(l[e]===c){var u;this._firstLevel=e;const t=c.bitrate,s=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${t}`),void 0===(null==(u=this.hls.userConfig)?void 0:u.abrEwmaDefaultEstimate)){const e=Math.min(t,this.hls.config.abrEwmaDefaultEstimateMax);e>s&&s===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=e)}break}const f=i&&!r,g=this.hls.config,m=!(!g.audioStreamController||!g.audioTrackController),p={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:i,video:r,altAudio:m&&!f&&a.some((e=>!!e.url))};d.end=performance.now(),this.hls.trigger(Events.MANIFEST_PARSED,p)}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(0===t.length)return;if(e<0||e>=t.length){const s=new Error("invalid level idx"),r=e<0;if(this.hls.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.LEVEL_SWITCH_ERROR,level:e,fatal:r,error:s,reason:s.message}),r)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,r=this.currentLevel,i=r?r.attrs["PATHWAY-ID"]:void 0,n=t[e],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=n,s===e&&r&&i===a)return;this.log(`Switching to level ${e} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${s}${i?" with Pathway "+i:""}`);const o={level:e,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(Events.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const e=this.switchParams(n.uri,null==r?void 0:r.details,l);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(void 0===this._startLevel){const e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),s=e.filter((e=>-1!==t.indexOf(e)));if(e.length<1)return void this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);this.steering.pathwayPriority=s}}onError(e,t){!t.fatal&&t.context&&t.context.type===PlaylistContextType.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(void 0!==t&&t.type===PlaylistLevelType.MAIN){const e=t.elementaryStreams;if(!Object.keys(e).some((t=>!!e[t])))return;const s=this._levels[t.level];null!=s&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(e,t){var s;const{level:r,details:i}=t,n=t.levelInfo;var a;if(!n)return this.warn(`Invalid level index ${r}`),void(null!=(a=t.deliveryDirectives)&&a.skip&&(i.deltaUpdateFailed=!0));if(n===this.currentLevel||t.withoutMultiVariant){0===n.fragmentError&&(n.loadError=0);let e=n.details;e===t.details&&e.advanced&&(e=void 0),this.playlistLoaded(r,t,e)}else null!=(s=t.deliveryDirectives)&&s.skip&&(i.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=this.getUrlWithDirectives(e.uri,t),r=this.currentLevelIndex,i=e.attrs["PATHWAY-ID"],n=e.details,a=null==n?void 0:n.age;this.log(`Loading level index ${r}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""}${i?" Pathway "+i:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${s}`),this.hls.trigger(Events.LEVEL_LOADING,{url:s,level:r,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(1===this._levels.length)return;const s=this._levels.filter(((t,s)=>s!==e||(this.steering&&this.steering.removeLevel(t),t===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,t.details&&t.details.fragments.forEach((e=>e.level=-1))),!1)));reassignFragmentLevelIndexes(s),this._levels=s,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const r=s.length-1;this._firstLevel=Math.min(this._firstLevel,r),this._startLevel&&(this._startLevel=Math.min(this._startLevel,r)),this.hls.trigger(Events.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(Events.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function assignTrackIdsByGroup(e){const t={};e.forEach((e=>{const s=e.groupId||"";e.id=t[s]=t[s]||0,t[s]++}))}function getSourceBuffer(){return self.SourceBuffer||self.WebKitSourceBuffer}function isMSESupported(){if(!getMediaSource())return!1;const e=getSourceBuffer();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}function isSupported(){if(!isMSESupported())return!1;const e=getMediaSource();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((t=>e.isTypeSupported(mimeTypeForCodec(t,"video"))))||["mp4a.40.2","fLaC"].some((t=>e.isTypeSupported(mimeTypeForCodec(t,"audio")))))}function changeTypeSupported(){var e;const t=getSourceBuffer();return"function"==typeof(null==t||null==(e=t.prototype)?void 0:e.changeType)}const TICK_INTERVAL=100;class StreamController extends BaseStreamController{constructor(e,t,s){super(e,t,s,"stream-controller",PlaylistLevelType.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const e=this.media,t=e?e.currentTime:null;if(null===t||!isFiniteNumber(t))return;if(this.log(`Media seeked to ${t.toFixed(3)}`),!this.getBufferedFrag(t))return;const s=this.getFwdBufferInfoAtPos(e,t,PlaylistLevelType.MAIN,0);null!==s&&0!==s.len?this.tick():this.warn(`Main forward buffer length at ${t} on "seeked" event ${s?s.len:"empty"})`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Events.LEVEL_LOADING,this.onLevelLoading,this),e.on(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Events.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Events.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(Events.BUFFER_CREATED,this.onBufferCreated,this),e.on(Events.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Events.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Events.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Events.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(Events.BUFFER_CREATED,this.onBufferCreated,this),e.off(Events.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Events.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:s,hls:r}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let e=r.startLevel;-1===e&&(r.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=r.firstAutoLevel),r.nextLoadLevel=e,this.level=r.loadLevel,this._hasEnoughToStart=!!t}s>0&&-1===e&&!t&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=State.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=State.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case State.WAITING_LEVEL:{const{levels:e,level:t}=this,s=null==e?void 0:e[t],r=null==s?void 0:s.details;if(r&&(!r.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(r))break;this.state=State.IDLE;break}if(this.hls.nextLoadLevel!==this.level){this.state=State.IDLE;break}break}case State.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate()}this.state===State.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),null!=(e=this.media)&&e.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:s,media:r}=this;if(null===t||!r&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const i=this.buffering?e.nextLoadLevel:e.loadLevel;if(null==s||!s[i])return;const n=s[i],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const e={};return 2===this.altAudio&&(e.type="video"),this.hls.trigger(Events.BUFFER_EOS,e),void(this.state=State.ENDED)}if(!this.buffering)return;e.loadLevel!==i&&-1===e.manualLevel&&this.log(`Adapting to level ${i} from level ${this.level}`),this.level=e.nextLoadLevel=i;const l=n.details;if(!l||this.state===State.WAITING_LEVEL||this.waitForLive(n))return this.level=i,this.state=State.WAITING_LEVEL,void(this.startFragRequested=!1);const d=a.len,h=this.getMaxBufferLength(n.maxBitrate);if(d>=h)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const c=this.backtrackFragment?this.backtrackFragment.start:a.end;let u=this.getNextFragment(c,l);if(this.couldBacktrack&&!this.fragPrevious&&u&&isMediaFragment(u)&&this.fragmentTracker.getState(u)!==FragmentState.OK){var f;const e=(null!=(f=this.backtrackFragment)?f:u).sn-l.startSN,t=l.fragments[e-1];t&&u.cc===t.cc&&(u=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(u&&this.isLoopLoading(u,c)){if(!u.gap){const e=this.audioOnly&&!this.altAudio?ElementaryStreamTypes.AUDIO:ElementaryStreamTypes.VIDEO,t=(e===ElementaryStreamTypes.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,PlaylistLevelType.MAIN)}u=this.getNextFragmentLoopLoading(u,l,a,PlaylistLevelType.MAIN,h)}u&&(!u.initSegment||u.initSegment.data||this.bitrateTest||(u=u.initSegment),this.loadFragment(u,n,c))}loadFragment(e,t,s){const r=this.fragmentTracker.getState(e);r===FragmentState.NOT_LOADED||r===FragmentState.PARTIAL?isMediaFragment(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,s):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,PlaylistLevelType.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(null!=t&&t.readyState){let s;const r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);const i=this.getLevelDetails();if(null!=i&&i.live){const e=this.getMainFwdBufferInfo();if(!e||e.len<2*i.targetduration)return}if(!t.paused&&e){const t=e[this.hls.nextLoadLevel],r=this.fragLastKbps;s=r&&this.fragCurrent?this.fragCurrent.duration*t.maxBitrate/(1e3*r)+1:0}else s=0;const n=this.getBufferedFrag(t.currentTime+s);if(n){const e=this.followingBufferedFrag(n);if(e){this.abortCurrentFrag();const t=e.maxStartPTS?e.maxStartPTS:e.start,s=e.duration,r=Math.max(n.end,t+Math.min(Math.max(s-this.config.maxFragLookUpTolerance,s*(this.couldBacktrack?.5:.125)),s*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(r,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case State.KEY_LOADING:case State.FRAG_LOADING:case State.FRAG_LOADING_WAITING_RETRY:case State.PARSING:case State.PARSED:this.state=State.IDLE}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,2===this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const s=t.media;addEventListener(s,"playing",this.onMediaPlaying),addEventListener(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:s}=this;s&&(removeEventListener(s,"playing",this.onMediaPlaying),removeEventListener(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t);!!t.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(Events.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let s=!1,r=!1;for(let e=0;e<t.levels.length;e++){const i=t.levels[e].audioCodec;i&&(s=s||-1!==i.indexOf("mp4a.40.2"),r=r||-1!==i.indexOf("mp4a.40.5"))}this.audioCodecSwitch=s&&r&&!changeTypeSupported(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:s}=this;if(!s||this.state!==State.IDLE)return;const r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=State.WAITING_LEVEL)}onLevelLoaded(e,t){var s;const{levels:r,startFragRequested:i}=this,n=t.level,a=t.details,o=a.totalduration;if(!r)return void this.warn(`Levels were reset while loading level ${n}`);this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=t.levelInfo,d=this.fragCurrent;!d||this.state!==State.FRAG_LOADING&&this.state!==State.FRAG_LOADING_WAITING_RETRY||d.level!==t.level&&d.loader&&this.abortCurrentFrag();let h=0;if(a.live||null!=(s=l.details)&&s.live){var c;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;h=this.alignPlaylists(a,l.details,null==(c=this.levelLastLoaded)?void 0:c.details)}if(l.details=a,this.levelLastLoaded=l,i||this.setStartPosition(a,h),this.hls.trigger(Events.LEVEL_UPDATED,{details:a,level:n}),this.state===State.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=State.IDLE}i&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:s}=this;if(!s)return;const r=this.hls.liveSyncPosition,i=this.getLoadPosition(),n=e.fragmentStart,a=e.edge,o=i>=n-t.maxFragLookUpTolerance&&i<=a;if(null!==r&&s.duration>r&&(i<r||!o)){const n=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!o&&s.readyState<4||i<a-n)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),s.readyState))if(this.warn(`Playback: ${i.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${r.toFixed(3)}`),"buffered"===this.config.liveSyncMode){var l;const e=BufferHelper.bufferInfo(s,r,0);if(null==(l=e.buffered)||!l.length)return void(s.currentTime=r);if(e.start<=i)return void(s.currentTime=r);const{nextStart:t}=BufferHelper.bufferedInfo(e.buffered,i,0);t&&(s.currentTime=t)}else s.currentTime=r}}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:r,payload:i}=e,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const a=n[s.level];if(!a)return void this.warn(`Level ${s.level} not found on progress`);const o=a.details;if(!o)return this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),void this.fragmentTracker.removeFragment(s);const l=a.videoCodec,d=o.PTSKnown||!o.live,h=null==(t=s.initSegment)?void 0:t.data,c=this._getAudioCodec(a),u=this.transmuxer=this.transmuxer||new TransmuxerInterface(this.hls,PlaylistLevelType.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=r?r.index:-1,g=-1!==f,m=new ChunkMetadata(s.level,s.sn,s.stats.chunkCount,i.byteLength,f,g),p=this.initPTS[s.cc];u.push(i,h,c,l,s,r,o.totalduration,d,m,p)}onAudioTrackSwitching(e,t){const s=this.hls,r=2===this.altAudio;if(useAlternateAudio(t.url,s))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const e=this.fragCurrent;e&&(this.log("Switching to main audio track, cancel main fragment load"),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(r)return this.fragmentTracker.removeAllFragments(),s.once(Events.BUFFER_FLUSHED,(()=>{this.hls&&this.hls.trigger(Events.AUDIO_TRACK_SWITCHED,t)})),void s.trigger(Events.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});s.trigger(Events.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const s=useAlternateAudio(t.url,this.hls);if(s){const e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=e)}this.altAudio=s?2:0,this.tick()}onBufferCreated(e,t){const s=t.tracks;let r,i,n=!1;for(const e in s){const t=s[e];if("main"===t.id){if(i=e,r=t,"video"===e){const t=s[e];t&&(this.videoBuffer=t.buffer)}}else n=!0}n&&r?(this.log(`Alternate track found, use ${i}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:s,part:r}=t,i=s.type===PlaylistLevelType.MAIN;if(i){if(this.fragContextChanged(s))return this.warn(`Fragment ${s.sn}${r?" p: "+r.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===State.PARSED&&(this.state=State.IDLE));const e=r?r.stats:s.stats;this.fragLastKbps=Math.round(8*e.total/(e.buffering.end-e.loading.first)),isMediaFragment(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,r)}const n=this.media;n&&(!this._hasEnoughToStart&&BufferHelper.getBuffered(n).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),i&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal)this.state=State.ERROR;else switch(t.details){case ErrorDetails.FRAG_GAP:case ErrorDetails.FRAG_PARSING_ERROR:case ErrorDetails.FRAG_DECRYPT_ERROR:case ErrorDetails.FRAG_LOAD_ERROR:case ErrorDetails.FRAG_LOAD_TIMEOUT:case ErrorDetails.KEY_LOAD_ERROR:case ErrorDetails.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(PlaylistLevelType.MAIN,t);break;case ErrorDetails.LEVEL_LOAD_ERROR:case ErrorDetails.LEVEL_LOAD_TIMEOUT:case ErrorDetails.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==State.WAITING_LEVEL||(null==(s=t.context)?void 0:s.type)!==PlaylistContextType.LEVEL||(this.state=State.IDLE);break;case ErrorDetails.BUFFER_ADD_CODEC_ERROR:case ErrorDetails.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case ErrorDetails.BUFFER_FULL_ERROR:if("main"!==t.parent)return;if(this.reduceLengthAndFlushBuffer(t)){!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}break;case ErrorDetails.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onFragLoadEmergencyAborted(){this.state=State.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==ElementaryStreamTypes.AUDIO||!this.altAudio){const e=(t===ElementaryStreamTypes.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;e&&(this.afterBufferFlushed(e,t,PlaylistLevelType.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let s=this.startPosition;if(s>=0&&t<s){if(e.seeking)return void this.log(`could not seek to ${s}, already seeking at ${t}`);const r=this.timelineOffset;r&&s&&(s+=r);const i=this.getLevelDetails(),n=BufferHelper.getBuffered(e),a=n.length?n.start(0):0,o=a-s,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==i?void 0:i.partTarget)||0)))&&(this.log(`adjusting start position by ${o} to match buffer start`),s+=o,this.startPosition=s),t<s&&(this.log(`seek to target start position ${s} from current time ${t} buffer start ${a}`),e.currentTime=s)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then((e=>{const{hls:s}=this,r=null==e?void 0:e.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=State.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const i=r.stats;i.parsing.start=i.parsing.end=i.buffering.start=i.buffering.end=self.performance.now(),s.trigger(Events.FRAG_LOADED,e),r.bitrateTest=!1})).catch((t=>{this.state!==State.STOPPED&&this.state!==State.ERROR&&(this.warn(t),this.resetFragmentLoading(e))}))}_handleTransmuxComplete(e){const t=this.playlistType,{hls:s}=this,{remuxResult:r,chunkMeta:i}=e,n=this.getCurrentContext(i);if(!n)return void this.resetWhenMissingContext(i);const{frag:a,part:o,level:l}=n,{video:d,text:h,id3:c,initSegment:u}=r,{details:f}=l,g=this.altAudio?void 0:r.audio;if(this.fragContextChanged(a))this.fragmentTracker.removeFragment(a);else{if(this.state=State.PARSING,u){const e=u.tracks;if(e){const r=a.initSegment||a;if(this.unhandledEncryptionError(u,a))return;this._bufferInitSegment(l,e,r,i),s.trigger(Events.FRAG_PARSING_INIT_SEGMENT,{frag:r,id:t,tracks:e})}const r=u.initPTS,n=u.timescale,o=this.initPTS[a.cc];if(isFiniteNumber(r)&&(!o||o.baseTime!==r||o.timescale!==n)){const e=u.trackId;this.initPTS[a.cc]={baseTime:r,timescale:n,trackId:e},s.trigger(Events.INIT_PTS_FOUND,{frag:a,id:t,initPTS:r,timescale:n,trackId:e})}}if(d&&f){g&&"audiovideo"===d.type&&this.logMuxedErr(a);const e=f.fragments[a.sn-1-f.startSN],t=a.sn===f.startSN,s=!e||a.cc>e.cc;if(!1!==r.independent){const{startPTS:e,endPTS:r,startDTS:n,endDTS:l}=d;if(o)o.elementaryStreams[d.type]={startPTS:e,endPTS:r,startDTS:n,endDTS:l};else if(d.firstKeyFrame&&d.independent&&1===i.id&&!s&&(this.couldBacktrack=!0),d.dropped&&d.independent){const i=this.getMainFwdBufferInfo(),n=(i?i.end:this.getLoadPosition())+this.config.maxBufferHole,o=d.firstKeyFramePTS?d.firstKeyFramePTS:e;if(!t&&n<o-this.config.maxBufferHole&&!s)return void this.backtrack(a);s&&(a.gap=!0),a.setElementaryStreamInfo(d.type,a.start,r,a.start,l,!0)}else t&&e-(f.appliedTimelineOffset||0)>2&&(a.gap=!0);a.setElementaryStreamInfo(d.type,e,r,n,l),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(d,a,o,i,t||s)}else{if(!t&&!s)return void this.backtrack(a);a.gap=!0}}if(g){const{startPTS:e,endPTS:t,startDTS:s,endDTS:r}=g;o&&(o.elementaryStreams[ElementaryStreamTypes.AUDIO]={startPTS:e,endPTS:t,startDTS:s,endDTS:r}),a.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO,e,t,s,r),this.bufferFragmentData(g,a,o,i)}if(f&&null!=c&&c.samples.length){const e={id:t,frag:a,details:f,samples:c.samples};s.trigger(Events.FRAG_PARSING_METADATA,e)}if(f&&h){const e={id:t,frag:a,details:f,samples:h.samples};s.trigger(Events.FRAG_PARSING_USERDATA,e)}}}logMuxedErr(e){this.warn(`${isMediaFragment(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,r){if(this.state!==State.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));const{audio:i,video:n,audiovideo:a}=t;if(i){const s=e.audioCodec;let r=pickMostCompleteCodecName(i.codec,s);"mp4a"===r&&(r="mp4a.40.5");const n=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){r&&(r=-1!==r.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const e=i.metadata;e&&"channelCount"in e&&1!==(e.channelCount||1)&&-1===n.indexOf("firefox")&&(r="mp4a.40.5")}r&&-1!==r.indexOf("mp4a.40.5")&&-1!==n.indexOf("android")&&"audio/mpeg"!==i.container&&(r="mp4a.40.2",this.log(`Android: force audio codec to ${r}`)),s&&s!==r&&this.log(`Swapping manifest audio codec "${s}" for "${r}"`),i.levelCodec=r,i.id=PlaylistLevelType.MAIN,this.log(`Init audio buffer, container:${i.container}, codecs[selected/level/parsed]=[${r||""}/${s||""}/${i.codec}]`),delete t.audiovideo}if(n){n.levelCodec=e.videoCodec,n.id=PlaylistLevelType.MAIN;const s=n.codec;if(4===(null==s?void 0:s.length))switch(s){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e"}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${e.videoCodec||""}/${s}]${n.codec!==s?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete t.audiovideo}a&&(this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.codecs}/${a.codec}]`),delete t.video,delete t.audio);const o=Object.keys(t);if(o.length){if(this.hls.trigger(Events.BUFFER_CODECS,t),!this.hls)return;o.forEach((e=>{const i=t[e].initSegment;null!=i&&i.byteLength&&this.hls.trigger(Events.BUFFER_APPENDING,{type:e,data:i,frag:s,part:null,chunkMeta:r,parent:s.type})}))}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,PlaylistLevelType.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,s=null==e?void 0:e[t];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=State.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&!1===e.seeking){const s=e.currentTime;if(BufferHelper.isBuffered(e,s)?t=this.getAppendedFrag(s):BufferHelper.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;const e=this.fragPlaying,s=t.level;e&&t.sn===e.sn&&e.level===s||(this.fragPlaying=t,this.hls.trigger(Events.FRAG_CHANGED,{frag:t}),e&&e.level===s||this.hls.trigger(Events.LEVEL_SWITCHED,{level:s}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return isFiniteNumber(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(isFiniteNumber(t)){const e=this.getLevelDetails(),s=this.currentFrag||(e?findFragmentByPTS(null,e.fragments,t):null);if(s){const e=s.programDateTime;if(null!==e){const r=e+1e3*(t-s.start);return new Date(r)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class KeyLoader extends Logger{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const s in this.keyIdToKeyInfo){const r=this.keyIdToKeyInfo[s].loader;if(r){var t;if(e&&e!==(null==(t=r.context)?void 0:t.frag.type))return;r.abort()}}}detach(){for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=ErrorDetails.KEY_LOAD_ERROR,s,r,i){return new LoadError({type:ErrorTypes.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:i,error:s,networkDetails:r||null})}loadClear(e,t,s){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let r=0,i=t.length;r<i;r++){const n=t[r];if(e.cc<=n.cc&&(!isMediaFragment(e)||!isMediaFragment(n)||e.sn<n.sn)||!s&&r==i-1)return this.emeController.selectKeySystemFormat(n).then((e=>{if(!this.emeController)return;n.setKeyFormat(e);const t=keySystemFormatToKeySystemDomain(e);return t?this.emeController.getKeySystemAccess([t]):void 0}))}if(this.config.requireKeySystemAccessOnStart){const e=getKeySystemsForConfig(this.config);if(e.length)return this.emeController.getKeySystemAccess(e)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then((t=>this.loadInternal(e,t))):this.loadInternal(e)}loadInternal(e,t){var s,r;t&&e.setKeyFormat(t);const i=e.decryptdata;if(!i){const s=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,ErrorDetails.KEY_LOAD_ERROR,s))}const n=i.uri;if(!n)return Promise.reject(this.createKeyLoadError(e,ErrorDetails.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));const a=getKeyId(i);let o=this.keyIdToKeyInfo[a];if(null!=(s=o)&&s.decryptdata.key)return i.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if(this.emeController&&null!=(r=o)&&r.keyLoadPromise){switch(this.emeController.getKeyStatus(o.decryptdata)){case"usable":case"usable-in-future":return o.keyLoadPromise.then((t=>{const{keyInfo:s}=t;return i.key=s.decryptdata.key,{frag:e,keyInfo:s}}))}}switch(this.log(`${this.keyIdToKeyInfo[a]?"Rel":"L"}oading${i.keyId?" keyId: "+arrayToHex(i.keyId):""} URI: ${i.uri} from ${e.type} ${e.level}`),o=this.keyIdToKeyInfo[a]={decryptdata:i,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},i.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===i.keyFormat?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,ErrorDetails.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${i.method}"`)))}}loadKeyEME(e,t){const s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var r;if(!e.decryptdata.keyId&&null!=(r=t.initSegment)&&r.data){const s=parseKeyIdsFromTenc(t.initSegment.data);if(s.length){const t=s[0];t.some((e=>0!==e))&&(this.log(`Using keyId found in init segment ${arrayToHex(t)}`),e.decryptdata.keyId=t,LevelKey.setKeyIdForUri(e.decryptdata.uri,t))}}const i=this.emeController.loadKey(s);return(e.keyLoadPromise=i.then((t=>(e.mediaKeySessionContext=t,s)))).catch((s=>{throw e.keyLoadPromise=null,"data"in s&&(s.data.frag=t),s}))}return Promise.resolve(s)}loadKeyHTTP(e,t){const s=this.config,r=new(0,s.loader)(s);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise(((i,n)=>{const a={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},o=s.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(e,t,s,r)=>{const{frag:a,keyInfo:o}=s,l=getKeyId(o.decryptdata);if(!a.decryptdata||o!==this.keyIdToKeyInfo[l])return n(this.createKeyLoadError(a,ErrorDetails.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),r));o.decryptdata.key=a.decryptdata.key=new Uint8Array(e.data),a.keyLoader=null,o.loader=null,i({frag:a,keyInfo:o})},onError:(e,s,r,i)=>{this.resetLoader(s),n(this.createKeyLoadError(t,ErrorDetails.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),r,_objectSpread2({url:a.url,data:void 0},e)))},onTimeout:(e,s,r)=>{this.resetLoader(s),n(this.createKeyLoadError(t,ErrorDetails.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),r))},onAbort:(e,s,r)=>{this.resetLoader(s),n(this.createKeyLoadError(t,ErrorDetails.INTERNAL_ABORTED,new Error("key loading aborted"),r))}};r.load(a,l,d)}))}resetLoader(e){const{frag:t,keyInfo:s,url:r}=e,i=s.loader;t.keyLoader===i&&(t.keyLoader=null,s.loader=null);const n=getKeyId(s.decryptdata)||r;delete this.keyIdToKeyInfo[n],i&&i.destroy()}}function getKeyId(e){if(e.keyFormat!==KeySystemFormats.FAIRPLAY){const t=e.keyId;if(t)return arrayToHex(t)}return e.uri}function mapContextToLevelType(e){const{type:t}=e;switch(t){case PlaylistContextType.AUDIO_TRACK:return PlaylistLevelType.AUDIO;case PlaylistContextType.SUBTITLE_TRACK:return PlaylistLevelType.SUBTITLE;default:return PlaylistLevelType.MAIN}}function getResponseUrl(e,t){let s=e.url;return void 0!==s&&0!==s.indexOf("data:")||(s=t.url),s}class PlaylistLoader{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.LEVEL_LOADING,this.onLevelLoading,this),e.on(Events.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(Events.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(Events.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.LEVEL_LOADING,this.onLevelLoading,this),e.off(Events.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(Events.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(Events.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,s=t.pLoader,r=t.loader,i=new(s||r)(t);return this.loaders[e.type]=i,i}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:PlaylistContextType.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:s,level:r,pathwayId:i,url:n,deliveryDirectives:a,levelInfo:o}=t;this.load({id:s,level:r,pathwayId:i,responseType:"text",type:PlaylistContextType.LEVEL,url:n,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(e,t){const{id:s,groupId:r,url:i,deliveryDirectives:n,track:a}=t;this.load({id:s,groupId:r,level:null,responseType:"text",type:PlaylistContextType.AUDIO_TRACK,url:i,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(e,t){const{id:s,groupId:r,url:i,deliveryDirectives:n,track:a}=t;this.load({id:s,groupId:r,level:null,responseType:"text",type:PlaylistContextType.SUBTITLE_TRACK,url:i,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(e,t){const s=this.loaders[PlaylistContextType.LEVEL];if(s){const e=s.context;e&&!t.levels.some((t=>t===e.levelOrTrack))&&(s.abort(),delete this.loaders[PlaylistContextType.LEVEL])}}load(e){var t;const s=this.hls.config;let r,i=this.getInternalLoader(e);if(i){const t=this.hls.logger,s=i.context;if(s&&s.levelOrTrack===e.levelOrTrack&&(s.url===e.url||s.deliveryDirectives&&!e.deliveryDirectives))return void(s.url===e.url?t.log(`[playlist-loader]: ignore ${e.url} ongoing request`):t.log(`[playlist-loader]: ignore ${e.url} in favor of ${s.url}`));t.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),i.abort()}if(r=e.type===PlaylistContextType.MANIFEST?s.manifestLoadPolicy.default:_extends({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(e),isFiniteNumber(null==(t=e.deliveryDirectives)?void 0:t.part)){let t;if(e.type===PlaylistContextType.LEVEL&&null!==e.level?t=this.hls.levels[e.level].details:e.type===PlaylistContextType.AUDIO_TRACK&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===PlaylistContextType.SUBTITLE_TRACK&&null!==e.id&&(t=this.hls.subtitleTracks[e.id].details),t){const e=t.partTarget,s=t.targetduration;if(e&&s){const t=1e3*Math.max(3*e,.8*s);r=_extends({},r,{maxTimeToFirstByteMs:Math.min(t,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,r.maxTimeToFirstByteMs)})}}}const n=r.errorRetry||r.timeoutRetry||{},a={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},o={onSuccess:(e,t,s,r)=>{const i=this.getInternalLoader(s);this.resetInternalLoader(s.type);const n=e.data;t.parsing.start=performance.now(),M3U8Parser.isMediaPlaylist(n)||s.type!==PlaylistContextType.MANIFEST?this.handleTrackOrLevelPlaylist(e,t,s,r||null,i):this.handleMasterPlaylist(e,t,s,r)},onError:(e,t,s,r)=>{this.handleNetworkError(t,s,!1,e,r)},onTimeout:(e,t,s)=>{this.handleNetworkError(t,s,!0,void 0,e)}};i.load(e,a,o)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,r){const i=this.hls,n=e.data,a=getResponseUrl(e,s),o=M3U8Parser.parseMasterPlaylist(n,a);if(o.playlistParsingError)return t.parsing.end=performance.now(),void this.handleManifestParsingError(e,s,o.playlistParsingError,r,t);const{contentSteering:l,levels:d,sessionData:h,sessionKeys:c,startTimeOffset:u,variableList:f}=o;this.variableList=f,d.forEach((e=>{const{unknownCodecs:t}=e;if(t){const{preferManagedMediaSource:s}=this.hls.config;let{audioCodec:r,videoCodec:i}=e;for(let n=t.length;n--;){const a=t[n];areCodecsMediaSourceSupported(a,"audio",s)?(e.audioCodec=r=r?`${r},${a}`:a,sampleEntryCodesISO.audio[r.substring(0,4)]=2,t.splice(n,1)):areCodecsMediaSourceSupported(a,"video",s)&&(e.videoCodec=i=i?`${i},${a}`:a,sampleEntryCodesISO.video[i.substring(0,4)]=2,t.splice(n,1))}}}));const{AUDIO:g=[],SUBTITLES:m,"CLOSED-CAPTIONS":p}=M3U8Parser.parseMasterPlaylistMedia(n,a,o);if(g.length){g.some((e=>!e.url))||!d[0].audioCodec||d[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 AttrList({}),bitrate:0,url:""}))}i.trigger(Events.MANIFEST_LOADED,{levels:d,audioTracks:g,subtitles:m,captions:p,contentSteering:l,url:a,stats:t,networkDetails:r,sessionData:h,sessionKeys:c,startTimeOffset:u,variableList:f})}handleTrackOrLevelPlaylist(e,t,s,r,i){const n=this.hls,{id:a,level:o,type:l}=s,d=getResponseUrl(e,s),h=isFiniteNumber(o)?o:isFiniteNumber(a)?a:0,c=mapContextToLevelType(s),u=M3U8Parser.parseLevelPlaylist(e.data,d,h,c,0,this.variableList);if(l===PlaylistContextType.MANIFEST){const e={attrs:new AttrList({}),bitrate:0,details:u,name:"",url:d};u.requestScheduled=t.loading.start+computeReloadInterval(u,0),n.trigger(Events.MANIFEST_LOADED,{levels:[e],audioTracks:[],url:d,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=u,this.handlePlaylistLoaded(u,e,t,s,r,i)}handleManifestParsingError(e,t,s,r,i){this.hls.trigger(Events.ERROR,{type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.MANIFEST_PARSING_ERROR,fatal:t.type===PlaylistContextType.MANIFEST,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:r,stats:i})}handleNetworkError(e,t,s=!1,r,i){let n=`A network ${s?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${e.type}`;e.type===PlaylistContextType.LEVEL?n+=`: ${e.level} id: ${e.id}`:e.type!==PlaylistContextType.AUDIO_TRACK&&e.type!==PlaylistContextType.SUBTITLE_TRACK||(n+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let o=ErrorDetails.UNKNOWN,l=!1;const d=this.getInternalLoader(e);switch(e.type){case PlaylistContextType.MANIFEST:o=s?ErrorDetails.MANIFEST_LOAD_TIMEOUT:ErrorDetails.MANIFEST_LOAD_ERROR,l=!0;break;case PlaylistContextType.LEVEL:o=s?ErrorDetails.LEVEL_LOAD_TIMEOUT:ErrorDetails.LEVEL_LOAD_ERROR,l=!1;break;case PlaylistContextType.AUDIO_TRACK:o=s?ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:ErrorDetails.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case PlaylistContextType.SUBTITLE_TRACK:o=s?ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:ErrorDetails.SUBTITLE_LOAD_ERROR,l=!1}d&&this.resetInternalLoader(e.type);const h={type:ErrorTypes.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:d,context:e,error:a,networkDetails:t,stats:i};if(r){let s=e.url;t&&"url"in t&&(s=t.url),h.response=_objectSpread2({url:s,data:void 0},r)}this.hls.trigger(Events.ERROR,h)}handlePlaylistLoaded(e,t,s,r,i,n){const a=this.hls,{type:o,level:l,levelOrTrack:d,id:h,groupId:c,deliveryDirectives:u}=r,f=getResponseUrl(t,r),g=mapContextToLevelType(r);let m="number"==typeof r.level&&g===PlaylistLevelType.MAIN?l:void 0;const p=e.playlistParsingError;if(p){if(this.hls.logger.warn(`${p} ${e.url}`),!a.config.ignorePlaylistParsingErrors)return void a.trigger(Events.ERROR,{type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:p,reason:p.message,response:t,context:r,level:m,parent:g,networkDetails:i,stats:s});e.playlistParsingError=null}if(e.fragments.length)switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case PlaylistContextType.MANIFEST:case PlaylistContextType.LEVEL:if(m)if(d){if(d!==a.levels[m]){const e=a.levels.indexOf(d);e>-1&&(m=e)}}else m=0;a.trigger(Events.LEVEL_LOADED,{details:e,levelInfo:d||a.levels[0],level:m||0,id:h||0,stats:s,networkDetails:i,deliveryDirectives:u,withoutMultiVariant:o===PlaylistContextType.MANIFEST});break;case PlaylistContextType.AUDIO_TRACK:a.trigger(Events.AUDIO_TRACK_LOADED,{details:e,track:d,id:h||0,groupId:c||"",stats:s,networkDetails:i,deliveryDirectives:u});break;case PlaylistContextType.SUBTITLE_TRACK:a.trigger(Events.SUBTITLE_TRACK_LOADED,{details:e,track:d,id:h||0,groupId:c||"",stats:s,networkDetails:i,deliveryDirectives:u})}else{const n=e.playlistParsingError=new Error("No Segments found in Playlist");a.trigger(Events.ERROR,{type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:n,reason:n.message,response:t,context:r,level:m,parent:g,networkDetails:i,stats:s})}}}class Hls{static get version(){return version}static isMSESupported(){return isMSESupported()}static isSupported(){return isSupported()}static getMediaSource(){return getMediaSource()}static get Events(){return Events}static get MetadataSchema(){return MetadataSchema}static get ErrorTypes(){return ErrorTypes}static get ErrorDetails(){return ErrorDetails}static get DefaultConfig(){return Hls.defaultConfig?Hls.defaultConfig:hlsDefaultConfig}static set DefaultConfig(e){Hls.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new EventEmitter,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 t=this.logger=enableLogs(e.debug||!1,"Hls instance",e.assetPlayerId),s=this.config=mergeConfig(Hls.DefaultConfig,e,t);this.userConfig=e,s.progressive&&enableStreamingMode(s,t);const{abrController:r,bufferController:i,capLevelController:n,errorController:a,fpsController:o}=s,l=new a(this),d=this.abrController=new r(this),h=new FragmentTracker(this),c=s.interstitialsController,u=c?this.interstitialsController=new c(this,Hls):null,f=this.bufferController=new i(this,h),g=this.capLevelController=new n(this),m=new o(this),p=new PlaylistLoader(this),E=s.contentSteeringController,y=E?new E(this):null,v=this.levelController=new LevelController(this,y),T=new ID3TrackController(this),S=new KeyLoader(this.config,this.logger),A=this.streamController=new StreamController(this,h,S),L=this.gapController=new GapController(this,h);g.setStreamController(A),m.setStreamController(A);const I=[p,v,A];u&&I.splice(1,0,u),y&&I.splice(1,0,y),this.networkControllers=I;const R=[d,f,L,g,m,T,h];this.audioTrackController=this.createController(s.audioTrackController,I);const D=s.audioStreamController;D&&I.push(this.audioStreamController=new D(this,h,S)),this.subtitleTrackController=this.createController(s.subtitleTrackController,I);const b=s.subtitleStreamController;b&&I.push(this.subtititleStreamController=new b(this,h,S)),this.createController(s.timelineController,R),S.emeController=this.emeController=this.createController(s.emeController,R),this.cmcdController=this.createController(s.cmcdController,R),this.latencyController=this.createController(LatencyController,R),this.coreComponents=R,I.push(l);const _=l.onErrorOut;"function"==typeof _&&this.on(Events.ERROR,_,l),this.on(Events.MANIFEST_LOADED,p.onManifestLoaded,p)}createController(e,t){if(e){const s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,r){this._emitter.off(e,t,s,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;const s=e===Events.ERROR;this.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERNAL_EXCEPTION,fatal:s,event:e,error:t}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(Events.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach((e=>e.destroy())),this.networkControllers.length=0,this.coreComponents.forEach((e=>e.destroy())),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const t=new Error(`attachMedia failed: invalid argument (${e})`);return void this.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.ATTACH_MEDIA_ERROR,fatal:!0,error:t})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,s=t?e.media:e,r=t?e:{media:s};this._media=s,this.trigger(Events.MEDIA_ATTACHING,r)}detachMedia(){this.logger.log("detachMedia");const e={};this.trigger(Events.MEDIA_DETACHING,e),this._media=null,this.trigger(Events.MEDIA_DETACHED,e)}transferMedia(){this._media=null;const e=this.bufferController.transferMedia(),t={transferMedia:e};return this.trigger(Events.MEDIA_DETACHING,t),this.trigger(Events.MEDIA_DETACHED,t),e}loadSource(e){this.stopLoad();const t=this.media,s=this._url,r=this._url=urlToolkitExports.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),t&&s&&(s!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(Events.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(e,t),this.started&&this.networkControllers);s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!this.started&&this.networkControllers);e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach((e=>{e.resumeBuffering&&e.resumeBuffering()})))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach((e=>{e.pauseBuffering&&e.pauseBuffering()})))}get inFlightFragments(){const e={[PlaylistLevelType.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[PlaylistLevelType.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[PlaylistLevelType.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=null==e?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=uuid()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return-1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){isHdcpLevel(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const s=e.length;for(let r=0;r<s;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this;let r;if(r=-1===t&&null!=e&&e.length?e.length-1:t,s)for(let t=r;t--;){const r=e[t].attrs["HDCP-LEVEL"];if(r&&r<=s)return t}return r}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return(null==(t=this.audioTrackController)?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return(null==(t=this.subtitleTrackController)?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return!!e&&e.subtitleDisplay}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!(null==(e=this.bufferController)||!e.bufferedToEnd)}get interstitialsManager(){var e;return(null==(e=this.interstitialsController)?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){return getMediaDecodingInfoPromise(e,getAudioTracksByGroup(t),navigator.mediaCapabilities)}}Hls.defaultConfig=void 0;const OPTIONS_MAP={liveSyncDuration:{key:"targetLatency",val:10},liveMaxLatencyDuration:{key:"maxLatency",val:20},backBufferLength:{key:"bufferBehind",val:10},initialLiveManifestSize:{key:"minSegmentsStartPlay",val:3},preferManagedMediaSource:[{key:"preferMMS",val:!1},{key:"preferMMSStreaming",val:!1}],lowLatencyMode:{key:"useLowLatency",val:!0},startPosition:{key:"startTime",val:0},interstitialLiveLookAhead:{key:"preloadTime",val:30}};function getHlsConfig(e){const t={};Object.keys(OPTIONS_MAP).forEach((s=>{const r=OPTIONS_MAP[s];r instanceof Array?r.forEach((e=>{t[s]=e.val})):t[s]=e[r.key]||r.val}));const s="number"==typeof e.retryCount?e.retryCount:3,r="number"==typeof e.retryDelay?e.retryDelay:1e3,i=e.loadTimeout||1e4,n="number"==typeof e.manifestLoadTimeout?e.manifestLoadTimeout:1e4,a={maxNumRetry:s,retryDelayMs:r,maxRetryDelayMs:r,shouldRetry:(e,t)=>t<e.maxNumRetry},o={maxNumRetry:s,retryDelayMs:r,maxRetryDelayMs:r,shouldRetry:(e,t)=>t<e.maxNumRetry};return t.manifestLoadPolicy={default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:n,timeoutRetry:a,errorRetry:o}},t.playlistLoadPolicy={default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:i,timeoutRetry:a,errorRetry:o}},t.fragLoadPolicy={default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:i,timeoutRetry:a,errorRetry:o}},{...t,...e}}function initHlsEvents(e,t){e.on(Hls.Events.SUBTITLE_FRAG_PROCESSED,((e,s)=>{(null==s?void 0:s.frag)&&t.emit("core_event",{eventName:"core.subtitlesegments",list:[s.frag]})})),e.on(Hls.Events.MANIFEST_PARSED,((e,{levels:s})=>{t.emit("core_event",{eventName:"core.hlsManifestParsed",list:s})})),e.on(Hls.Events.MANIFEST_LOADING,((e,{url:s})=>{t.emit("core_event",{eventName:"core.loadstart",url:s})})),e.on(Hls.Events.LEVEL_LOADING,((e,{url:s})=>{t.emit("core_event",{eventName:"core.loadstart",url:s})})),e.on(Hls.Events.FRAG_LOADING,((e,{frag:s})=>{t.emit("core_event",{eventName:"core.loadstart",url:s.url})})),e.on(Hls.Events.MANIFEST_LOADED,((e,s)=>{const{url:r}=s;t.emit("core_event",{eventName:"core.loadcomplete",url:r})})),e.on(Hls.Events.LEVEL_LOADED,((e,s)=>{const{details:r,stats:i}=s;t.emit("core_event",{eventName:"core.loadcomplete",...i,url:null==r?void 0:r.url})})),e.on(Hls.Events.FRAG_LOADED,((e,s)=>{const{frag:r}=s;t.emit("core_event",{eventName:"core.loadcomplete",url:r.url})})),e.on(Hls.Events.FRAG_PARSING_USERDATA,((e,s)=>{const{samples:r}=s;r.forEach((e=>{let s;e.customSeiMessage&&(s={originPts:e.pts,pts:e.pts,time:0,data:{payload:e.payload,type:e.payloadType,size:e.payloadSize,uuid:5===e.payloadType?e.uuid:""},sei:{code:e.payloadType,content:e.payload,dts:e.pts}},t.emit("core_event",{eventName:"core.sei",...s}))}))})),e.on(Hls.Events.MANIFEST_LOADED,((e,{levels:s,networkDetails:r})=>{t.emit("core_event",{eventName:"core.hlsmanifestloaded",playlist:s}),t.emit("core_event",{eventName:"core.loadresponseheaders",headers:r.headers})})),e.on(Hls.Events.LEVEL_LOADED,((e,{details:s})=>{const r={};Object.keys(s.dateRanges).forEach((e=>{r[e]=s.dateRanges[e].attr["START-DATE"]})),t.emit("core_event",{eventName:"core.hlslevelloaded",playlist:{...s,segments:s.fragments,dateRanges:r}})})),[Hls.Events.AUDIO_TRACKS_UPDATED,Hls.Events.AUDIO_TRACK_SWITCHING,Hls.Events.AUDIO_TRACK_SWITCHED,Hls.Events.AUDIO_TRACK_LOADING,Hls.Events.AUDIO_TRACK_LOADED].forEach((s=>e.on(s,((e,r)=>t.emit(s,r))))),e.on(Hls.Events.ERROR,((s,r)=>{const{details:i,fatal:n,type:a,response:o,reason:l,error:d}=r;if(!n)return;let h,c;switch(a){case Hls.ErrorTypes.NETWORK_ERROR:h=2100,i.includes("TimeOut")?h=2101:403===(null==o?void 0:o.code)?h=2103:404===(null==o?void 0:o.code)&&(h=2104),t.emit("error",{errorType:"network",errorCode:h,message:(null==d?void 0:d.message)||i,originError:r});break;case Hls.ErrorTypes.MEDIA_ERROR:c="media",i===Hls.ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR?h=5104:i===Hls.ErrorDetails.FRAG_DECRYPT_ERROR?h=5105:i===Hls.ErrorDetails.FRAG_PARSING_ERROR?(h=1100,c="manifest"):i===Hls.ErrorDetails.FRAG_GAP?h=5104:i===Hls.ErrorDetails.BUFFER_ADD_CODEC_ERROR?h=5200:i===Hls.ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR?h=5104:i===Hls.ErrorDetails.BUFFER_APPEND_ERROR||i===Hls.ErrorDetails.BUFFER_APPENDING_ERROR?h=5201:i===Hls.ErrorDetails.BUFFER_STALLED_ERROR||i===Hls.ErrorDetails.BUFFER_FULL_ERROR?h=5203:(i===Hls.ErrorDetails.BUFFER_SEEK_OVER_HOLE||i===Hls.ErrorDetails.BUFFER_NUDGE_ON_STALL)&&(h=5202),t.emit("error",{errorType:c||a,errorCode:h,message:(null==d?void 0:d.message)||i,originError:r});break;case Hls.ErrorTypes.MUX_ERROR:h=4100,t.emit("error",{errorType:"remux",errorCode:h,message:(null==d?void 0:d.message)||i,originError:r});break;case Hls.ErrorTypes.KEY_SYSTEM_ERROR:h=7111,i===Hls.ErrorDetails.KEY_SYSTEM_NO_KEYS?h=7103:i===Hls.ErrorDetails.KEY_SYSTEM_NO_ACCESS?h=7101:i===Hls.ErrorDetails.KEY_SYSTEM_NO_SESSION?h=7104:i===Hls.ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE?h=7107:i===Hls.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED?h=7108:i===Hls.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED||i===Hls.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED?h=7110:i===Hls.ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED?h=7104:i===Hls.ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR&&(h=7111),t.emit("error",{errorType:"drm",errorCode:h,message:(null==d?void 0:d.message)||l||i,originError:r});break;default:i===Hls.ErrorDetails.LEVEL_SWITCH_ERROR&&(h=2100,c="network"),t.emit("error",{errorType:c||"other",errorCode:h,message:(null==d?void 0:d.message)||l||i,originError:r})}try{e.stopLoad(),t.pause()}catch(e){}})),e.on(Hls.Events.MEDIA_ATTACHED,(()=>{t.emit("sourceopen")})),e.on(Hls.Events.BUFFER_APPENDED,(()=>{t.emit("bufferappend")})),e.on(Hls.Events.AUDIO_TRACKS_UPDATED,((e,{audioTracks:s})=>{t.emit("core_event",{eventName:"core.audiotracksupdate",audioTracks:s})})),e.on(Hls.Events.AUDIO_TRACK_SWITCHING,((e,s)=>{t.emit("core_event",{eventName:"core.audiotrackswitching",...s})})),e.on(Hls.Events.AUDIO_TRACK_SWITCHED,((e,s)=>{t.emit("core_event",{eventName:"core.audiotrackswitched",...s})})),e.on(Hls.Events.SUBTITLE_TRACKS_UPDATED,((e,s)=>{t.emit("core_event",{eventName:"core.subtitleplaylist",list:Array.isArray(null==s?void 0:s.subtitleTracks)?s.subtitleTracks:[]})})),e.on(Hls.Events.SUBTITLE_TRACKS_CLEARED,(()=>{t.emit("core_event",{eventName:"core.subtitletracksclear"})})),e.on(Hls.Events.SUBTITLE_TRACK_SWITCH,((e,s)=>{t.emit("core_event",{eventName:"core.subtitletrackswitch",...s})})),e.on(Hls.Events.SUBTITLE_TRACK_LOADING,((e,s)=>{t.emit("core_event",{eventName:"core.subtitletrackloading",...s})})),e.on(Hls.Events.SUBTITLE_TRACK_LOADED,((e,s)=>{t.emit("core_event",{eventName:"core.subtitletrackloaded",...s})}))}class TrackManager{constructor(e,t){this.hls=e,this.player=t}getAudioTracks(){if(!this.hls)return console.warn("HLS instance not initialized"),[];try{return this.hls.audioTracks||[]}catch(e){return console.error("Failed to get audio tracks:",e),[]}}getCurrentAudioTrack(){if(!this.hls)return console.warn("HLS instance not initialized"),-1;try{return this.hls.audioTrack}catch(e){return console.error("Failed to get current audio track:",e),-1}}switchAudioTrack(e){if(!this.hls)return console.warn("HLS instance not initialized"),!1;const t=this.getAudioTracks();if(0===t.length)return console.warn("No audio tracks available"),!1;if(!t.some(((t,s)=>s===e)))return console.warn(`Audio track with ID ${e} not found`),!1;try{return this.hls.audioTrack=e,this.player.emit("core_event",{eventName:"core.audiotrackchange",trackId:e,trackInfo:t[e]||null}),!0}catch(e){return console.error("Failed to switch audio track:",e),!1}}getSubtitleTracks(){if(!this.hls)return console.warn("HLS instance not initialized"),[];try{return this.hls.subtitleTracks||[]}catch(e){return console.error("Failed to get subtitle tracks:",e),[]}}getAllSubtitleTracks(){if(!this.hls)return console.warn("HLS instance not initialized"),[];try{return this.hls.allSubtitleTracks||[]}catch(e){return console.error("Failed to get all subtitle tracks:",e),[]}}getCurrentSubtitleTrack(){if(!this.hls)return console.warn("HLS instance not initialized"),-1;try{return this.hls.subtitleTrack}catch(e){return console.error("Failed to get current subtitle track:",e),-1}}switchSubtitleTrack(e){if(!this.hls)return console.warn("HLS instance not initialized"),!1;const t=this.getSubtitleTracks();if(-1===e)try{return this.hls.subtitleTrack=-1,this.player.emit("core_event",{eventName:"core.subtitletrackchange",trackId:-1,trackInfo:null}),!0}catch(e){return console.error("Failed to disable subtitle track:",e),!1}if(0===t.length)return console.warn("No subtitle tracks available"),!1;if(!t.some(((t,s)=>s===e)))return console.warn(`Subtitle track with ID ${e} not found`),!1;try{return this.hls.subtitleTrack=e,this.player.emit("core_event",{eventName:"core.subtitletrackchange",trackId:e,trackInfo:t[e]||null}),!0}catch(e){return console.error("Failed to switch subtitle track:",e),!1}}getSubtitleDisplay(){if(!this.hls)return console.warn("HLS instance not initialized"),!1;try{return this.hls.subtitleDisplay}catch(e){return console.error("Failed to get subtitle display status:",e),!1}}setSubtitleDisplay(e){if(!this.hls)return console.warn("HLS instance not initialized"),!1;try{return this.hls.subtitleDisplay=e,this.player.emit("core_event",{eventName:"core.subtitledisplaychange",enabled:e}),!0}catch(e){return console.error("Failed to set subtitle display:",e),!1}}}const MAX_HOLE=.1,_XgHls=class extends BasePlugin{constructor(e){super({...e,pluginName:_XgHls.pluginName}),this._tickInterval=500,this._currentIndex=0,this._onPlay=()=>{this.hls.startLoad()},this.onUrlChange=e=>{/^blob/.test(e)||(this.playerConfig.url=e,this.register(e))},this._getBufferend=e=>{const{buffered:t}=e;let s=0;return s=t&&t.length?t.end(t.length-1):0,s},this._tick=()=>{clearTimeout(this._tickTimer);const e=this.player.media;if(!e)return;this._tickTimer=setTimeout(this._tick,this._tickInterval);const t=this._getBufferend(e);t<.1||!e.readyState||this.player.config.isLive&&4===e.readyState&&e.paused&&t-e.currentTime>this.config.disconnectTime&&this.hls.stopLoad()},this.on=(e,t)=>{var s;null==(s=this.hls)||s.on(e,t)},this.config=e.config||{},this.player.handleSource=!1}static get pluginName(){return"hls"}beforePlayerInit(){this.register(this.player.config.url)}initEvt(){initHlsEvents(this.hls,this.player)}afterCreate(){const e=this.player.media;this.player.on(URL_CHANGE,this.onUrlChange);try{BasePlugin.defineGetterOrSetter(this.player,{url:{get:()=>{try{return e.src}catch(e){return null}},configurable:!0}})}catch(e){}}register(e){const{player:t}=this;this.hls&&this.hls.destroy();const s=getHlsConfig(this.config);if(this.hls=new Hls(s),this._trackManager=new TrackManager(this.hls,this.player),this.initEvt(),t.config.preProcessUrl&&e){const{url:s}=t.config.preProcessUrl(e);e=s}e&&this.hls.loadSource(e);const r=this.player.media;this.hls.attachMedia(r),this._tickTimer&&clearTimeout(this._tickTimer),this._tickTimer=setTimeout(this._tick,this._tickInterval),r.removeEventListener("play",this._onPlay),r.addEventListener("play",this._onPlay)}switchUrl(e,{startTime:t,bitrate:s,seamless:r}){if(this.hls.loadSource(e),void 0!==t){this.player.media.currentTime=t}}getAudioTracks(){return this._trackManager.getAudioTracks()}getCurrentAudioTrack(){return this._trackManager.getCurrentAudioTrack()}switchAudioTrack(e){return this._trackManager.switchAudioTrack(e)}getSubtitleTracks(){return this._trackManager.getSubtitleTracks()}getAllSubtitleTracks(){return this._trackManager.getAllSubtitleTracks()}getCurrentSubtitleTrack(){return this._trackManager.getCurrentSubtitleTrack()}switchSubtitleTrack(e){return this._trackManager.switchSubtitleTrack(e)}getSubtitleDisplay(){return this._trackManager.getSubtitleDisplay()}setSubtitleDisplay(e){return this._trackManager.setSubtitleDisplay(e)}destroy(){var e;clearTimeout(this._tickTimer),this.player.off(URL_CHANGE,this.onUrlChange);const t=this.player.media;null==t||t.removeEventListener("play",this._onPlay),null==(e=this.hls)||e.destroy()}};let XgHls=_XgHls;XgHls.isStreamingPlugin=!0;export{XgHls as default};
|