var __webpack_modules__=[,,t=>{t.exports=window.Wistia.Preact},(t,e,i)=>{i.d(e,{elemAppend:()=>f,elemBind:()=>A,elemCancelFullscreen:()=>I,elemFromObject:()=>h,elemHeight:()=>b,elemInDom:()=>S,elemRemove:()=>g,elemRequestFullscreen:()=>R,elemStyle:()=>m,elemUnbind:()=>L,elemWidth:()=>T,inUserEventContext:()=>D,pageLoaded:()=>n.pageLoaded,safeRequestAnimationFrame:()=>P});var r,s=i(4),n=(i(6),i(8)),a=i(9),o=i(12),l=(i(21),i(22),i(28)),u=i(16),c=function(t,e){if(null==t)throw new TypeError("Cannot convert undefined or null to object");return Object.prototype.hasOwnProperty.call(Object(t),e)},d=(u.Wistia,(0,a.cachedDetect)()),h=function(t){if((0,s.isArray)(t)){for(var e=[],i=0;i<t.length;i++)e.push(h(t[i]));return e}var r=t.tagName||"div",n=t.childNodes||[];(0,s.isArray)(n)||(n=[n]);var a=document.createElement(r);for(var o in t)if(c(t,o)){var l=t[o];if("childNodes"!==o&&"tagName"!==o&&"ref"!==o){var u=o.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase();if("style"===o)if((0,s.isObject)(l))for(var d in l)a.style[d]=l[d];else for(var g=l.split(";"),m=0;m<g.length;m++){var p=g[m].split(/\s*:\s*/),v=p[0],y=p[1];v&&y&&(a.style[v]=y)}else if("events"===o)for(var E in l){var T=l[E];A(a,E,T)}else"className"===o||"class"===o?a.className=l:"innerHTML"===o?a.innerHTML=l:"innerText"===o?a.innerText=l:null!=l&&"function"==typeof l.toString&&a.setAttribute(u,l.toString())}}for(var b=0;b<n.length;b++){var S=n[b];if((0,s.isObject)(S)){var L=h(S);f(a,L)}else{var k=document.createTextNode(S.toString());f(a,k)}}return"function"==typeof t.ref&&t.ref(a),a},f=function(t,e){if((0,s.isArray)(e))for(var i=0;i<e.length;i++)f(t,e[i]);else t.tagName.includes("-")?t.shadowRoot.appendChild(e,{wistiaGridCaller:!0}):t.appendChild(e,{wistiaGridCaller:!0})},g=function(t){var e;if((0,s.isArray)(t)||window.NodeList&&t instanceof NodeList)for(var i=0;i<t.length;i++)g(t[i]);else null==t||1!==t.nodeType&&3!==t.nodeType||!(e=t.parentNode)||(e.removeChild(t),t=null)},m=function(t){for(var e=arguments.length,i=new Array(e>1?e-1:0),r=1;r<e;r++)i[r-1]=arguments[r];if((0,s.isArray)(t)||window.NodeList&&t instanceof NodeList){for(var n=[],a=0;a<t.length;a++){var l=t[a];1===l.nodeType&&n.push(m.apply(void 0,[l].concat(i)))}return n}if(2===i.length){var u=i[0],c=i[1];t.style[u]=c}else if(1===i.length)if("string"==typeof i[0]){var d=i[0];try{return t.currentStyle?t.currentStyle[d]:window.getComputedStyle?window.getComputedStyle(t,null).getPropertyValue(d):null}catch(t){o.wlog.notice(t)}}else{var h=y(i[0]);for(var f in h){var g=h[f];t.style[f]=g}}else o.wlog.apply(void 0,["Unexpected args",t].concat(i))},p={borderImage:!0,mixBlendMode:!0,transform:!0,transition:!0,transitionDuration:!0},v=["webkit","moz","o","ms"],y=function(t){if(d.chrome)return t;var e={};for(var i in t){var r=t[i];if(e[i]=r,p[i])for(var s=v,n=0;n<s.length;n++){var a=s[n]+i.charAt(0).toUpperCase()+i.slice(1);i[a]||(e[a]=r)}}return e},E=function(t,e){if(!window.getComputedStyle)return null;var i=window.getComputedStyle(t,null);return null==i?null:null!=e?i[e]:i},T=function(t){if(t===window)return window.innerWidth?window.innerWidth:document.documentElement?document.documentElement.offsetWidth:document.body.offsetWidth;if(t===document){var e=document.body,i=document.documentElement;return Math.max(e.scrollWidth,e.offsetWidth,i.clientWidth,i.scrollWidth,i.offsetWidth)}var r;return(r=E(t,"width"))&&null!=r?parseFloat(r):t.currentStyle?t.offsetWidth:-1},b=function(t){if(t===window)return window.innerHeight?window.innerHeight:document.documentElement?document.documentElement.offsetHeight:document.body.offsetHeight;if(t===document){var e=document.body,i=document.documentElement;return Math.max(e.scrollHeight,e.offsetHeight,i.clientHeight,i.scrollHeight,i.offsetHeight)}var r;return(r=E(t,"height"))&&null!=r?parseFloat(r):t.currentStyle?t.offsetHeight:-1},S=function(t){for(;t;){if(t===document)return!0;t=t.parentNode||t.getRootNode().host}return!1},A=function(t,e,i){var r=arguments.length>3&&void 0!==arguments[3]&&arguments[3],s=function(r){(r=r||window.event).pageX||r.pageY||!r.clientX&&!r.clientY||(r.pageX=r.clientX+w(),r.pageY=r.clientY+_()),r.preventDefault||(r.preventDefault=function(){r.returnValue=!1}),r.stopPropagation||(r.stopPropagation=function(){r.cancelBubble=!0}),null==r.which&&(r.which=null!=r.charCode?r.charCode:r.keyCode),null==r.which&&null!=r.button&&(1&r.button?r.which=1:2&r.button?r.which=3:4&r.button?r.which=2:r.which=0),r.target||r.srcElement&&(r.target=r.srcElement),r.target&&3===r.target.nodeType&&(r.target=r.target.parentNode);for(var s=arguments.length,n=new Array(s>1?s-1:0),a=1;a<s;a++)n[a-1]=arguments[a];var o=i.apply(r.target,[r].concat(n));return o===L&&L(t,e,i),o};u.Wistia._elemBind=u.Wistia._elemBind||{};var n=k(t,e,i);return u.Wistia._elemBind[n]=s,s.elem=t,s.event=e,t.addEventListener(e,s,r),function(){L(t,e,i,r)}},L=function(t,e,i){var r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(null!=t&&null!=t._wistiaElemId&&null!=i&&i._wistiaBindId){var s=k(t,e,i),n=u.Wistia._elemBind[s];return n&&(t.removeEventListener(e,n,r),n.elem=null,n.event=null),delete u.Wistia._elemBind[s]}},k=function(t,e,i){return t._wistiaElemId=t._wistiaElemId||(0,l.seqId)("wistia_elem_"),i._wistiaBindId=i._wistiaBindId||(0,l.seqId)("wistia_bind_"),"".concat(t._wistiaElemId,".").concat(e,".").concat(i._wistiaBindId)},R=function(t){try{if(t.requestFullscreen&&document.fullscreenEnabled)return t.requestFullscreen().catch((function(t){return o.wlog.notice("requestFullscreen failed",t),Promise.reject(t)}));if(t.webkitEnterFullscreen)return t.webkitEnterFullscreen(),Promise.resolve()}catch(t){return o.wlog.notice("requestFullscreen failed",t),Promise.reject(t)}return o.wlog.notice("no requestFullscreen functionality detected"),Promise.resolve()},I=function(t){return document.exitFullscreen?document.exitFullscreen():t&&t.webkitExitFullscreen?new Promise((function(e){t.webkitExitFullscreen(),e()})):(o.wlog.notice("no cancelFullscreen functionality detected"),Promise.resolve())},_=function(t){var e=document.body,i=document.documentElement;if(null==t)return i&&i.scrollTop||e&&e.scrollTop||0;e&&(e.scrollTop=t),i&&(i.scrollTop=t)},w=function(t){var e=document.body,i=document.documentElement;if(null==t)return i&&i.scrollLeft||e&&e.scrollLeft||0;e&&(e.scrollLeft=t),i&&(i.scrollLeft=t)},P=function(t){return(window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||function(t){return setTimeout(t,1e3/60)})(t)},D=function(){return!!r};["auxclick","click","contextmenu","dblclick","focus","keydown","keypress","keyup","mousedown","mouseup","reset","submit","touchend","touchstart"].forEach((function(t){A(document,t,(function(t){r=t,Date.now(),setTimeout((function(){r===t&&(r=void 0)}),0)}),!d.passiveSupported||{capture:!0,passive:!0})}))},(t,e,i)=>{i.d(e,{assign:()=>r.assign,cast:()=>p,clone:()=>c,eachLeaf:()=>x,except:()=>T,filter:()=>L,getDeep:()=>d,isArray:()=>R,isEmpty:()=>C,isObject:()=>_,merge:()=>a,only:()=>E,select:()=>b,setAndPreserveUndefined:()=>f,setDeep:()=>h,sort:()=>A,unsetDeep:()=>m});var r=i(5),s=function(t,e){if(null==t)throw new TypeError("Cannot convert undefined or null to object");return Object.prototype.hasOwnProperty.call(Object(t),e)},n=Array.prototype.slice,a=function(t){if(0==(arguments.length<=1?0:arguments.length-1))return t;for(var e=0;e<(arguments.length<=1?0:arguments.length-1);e++)o(t,e+1<1||arguments.length<=e+1?void 0:arguments[e+1]);return t},o=function(t,e){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:l,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:u;if(R(e)){R(t)||(t=[]);for(var n=0;n<e.length;n++){var a=e[n];null==t[n]&&null!=a&&(R(a)?t[n]=[]:_(a)&&(t[n]={}));var c=o(t[n],a,i);r(e,n,c)?delete t[n]:t[n]=c}return i(t)}if(_(e)){for(var d in e)if(s(e,d)&&(s(t,d)||null==t[d])){var h=e[d];R(h)?(R(t[d])||(t[d]=[]),o(t[d],h,i),t[d]=i(t[d])):_(h)?(_(t[d])||(t[d]={}),o(t[d],h,i),t[d]=i(t[d])):null==t?(t={},r(e,d,h)||(t[d]=i(h))):r(e,d,h)?delete t[d]:t[d]=i(h)}return i(t)}return i(e)},l=function(t){return t},u=function(t,e,i){return null==i},c=function(t,e){return R(t)?o([],t,e):o({},t,e)},d=function(t,e,i){e="string"==typeof e?e.split("."):n.call(e);for(var r,a=t;null!=t&&e.length;){var o=e.shift();void 0!==t[o]&&(_(t[o])||R(t[o]))||!i||(0===o?(t=a[r]=[])[o]={}:t[o]={}),a=t,r=o,t=s(t,o)?t[o]:void 0}return t},h=function(t,e,i){return g(t,e,i,!0)},f=function(t,e,i){return g(t,e,i,!1)},g=function(t,e,i){var r=!(arguments.length>3&&void 0!==arguments[3])||arguments[3],s=(e="string"==typeof e?e.split("."):n.call(e)).pop();null!=(t=d(t,e,!0))&&(_(t)||R(t))&&null!=s&&(r&&null==i?delete t[s]:t[s]=i)},m=function(t,e){return h(t,e)},p=function(t){return null==t?t:_(t)||R(t)?y(t):v("".concat(t),t)},v=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:t;return/^-?[1-9]\d*?$/.test(t)?parseInt(t,10):"0"===t||"-0"===t?0:/^-?\d*\.\d+$/.test(t)?parseFloat(t):!!/^true$/i.test(t)||!/^false$/i.test(t)&&e},y=function(t){return o(t,t,(function(t){return"string"==typeof t?v(t):t}),(function(){return!1}))},E=function(t,e){for(var i={},r={},s=0;s<e.length;s++)r[e[s]]=!0;for(var n in t)r[n]&&(i[n]=t[n]);return i},T=function(t,e){for(var i={},r={},s=0;s<e.length;s++)r[e[s]]=!0;for(var n in t)r[n]||(i[n]=t[n]);return i},b=function(t,e){for(var i=[],r="function"==typeof e,s=r?e:null,n=0;n<t.length;n++){var a=t[n];if(r)s(a)&&i.push(a);else{var o=!0;for(var l in e){var u=e[l];if(u instanceof Array){if(!a[l]||a[l]<u[0]||a[l]>u[1]){o=!1;break}}else if(u instanceof RegExp){if(!u.test(a[l])){o=!1;break}}else if(u instanceof S){for(var c=!1,d=0;d<u.values.length;d++){var h=u.values[d];if(a[l]===h){c=!0;break}}if(!c){o=!1;break}}else if("function"==typeof u){if(null==a[l]||!u(a[l])){o=!1;break}}else if(a[l]!==u){o=!1;break}}o&&i.push(a)}}return i},S=function(t){var e=this;return e.values=t,e},A=function(t,e){var i="function"==typeof e,r=i?e:null,s=n.call(t);return i?s.sort(r):s.sort((function(t,i){var r;r=e instanceof Array?c(e):e.split(/\s*,\s*/);for(var s=0;0===s&&r.length>0;){var n=r.shift().split(/\s+/),a=n[0],o=n[1];if(o="desc"===o?-1:1,t[a]<i[a]){s=-1*o;break}if(t[a]!==i[a]){s=1*o;break}s=0}return s})),s},L=function(t,e,i){for(var r=void 0===i?undefined:i,s=[],n=0;n<t.length;n++)e.call(r,t[n],n,t)&&s.push(t[n]);return s},k=/^\s*function Array()/,R=function(t){return null!=t&&t.push&&k.test(t.constructor)},I=/^\s*function Object()/,_=function(t){return null!=t&&"object"==typeof t&&I.test(t.constructor)},w=/^\s*function RegExp()/,P=/^string|number|boolean|function$/i,D=function(t){return null!=t&&(P.test(typeof t)||function(t){return null!=t&&w.test(t.constructor)}(t))},C=function(t){return null==t||(!(!R(t)||t.length)||!!_(t)&&!Object.keys(t).length)},O=function(t,e,i,r,a){if(null==i&&(i=[]),D(t))e(t,i,r,a);else if(_(t)||R(t)){for(var o in e(t,i,r,a),t)if(s(t,o)){var l=n.call(i);l.push(o),O(t[o],e,l,t,o)}}else e(t,i,r,a)},x=function(t,e){O(t,(function(t,i,r,s){R(t)||_(t)||e(t,i,r,s)}))}},(t,e,i)=>{i.d(e,{assign:()=>s});var r=function(t,e){if(null==t)throw new TypeError("Cannot convert undefined or null to object");return Object.prototype.hasOwnProperty.call(Object(t),e)},s=function(t){for(var e=arguments.length,i=new Array(e>1?e-1:0),r=1;r<e;r++)i[r-1]=arguments[r];if(Object.assign)return Object.assign.apply(Object,[t].concat(i));for(var s=0;s<i.length;s++)n(t,i[s]);return t},n=function(t,e){for(var i in e)r(e,i)&&(t[i]=e[i]);return t}},(t,e,i)=>{i(7)},(t,e,i)=>{i.d(e,{poll:()=>r});var r=function(t,e,i,r,s){var n=null,a=(new Date).getTime(),o=function(){(new Date).getTime()-a>r?"function"==typeof s&&s():t()?e():(clearTimeout(n),n=setTimeout(o,i))};n=setTimeout(o,1)}},(t,e,i)=>{i.d(e,{pageLoaded:()=>r});var r=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4e3,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:document,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:window;if(/loaded|complete/.test(i.readyState))setTimeout(t,0);else{var s=function(){r.removeEventListener("load",n,!1)},n=function(){clearTimeout(a),s(),t()};r.addEventListener("load",n,!1);var a=setTimeout((function(){s(),t()}),e)}}},(t,e,i)=>{i.d(e,{cachedDetect:()=>U});var r,s=i(10),n=i(11),a=navigator.userAgent,o=null,l=/(webkit)[ /]([^\s]+)/i,u=/OPR\/([^\s]+)/i,c=/(edge)\/(\d+(?:\.\d+)?)/i,d=/(mozilla)(?:.*? rv:([^\s)]+))?/i,h=/(android) ([^;]+)/i,f=/(iphone)/i,g=/(Windows Phone OS (\d+(?:\.\d+)?))/,m=/OS (\d+)_(\d+)/i,p=/(firefox)/i,v=/Mobile VR/i,y=/Version\/([^\s]+)/i,E=function(){return(b()[1]||"webkit").toLowerCase()},T=function(){return b()[2]},b=function(){var t;return(t=a.match(c))||(t=a.match(l))||(t=a.match(u))?t:t?(null!=document.documentMode&&(t[2]=document.documentMode),t):(t=a.match(d))||[]},S=function(){var t=a.match(h);return null!=t&&{version:t[2]}},A=function(){return f.test(a)},L=function(){return P()>0||S()||R()},k=function(){try{var t=matchMedia("(hover:hover)");if("not all"!==t.media)return t.matches}catch(t){}return!L()},R=function(){return/Macintosh/i.test(navigator.userAgent)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>1},I=function(){return l.test(a)&&!/chrome/i.test(a)&&!R()&&!A()},_=function(){return!(!/Chrome/.test(a)||!/Google Inc/.test(navigator.vendor))&&{version:w()}},w=function(){var t=a.match(/\bChrome\/([^\s]+)/);return t&&t[1]},P=function(){var t=a.match(m),e=a.match(y);return null!=t?parseFloat("".concat(t[1],".").concat(t[2])):null!=e&&e[1]&&R()?parseFloat(e[1]):0},D=function(){return c.test(a)},C=function(){return p.test(a)},O=function(){var t=document.createElement("video"),e=!1;try{if(t.canPlayType){var i='video/mp4; codecs="avc1.42E01E';(e={}).h264=!!t.canPlayType("".concat(i,'"'))||!!t.canPlayType("".concat(i,', mp4a.40.2"')),e.webm=!!t.canPlayType('video/webm; codecs="vp9, vorbis"'),e.nativeHls=!!t.canPlayType("application/vnd.apple.mpegURL")}}catch(t){e={ogg:!1,h264:!1,webm:!1,nativeHls:!1}}return e},x=function(){try{return"localStorage"in s.root&&null!=s.root.localStorage}catch(t){return!1}},M=["WebKit","Moz","O","Ms",""],F=function(){for(var t=0;t<M.length;t++){var e="".concat(M[t],"MutationObserver");if(s.root[e])return e}return null},N=function(){if(null!=r)return r;try{var t=Object.defineProperty({},"passive",{get:function(){r=!0}});window.addEventListener("test",null,t)}catch(t){r=!1}return r},B=function(){var t=_(),e=C(),i=D(),r=u.test(a),s=t&&T()>=32,n=t&&T()>=75&&S(),o=e&&T()>=65,l=e&&T()>=67&&S(),c=i&&T()>=18,d=r&&T()>=19;return s||n||o||l||c||d},U=function(){return o||(o=$())},$=function(){var t,e,i,r,o,l,u,c,d,h,f,m,p,y={browser:{version:T()},edge:D(),firefox:C(),gearvr:v.test(a),hdr:!(null===(m=(p=window).matchMedia)||void 0===m||!m.call(p,"(dynamic-range: high)").matches)||!!(screen.colorDepth&&screen.colorDepth>=30),hdrCodecs:{hevc:null!==(i=null===(r=window.MediaSource)||void 0===r||null===(o=r.isTypeSupported)||void 0===o?void 0:o.call(r,'video/mp4; codecs="hvc1.2.4.L153.B0"'))&&void 0!==i&&i,av1:null!==(l=null===(u=window.MediaSource)||void 0===u||null===(c=u.isTypeSupported)||void 0===c?void 0:c.call(u,'video/mp4; codecs="av01.0.08M.10.0.110.09.16.09"'))&&void 0!==l&&l,vp92:null!==(d=null===(h=window.MediaSource)||void 0===h||null===(f=h.isTypeSupported)||void 0===f?void 0:f.call(h,'video/mp4; codecs="vp09.02.10.10.01.09.16.09"'))&&void 0!==d&&d},android:S(),oldandroid:S()&&parseFloat(S().version)<4.1,iphone:A(),ipad:R(),safari:I(),chrome:_(),winphone:{version:g.test(a)[2]},ios:{version:P()},windows:/win/i.test(navigator.platform),mac:/mac/i.test(navigator.platform),retina:null!=s.root.devicePixelRatio&&s.root.devicePixelRatio>1,hoverIsNatural:k(),touchScreen:L(),video:O(),managedMediaSource:"ManagedMediaSource"in window&&"function"==typeof(null===(e=window.ManagedMediaSource)||void 0===e?void 0:e.isTypeSupported),mediaSource:s.root.MediaSource&&s.root.MediaSource.isTypeSupported("".concat('video/mp4; codecs="avc1.42E01E',', mp4a.40.2"')),nativeHls:(A()||R()||I())&&O().nativeHls,localstorage:x(),fullscreenEnabled:document.fullscreenEnabled||document.mozFullScreenEnabled||document.webkitFullscreenEnabled||document.msFullscreenEnabled,vulcanV2Support:(t=/webkit|mozilla|edge/.test(E()),!!(A()||R()||S())||Boolean(t&&O().h264&&Object.defineProperties)),mutationObserver:F(),callingPlayRequiresEventContext:P()>0||S()||I(),passiveSupported:N(),webp:B(),performanceMeasure:(0,n.hasPerformanceMeasureSupport)()};return y.browser[E()]=!0,y}},(t,e,i)=>{var r;i.d(e,{root:()=>s});try{(r=self).self!==r&&void 0!==r.self&&"undefined"!=typeof window&&(r=window)}catch(t){r="undefined"!=typeof globalThis?globalThis:window}var s=r},(t,e,i)=>{i.d(e,{hasPerformanceMeasureSupport:()=>r});var r=function(){var t=window.performance;return Boolean(t)&&Boolean(t.measure)}},(t,e,i)=>{i.d(e,{wlog:()=>p});var r=i(13),s=i(16);function n(t){return function(t){if(Array.isArray(t))return a(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||function(t,e){if(t){if("string"==typeof t)return a(t,e);var i={}.toString.call(t).slice(8,-1);return"Object"===i&&t.constructor&&(i=t.constructor.name),"Map"===i||"Set"===i?Array.from(t):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?a(t,e):void 0}}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function a(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,r=Array(e);i<e;i++)r[i]=t[i];return r}var o={ERROR:0,WARNING:1,NOTICE:2,INFO:3,DEBUG:4,error:0,warning:1,notice:2,info:3,debug:4},l=function(){},u=function(t){var e=this;null==t&&(t={});return e.error=function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return e.log(0,i)},e.warn=function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return e.log(1,i)},e.notice=function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return e.log(1,i)},e.info=function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return e.log(3,i)},e.debug=function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return e.log(4,i)},e.ctx=t,e.ctx.initializedAt||e.reset(),e},c=u.prototype;c.reset=function(){this.ctx.level=0,this.ctx.grep=null,this.ctx.grepv=null,this.ctx.first1000LogLines=[],this.ctx.last1000LogLines=[],this.ctx.initializedAt=(new Date).getTime()},c.setLevel=function(t){var e=this.logFunc(3);null!=o[t]?(this.ctx.level=o[t],e('Log level set to "'.concat(t,'" (').concat(o[t],")"))):e('Unknown log level "'.concat(t,'"'))},c.setGrep=function(t){this.ctx.grep=t},c.setGrepv=function(t){this.ctx.grepv=t},c.first1000LogLines=function(){return this.ctx.first1000LogLines},c.last1000LogLines=function(){return this.ctx.last1000LogLines},c.matchedGrep=function(t){var e=!1;if(this.ctx.grep||this.ctx.grepv){for(var i=[],r=0;r<t.length;r++)try{var s=t[r];i.push(s.toString&&s.toString())}catch(t){i.push("")}var n=i.join(" "),a=!this.ctx.grep||n.match(this.ctx.grep),o=!this.ctx.grepv||!n.match(this.ctx.grepv);e=a&&o}else e=!0;return e},c.now=function(){return"undefined"!=typeof performance&&"function"==typeof performance.now?performance.now().toFixed(3):Date.now?Date.now()-this.ctx.initializedAt:(new Date).getTime()-this.ctx.initializedAt},c.messagesToLogLine=function(t,e,i){var r,s=[t,e];s=s.concat(i);try{(r=s.join(" ")||"").length>200&&(r=r.slice(0,200))}catch(t){r="could not serialize"}return r},c.persistLine=function(t){this.ctx.first1000LogLines.length<1e3?this.ctx.first1000LogLines.push(t):(this.ctx.last1000LogLines.length>=1e3&&this.ctx.last1000LogLines.shift(),this.ctx.last1000LogLines.push(t))},c.log=function(t,e){var i,s=t<=this.ctx.level,a=t<4,o=(s||a)&&this.matchedGrep(e);if(0===t&&(0,r.globalTrigger)("problem",{type:"error-logged",data:{messages:e}}),o&&(s||a)&&(i=this.now()),a&&o){var l=this.messagesToLogLine(t,i,e);this.persistLine(l)}if(s&&o){var u,c=this.logFunc(t);1===e.length&&(u=e[0])instanceof Error?(c(u.message),u.stack&&c(u.stack)):c.apply(void 0,n(e))}};var d=function(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];console.error.apply(console,e)},h=function(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];console.warn.apply(console,e)},f=function(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];console.info.apply(console,e)},g=function(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];console.debug.apply(console,e)},m=function(t){console.log.apply(console,t)};c.logFunc=function(t){return null==t&&(t=this.level),console?(0===t?e=d:1===t?e=h:3===t?e=f:4===t&&(e=g),e||(e=m),"function"!=typeof e&&(this.noConsoleLog=!0,e=l),e):l;var e},c.maybePrefix=function(t,e){if(t){if("function"==typeof t)try{t=t()}catch(e){t='prefix err "'.concat(e.message,'"')}return t instanceof Array?t.concat(e):[t].concat(e)}return e},c.getPrefixedFunctions=function(t){var e=this;return{log:function(){for(var i=arguments.length,r=new Array(i),s=0;s<i;s++)r[s]=arguments[s];return e.log(0,e.maybePrefix(t,r))},error:function(){for(var i=arguments.length,r=new Array(i),s=0;s<i;s++)r[s]=arguments[s];return e.log(0,e.maybePrefix(t,r))},warn:function(){for(var i=arguments.length,r=new Array(i),s=0;s<i;s++)r[s]=arguments[s];return e.log(1,e.maybePrefix(t,r))},notice:function(){for(var i=arguments.length,r=new Array(i),s=0;s<i;s++)r[s]=arguments[s];return e.log(1,e.maybePrefix(t,r))},info:function(){for(var i=arguments.length,r=new Array(i),s=0;s<i;s++)r[s]=arguments[s];return e.log(3,e.maybePrefix(t,r))},debug:function(){for(var i=arguments.length,r=new Array(i),s=0;s<i;s++)r[s]=arguments[s];return e.log(4,e.maybePrefix(t,r))}}},s.Wistia&&null==s.Wistia.wlogCtx&&(s.Wistia.wlogCtx={});var p=new u(s.Wistia.wlogCtx)},(t,e,i)=>{i.d(e,{globalTrigger:()=>n});var r=i(14),s=i(16);(0,r.makeWbindable)(s.Wistia);s.Wistia.bind.bind(s.Wistia),s.Wistia.on.bind(s.Wistia),s.Wistia.off.bind(s.Wistia),s.Wistia.rebind.bind(s.Wistia);var n=s.Wistia.trigger.bind(s.Wistia);s.Wistia.unbind.bind(s.Wistia)},(t,e,i)=>{i.d(e,{makeWbindable:()=>a});var r=i(15),s=i(16),n=i(19);s.Wistia.bindable||(s.Wistia.EventShepherdManager||(s.Wistia.EventShepherdManager={}),s.Wistia.bindable={bind:function(t,e){if("crosstime"===t&&this.crossTime)return this.crossTime.addBinding(arguments[1],arguments[2]),this;if("betweentimes"===t&&this.betweenTimes)return this.betweenTimes.addBinding(arguments[1],arguments[2],arguments[3]),this;var i=this.embedElement||this.container;if(Object.keys(n.convertedEventNames).includes(t)&&i){var a=o(i);return void 0===s.Wistia.EventShepherdManager[a]&&(s.Wistia.EventShepherdManager[a]=new n.EventShepherd),s.Wistia.EventShepherdManager[a].addListener(t,i,e),this}if(e)return r.bind.call(this,t,e),this;s.Wistia.warn&&s.Wistia.warn(this.constructor.name,"bind","falsey value passed in as callback:",e)},unbind:function(t,e){if("crosstime"===t&&this.crossTime)return e?this.crossTime.removeBinding(arguments[1],arguments[2]):this.crossTime.removeAllBindings(),this;if("betweentimes"===t&&this.betweenTimes)return e?this.betweenTimes.removeBinding(arguments[1],arguments[2],arguments[3]):this.betweenTimes.removeAllBindings(),this;var i=this.embedElement||this.container;if(Object.keys(n.convertedEventNames).includes(t)&&i){var a=o(i);return void 0===s.Wistia.EventShepherdManager[a]||s.Wistia.EventShepherdManager[a].removeListener(t,i,e),this}return e?r.unbind.call(this,t,e):this._bindings&&(this._bindings[t]=[]),this._bindings&&this._bindings[t]&&!this._bindings[t].length&&(this._bindings[t]=null,delete this._bindings[t]),this},on:function(t,e){var i=arguments,a=this;if("crosstime"===t&&this.crossTime)return this.crossTime.addBinding(arguments[1],arguments[2]),function(){a.crossTime.removeBinding(i[1],i[2])};if("betweentimes"===t&&this.betweenTimes)return this.betweenTimes.addBinding(arguments[1],arguments[2],arguments[3]),function(){a.betweenTimes.removeBinding(i[1],i[2],i[3])};var l=this.embedElement||this.container;if(Object.keys(n.convertedEventNames).includes(t)&&l){var u=o(l);return void 0===s.Wistia.EventShepherdManager[u]&&(s.Wistia.EventShepherdManager[u]=new n.EventShepherd(l)),s.Wistia.EventShepherdManager[u].addListener(t,l,e),function(){s.Wistia.EventShepherdManager[u].removeListener(t,l,e)}}return r.bind.call(this,t,e)},off:function(t,e){if("crosstime"===t&&this.crossTime)return this.crossTime.removeBinding(arguments[1],arguments[2]);if("betweentimes"===t&&this.betweenTimes)return this.betweenTimes.removeBinding(arguments[1],arguments[2],arguments[3]);var i=this.embedElement||this.container;if(Object.keys(n.convertedEventNames).includes(t)&&i){var a=o(i);return void 0===s.Wistia.EventShepherdManager[a]?function(){}:s.Wistia.EventShepherdManager[a].removeListener(t,i,e)}return r.unbind.call(this,t,e)},rebind:function(t,e){return this.unbind(t,e),this.bind(t,e),this},trigger:function(t){for(var e,i=arguments.length,s=new Array(i>1?i-1:0),n=1;n<i;n++)s[n-1]=arguments[n];return(e=r.trigger).call.apply(e,[this,t].concat(s)),this},bindNamed:function(){return r.bindNamed.apply(this,arguments)},unbindNamed:function(){return r.unbindNamed.apply(this,arguments)},unbindAllInNamespace:function(){return r.unbindAllInNamespace.apply(this,arguments)}});var a=function(t){for(var e in s.Wistia.bindable){var i=s.Wistia.bindable[e];t[e]||(t[e]=i)}},o=function(t){return null!=t&&t.mediaId?t.mediaId:null!=t&&t.id?t.id:void 0}},(t,e,i)=>{i.d(e,{bind:()=>l,bindNamed:()=>g,bindify:()=>y,trigger:()=>d,unbind:()=>u,unbindAllInNamespace:()=>p,unbindNamed:()=>m});var r=i(16),s=function(t,e){if(null==t)throw new TypeError("Cannot convert undefined or null to object");return Object.prototype.hasOwnProperty.call(Object(t),e)};function n(t){return function(t){if(Array.isArray(t))return a(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||function(t,e){if(t){if("string"==typeof t)return a(t,e);var i={}.toString.call(t).slice(8,-1);return"Object"===i&&t.constructor&&(i=t.constructor.name),"Map"===i||"Set"===i?Array.from(t):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?a(t,e):void 0}}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function a(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,r=Array(e);i<e;i++)r[i]=t[i];return r}var o=Array.prototype.slice,l=function(t,e){var i=this;return i._bindings||(i._bindings={}),i._bindings[t]||(i._bindings[t]=[]),i._bindings[t].push(e),function(){i.unbind(t,e)}},u=function(t,e){if(!this._bindings)return this;if(!this._bindings[t])return this;for(var i=[],r=0;r<this._bindings[t].length;r++){var s=this._bindings[t][r];s!==e&&i.push(s)}this._bindings[t]=i},c=function(t,e){return this.unbind(t,e),this.bind(t,e),{event:t,fn:e}},d=function(t){for(var e=arguments.length,i=new Array(e>1?e-1:0),r=1;r<e;r++)i[r-1]=arguments[r];return this._bindings&&null!=this._bindings.all&&h.apply(this,["all",t].concat(i)),h.apply(this,[t].concat(i))},h=function(t){if(!this._bindings)return this;if(!this._bindings[t])return this;for(var e,i=o.call(arguments,1),s=n(this._bindings[t]),a=0;a<s.length;a++){var l=s[a];try{l.apply(this,i)===this.unbind&&(null==e&&(e=[]),e.push({event:t,fn:l}))}catch(t){if(this._throwTriggerErrors)throw t;r.Wistia.error&&r.Wistia.error(t)}}if(e)for(var u=0;u<e.length;u++){var c=e[u];this.unbind(c.event,c.fn)}return this},f=function(t,e){null==t._namedBindings&&(t._namedBindings={}),null==t._namedBindings[e]&&(t._namedBindings[e]={})},g=function(t,e,i,r){return this.unbindNamed(t,e),function(t,e,i,r,s){f(t,e),t._namedBindings[e][i]={event:r,fn:s}}(this,t,e,i,r),this.bind(i,r),function(){this.unbindNamed(t,e)}},m=function(t,e){f(this,t);var i=function(t,e,i){return f(t,e),t._namedBindings[e][i]}(this,t,e);if(i){var r=i.event,s=i.fn;this.unbind(r,s)}var n=this._namedBindings;return delete n[t][e],v(n[t])&&delete n[t],this},p=function(t){var e=this._namedBindings&&this._namedBindings[t];if(null==e)return this;for(var i in e)s(e,i)&&this.unbindNamed(t,i)},v=function(t){for(var e in t)if(s(t,e))return!1;return!0},y=function(t){return t.bind=l,t.unbind=u,t.on=l,t.off=u,t.rebind=c,t.trigger=d,t.bindNamed=g,t.unbindNamed=m,t.unbindAllInNamespace=p,t};y(function(){}.prototype)},(t,e,i)=>{i.d(e,{Wistia:()=>Y});var r,s,n,a,o,l,u,c,d,h,f,g,m,p,v,y,E,T,b,S,A,L,k,R,I,_,w,P,D,C,O,x,M,F,N,B,U,$=i(2),G=i(17),H=i(18),V=i(10);function j(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),i.push.apply(i,r)}return i}function K(t){for(var e=1;e<arguments.length;e++){var i=null!=arguments[e]?arguments[e]:{};e%2?j(Object(i),!0).forEach((function(e){W(t,e,i[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):j(Object(i)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))}))}return t}function W(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var r=i.call(t,e||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}null!==(r=V.root.Wistia)&&void 0!==r||(V.root.Wistia={}),null!==(n=(s=V.root.Wistia).Preact)&&void 0!==n||(s.Preact=K(K({},$),{},{hooks:G,compat:H})),null!==(o=(a=V.root.Wistia)._destructors)&&void 0!==o||(a._destructors={}),null!==(u=(l=V.root.Wistia)._initializers)&&void 0!==u||(l._initializers={}),null!==(d=(c=V.root.Wistia)._remoteData)&&void 0!==d||(c._remoteData=new Map),null!==(f=(h=V.root.Wistia).api)&&void 0!==f||(h.api=function(){return console.error("Accessed Wistia.api() before it was initialized"),null}),null!==(m=(g=V.root.Wistia).defineControl)&&void 0!==m||(g.defineControl=function(){return console.error("Accessed Wistia.defineControl() before it was initialized"),null}),null!==(v=(p=V.root.Wistia).EventShepherdManager)&&void 0!==v||(p.EventShepherdManager={}),null!==(E=(y=V.root.Wistia).mixin)&&void 0!==E||(y.mixin=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};Object.keys(e).forEach((function(i){(function(t,e){if(null==t)throw new TypeError("Cannot convert undefined or null to object");return Object.prototype.hasOwnProperty.call(Object(t),e)})(e,i)&&(t[i]=e[i])}))}),null!==(b=(T=V.root.Wistia).playlistMethods)&&void 0!==b||(T.playlistMethods=new Map),null!==(A=(S=V.root.Wistia).PublicApi)&&void 0!==A||(S.PublicApi=null),null!==(k=(L=V.root.Wistia).uncacheMedia)&&void 0!==k||(L.uncacheMedia=function(){return console.error("Accessed Wistia.uncacheMedia() before it was initialized"),null}),null!==(I=(R=V.root.Wistia).VisitorKey)&&void 0!==I||(R.VisitorKey=null),null!==(w=(_=V.root.Wistia).visitorKey)&&void 0!==w||(_.visitorKey=null),null!==(D=(P=V.root.Wistia).wistia)&&void 0!==D||(P.wistia=void 0),null!==(O=(C=V.root.Wistia)._liveStreamEventDataPromises)&&void 0!==O||(C._liveStreamEventDataPromises={}),null!==(M=(x=V.root.Wistia)._mediaDataPromises)&&void 0!==M||(x._mediaDataPromises={}),null!==(N=(F=V.root.Wistia)._liveStreamPollingPromises)&&void 0!==N||(F._liveStreamPollingPromises={}),null!==(U=(B=V.root.Wistia).first)&&void 0!==U||(B.first=function(){var t;return null!==(t=V.root.Wistia.api())&&void 0!==t?t:document.querySelector("wistia-player")});var Y=V.root.Wistia},t=>{t.exports=window.Wistia.Preact.hooks},t=>{t.exports=window.Wistia.Preact.compat},(t,e,i)=>{function r(t,e){for(var i=0;i<e.length;i++){var r=e[i];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,s(r.key),r)}}function s(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var r=i.call(t,e||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}i.d(e,{EventShepherd:()=>o,convertedEventNames:()=>n});var n={mutechange:i(20).MUTE_CHANGE_EVENT},a={mutechange:function(t){return t.isMuted}},o=function(){return t=function t(){var e,i,r;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),e=this,r={},(i=s(i="convertedEventsMap"))in e?Object.defineProperty(e,i,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[i]=r},(e=[{key:"addListener",value:function(t,e,i){var r,s,o,l=null!==(r=n[t])&&void 0!==r?r:t;null!==(o=(s=this.convertedEventsMap)[l])&&void 0!==o||(s[l]=[]);var u=function(e){if(a[t]){var r=a[t](e.detail);i(r)}else i()};this.convertedEventsMap[l].push({givenCallback:i,eventListenerCallback:u}),e.addEventListener(l,u)}},{key:"removeAllListeners",value:function(t){var e=this;Object.keys(this.convertedEventsMap).forEach((function(i){var r;null===(r=e.convertedEventsMap[i])||void 0===r||r.forEach((function(e){t.removeEventListener(i,e.eventListenerCallback)})),e.convertedEventsMap[i]=[]}))}},{key:"removeListener",value:function(t,e,i){var r,s=this,a=null!==(r=n[t])&&void 0!==r?r:t,o=[];i?(e.removeEventListener(a,i),this.convertedEventsMap[a]&&(this.convertedEventsMap[a].forEach((function(t,r){t.givenCallback===i&&(o.push(r),e.removeEventListener(a,t.eventListenerCallback))})),o.forEach((function(t){s.convertedEventsMap[a]&&s.convertedEventsMap[a].splice(t,1)})))):this.convertedEventsMap[a]=[]}}])&&r(t.prototype,e),i&&r(t,i),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e,i}()},(t,e,i)=>{i.d(e,{MUTE_CHANGE_EVENT:()=>r});var r="mute-change"},(t,e,i)=>{var r;i.d(e,{elemOffset:()=>n});var s=function(){if(null!=r)return r;var t=document.createElement("div");return t.style.paddingLeft=t.style.width="1px",document.body.appendChild(t),r=2===t.offsetWidth,document.body.removeChild(t),r},n=function(t){var e,i,r=document.body,n=document.defaultView,o=document.documentElement,l=t.getBoundingClientRect(),u=o.clientTop||r.clientTop||0,c=o.clientLeft||r.clientLeft||0;e=n&&null!=n.pageYOffset?n.pageYOffset:s()&&o&&null!=o.scrollTop?o.scrollTop:r.scrollTop,i=n&&null!=n.pageXOffset?n.pageXOffset:s()&&o&&null!=o.scrollLeft?o.scrollLeft:r.scrollLeft;var d=a(t);return{height:l.height*d,top:l.top*d+e-u,left:l.left*d+i-c,width:l.width*d,zoom:d}},a=function(t){return t&&t!==document.documentElement?a(t.parentElement)*(getComputedStyle(t).zoom||1):1}},(__unused_webpack___webpack_module__,__webpack_exports__,__webpack_require__)=>{__webpack_require__.d(__webpack_exports__,{execScriptTags:()=>execScriptTags,getScriptTags:()=>getScriptTags,removeScriptTags:()=>removeScriptTags});var utilities_script_utils_js__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(23),getScriptTags=function(t){return t.match(/<script.*?src[^>]*>\s*<\/script>|<script.*?>[\s\S]+?<\/script>/gi)||[]},scriptTagsToRunScriptsInput=function scriptTagsToRunScriptsInput(scriptTags){if(!scriptTags)return[];scriptTags instanceof Array||(scriptTags=getScriptTags(scriptTags));for(var hashes=[],_loop=function _loop(){var scriptTag=scriptTags[i],hash={},matches=scriptTag.match(/<script.*?>/i);if(matches&&(matches=matches[0].match(/src="([^"]+)"/i),matches&&(hash.src=matches[1],hash.async=/async/i.test(scriptTag.replace(hash.src,"")))),!matches&&(matches=scriptTag.match(/<script>([\s\S]+?)<\/script>/i),matches)){var src=matches[1];hash.fn=function(){return eval(src)}}hashes.push(hash)},i=0;i<scriptTags.length;i++)_loop();return hashes},execScriptTags=function(t,e){if(!t)return null;var i=scriptTagsToRunScriptsInput(t);return(0,utilities_script_utils_js__WEBPACK_IMPORTED_MODULE_0__.runScripts)(i).then(e)},removeScriptTags=function(t){return t.replace(/<script.*?src[^>]*>\s*<\/script>|<script>[\s\S]+?<\/script>/g,"")}},(t,e,i)=>{i.d(e,{runScripts:()=>c});var r=i(12),s=i(4),n=i(24);function a(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),i.push.apply(i,r)}return i}function o(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var r=i.call(t,e||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}var l=function(t){for(var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=document.getElementsByTagName("script"),r=0;r<i.length;r++){var s=i[r],n=s.getAttribute("src")||"";if(e.ignoreQueryParams){var a=n.split("?");n=a[0]}if(!e.scriptRegex&&e.ignoreProtocol&&(n=n.replace(/^https?:/,""),t=t.replace(/^https?:/,"")),e.scriptRegex&&e.scriptRegex.test(n))return s;if(e.testStartsWith&&0===n.indexOf(t))return s;if(n===t)return s}return null},u=function(t){var e,i,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:8e3,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return null==r&&(r=8e3),null==s&&(s={}),new Promise((function(a){!0===s.once&&(e=l(t))&&(i=!0),s.once&&i?e.readyState&&!/loaded|complete/.test(e.readyState)||setTimeout((function(){a()}),1):(0,n.runScript)(t,r).then(a).catch((function(t){a(t),setTimeout((function(){console.error(t)}),1)}))}))},c=function(){for(var t,e=arguments.length,i=new Array(e),s=0;s<e;s++)i[s]=arguments[s];t=i[0]instanceof Array?i[0]:i,t=d(t);var n=[],l=[],c=[];return t.forEach((function(t){var e=function(t){for(var e=1;e<arguments.length;e++){var i=null!=arguments[e]?arguments[e]:{};e%2?a(Object(i),!0).forEach((function(e){o(t,e,i[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):a(Object(i)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))}))}return t}({},t),i=new Promise((function(t){e.resolve=t}));e.promise=i,c.push(e.promise),t.async?n.push(e):l.push(e)})),l.reduce((function(t,e){if(e.fn)try{e.fn()}catch(t){r.wlog.error(t)}finally{e.resolve()}else e.src&&u(e.src,null,e).then(e.resolve);return t.then(e.promise)}),Promise.resolve()),setTimeout((function(){n.forEach((function(t){if(t.fn)try{t.fn()}catch(t){r.wlog.error(t)}finally{t.resolve()}else t.src&&u(t.src,null,t).then(t.resolve)}))}),1),Promise.all(c)},d=function(t){for(var e=[],i=0;i<t.length;i++){var r=t[i];"string"==typeof r?e.push({src:r,async:!1}):(0,s.isObject)(r)?e.push(r):e.push({fn:r,async:!1})}return e}},(t,e,i)=>{i.d(e,{runScript:()=>s});var r=i(25),s=function(t,e){var i=r.TAGGED_VERSION;return new Promise((function(r,s){var n;null==e&&(e=8e3),(n=document.createElement("script")).src=t,n.async=!0,n.type="text/javascript",/https?:\/\/fast\.wistia\./.test(n.src)&&""!==i&&i.length>0&&(n.src="".concat(n.src,"@").concat(i));var a=null,o=!1,l=function(){n.onerror=n.onreadystatechange=n.onload=null,clearTimeout(a),clearTimeout(c),a=setTimeout((function(){n&&n.parentNode&&n.parentNode.removeChild(n)}),500)},u=function(){var t=n.readyState;o||t&&!/loaded|complete/.test(t)||(o=!0,setTimeout((function(){r(),l()}),1))},c=setTimeout((function(){o=!0,l(),s(new Error("timeout"))}),e);n.onerror=function(t){o=!0,l(),s(t)},n.onreadystatechange=u,n.onload=u,(document.body||document.head).appendChild(n)}))}},(t,e,i)=>{i.d(e,{EMBED_HOST:()=>l,PROD_EMBED_HOST:()=>d,PROD_FASTLY_SSL_HOST:()=>f,PROD_FAST_HOSTNAME_COM:()=>c,PROD_FAST_HOSTNAME_NET:()=>u,PROD_SSL_EMBED_HOST:()=>h,SSL_EMBED_HOST:()=>g,TAGGED_VERSION:()=>m,cdnFastProtectedWistiaComHost:()=>T,cdnFastWistiaComHost:()=>E,deliveryHost:()=>v,eV1HostWithPort:()=>L,eV1Protocol:()=>k,mediaDataHost:()=>R,metricsHost:()=>I});var r=i(10),s=i(26),n=i(27),a=((0,n.appHostname)("app"),(0,n.appHostname)("fast-protected")),o=(0,n.appHostname)("fast"),l="embed.wistia.com",u="fast.wistia.net",c="fast.wistia.com",d="embed.wistia.com",h="embed-ssl.wistia.com",f="embed-fastly.wistia.com",g="embed-ssl.wistia.com",m="",p="undefined"!=typeof window&&r.root===window&&r.root.location?r.root.location.protocol:"https:",v=function(){return function(t,e,i){return"https:"===t?e:i}(arguments.length>0&&void 0!==arguments[0]?arguments[0]:p,g,l)},y=function(){var t=(0,n.getSubdomainSuffixHostname)("fast");return t||null},E=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:void 0;if(t)return t;var e=y();return e||o},T=function(t){return t||a},b=function(){var t=y();if(t)return t;return"fast.".concat("wistia.net")},S=function(){for(var t=document.getElementsByTagName("script"),e=0;e<t.length;e++){var i=t[e];if(i.src){var r=new s.Url(i.src),n=/\/assets\/external\/E-v1?\.js$/.test(r.rawPath),a=r.host===E()||r.host===b()||"fast-canary.wistia.net"===r.host,o="https:"===location.protocol&&"https:"===r.protocol,l=""===r.protocol||null==r.protocol,u=o||l||"http:"===location.protocol,c=!i.readyState||/loaded|complete/.test(i.readyState);if(n&&a&&u&&c)return r}}return new s.Url("".concat((0,s.proto)(),"//").concat(b(),"/E-v1.js"))}(),A=function(){return S.host},L=function(){return S.port?"".concat(A(),":").concat(S.port):A()},k=function(){return S.protocol},R=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t.embedHost?P(t.embedHost):L()},I=function(){return"pipedream.".concat("wistia.com")},_=[].concat(["wistia.net","wistia.com"],["wistia.mx","wistia.dev","wistia.tech","wistia.am","wistia.se","wistia.io","wistia.st"]),w=new RegExp("(".concat(_.map((function(t){return"\\.".concat(t.replace(".","\\."))})).join("|"),")$")),P=function(t){return t&&w.test(t)?t:L()}},(t,e,i)=>{i.d(e,{Url:()=>c,proto:()=>n});var r=i(4),s=i(12),n=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:location.href;return/^http:\/\//.test(t)?"http:":"https:"},a=function(t){if(null==t)return t;var e;try{e=decodeURIComponent(t)}catch(i){setTimeout((function(){s.wlog.notice(i)}),50),e=t}return e},o=function(t){for(var e=t[0],i=1;i<t.length;i++)e+="[".concat(t[i],"]");return e},l=function(t){return t.match(/([\w\-_]+)/g)},u=["protocol","host","port","params","path"],c=function(t){var e=this;e.params={},e.path=[],e.host="",e.rawPath="","object"==typeof t?e.fromOptions(t):t&&e.fromRaw(t)},d=c.prototype;d.fromOptions=function(t){for(var e=0;e<u.length;e++){var i=u[e];null!=t[i]&&(this[i]=t[i])}return this},d.fromRaw=function(t){var e;return this.rawUrl=t,(e=t.match(/^((?:https?:)|(?:file:)|(?:ftp:))?\/\//))&&(this.protocol=e[1]||void 0),(e=t.match(/\/\/([^:?#/]*)/))&&(this.host=e[1]||void 0),(e=t.match(/\/\/.*?(\/[^?#$]+)/)||t.match(/(^\/[^/][^?#$]+)/))&&this.setPath(e[1]),(e=t.match(/:(\d+)/))&&(this.port=parseInt(e[1],10)),(e=t.match(/\?([^#]+)/))&&(this.rawParams=e[1],this.params=function(t){var e={};if(!t)return e;for(var i=t.split("&"),n=function(){var t=i[o].split("="),n=t[0],u=t[1];try{n=l(decodeURIComponent(n))||""}catch(t){setTimeout((function(){s.wlog.notice(t)}),50),n=""}(0,r.cast)(n);var c=(0,r.getDeep)(e,n);if(null!=c)if((0,r.isArray)(c))c.push(a(u));else{var d=[c];d.push(a(u)),(0,r.setAndPreserveUndefined)(e,n,d)}else(0,r.setAndPreserveUndefined)(e,n,a(u))},o=0;o<i.length;o++)n();return e}(this.rawParams)),(e=t.match(/#(.*)$/))&&(this.anchor=e[1]),this},d.clone=function(){return new c({protocol:this.protocol,host:this.host,port:this.port,path:(0,r.clone)(this.path),params:(0,r.clone)(this.params),anchor:this.anchor})},d.ext=function(t){if(null!=t){var e=this.ext(),i=this.path.length-1,r=new RegExp("\\.".concat(e),"g");return e&&(this.path[i]="".concat(this.path[i].replace(r,""))),this.path[i]="".concat(this.path[i],".").concat(t)}var s=this.path[this.path.length-1].match(/\.(.*)$/);return null!=s&&s[1]||null},d.isRelative=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:window.location,e=this.protocol,i=this.host;return!(null!=e&&""!==e&&e!==t.protocol||i&&i!==t.hostname)},d.toString=function(){return this.isRelative()?this.relative():this.absolute()},d.absolute=function(){var t="";null!=this.protocol&&(t=this.protocol);var e="";return null!=this.port&&(e=":".concat(this.port)),"".concat(t,"//").concat(this.host||location.host).concat(e).concat(this.relative())},d.relative=function(){var t,e="";this.path.length>0&&("string"==typeof(t=this.path)&&(t=t.split("/")),e=null==t?"":"/".concat(t.join("/")),this._hasTrailingSlash&&(e+="/"));var i,s,n="?".concat((i=this.params,s=[],(0,r.eachLeaf)(i,(function(t,e){null!=t?s.push("".concat(encodeURIComponent(o(e)),"=").concat(encodeURIComponent(t))):s.push(encodeURIComponent(o(e)))})),s.join("&")));return 1===n.length&&(n=""),"".concat(e).concat(n).concat(this.relativeAnchor())},d.authority=function(){var t=null!=this.port?":".concat(this.port):"";return"".concat(this.host).concat(t)},d.relativeProtocol=function(){var t="";return null!=this.port&&(t=":".concat(this.port)),"//".concat(this.host).concat(t).concat(this.relative())},d.relativeAnchor=function(){var t="";return null!=this.anchor&&(t="#".concat(this.anchor)),"".concat(t)},d.setPath=function(t){this.rawPath=t,this._hasTrailingSlash=/\/$/.test(this.rawPath),this.path=function(t){var e=[];if(null==t)return e;for(var i=t.split(/\/+/),r=0;r<i.length;r++){var s=i[r];null!=s&&""!==s&&e.push(s)}return e}(this.rawPath)},c.create=function(t){return new c(t)};c.create;c.parse=function(t){return new c(t)};c.parse},(t,e,i)=>{i.d(e,{appHostname:()=>a,getSubdomainSuffixHostname:()=>o});var r=/([a-z0-9-]+)-cde-([a-z0-9-]+)\.([a-z0-9-]+)\.wistia\.io/i,s=/([a-z0-9-]+)-cde-([a-z0-9-]+)\.([a-z0-9-]+)\.claw\.wistia\.io/i,n=/([a-z0-9-]+)-txl-([a-z0-9-]+)\.([a-z0-9-]+)\.mtl\.wistia\.io/i,a=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"app",e=o(t);return e||"".concat(t,".").concat("wistia.com")},o=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"app";if("undefined"!=typeof window&&window.location){var e=window.location.hostname,i=r.exec(e);if(i)return"".concat(t,"-cde-").concat(i[2],".").concat(i[3],".wistia.io");var a=s.exec(e);if(a)return"".concat(t,"-cde-").concat(a[2],".").concat(a[3],".claw.wistia.io");var o=n.exec(e);if(o)return"".concat(t,"-txl-").concat(o[2],".").concat(o[3],".mtl.wistia.io")}return null}},(t,e,i)=>{i.d(e,{seqId:()=>s});var r=i(16),s=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"wistia_",e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",i=r.Wistia._sequenceVal||1,s="".concat(t).concat(i).concat(e);return r.Wistia._sequenceVal=i+1,s}},,,,,,,,,(t,e,i)=>{i.d(e,{isNil:()=>n,isNotNil:()=>a});Number.NaN;var r=t=>null===t,s=t=>void 0===t,n=t=>r(t)||s(t),a=t=>!n(t)},,,(t,e,i)=>{i.d(e,{isVisitorTrackingEnabled:()=>d});var r=i(13),s=i(41),n=i(43),a=i(16);function o(t){return function(t){if(Array.isArray(t))return l(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||function(t,e){if(t){if("string"==typeof t)return l(t,e);var i={}.toString.call(t).slice(8,-1);return"Object"===i&&t.constructor&&(i=t.constructor.name),"Map"===i||"Set"===i?Array.from(t):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?l(t,e):void 0}}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function l(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,r=Array(e);i<e;i++)r[i]=t[i];return r}var u;a.Wistia._visitorTrackingDomain||(a.Wistia._visitorTrackingDomain=location.hostname||""),a.Wistia._visitorTracking||(null!=(u=(0,s.getWistiaLocalStorage)().visitorTrackingEnabled)&&((0,s.updateWistiaLocalStorage)((function(t){return delete t.visitorTrackingEnabled})),a.Wistia._visitorTracking={},a.Wistia._visitorTracking[a.Wistia._visitorTrackingDomain]={isEnabled:u,updatedAt:Date.now()},(0,s.updateWistiaLocalStorage)((function(t){return t.visitorTracking=a.Wistia._visitorTracking}))),a.Wistia._visitorTracking=(0,s.getWistiaLocalStorage)().visitorTracking||{});a.Wistia.consent=function(t){return null==t?d():c(t)};var c=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:a.Wistia._visitorTrackingDomain;"default"===t?delete a.Wistia._visitorTracking[e]:a.Wistia._visitorTracking[e]={isEnabled:"true"==="".concat(t),updatedAt:Date.now()},(0,s.updateWistiaLocalStorage)((function(t){return t.visitorTracking=a.Wistia._visitorTracking})),(0,r.globalTrigger)("visitortrackingchange",t),o(document.getElementsByTagName("wistia-player")).forEach((function(e){e.dispatchEvent(new CustomEvent("visitor-tracking-change",{detail:{isTrackingEnabled:t}}))}))},d=function(){if("boolean"==typeof a.Wistia._visitorTracking)return a.Wistia._visitorTracking;if(a.Wistia._visitorTracking){var t=function(){if(a.Wistia._visitorTrackingDomain)for(var t=a.Wistia._visitorTrackingDomain.split(".");t.length>0;){var e=a.Wistia._visitorTracking[t.join(".")],i=e&&e.isEnabled;if(null!=i)return i;t.shift()}}();if(null!=t)return Boolean(t)}var e=(0,n.getAllApiHandles)();if(a.Wistia.channel&&a.Wistia.channel.all)try{e.push.apply(e,o(a.Wistia.channel.all()))}catch(t){}return!e.some((function(t){return!0===(t._mediaData||t._galleryData||{}).privacyMode}))}},(t,e,i)=>{i.d(e,{getWistiaLocalStorage:()=>a,removeWistiaLocalStorage:()=>o,updateWistiaLocalStorage:()=>l});var r=i(42),s=i(16),n="wistia",a=function(){return(0,r.getLocalStorage)(n)},o=function(){return s.Wistia._localStorage=(0,r.removeLocalStorage)(n),s.Wistia._localStorage},l=function(t){return s.Wistia._localStorage=(0,r.updateLocalStorage)(n,t),s.Wistia._localStorage}},(t,e,i)=>{i.d(e,{getLocalStorage:()=>l,removeLocalStorage:()=>u,setLocalStorage:()=>c,updateLocalStorage:()=>d});var r=i(16),s=function(t){setTimeout((function(){throw t}),0)},n="_namespacedLocalStorage",a=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"wistia-test-localstorage";if(null!=r.Wistia._localStorageWorks)return r.Wistia._localStorageWorks;try{var e=localStorage.getItem(t);localStorage.removeItem(t),localStorage.setItem(t,e),localStorage.removeItem(t),r.Wistia._localStorageWorks=!0}catch(t){r.Wistia._localStorageWorks=!1}return r.Wistia._localStorageWorks},o=function(){return null==r.Wistia[n]&&(r.Wistia[n]={}),r.Wistia[n]},l=function(t){if(!a())return o()[t]||{};if(localStorage[t])try{return"null"===localStorage[t]?{}:JSON.parse(localStorage[t])}catch(t){s(t)}return{}},u=function(t){if(a())try{localStorage.removeItem(t)}catch(t){s(t)}else o()[t]={}},c=function(t,e){if(!a())return null!=e&&"object"==typeof e&&(o()[t]=e),e;try{o()[t]=e,localStorage[t]=JSON.stringify(e)}catch(t){s(t)}return e},d=function(t,e){var i=l(t);try{e(i)}catch(t){s(t)}return c(t,i)}},(t,e,i)=>{i.d(e,{getAllApiHandles:()=>s});i(44),i(12);var r=i(45);i(46);var s=function(){return(void 0===(0,r.wData)("video")?[]:Object.values((0,r.wData)("video"))).concat(void 0===(0,r.wData)("iframe_api")?[]:Object.values((0,r.wData)("iframe_api")))}},(t,e,i)=>{i.d(e,{getAllApiEmbedElements:()=>r});var r=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"wistia_embed",e=document.querySelectorAll("div.".concat(t,",span.").concat(t,",iframe.").concat(t));return Array.from(e).map((function(t){var e;return"WISTIA-PLAYER"===(null===(e=t.lastChild)||void 0===e?void 0:e.nodeName)?t.lastChild:t}))}},(t,e,i)=>{i.d(e,{wData:()=>n});var r=i(4),s=i(16),n=function(t,e){return(0,r.isArray)(t)||(t=t.split(".")),null!=e&&(0,r.setDeep)(s.Wistia,["_data"].concat(t),e),(0,r.getDeep)(s.Wistia,["_data"].concat(t))}},(t,e,i)=>{i.d(e,{ensureString:()=>r});var r=function(t){return null==t?"":t.toString()}},,,,,,,,,,(t,e,i)=>{i.d(e,{cacheMediaData:()=>l,getMediaDataFromCache:()=>o});var r=i(37),s=i(16),n=i(12),a=function(t,e){if(null==t)throw new TypeError("Cannot convert undefined or null to object");return Object.prototype.hasOwnProperty.call(Object(t),e)},o=function(t){var e=s.Wistia._remoteData.get("media_".concat(t));return(0,r.isNil)(e)?null:(a(e,"error")&&n.wlog.error("Received cached error response instead of MediaData when retrieving cached mediaData for ".concat(t)),e)},l=function(t,e){s.Wistia._remoteData.set("media_".concat(t),e)}},,,,(t,e,i)=>{i.d(e,{mediaDataTransforms:()=>g});var r=i(4),s=i(26),n=i(9),a=i(37),o=i(61);function l(t){return function(t){if(Array.isArray(t))return c(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||u(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function u(t,e){if(t){if("string"==typeof t)return c(t,e);var i={}.toString.call(t).slice(8,-1);return"Object"===i&&t.constructor&&(i=t.constructor.name),"Map"===i||"Set"===i?Array.from(t):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?c(t,e):void 0}}function c(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,r=Array(e);i<e;i++)r[i]=t[i];return r}var d=(0,n.cachedDetect)(),h=function(t,e){if(t&&e){e.plugin||(e.plugin={}),e.plugin.form||(e.plugin.form={});var i=e.plugin.form;t.form_button_text&&(i.formButtonText=t.form_button_text),t.form_lower_text&&(i.formLowerText=t.form_lower_text),t.title&&(i.title=t.title)}},f=function(t){if(h(t.formCustomizations,t.embedOptions),Array.isArray(t.translatedMediaData)){var e,i=function(t,e){var i="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!i){if(Array.isArray(t)||(i=u(t))||e&&t&&"number"==typeof t.length){i&&(t=i);var r=0,s=function(){};return{s,n:function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:s}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var n,a=!0,o=!1;return{s:function(){i=i.call(t)},n:function(){var t=i.next();return a=t.done,t},e:function(t){o=!0,n=t},f:function(){try{a||null==i.return||i.return()}finally{if(o)throw n}}}}(t.translatedMediaData);try{for(i.s();!(e=i.n()).done;){var r=e.value;h(r.formCustomizations,r.embedOptions)}}catch(t){i.e(t)}finally{i.f()}}},g=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function(t){if(!0===(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).allowOriginalAsMp4){var e=t.assets.filter((function(t){return"original"===t.type}))[0];(0,o.readyPublicOver400)(t.assets).length>0||(t.assets=[].concat(l(t.assets),[(0,r.assign)({},e,{display_name:"".concat(e.display_name," copy"),container:"mp4",codec:"h264",type:"mp4_video"})]))}}(t,e),function(t){t.assets&&d.webp&&(t.assets=t.assets.map((function(t){if("still_image"===t.type&&Object(t).url){var e=new s.Url(t.url);e.ext("webp"),t.url=e.absolute()}return t})))}(t),function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};(0,a.isNotNil)(e.channelId)&&t.embedOptions&&(t.embedOptions.channelId=e.channelId)}(t,e),function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};(0,a.isNotNil)(e.channelPassword)&&t.embedOptions&&(t.embedOptions.channelPassword=e.channelPassword)}(t,e),f(t),t}},(t,e,i)=>{i.d(e,{READY:()=>d,filter:()=>f,findClosestAssetByQuality:()=>E,isBakeryUrl:()=>b,nearestOutsideRange:()=>_,numericSizeSnapped:()=>y,originalAspect:()=>I,readyPublicOver400:()=>p,videoAspect:()=>R,withinQualityRange:()=>v});var r=i(4),s=i(26),n=(i(9),i(25)),a=i(12),o=i(27);function l(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var i=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=i){var r,s,n,a,o=[],l=!0,u=!1;try{if(n=(i=i.call(t)).next,0===e){if(Object(i)!==i)return;l=!1}else for(;!(l=(r=n.call(i)).done)&&(o.push(r.value),o.length!==e);l=!0);}catch(t){u=!0,s=t}finally{try{if(!l&&null!=i.return&&(a=i.return(),Object(a)!==a))return}finally{if(u)throw s}}return o}}(t,e)||function(t,e){if(t){if("string"==typeof t)return u(t,e);var i={}.toString.call(t).slice(8,-1);return"Object"===i&&t.constructor&&(i=t.constructor.name),"Map"===i||"Set"===i?Array.from(t):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?u(t,e):void 0}}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function u(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,r=Array(e);i<e;i++)r[i]=t[i];return r}var c=Array.prototype.slice,d=2,h=["select","sortFn","sortBy","unique"],f=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!t)return[];t.assets&&(t=t.assets),null==e.qualityMin&&null==e.qualityMax||(t=v(t,e.qualityMin,e.qualityMax),e=(0,r.except)(e,["qualityMin","qualityMax"]));var i=(0,r.only)(e,h),s=i.select||(0,r.except)(e,h);s&&(i.select=s);var n=i.select?(0,r.select)(t,i.select):(0,r.clone)(t);if((i.sortFn||i.sortBy)&&(n=(0,r.sort)(n,i.sortFn||i.sortBy)),i.unique){for(var a={},o=0;o<n.length;o++){var l=n[o],u=l["".concat(i.unique)]||"__undefined__";a[u]||(a[u]=l)}for(var c in n=[],a)n.push(a[c])}return n},g=function(t,e){return f(t,e)[0]||null},m=function(t){for(var e=[],i=0;i<t.length;i++){var r=t[i],s=null!=r.opt_vbitrate&&r.opt_vbitrate>=500&&r.opt_vbitrate<=1e5,n=null!=r.width&&r.width>400;(s||n)&&e.push(r)}return e},p=function(t){return m(f(t,{container:/mp4/,public:!0,status:d}))},v=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:100,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1e4;return f(t,{select:function(t){var r=y(t.width,t.height);return e<=r&&r<=i}})},y=function(t,e){if(e>t){var i=t;t=e,e=i}return t/e<1.05&&(t=e*(16/9)),t>=3740?2160:t>=3100?1800:t>=2460?1440:t>=1820?1080:t>=1180?720:t>=860?540:t>=540?360:e},E=function(t,e){var i;i="4k"===e?2160:parseInt(e,10);var r=v(t,i,i)[0];if(r)return r;var s=_(t,i,i);if(1===s.length)return s[0];var n=R(t),a=Math.round(n*i),o=l(s,2),u=o[0],c=o[1];return Math.abs(u.width-a)<Math.abs(c.width-a)?u:c},T=((0,o.appHostname)("fast"),[n.EMBED_HOST,n.SSL_EMBED_HOST,(0,o.appHostname)("embed"),(0,o.appHostname)("prime"),(0,o.appHostname)("mixergy-cdn"),(0,o.appHostname)("embed-fastly"),n.PROD_EMBED_HOST,n.PROD_SSL_EMBED_HOST,n.PROD_FASTLY_SSL_HOST]),b=function(t){if(null==t)return!1;var e=new s.Url(t);return!!e.host&&T.join(",").indexOf(e.host)>=0},S=function(t,e,i){return i=(0,r.merge)({container:e,public:!0,status:d},i),g(t,i)},A=function(t,e){return S(t,"mp4",e)},L=function(t,e){return S(t,"webm",e)},k=function(t){return g(t,{type:"original"})},R=function(t){var e=A(t)||function(t,e){return S(t,"m3u8",e)}(t)||L(t)||k(t);return e&&e.height?e.width/e.height:640/360},I=function(t){var e=R(t),i=k(t);if(i&&i.width&&i.height){var r=i.width/i.height;return r>1&&e<1||r<1&&e>1?1/r:r}return e},_=function(t,e,i){if(0===t.length)return[];for(var r,s,n=c.call(t).sort((function(t,e){return y(t.width,t.height)-y(e.width,e.height)})),o=0;o<n.length;o++){var l=n[o],u=y(l.width,l.height);if(u<e&&(r=l),u>=i){s=l;break}}var d=[];return r&&d.push(r),s&&d.push(s),0===d.length&&(a.wlog.error("nearestOutsideRange: no nearby assets found, using first in list",n[0]),d.push(n[0])),d}},,(t,e,i)=>{i.d(e,{globalEventLoop:()=>l});var r=i(12),s=i(16),n=r.wlog.getPrefixedFunctions("event_loop"),a=function(){var t=this,e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this._timeoutId=null,this._latency=null!=e.latency?e.latency:100,this._blurLatency=null!=e.blurLatency?e.blurLatency:2e3,this._functions={},this._paused={},window.addEventListener("blur",(function(){return t.blur()}),!1),window.addEventListener("focus",(function(){return t.focus()}),!1),this.start()},o=a.prototype;o.start=function(){var t=this;clearTimeout(this._timeoutId),this._loopFn=this._loopFn||function(){t.runFunctions(),t._timeoutId=setTimeout(t._loopFn,t._latency)},this._loopFn()},o.resync=function(){this.start()},o.resyncNextTick=function(){var t=this;setTimeout((function(){t.resync()}),0)},o.stop=function(){clearTimeout(this._timeoutId)},o.clear=function(){this._functions={}},o.runFunctions=function(){this._pausedDirty&&this.updatePaused();var t=[];for(var e in this._functions){var i=this._functions[e],r=(new Date).getTime(),s=r-i.lastRanAt;if(!i.paused&&s>=i.interval){i.lastRanAt=r;try{i.fn()===this.remove&&t.push(e)}catch(t){n.error(t)}}}for(var a=0;a<t.length;a++)this.remove(t[a])},o.add=function(t,e,i){var r=(new Date).getTime();this._functions[t]={addedAt:r,lastRanAt:-1,interval:e,fn:i};var s=i();this._functions[t]&&(this._functions[t].lastRanAt=(new Date).getTime()),this._functions[t]&&s===this.remove?delete this._functions[t]:this._pausedDirty=!0},o.remove=function(t){var e=this;this.forEachMatchingKey(t,(function(t){delete e._functions[t]}))},o.forEachMatchingKey=function(t,e){for(var i in this._functions){var r=this._functions[i];this.key1IncludesKey2(t,i)&&e(i,r)}},o.latency=function(t){if(null==t)return this._latency;this._latency=t},o.interval=function(t,e){if(null==e)return this._functions[t].interval;null==this._functions[t]?n.notice("setting interval of ",t,"to",e,"failed because",t,"is not defined"):this._functions[t].interval=e},o.pause=function(t){this._paused[t]=!0,this._pausedDirty=!0},o.unpause=function(t){this._paused[t]=!1,this._pausedDirty=!0},o.isPaused=function(t){for(var e in this.paused){if(this._paused[e]&&this.key1IncludesKey2(e,t))return!0}return!1},o.updatePaused=function(){for(var t in this._functions){this._functions[t].paused=this.isPaused(t)}this._pausedDirty=!1},o.key1IncludesKey2=function(t,e){return"function"==typeof e.indexOf&&0===e.indexOf(t)&&(e.length===t.length||"."===e.charAt(t.length))},o.blur=function(){this._blurred||(this._blurred=!0,this._savedLatency=this._latency,this._latency=this._blurLatency)},o.focus=function(){this._blurred&&(this._blurred=!1,this._latency=this._savedLatency,this.resync())},null==s.Wistia.eventLoop&&(s.Wistia.eventLoop=new a({latency:100,blurLatency:100}));var l=s.Wistia.eventLoop},,,,,,,,,,,,(t,e,i)=>{i.d(e,{clearTimeouts:()=>a,doTimeout:()=>n});var r=i(4),s=i(16);s.Wistia;null==s.Wistia._timeouts&&(s.Wistia._timeouts={});var n=function(t,e){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;(0,r.isArray)(t)&&(t=t.join("."));var n=l(t);if(a(t,n),e){var o=s.Wistia._timeouts[n];null==o&&(o=s.Wistia._timeouts[n]={});var u=setTimeout((function(){delete o[t],e()}),i);return o[t]=u,u}return s.Wistia._timeouts[n][t]},a=function(t){var e,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;if((0,r.isArray)(t)&&(t=t.join(".")),"__global__"===(i=i||l(t))&&(e=s.Wistia._timeouts[t]))for(var n in e){var a=e[n];clearTimeout(a),delete e[n]}if(e=s.Wistia._timeouts[i])for(var u in e){var c=e[u];!u.indexOf||0!==u.indexOf(t)||u.length!==t.length&&"."!==u.charAt(t.length)||(clearTimeout(c),delete e[u])}s.Wistia.blockSweepTimeouts||(s.Wistia.blockSweepTimeouts=!0,setTimeout(o,0),setTimeout((function(){s.Wistia.blockSweepTimeouts=!1}),5e3))},o=function(){for(var t in s.Wistia._timeouts){var e=s.Wistia._timeouts[t];(0,r.isEmpty)(e)&&delete s.Wistia._timeouts[t]}},l=function(t){var e=t.indexOf(".");return e>0?t.substring(0,e):"__global__"}},,,,,,,,,,,,,,,,,,,,(t,e,i)=>{i.d(e,{fetchMediaData:()=>b});var r=i(37),s=i(16),n=i(25),a=i(60),o=i(56),l=i(96),u=i(97),c=i(98);function d(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),i.push.apply(i,r)}return i}function h(t){for(var e=1;e<arguments.length;e++){var i=null!=arguments[e]?arguments[e]:{};e%2?d(Object(i),!0).forEach((function(e){f(t,e,i[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):d(Object(i)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))}))}return t}function f(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var r=i.call(t,e||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function g(t){return function(t){if(Array.isArray(t))return m(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||function(t,e){if(t){if("string"==typeof t)return m(t,e);var i={}.toString.call(t).slice(8,-1);return"Object"===i&&t.constructor&&(i=t.constructor.name),"Map"===i||"Set"===i?Array.from(t):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?m(t,e):void 0}}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function m(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,r=Array(e);i<e;i++)r[i]=t[i];return r}function p(){var t,e,i="function"==typeof Symbol?Symbol:{},r=i.iterator||"@@iterator",s=i.toStringTag||"@@toStringTag";function n(i,r,s,n){var l=r&&r.prototype instanceof o?r:o,u=Object.create(l.prototype);return v(u,"_invoke",function(i,r,s){var n,o,l,u=0,c=s||[],d=!1,h={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,i){return n=e,o=0,l=t,h.n=i,a}};function f(i,r){for(o=i,l=r,e=0;!d&&u&&!s&&e<c.length;e++){var s,n=c[e],f=h.p,g=n[2];i>3?(s=g===r)&&(l=n[(o=n[4])?5:(o=3,3)],n[4]=n[5]=t):n[0]<=f&&((s=i<2&&f<n[1])?(o=0,h.v=r,h.n=n[1]):f<g&&(s=i<3||n[0]>r||r>g)&&(n[4]=i,n[5]=r,h.n=g,o=0))}if(s||i>1)return a;throw d=!0,r}return function(s,c,g){if(u>1)throw TypeError("Generator is already running");for(d&&1===c&&f(c,g),o=c,l=g;(e=o<2?t:l)||!d;){n||(o?o<3?(o>1&&(h.n=-1),f(o,l)):h.n=l:h.v=l);try{if(u=2,n){if(o||(s="next"),e=n[s]){if(!(e=e.call(n,l)))throw TypeError("iterator result is not an object");if(!e.done)return e;l=e.value,o<2&&(o=0)}else 1===o&&(e=n.return)&&e.call(n),o<2&&(l=TypeError("The iterator does not provide a '"+s+"' method"),o=1);n=t}else if((e=(d=h.n<0)?l:i.call(r,h))!==a)break}catch(e){n=t,o=1,l=e}finally{u=1}}return{value:e,done:d}}}(i,s,n),!0),u}var a={};function o(){}function l(){}function u(){}e=Object.getPrototypeOf;var c=[][r]?e(e([][r]())):(v(e={},r,(function(){return this})),e),d=u.prototype=o.prototype=Object.create(c);function h(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,u):(t.__proto__=u,v(t,s,"GeneratorFunction")),t.prototype=Object.create(d),t}return l.prototype=u,v(d,"constructor",u),v(u,"constructor",l),l.displayName="GeneratorFunction",v(u,s,"GeneratorFunction"),v(d),v(d,s,"Generator"),v(d,r,(function(){return this})),v(d,"toString",(function(){return"[object Generator]"})),(p=function(){return{w:n,m:h}})()}function v(t,e,i,r){var s=Object.defineProperty;try{s({},"",{})}catch(t){s=0}v=function(t,e,i,r){function n(e,i){v(t,e,(function(t){return this._invoke(e,i,t)}))}e?s?s(t,e,{value:i,enumerable:!r,configurable:!r,writable:!r}):t[e]=i:(n("next",0),n("throw",1),n("return",2))},v(t,e,i,r)}function y(t,e,i,r,s,n,a){try{var o=t[n](a),l=o.value}catch(t){return void i(t)}o.done?e(l):Promise.resolve(l).then(r,s)}function E(t){return function(){var e=this,i=arguments;return new Promise((function(r,s){var n=t.apply(e,i);function a(t){y(n,r,s,a,o,"next",t)}function o(t){y(n,r,s,a,o,"throw",t)}a(void 0)}))}}var T=function(){var t=E(p().m((function t(e){var i,u,c,d,h,f,g,m,v,y,E=arguments;return p().w((function(t){for(;;)switch(t.n){case 0:if(d=E.length>1&&void 0!==E[1]?E[1]:{},h=e,!(f=(0,o.getMediaDataFromCache)(h))||!0===d.skipCache){t.n=1;break}return t.a(2,Promise.resolve(f));case 1:if(!(0,r.isNotNil)(s.Wistia._mediaDataPromises[h])||!0===d.skipCache){t.n=2;break}return t.a(2,s.Wistia._mediaDataPromises[h]);case 2:return g=(0,n.mediaDataHost)(d),m=new window.URL("https://".concat(g,"/embed/medias/").concat(e,".json")),(0,r.isNotNil)(d.channelId)&&m.searchParams.set("channelId",d.channelId.toString()),v=null!==(i=d.channelPassword)&&void 0!==i?i:null===(u=d.plugin)||void 0===u||null===(c=u.passwordProtectedChannel)||void 0===c?void 0:c.password,(0,r.isNotNil)(v)&&m.searchParams.set("channelPassword",v),(0,r.isNotNil)(d.password)&&m.searchParams.set("password",d.password),d.deferFetchingToCarousel&&m.searchParams.set("defer_fetching_to_carousel","true"),d.bypassOriginShield&&m.searchParams.set("bos","1"),y=fetch(m.href).then((function(t){return t.json()})).then((function(t){var e;if((0,l.isMediaDataError)(t))return t;var i=t.media;return(0,a.mediaDataTransforms)(i,d),(0,o.cacheMediaData)(null!==(e=i.hashedId)&&void 0!==e?e:"",i),i})).finally((function(){Reflect.deleteProperty(s.Wistia._mediaDataPromises,h)})),s.Wistia._mediaDataPromises[h]=y,t.a(2,y)}}),t)})));return function(e){return t.apply(this,arguments)}}(),b=function(){var t=E(p().m((function t(e){var i,r,s,n,a,o,d,f,m,v,y=arguments;return p().w((function(t){for(;;)switch(t.n){case 0:return i=y.length>1&&void 0!==y[1]?y[1]:{},t.n=1,T(e,i);case 1:if(r=t.v,!(0,l.isMediaDataError)(r)){t.n=2;break}return t.a(2,r);case 2:if(null!=(s=r).localizations&&0!==s.localizations.length){t.n=3;break}return t.a(2,s);case 3:if(n=(0,c.getViewerPreferences)(),a=n.localization,o=[],null!=i.overrideMediaLanguage&&o.push(i.overrideMediaLanguage),null!=(null==a?void 0:a.bcp47LanguageTag)&&o.push(a.bcp47LanguageTag),null!=i.defaultMediaLanguage&&o.push(i.defaultMediaLanguage),d=o.filter((function(t,e){return o.indexOf(t)===e})),-1===(f=(0,u.getPreferredAvailableLanguageIndex)(s.localizations.map((function(t){return t.bcp47LanguageTag})),d))&&(f=(0,u.getPreferredAvailableLanguageIndex)(s.localizations.map((function(t){return t.wistiaLanguageCode})),d)),-1===f&&(f=(0,u.getPreferredAvailableLanguageIndex)(s.localizations.map((function(t){return t.bcp47LanguageTag})),g(null!==(m=navigator.languages)&&void 0!==m?m:["en"]))),!(f>=0)){t.n=6;break}if(v=s.localizations[f],s.hashedId!==v.hashedId){t.n=4;break}return t.a(2,s);case 4:if("alternate_audio"!==v.localizationIntent){t.n=5;break}return t.a(2,s);case 5:return t.a(2,T(v.hashedId,h({},i)));case 6:return t.a(2,s)}}),t)})));return function(e){return t.apply(this,arguments)}}()},(t,e,i)=>{i.d(e,{isMediaDataError:()=>s});var r=i(37),s=function(t){return!(!function(t,e){if(null==t)throw new TypeError("Cannot convert undefined or null to object");return Object.prototype.hasOwnProperty.call(Object(t),e)}(t,"error")||(0,r.isNil)(t.error))&&("true"===t.error||!0===t.error)}},(t,e,i)=>{function r(t,e){var i="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!i){if(Array.isArray(t)||(i=function(t,e){if(t){if("string"==typeof t)return s(t,e);var i={}.toString.call(t).slice(8,-1);return"Object"===i&&t.constructor&&(i=t.constructor.name),"Map"===i||"Set"===i?Array.from(t):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?s(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){i&&(t=i);var r=0,n=function(){};return{s:n,n:function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:n}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,o=!0,l=!1;return{s:function(){i=i.call(t)},n:function(){var t=i.next();return o=t.done,t},e:function(t){l=!0,a=t},f:function(){try{o||null==i.return||i.return()}finally{if(l)throw a}}}}function s(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,r=Array(e);i<e;i++)r[i]=t[i];return r}i.d(e,{getPreferredAvailableLanguageIndex:()=>o});var n=function(t){return t.split("-")[0]},a=function(){var t;return null===(t=(new Error).stack)||void 0===t?void 0:t.split("\n").slice(2).join("\n")},o=function(t,e){t.some((function(t){return"string"!=typeof t}))&&(console.error("availableLanguages has non-string values",t,a()),t=t.filter((function(t){return"string"==typeof t}))),e.some((function(t){return"string"!=typeof t}))&&(console.error("preferredLanguages has non-string values",e,a()),e=e.filter((function(t){return"string"==typeof t})));var i,s=r(e);try{var o,l=function(){var e=i.value;if(t.includes(e))return{v:t.indexOf(e)};var r=n(e);return t.some((function(t){return n(t)===r}))?{v:t.findIndex((function(t){return n(t)===r}))}:void 0};for(s.s();!(i=s.n()).done;)if(o=l())return o.v}catch(t){s.e(t)}finally{s.f()}return-1}},(t,e,i)=>{i.d(e,{getViewerPreferences:()=>a});var r=i(42),s=i(16),n=function(){return"wistia-viewer-preferences"},a=function(){return!1===s.Wistia._viewerPreferencesEnabled?{}:(0,r.getLocalStorage)(n())}},,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,(t,e,i)=>{i.d(e,{count:()=>g});var r=i(75),s=i(12),n=i(4),a=i(3),o=i(26),l=i(25),u=i(40),c=i(16);c.Wistia;null==c.Wistia._metricsCache&&(c.Wistia._metricsCache={});var d=c.Wistia._metricsCache,h=function(t,e,i){var o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};try{null==d.toMput&&(d.toMput=[]),null==d.requestId&&(d.requestId=0);var l=(0,n.merge)({type:t,key:e,value:null!=i?i:null,request_id:d.requestId},o),u=JSON.stringify(l);s.wlog.debug("send metrics",u),d.toMput.push(u),(0,r.doTimeout)("metrics.debounce",(function(){(0,a.pageLoaded)((function(){f.apply(undefined,d.toMput),d.toMput=[],d.requestId+=1}))}),500)}catch(t){s.wlog.error(t)}},f=function(){if((0,u.isVisitorTrackingEnabled)()){for(var t="".concat((0,o.proto)(),"//").concat((0,l.metricsHost)(),"/mput?topic=metrics"),e=arguments.length,i=new Array(e),r=0;r<e;r++)i[r]=arguments[r];return fetch(t,{method:"POST",mode:"cors",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i.join("\n")}).then((function(t){t.ok||console.error(t)})).catch((function(t){console.error(t)}))}},g=function(t){return h("count",t,arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})}},(t,e,i)=>{i.d(e,{setOrGet:()=>a});var r=i(41),s=i(4),n=i(16);n.Wistia._localStorage||(n.Wistia._localStorage=(0,r.getWistiaLocalStorage)());var a=function(t,e){if(null!=e){var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2]?s.unsetDeep:s.setDeep;return n.Wistia._localStorage=(0,r.updateWistiaLocalStorage)((function(r){return i(r,t,e)})),e}return null!=t?(0,s.getDeep)(n.Wistia._localStorage,t):n.Wistia._localStorage};r.removeWistiaLocalStorage},,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,(t,e,i)=>{i.d(e,{default:()=>W});var r=i(270),s=i(61),n=i(4),a=i(12),o=i(28),l=i(227),u=i(226),c=i(9),d=i(271),h=i(273),f=i(274),g=i(275),m=i(276),p=i(277),v=i(296),y=i(286),E=i(299),T=i(300),b=i(301),S=i(95),A=i(298);function L(){var t,e,i="function"==typeof Symbol?Symbol:{},r=i.iterator||"@@iterator",s=i.toStringTag||"@@toStringTag";function n(i,r,s,n){var l=r&&r.prototype instanceof o?r:o,u=Object.create(l.prototype);return k(u,"_invoke",function(i,r,s){var n,o,l,u=0,c=s||[],d=!1,h={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,i){return n=e,o=0,l=t,h.n=i,a}};function f(i,r){for(o=i,l=r,e=0;!d&&u&&!s&&e<c.length;e++){var s,n=c[e],f=h.p,g=n[2];i>3?(s=g===r)&&(l=n[(o=n[4])?5:(o=3,3)],n[4]=n[5]=t):n[0]<=f&&((s=i<2&&f<n[1])?(o=0,h.v=r,h.n=n[1]):f<g&&(s=i<3||n[0]>r||r>g)&&(n[4]=i,n[5]=r,h.n=g,o=0))}if(s||i>1)return a;throw d=!0,r}return function(s,c,g){if(u>1)throw TypeError("Generator is already running");for(d&&1===c&&f(c,g),o=c,l=g;(e=o<2?t:l)||!d;){n||(o?o<3?(o>1&&(h.n=-1),f(o,l)):h.n=l:h.v=l);try{if(u=2,n){if(o||(s="next"),e=n[s]){if(!(e=e.call(n,l)))throw TypeError("iterator result is not an object");if(!e.done)return e;l=e.value,o<2&&(o=0)}else 1===o&&(e=n.return)&&e.call(n),o<2&&(l=TypeError("The iterator does not provide a '"+s+"' method"),o=1);n=t}else if((e=(d=h.n<0)?l:i.call(r,h))!==a)break}catch(e){n=t,o=1,l=e}finally{u=1}}return{value:e,done:d}}}(i,s,n),!0),u}var a={};function o(){}function l(){}function u(){}e=Object.getPrototypeOf;var c=[][r]?e(e([][r]())):(k(e={},r,(function(){return this})),e),d=u.prototype=o.prototype=Object.create(c);function h(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,u):(t.__proto__=u,k(t,s,"GeneratorFunction")),t.prototype=Object.create(d),t}return l.prototype=u,k(d,"constructor",u),k(u,"constructor",l),l.displayName="GeneratorFunction",k(u,s,"GeneratorFunction"),k(d),k(d,s,"Generator"),k(d,r,(function(){return this})),k(d,"toString",(function(){return"[object Generator]"})),(L=function(){return{w:n,m:h}})()}function k(t,e,i,r){var s=Object.defineProperty;try{s({},"",{})}catch(t){s=0}k=function(t,e,i,r){function n(e,i){k(t,e,(function(t){return this._invoke(e,i,t)}))}e?s?s(t,e,{value:i,enumerable:!r,configurable:!r,writable:!r}):t[e]=i:(n("next",0),n("throw",1),n("return",2))},k(t,e,i,r)}function R(t,e,i,r,s,n,a){try{var o=t[n](a),l=o.value}catch(t){return void i(t)}o.done?e(l):Promise.resolve(l).then(r,s)}function I(t){return function(){var e=this,i=arguments;return new Promise((function(r,s){var n=t.apply(e,i);function a(t){R(n,r,s,a,o,"next",t)}function o(t){R(n,r,s,a,o,"throw",t)}a(void 0)}))}}function _(t,e){for(var i=0;i<e.length;i++){var r=e[i];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,w(r.key),r)}}function w(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var r=i.call(t,e||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}function P(t,e,i){return e=O(e),function(t,e){if(e&&("object"==typeof e||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}(t,D()?Reflect.construct(e,i||[],O(t).constructor):e.apply(t,i))}function D(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(t){}return(D=function(){return!!t})()}function C(){return C="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(t,e,i){var r=function(t,e){for(;!{}.hasOwnProperty.call(t,e)&&null!==(t=O(t)););return t}(t,e);if(r){var s=Object.getOwnPropertyDescriptor(r,e);return s.get?s.get.call(arguments.length<3?t:i):s.value}},C.apply(null,arguments)}function O(t){return O=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},O(t)}function x(t,e){return x=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},x(t,e)}function M(t,e,i){(function(t,e){if(e.has(t))throw new TypeError("Cannot initialize the same private elements twice on an object")})(t,e),e.set(t,i)}function F(t,e,i){return t.set(B(t,e),i),i}function N(t,e){return t.get(B(t,e))}function B(t,e,i){if("function"==typeof t?t===e:t.has(e))return arguments.length<3?e:i;throw new TypeError("Private element is not present on this object")}var U=(0,c.cachedDetect)(),$=p.default.delegatePublicMethods,G=a.wlog.getPrefixedFunctions("hls_video"),H=new WeakMap,V=new WeakMap,j=new WeakMap,K=function(t){function e(t,i,r,s){var a;return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),M(a=P(this,e,[t,i,r,s]),H,void 0),M(a,V,void 0),M(a,j,void 0),a.uuid=(0,o.seqId)("wistia_hls_video_"),a.root=t,a.name="HlsVideo",a.mediaData=i,a.allAssets=a.mediaData.assets,a.attributes=(0,n.assign)(a.defaultAttributes(),r||{}),a._startPosition=Number(a.attributes.startPosition)||-1,a.state={},a.simpleVideo=new p.default(a.root,a.mediaData,a.attributes,s),a.setupHls(),a}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&x(t,e)}(e,t),i=e,c=[{key:"abrBandWidthFactor",value:function(){return 1.1}},{key:"abrBandWidthUpFactor",value:function(){return 1.4}},{key:"adaptiveAsset",value:function(){var t=g.multivariantM3u8Url(this),e=g.buildMasterM3u8Asset(t);return e.display_name="Auto",e.slug="Auto",e}},{key:"addTextTracks",value:function(){}},{key:"adjustLevelsForHdr",value:function(){var t=this,e=0;this.hls.levels.forEach((function(i,r){var s=t.hls.levels[r+1],n=t.hls.levels[r-1];if(t.attributes.allowHdr&&U.hdr){var a=(null==s?void 0:s.name.includes("HDR"))&&s.width===i.width,o=(null==n?void 0:n.name.includes("HDR"))&&n.width===i.width;!a&&!o||i.name.includes("HDR")||(t.hls.removeLevel(r-e),e+=1)}else i.name.includes("HDR")&&(t.hls.removeLevel(r-e),e+=1)}))}},{key:"assetFromQuality",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:t,i=(0,s.withinQualityRange)(this.allAssets,t,e);return 0===i.length&&(i=(0,s.nearestOutsideRange)(this.allAssets,t,e)),i[0]}},{key:"canLiveStreamStart",value:function(t){var e,i,r;return(null===(e=t.liveStreamEventDetails)||void 0===e?void 0:e.startedAt)&&(null===(i=t.liveStreamEventDetails)||void 0===i?void 0:i.m3u8RenditionProgramTime)&&(null===(r=t.liveStreamEventDetails)||void 0===r?void 0:r.manifestUrl)}},{key:"changeAudioTrack",value:function(t){var e=this;return new Promise((function(i){var s="beforeplay"===e.getPlaybackMode(),n=e.getCurrentAudioTrack().id;s||n===t||e.hls.once(r.default.Events.AUDIO_TRACK_SWITCHED,(function(){i()})),e.hls.audioTracks[t]&&n!==t?e.hls.audioTrack=t:"beforeplay"===e.getPlaybackMode()?e.onReady().then((function(){e.hls.audioTrack=t,i()})):i()}))}},{key:"changeLevel",value:function(t){var e=this;this.hls.currentLevel!==t&&this.hls.startLevel!==t&&(this.hls.startLevel=t),"playing"===this.getPlaybackMode()&&-1!==t&&(this.hls.once(r.default.Events.LEVEL_SWITCHED,(function(){e.play()})),this.pause()),this.hls.currentLevel!==t&&(this.hls.nextLevel=t)}},{key:"changeQuality",value:function(t,e,i){if("auto"===t.toString().toLowerCase())return this.changeStream(-1,e,i);var r=this.hls.levels;t.toString().includes("HDR")&&(r=r.filter((function(t){return t.name.includes("HDR")})));var n=(0,s.findClosestAssetByQuality)(r,t),a=(0,E.deliveryUrlToLevel)(this,n.url[0]);return this.changeStream(a,e,i)}},{key:"changeStream",value:function(t){var e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return this.changeLevel(t),e?this.play():Promise.resolve()}},{key:"changeStreamWithoutLoad",value:function(t){if((0,E.assetToLevel)(this,t)!==this.hls.currentLevel){var e=(0,E.assetToLevel)(this,t);this.stopLoad(),this.changeLevel(e)}}},{key:"changeVideo",value:function(t,e){var i=this;return new Promise((function(r){i.mediaData=null,i.allAssets=[],i.attributes={},i.state={},i.state.isChangingVideo=!0,i._bindings={},i.destroyHls(),(0,y.teardownBeforeChangeVideo)(i.simpleVideo),i.mediaData=t,i.allAssets=t.assets,i.attributes=e,(0,y.initAfterChangeVideo)(i.simpleVideo,t,e),i.setAttributes({bwEstimateOnInit:(0,l.setOrGet)("hls.bandwidth_estimate")}),i.setupHls(),i.state.isChangingVideo=!1,r()}))}},{key:"currentLevel",value:function(){return this.hls.currentLevel}},{key:"currentAsset",value:function(){return this.hls.currentLevel>=0?(0,E.levelToAsset)(this,this.hls.currentLevel)||this.adaptiveAsset():null!=this.hls.startLevel&&this.hls.startLevel>=0&&(0,E.levelToAsset)(this,this.hls.startLevel)||this.adaptiveAsset()}},{key:"defaultAttributes",value:function(){return{contentType:"video/m3u8",qualityMin:360,qualityMax:2160,preload:"metadata"}}},{key:"destroy",value:function(){var t,i,r,s,n;return this.destroyHls(),clearTimeout(this._pollForLiveStreamTimeout),(t=e,i="destroy",r=this,n=C(O(1&(s=3)?t.prototype:t),i,r),2&s&&"function"==typeof n?function(t){return n.apply(r,t)}:n)([]),this.simpleVideo.destroy()}},{key:"destroyHls",value:function(){var t=this,e=function(t){try{return t()}catch(t){G.error(t)}};e((function(){f.teardown(t)})),e((function(){d.teardown(t)})),e((function(){h.teardown(t)})),e((function(){m.teardown(t)})),e((function(){(0,E.teardown)(t)})),this.hls&&(this.hls.destroy(),this.hls=null)}},{key:"determineMinAutoBitrate",value:function(){var t=this.hlsAssetFromQuality(360,1080);return t&&t.metadata&&t.metadata.max_bitrate?t.metadata.max_bitrate-1:6e5}},{key:"diagnosticData",value:function(){var t=this,e=function(t){try{return t()}catch(t){return"ERROR: ".concat(t.message)}},i={simpleVideo:this.simpleVideo.diagnosticData(),attributes:this.attributes,currentLevel:e((function(){return t.currentLevel()})),startLevel:e((function(){return t.hls.startLevel})),nextLevel:e((function(){return t.hls.nextLevel})),loadLevel:e((function(){return t.hls.loadLevel})),autoLevel:e((function(){return t.hls.autoLevel})),autoLevelCapping:e((function(){return t.hls.autoLevelCapping})),nextAutoLevel:e((function(){return t.hls.nextAutoLevel})),manualLevel:e((function(){return t.hls.manualLevel})),bandwidthEstimate:e((function(){return t.hls.abrController.bwEstimator.getEstimate()}))};return this.hls.currentLevel&&(i.currentAsset=(0,E.levelToAsset)(this,this.hls.currentLevel)),"auto"!==this.selectedQuality()&&this.hls.manualLevel>-1&&(i.selectedAsset=(0,E.levelToAsset)(this,this.hls.manualLevel)),i}},{key:"filteredVideoAssets",value:function(){var t=g.allMp4VideoAssets(this.allAssets);return(0,E.filteredHlsAssets)(this,t)}},{key:"getAudioTracks",value:(k=I(L().m((function t(){var e,i,r,s=this;return L().w((function(t){for(;;)switch(t.n){case 0:if(i=this.m3u8AudioAssets(),!((null===(e=this.hls)||void 0===e?void 0:e.audioTracks.length)>0)){t.n=1;break}return r=this.hls.audioTracks.map((function(t,e){var r=i[e-1];return t.isSelected=e===s.getHlsAudioTrackId(),t.label=null==r?void 0:r.details.languageMetadata.nativeName,0===e&&(t.label="Original"),t})),t.a(2,Promise.resolve(r));case 1:return t.a(2,Promise.resolve(g.audioTracksForVideo(i)))}}),t,this)}))),function(){return k.apply(this,arguments)})},{key:"getCurrentAudioTrack",value:(A=I(L().m((function t(){var e,i;return L().w((function(t){for(;;)if(0===t.n)return this.loadForAudioTracks(),e=this.getHlsAudioTrackId(),(i=this.hls.audioTracks[e]||{}).isSelected=!0,t.a(2,Promise.resolve(i))}),t,this)}))),function(){return A.apply(this,arguments)})},{key:"getCurrentAudioTrackId",value:function(){return this.getCurrentAudioTrack().id}},{key:"getCurrentQuality",value:function(){var t=this.hls.currentLevel>=0?this.hls.currentLevel:this.hls.startLevel,e=this.hls.levels[t];return e?e?this.qualityForLevel(t):"?":"auto"}},{key:"getCurrentTime",value:function(){var t;if(!this.attributes.liveMedia||!N(H,this)||null===(t=this.mediaData.liveStreamEventDetails)||void 0===t||!t.m3u8RenditionProgramTime)return this.simpleVideo.getCurrentTime();var e=new Date(this.mediaData.liveStreamEventDetails.m3u8RenditionProgramTime).getTime();return(N(H,this)-e)/1e3+this.simpleVideo.getCurrentTime()}},{key:"getHlsAudioTrackId",value:function(){return-1===this.hls.audioTrack?0:this.hls.audioTrack}},{key:"getMaxMaxBufferLengthForConfig",value:function(){switch(this.attributes.preload){case"auto":case!0:return 27;case"metadata":return 1;default:return this.getMaxMaxBufferLengthAfterPlay()}}},{key:"getMaxMaxBufferLengthAfterPlay",value:function(){return this.attributes.isInstantHls?12:60}},{key:"hlsAssetFromQuality",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:t,i=(0,s.withinQualityRange)(this.filteredVideoAssets(),t,e);return 0===i.length&&(i=(0,s.nearestOutsideRange)(this.filteredVideoAssets(),t,e)),i[0]}},{key:"isChangingVideo",value:function(){return!!this.state.isChangingVideo}},{key:"loadForAudioTracks",value:function(){0===this.hls.audioTracks.length&&this.startHlsLoadOnce()}},{key:"liveConfig",value:function(){return{abrBandWidthFactor:1.1,abrBandWidthUpFactor:1.4,abrEwmaDefaultEstimate:this.attributes.bwEstimateOnInit,testBandwidth:!1,autoStartLoad:!1,debug:{log:function(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];a.wlog.info.apply(a.wlog,["hlsjs log >"].concat(e))},error:function(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];a.wlog.notice.apply(a.wlog,["hlsjs error >"].concat(e))},warn:function(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];a.wlog.notice.apply(a.wlog,["hlsjs warn >"].concat(e))},info:function(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];a.wlog.info.apply(a.wlog,["hlsjs info >"].concat(e))},debug:function(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];a.wlog.debug.apply(a.wlog,["hlsjs debug >"].concat(e))}},maxBufferSize:6e7,maxFragLookUpTolerance:.2,maxMaxBufferLength:this.attributes.maxMaxBufferLength||this.getMaxMaxBufferLengthAfterPlay(),seekHoleNudgeDuration:.1}}},{key:"loadSource",value:function(){var t=this.adaptiveAsset();this.attributes.liveMedia?this.canLiveStreamStart(this.mediaData)?this.hls.loadSource(t.url):console.error("Live stream not ready to start"):this.hls.loadSource(t.url)}},{key:"m3u8AudioAssets",value:function(){return g.allHlsAudioAssets(this.allAssets)}},{key:"onEnterFullscreen",value:function(){this.simpleVideo.onEnterFullscreen(),"beforeplay"!==this.getPlaybackMode()&&this.changeLevel(-1)}},{key:"onHeightChange",value:function(t){this.simpleVideo.onHeightChange(t),this.setAttributes({height:t})}},{key:"onMediaDataChanged",value:function(t){this.mediaData=t}},{key:"onReady",value:function(){var t=this;return this.readyPromise||(this.readyPromise=this.simpleVideo.onReady().then((function(){return Promise.all([t.mediaAttachedPromise,t.manifestParsedPromise])}))),this.readyPromise}},{key:"onWidthChange",value:function(t){this.simpleVideo.onWidthChange(t),this.setAttributes({width:t})}},{key:"play",value:function(t){var e=this;return this.hls.config.autoStartLoad||this.startHlsLoadOnce(),this.hls.config.maxMaxBufferLength=this.getMaxMaxBufferLengthAfterPlay(),this.attributes.liveMedia?((0,u.count)("live_stream/play",1,{hashed_id:this.attributes.hashedId}),this.setCurrentTimeToLiveEdge().then((function(){return e.simpleVideo.play(t)})).then((function(t){return(0,u.count)("live_stream/play/success",1,{hashed_id:e.attributes.hashedId}),t}))):this.simpleVideo.play(t)}},{key:"qualityForLevel",value:function(t){var e;if(-1===t)return"auto";var i=this.hls.levels[t];return null!==(e=i.name)&&void 0!==e&&e.toLowerCase().includes("hdr")?"".concat((0,s.numericSizeSnapped)(i.width,i.height)," (HDR)"):(0,s.numericSizeSnapped)(i.width,i.height)}},{key:"qualityMax",value:function(t){this.hls.config&&(this.hls.config.qualityMax=t)}},{key:"qualityMin",value:function(t){this.hls.config&&(this.hls.config.qualityMin=t)}},{key:"removeTextTracks",value:function(){}},{key:"reset",value:function(){this.simpleVideo.reset()}},{key:"seek",value:function(t,e){return this.startHlsLoadOnce(t),this.simpleVideo.seek(t,e)}},{key:"selectableQualities",value:function(){var t=this,e=this.hls.levels.map((function(e,i){return t.qualityForLevel(i)}));return[this.qualityForLevel(-1)].concat(e)}},{key:"selectedQuality",value:function(){return this.hls.manualLevel>=0?this.qualityForLevel(this.hls.manualLevel):"auto"}},{key:"setAttributes",value:function(t){return(0,n.assign)(this.attributes,t),this.simpleVideo.setAttributes(t)}},{key:"setCurrentTimeToLiveEdge",value:function(){return"beforeplay"!==this.getPlaybackMode()?this.seek(this.hls.liveSyncPosition):Promise.resolve()}},{key:"setupEventListeners",value:function(){var t=this;this.manifestParsedPromise=new Promise((function(e){t.hls.on(r.default.Events.MANIFEST_PARSED,e)})),this.mediaAttachedPromise=new Promise((function(e){t.hls.on(r.default.Events.MEDIA_ATTACHED,e)})),this.hls.on(r.default.Events.MEDIA_ATTACHED,(function(){var e=t.hls._media,i=document.createElement("source");i.setAttribute("type","application/x-mpegURL"),i.setAttribute("src",g.multivariantM3u8Url(t)),e.appendChild(i),e.disableRemotePlayback=!1,e.addEventListener("webkitcurrentplaybacktargetiswirelesschanged",(function(){if(e.webkitCurrentPlaybackTargetIsWireless){var i=t.simpleVideo.getMediaElement().paused;t.pause(),t.hls.stopLoad(),e.autoplay=!0,i&&t.play()}else t.hls.startLoad(),e.autoplay=!1}))})),this.hls.on(r.default.Events.AUDIO_TRACKS_UPDATED,(function(){t.trigger("audiotracksupdated")})),this.hls.on(r.default.Events.LEVEL_SWITCHED,(function(e,i){var r,s=(0,E.levelToAsset)(t,i.level);null!==(r=t.hls.levels[i.level].name)&&void 0!==r&&r.includes("HDR")&&(0,u.count)("player/hlsjs/using-hdr-asset",1),t.trigger("hlslevelswitched",{asset:s})})),this.hls.once(r.default.Events.LEVEL_LOADED,(function(e,i){var r,s,n;F(H,t,null===(r=i.details)||void 0===r||null===(s=r.fragments)||void 0===s||null===(n=s[0])||void 0===n?void 0:n.programDateTime)}))}},{key:"setupHls",value:function(){this.attributes.liveMedia?this.setupLiveHls():this.setupVodHls()}},{key:"setupLiveHls",value:function(){var t,e,i=this,s=this.liveConfig();this.hls=new r.default(s),m.setup(this),this.setupEventListeners(),this.hls.attachMedia(this.simpleVideo.getMediaElement()),d.setup(this),f.setup(this),null!==(t=this.mediaData.liveStreamEventDetails)&&void 0!==t&&t.startedAt&&null!==(e=this.mediaData.liveStreamEventDetails)&&void 0!==e&&e.m3u8RenditionProgramTime&&(F(V,this,this.mediaData.liveStreamEventDetails.startedAt),F(j,this,this.mediaData.liveStreamEventDetails.m3u8RenditionProgramTime),this.loadSource(),this.onReady().then((function(){i.trigger("livestreamready")})));var n=function(){(0,S.fetchMediaData)(i.attributes.hashedId,{embedHost:i.attributes.embedHost,skipCache:!0,bypassOriginShield:!0}).then(function(){var t=I(L().m((function t(e){var r,s,a;return L().w((function(t){for(;;)switch(t.n){case 0:if(!i.canLiveStreamStart(e)){t.n=3;break}if(r=e.liveStreamEventDetails,s=r.startedAt,a=r.m3u8RenditionProgramTime,i.onMediaDataChanged(e),void 0!==N(V,i)||void 0!==N(j,i)){t.n=2;break}return F(V,i,s),F(j,i,a),i.loadSource(),t.n=1,i.onReady();case 1:i.trigger("livestreamready"),t.n=3;break;case 2:s!==N(V,i)&&a!==N(j,i)&&i.trigger("livestream-mediadata-changed",e);case 3:i._pollForLiveStreamTimeout=setTimeout(n,1e3);case 4:return t.a(2)}}),t)})));return function(e){return t.apply(this,arguments)}}())};n()}},{key:"setupVodHls",value:function(){var t=this,e=this.vodConfig();this.hls=new r.default(e),m.setup(this),this.loadSource(),this.setupEventListeners(),this.hls.attachMedia(this.simpleVideo.getMediaElement()),h.setup(this),f.setup(this),d.setup(this),this.hls.once(r.default.Events.MANIFEST_PARSED,(function(){t.adjustLevelsForHdr(),t.hls.startLevel=(0,E.bestStartingLevel)(t),null!=t.attributes.playbackRate&&t.simpleVideo.setPlaybackRate(t.attributes.playbackRate),U.hdr&&(0,u.count)("player/hlsjs/hdr-supported",1)}))}},{key:"selectedAsset",value:function(){if(0!==this.hls.levels.length)return this.hls.currentLevel?this.hls.levels[this.hls.currentLevel]:this.hls.levels[this.hls.startLevel]}},{key:"showFirstFrame",value:function(){return this.seek(.01)}},{key:"startHlsLoadOnce",value:function(t){var e=t||this._startPosition;(0,E.startLoadOnce)(this,e)}},{key:"stopLoad",value:function(){(0,E.stopLoad)(this)}},{key:"updateStartPosition",value:function(t){this.hls.config.startPosition!==t&&(this.attributes.startPosition=t,this._startPosition=t,this.hls.config.startPosition=t,this.hls&&this.loadSource())}},{key:"usingInstantHls",value:function(){return(this.attributes.forceInstantHls||!this.mediaData.playableWithoutInstantHls)&&this.mediaData.instantHlsAssetsReady}},{key:"vodConfig",value:function(){var t={abrBandWidthFactor:1.1,abrBandWidthUpFactor:1.4,abrController:T.default,abrEwmaFastVoD:4,abrEwmaSlowVoD:15,autoStartLoad:"none"!==this.attributes.preload&&!1!==this.attributes.preload,capLevelToPlayerSize:!0,capLevelController:b.default,debug:{log:function(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];a.wlog.info.apply(a.wlog,["hlsjs log >"].concat(e))},error:function(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];a.wlog.notice.apply(a.wlog,["hlsjs error >"].concat(e))},warn:function(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];a.wlog.notice.apply(a.wlog,["hlsjs warn >"].concat(e))},info:function(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];a.wlog.info.apply(a.wlog,["hlsjs info >"].concat(e))},debug:function(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];a.wlog.debug.apply(a.wlog,["hlsjs debug >"].concat(e))}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:this.attributes.authorization?3e4:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:this.attributes.isInstantHls?3e4:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:this.attributes.isInstantHls?2:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:this.attributes.isInstantHls?2:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},maxBufferSize:6e7,maxFragLookUpTolerance:.2,maxMaxBufferLength:this.getMaxMaxBufferLengthForConfig(),minAutoBitrate:this.determineMinAutoBitrate(),seekHoleNudgeDuration:.1,startPosition:this._startPosition,qualityMin:this.attributes.qualityMin||360,qualityMax:this.attributes.qualityMax||2160};return this.attributes.audioPreference&&(t.audioPreference=this.attributes.audioPreference),t}}],c&&_(i.prototype,c),v&&_(i,v),Object.defineProperty(i,"prototype",{writable:!1}),i;var i,c,v,A,k}(A.PlaybackEngine);$(K.prototype,(function(){return this.simpleVideo})),(0,v.default)("HlsVideo",K);const W=K},(t,e,i)=>{i.d(e,{default:()=>gl});const r=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},s=Number.isSafeInteger||function(t){return"number"==typeof t&&Math.abs(t)<=n},n=Number.MAX_SAFE_INTEGER||9007199254740991;let a=function(t){return t.NETWORK_ERROR="networkError",t.MEDIA_ERROR="mediaError",t.KEY_SYSTEM_ERROR="keySystemError",t.MUX_ERROR="muxError",t.OTHER_ERROR="otherError",t}({}),o=function(t){return t.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",t.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",t.KEY_SYSTEM_NO_SESSION="keySystemNoSession",t.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",t.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",t.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",t.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",t.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",t.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",t.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",t.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",t.MANIFEST_LOAD_ERROR="manifestLoadError",t.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",t.MANIFEST_PARSING_ERROR="manifestParsingError",t.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",t.LEVEL_EMPTY_ERROR="levelEmptyError",t.LEVEL_LOAD_ERROR="levelLoadError",t.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",t.LEVEL_PARSING_ERROR="levelParsingError",t.LEVEL_SWITCH_ERROR="levelSwitchError",t.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",t.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",t.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",t.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",t.FRAG_LOAD_ERROR="fragLoadError",t.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",t.FRAG_DECRYPT_ERROR="fragDecryptError",t.FRAG_PARSING_ERROR="fragParsingError",t.FRAG_GAP="fragGap",t.REMUX_ALLOC_ERROR="remuxAllocError",t.KEY_LOAD_ERROR="keyLoadError",t.KEY_LOAD_TIMEOUT="keyLoadTimeOut",t.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",t.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",t.BUFFER_APPEND_ERROR="bufferAppendError",t.BUFFER_APPENDING_ERROR="bufferAppendingError",t.BUFFER_STALLED_ERROR="bufferStalledError",t.BUFFER_FULL_ERROR="bufferFullError",t.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",t.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",t.ASSET_LIST_LOAD_ERROR="assetListLoadError",t.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",t.ASSET_LIST_PARSING_ERROR="assetListParsingError",t.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.ATTACH_MEDIA_ERROR="attachMediaError",t.UNKNOWN="unknown",t}({}),l=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.MEDIA_ENDED="hlsMediaEnded",t.STALL_RESOLVED="hlsStallResolved",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFERED_TO_END="hlsBufferedToEnd",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached",t.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",t.ASSET_LIST_LOADING="hlsAssetListLoading",t.ASSET_LIST_LOADED="hlsAssetListLoaded",t.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",t.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",t.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",t.INTERSTITIAL_STARTED="hlsInterstitialStarted",t.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",t.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",t.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",t.INTERSTITIAL_ENDED="hlsInterstitialEnded",t.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",t.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",t.EVENT_CUE_ENTER="hlsEventCueEnter",t}({});var u="manifest",c="level",d="audioTrack",h="subtitleTrack",f="main",g="audio",m="subtitle";class p{constructor(t,e=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=i}sample(t,e){const i=Math.pow(this.alpha_,t);this.estimate_=e*(1-i)+i*this.estimate_,this.totalWeight_+=t}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}}class v{constructor(t,e,i,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new p(t),this.fast_=new p(e),this.defaultTTFB_=r,this.ttfb_=new p(t)}update(t,e){const{slow_:i,fast_:r,ttfb_:s}=this;i.halfLife!==t&&(this.slow_=new p(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.fast_=new p(e,r.getEstimate(),r.getTotalWeight())),s.halfLife!==t&&(this.ttfb_=new p(t,s.getEstimate(),s.getTotalWeight()))}sample(t,e){const i=(t=Math.max(t,this.minDelayMs_))/1e3,r=8*e/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}sampleTTFB(t){const e=t/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(i,Math.max(t,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function y(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var r=i.call(t,e);if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function E(){return E=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var r in i)({}).hasOwnProperty.call(i,r)&&(t[r]=i[r])}return t},E.apply(null,arguments)}function T(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),i.push.apply(i,r)}return i}function b(t){for(var e=1;e<arguments.length;e++){var i=null!=arguments[e]?arguments[e]:{};e%2?T(Object(i),!0).forEach((function(e){y(t,e,i[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):T(Object(i)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))}))}return t}class S{constructor(t,e){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const i=`[${t}]:`;this.trace=A,this.debug=e.debug.bind(null,i),this.log=e.log.bind(null,i),this.warn=e.warn.bind(null,i),this.info=e.info.bind(null,i),this.error=e.error.bind(null,i)}}const A=function(){},L={trace:A,debug:A,log:A,warn:A,info:A,error:A};function k(){return E({},L)}function R(t,e,i){return e[t]?e[t].bind(e):function(t,e){const i=self.console[t];return i?i.bind(self.console,`${e?"["+e+"] ":""}[${t}] >`):A}(t,i)}const I=k();const _=I;function w(t=!0){if("undefined"==typeof self)return;return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function P(t,e){const i=Object.keys(t),r=Object.keys(e),s=i.length,n=r.length;return!s||!n||s===n&&!i.some((t=>-1===r.indexOf(t)))}function D(t,e=!1){if("undefined"!=typeof TextDecoder){const i=new TextDecoder("utf-8").decode(t);if(e){const t=i.indexOf("\0");return-1!==t?i.substring(0,t):i}return i.replace(/\0/g,"")}const i=t.length;let r,s,n,a="",o=0;for(;o<i;){if(r=t[o++],0===r&&e)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:s=t[o++],a+=String.fromCharCode((31&r)<<6|63&s);break;case 14:s=t[o++],n=t[o++],a+=String.fromCharCode((15&r)<<12|(63&s)<<6|63&n)}}return a}function C(t){let e="";for(let i=0;i<t.length;i++){let r=t[i].toString(16);r.length<2&&(r="0"+r),e+=r}return e}function O(t){return Uint8Array.from(t.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function x(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var M,F={exports:{}};var N,B,U,$,G,H=(M||(M=1,N=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,B=/^(?=([^\/?#]*))\1([^]*)$/,U=/(?:\/|^)\.(?=\/)/g,$=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,F.exports=G={buildAbsoluteURL:function(t,e,i){if(i=i||{},t=t.trim(),!(e=e.trim())){if(!i.alwaysNormalize)return t;var r=G.parseURL(t);if(!r)throw new Error("Error trying to parse base URL.");return r.path=G.normalizePath(r.path),G.buildURLFromParts(r)}var s=G.parseURL(e);if(!s)throw new Error("Error trying to parse relative URL.");if(s.scheme)return i.alwaysNormalize?(s.path=G.normalizePath(s.path),G.buildURLFromParts(s)):e;var n=G.parseURL(t);if(!n)throw new Error("Error trying to parse base URL.");if(!n.netLoc&&n.path&&"/"!==n.path[0]){var a=B.exec(n.path);n.netLoc=a[1],n.path=a[2]}n.netLoc&&!n.path&&(n.path="/");var o={scheme:n.scheme,netLoc:s.netLoc,path:null,params:s.params,query:s.query,fragment:s.fragment};if(!s.netLoc&&(o.netLoc=n.netLoc,"/"!==s.path[0]))if(s.path){var l=n.path,u=l.substring(0,l.lastIndexOf("/")+1)+s.path;o.path=G.normalizePath(u)}else o.path=n.path,s.params||(o.params=n.params,s.query||(o.query=n.query));return null===o.path&&(o.path=i.alwaysNormalize?G.normalizePath(s.path):s.path),G.buildURLFromParts(o)},parseURL:function(t){var e=N.exec(t);return e?{scheme:e[1]||"",netLoc:e[2]||"",path:e[3]||"",params:e[4]||"",query:e[5]||"",fragment:e[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(U,"");t.length!==(t=t.replace($,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}}),F.exports);class V{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 j="audio",K="video",W="audiovideo";class Y{constructor(t){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof t&&(t={url:t}),this.base=t,function(t,e){const i=Q(t,e);i&&(i.enumerable=!0,Object.defineProperty(t,e,i))}(this,"stats")}setByteRange(t,e){const i=t.split("@",2);let r;r=1===i.length?(null==e?void 0:e.byteRangeEndOffset)||0:parseInt(i[1]),this._byteRange=[r,parseInt(i[0])+r]}get 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={[j]:null,[K]:null,[W]:null}),this._streams}set elementaryStreams(t){this._streams=t}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new V),this._stats}set stats(t){this._stats=t}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=H.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[j]=null,t[K]=null,t[W]=null}}function q(t){return"initSegment"!==t.sn}class z extends Y{constructor(t,e){super(e),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=t}get byteLength(){if(this.hasStats){const t=this.stats.total;if(t)return t}if(this.byteRange.length){const t=this.byteRange[0],e=this.byteRange[1];if(r(t)&&r(e))return e-t}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(t){this._bitrate=t}get decryptdata(){var t;const{levelkeys:e}=this;if(!e||e.NONE)return null;if(e.identity)this._decryptdata||(this._decryptdata=e.identity.getDecryptData(this.sn));else if(null==(t=this._decryptdata)||!t.keyId){const t=Object.keys(e);if(1===t.length){const i=this._decryptdata=e[t[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,e))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;const t=r(this.duration)?this.duration:0;return this.programDateTime+1e3*t}get encrypted(){var t;if(null!=(t=this._decryptdata)&&t.encrypted)return!0;if(this.levelkeys){var e;const t=Object.keys(this.levelkeys),i=t.length;if(i>1||1===i&&null!=(e=this.levelkeys[t[0]])&&e.encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(t){r(t)?this._programDateTime=t:this._programDateTime=this.rawProgramDateTime=null}get ref(){return q(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(t){this.setStart(this.start+t)}setStart(t){this.start=t,this._ref&&(this._ref.start=t)}setDuration(t){this.duration=t,this._ref&&(this._ref.duration=t)}setKeyFormat(t){const e=this.levelkeys;if(e){var i;const r=e[t];!r||null!=(i=this._decryptdata)&&i.keyId||(this._decryptdata=r.getDecryptData(this.sn,e))}}abortRequests(){var t,e;null==(t=this.loader)||t.abort(),null==(e=this.keyLoader)||e.abort()}setElementaryStreamInfo(t,e,i,r,s,n=!1){const{elementaryStreams:a}=this,o=a[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,i),o.startDTS=Math.min(o.startDTS,r),o.endDTS=Math.max(o.endDTS,s)):a[t]={startPTS:e,endPTS:i,startDTS:r,endDTS:s,partial:n}}}class X extends Y{constructor(t,e,i,r,s){super(i),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=e,this.index=r;const n=t.enumeratedString("BYTERANGE");n&&this.setByteRange(n,s),s&&(this.fragOffset=s.fragOffset+s.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:t}=this;return!!(t.audio||t.video||t.audiovideo)}}function Q(t,e){const i=Object.getPrototypeOf(t);if(i){const t=Object.getOwnPropertyDescriptor(i,e);return t||Q(i,e)}}const Z=Math.pow(2,32)-1,J=[].push,tt={video:1,audio:2,id3:3,text:4};function et(t){return String.fromCharCode.apply(null,t)}function it(t,e){const i=t[e]<<8|t[e+1];return i<0?65536+i:i}function rt(t,e){const i=nt(t,e);return i<0?4294967296+i:i}function st(t,e){let i=rt(t,e);return i*=Math.pow(2,32),i+=rt(t,e+4),i}function nt(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function at(t,e){const i=[];if(!e.length)return i;const r=t.byteLength;for(let s=0;s<r;){const n=rt(t,s),a=n>1?s+n:r;if(et(t.subarray(s+4,s+8))===e[0])if(1===e.length)i.push(t.subarray(s+8,a));else{const r=at(t.subarray(s+8,a),e.slice(1));r.length&&J.apply(i,r)}s=a}return i}function ot(t){const e=[],i=t[0];let r=8;const s=rt(t,r);r+=4;let n=0,a=0;0===i?(n=rt(t,r),a=rt(t,r+4),r+=8):(n=st(t,r),a=st(t,r+8),r+=16),r+=2;let o=t.length+a;const l=it(t,r);r+=2;for(let i=0;i<l;i++){let i=r;const n=rt(t,i);i+=4;const a=2147483647&n;if(1===(2147483648&n)>>>31)return _.warn("SIDX has hierarchical references (not supported)"),null;const l=rt(t,i);i+=4,e.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/s,start:o,end:o+a-1}}),o+=a,i+=4,r=i}return{earliestPresentationTime:n,timescale:s,version:i,referencesCount:l,references:e}}function lt(t){const e=[],i=at(t,["moov","trak"]);for(let t=0;t<i.length;t++){const r=i[t],s=at(r,["tkhd"])[0];if(s){let t=s[0];const i=rt(s,0===t?12:20),n=at(r,["mdia","mdhd"])[0];if(n){t=n[0];const s=rt(n,0===t?12:20),a=at(r,["mdia","hdlr"])[0];if(a){const t=et(a.subarray(8,12)),n={soun:j,vide:K}[t],o=ut(at(r,["mdia","minf","stbl","stsd"])[0]);n?(e[i]={timescale:s,type:n,stsd:o},e[n]=b({timescale:s,id:i},o)):e[i]={timescale:s,type:t,stsd:o}}}}}return at(t,["moov","mvex","trex"]).forEach((t=>{const i=rt(t,4),r=e[i];r&&(r.default={duration:rt(t,12),flags:rt(t,20)})})),e}function ut(t){const e=t.subarray(8),i=e.subarray(86),r=et(e.subarray(4,8));let s,n=r;const a="enca"===r||"encv"===r;if(a){const t=at(e,[r])[0];at(t.subarray("enca"===r?28:78),["sinf"]).forEach((t=>{const e=at(t,["schm"])[0];if(e){const i=et(e.subarray(4,8));if("cbcs"===i||"cenc"===i){const e=at(t,["frma"])[0];e&&(n=et(e))}}}))}const o=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const t=at(i,["avcC"])[0];t&&t.length>3&&(n+="."+ht(t[1])+ht(t[2])+ht(t[3]),s=ct("avc1"===o?"dva1":"dvav",i));break}case"mp4a":{const t=at(e,[r])[0],i=at(t.subarray(28),["esds"])[0];if(i&&i.length>7){let t=4;if(3!==i[t++])break;t=dt(i,t),t+=2;const e=i[t++];if(128&e&&(t+=2),64&e&&(t+=i[t++]),4!==i[t++])break;t=dt(i,t);const r=i[t++];if(64!==r)break;if(n+="."+ht(r),t+=12,5!==i[t++])break;t=dt(i,t);const s=i[t++];let a=(248&s)>>3;31===a&&(a+=1+((7&s)<<3)+((224&i[t])>>5)),n+="."+a}break}case"hvc1":case"hev1":{const t=at(i,["hvcC"])[0];if(t&&t.length>12){const e=t[1],i=["","A","B","C"][e>>6],r=31&e,s=rt(t,2),a=(32&e)>>5?"H":"L",o=t[12],l=t.subarray(6,12);n+="."+i+r,n+="."+function(t){let e=0;for(let i=0;i<32;i++)e|=(t>>i&1)<<31-i;return e>>>0}(s).toString(16).toUpperCase(),n+="."+a+o;let u="";for(let t=l.length;t--;){const e=l[t];if(e||u){u="."+e.toString(16).toUpperCase()+u}}n+=u}s=ct("hev1"==o?"dvhe":"dvh1",i);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=ct(n,i)||n;break;case"vp09":{const t=at(i,["vpcC"])[0];if(t&&t.length>6){const e=t[4],i=t[5],r=t[6]>>4&15;n+="."+ft(e)+"."+ft(i)+"."+ft(r)}break}case"av01":{const t=at(i,["av1C"])[0];if(t&&t.length>2){const e=t[1]>>>5,r=31&t[1],a=t[2]>>>7?"H":"M",o=(64&t[2])>>6,l=(32&t[2])>>5,u=2===e&&o?l?12:10:o?10:8,c=(16&t[2])>>4,d=(8&t[2])>>3,h=(4&t[2])>>2,f=3&t[2],g=1,m=1,p=1,v=0;n+="."+e+"."+ft(r)+a+"."+ft(u)+"."+c+"."+d+h+f+"."+ft(g)+"."+ft(m)+"."+ft(p)+"."+v,s=ct("dav1",i)}break}}return{codec:n,encrypted:a,supplemental:s}}function ct(t,e){const i=at(e,["dvvC"]),r=i.length?i[0]:at(e,["dvcC"])[0];if(r){const e=r[2]>>1&127,i=r[2]<<5&32|r[3]>>3&31;return t+"."+ft(e)+"."+ft(i)}}function dt(t,e){const i=e+5;for(;128&t[e++]&&e<i;);return e}function ht(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function ft(t){return(t<10?"0":"")+t}function gt(t,e){at(t,["moov","trak"]).forEach((t=>{const i=at(t,["mdia","minf","stbl","stsd"])[0];if(!i)return;const r=i.subarray(8);let s=at(r,["enca"]);const n=s.length>0;n||(s=at(r,["encv"])),s.forEach((t=>{at(n?t.subarray(28):t.subarray(78),["sinf"]).forEach((t=>{const i=mt(t);i&&e(i,n)}))}))}))}function mt(t){const e=at(t,["schm"])[0];if(e){const i=et(e.subarray(4,8));if("cbcs"===i||"cenc"===i){const e=at(t,["schi","tenc"])[0];if(e)return e}}}function pt(t,e){const i=new Uint8Array(t.length+e.length);return i.set(t),i.set(e,t.length),i}function vt(t,e){const i=[],r=e.samples,s=e.timescale,n=e.id;let a=!1;return at(r,["moof"]).map((o=>{const l=o.byteOffset-8;at(o,["traf"]).map((o=>{const u=at(o,["tfdt"]).map((t=>{const e=t[0];let i=rt(t,4);return 1===e&&(i*=Math.pow(2,32),i+=rt(t,8)),i/s}))[0];return void 0!==u&&(t=u),at(o,["tfhd"]).map((u=>{const c=rt(u,4),d=16777215&rt(u,0);let h=0;const f=!!(16&d);let g=0;const m=!!(32&d);let p=8;c===n&&(!!(1&d)&&(p+=8),!!(2&d)&&(p+=4),!!(8&d)&&(h=rt(u,p),p+=4),f&&(g=rt(u,p),p+=4),m&&(p+=4),"video"===e.type&&(a=yt(e.codec)),at(o,["trun"]).map((n=>{const o=n[0],u=16777215&rt(n,0),c=!!(1&u);let d=0;const f=!!(4&u),m=!!(256&u);let p=0;const v=!!(512&u);let y=0;const E=!!(1024&u),T=!!(2048&u);let b=0;const S=rt(n,4);let A=8;c&&(d=rt(n,A),A+=4),f&&(A+=4);let L=d+l;for(let l=0;l<S;l++){if(m?(p=rt(n,A),A+=4):p=h,v?(y=rt(n,A),A+=4):y=g,E&&(A+=4),T&&(b=0===o?rt(n,A):nt(n,A),A+=4),e.type===K){let e=0;for(;e<y;){const n=rt(r,L);if(L+=4,Et(a,r[L])){Tt(r.subarray(L,L+n),a?2:1,t+b/s,i)}L+=n,e+=n+4}}t+=p/s}})))}))}))})),i}function yt(t){if(!t)return!1;const e=t.substring(0,4);return"hvc1"===e||"hev1"===e||"dvh1"===e||"dvhe"===e}function Et(t,e){if(t){const t=e>>1&63;return 39===t||40===t}return 6===(31&e)}function Tt(t,e,i,r){const s=bt(t);let n=0;n+=e;let a=0,o=0,l=0;for(;n<s.length;){a=0;do{if(n>=s.length)break;l=s[n++],a+=l}while(255===l);o=0;do{if(n>=s.length)break;l=s[n++],o+=l}while(255===l);const t=s.length-n;let e=n;if(o<t)n+=o;else if(o>t){_.error(`Malformed SEI payload. ${o} is too small, only ${t} bytes left to parse.`);break}if(4===a){if(181===s[e++]){const t=it(s,e);if(e+=2,49===t){const t=rt(s,e);if(e+=4,1195456820===t){const t=s[e++];if(3===t){const n=s[e++],o=64&n,l=o?2+3*(31&n):0,u=new Uint8Array(l);if(o){u[0]=n;for(let t=1;t<l;t++)u[t]=s[e++]}r.push({type:t,payloadType:a,pts:i,bytes:u})}}}}}else if(5===a&&o>16){const t=[];for(let i=0;i<16;i++){const r=s[e++].toString(16);t.push(1==r.length?"0"+r:r),3!==i&&5!==i&&7!==i&&9!==i||t.push("-")}const n=o-16,l=new Uint8Array(n);for(let t=0;t<n;t++)l[t]=s[e++];r.push({payloadType:a,pts:i,uuid:t.join(""),userData:D(l),userDataBytes:l})}}}function bt(t){const e=t.byteLength,i=[];let r=1;for(;r<e-2;)0===t[r]&&0===t[r+1]&&3===t[r+2]?(i.push(r+2),r+=2):r++;if(0===i.length)return t;const s=e-i.length,n=new Uint8Array(s);let a=0;for(r=0;r<s;a++,r++)a===i[0]&&(a++,i.shift()),n[r]=t[a];return n}function St(t,e,i){if(16!==t.byteLength)throw new RangeError("Invalid system id");let r,s,n;r=0,s=new Uint8Array,n=new Uint8Array;const a=new Uint8Array(4);return i.byteLength>0&&new DataView(a.buffer).setUint32(0,i.byteLength,!1),function(t,...e){const i=e.length;let r=8,s=i;for(;s--;)r+=e[s].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(t,4),s=0,r=8;s<i;s++)n.set(e[s],r),r+=e[s].byteLength;return n}([112,115,115,104],new Uint8Array([0,0,0,0]),t,n,s,a,i)}function At(t){const e=t.getUint32(0),i=t.byteOffset,r=t.byteLength;if(r<e)return{offset:i,size:r};if(1886614376!==t.getUint32(4))return{offset:i,size:e};const s=t.getUint32(8)>>>24;if(0!==s&&1!==s)return{offset:i,size:e};const n=t.buffer,a=C(new Uint8Array(n,i+12,16));let o=null,l=null,u=0;if(0===s)u=28;else{const s=t.getUint32(28);if(!s||r<32+16*s)return{offset:i,size:e};o=[];for(let t=0;t<s;t++)o.push(new Uint8Array(n,i+32+16*t,16));u=32+16*s}if(!u)return{offset:i,size:e};const c=t.getUint32(u);return e-32<c?{offset:i,size:e}:(l=new Uint8Array(n,i+u+4,c),{version:s,systemId:a,kids:o,data:l,offset:i,size:e})}const Lt=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),kt={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 Rt(t,e){const i=kt[e];return!!i&&!!i[t.slice(0,4)]}function It(t,e,i=!0){return!t.split(",").some((t=>!_t(t,e,i)))}function _t(t,e,i=!0){var r;const s=w(i);return null!=(r=null==s?void 0:s.isTypeSupported(wt(t,e)))&&r}function wt(t,e){return`${e}/mp4;codecs=${t}`}function Pt(t){if(t){const e=t.substring(0,4);return kt.video[e]}return 2}function Dt(t){const e=Lt();return t.split(",").reduce(((t,i)=>{const r=e&&yt(i)?9:kt.video[i];return r?(2*r+t)/(t?3:2):(kt.audio[i]+t)/(t?2:1)}),0)}const Ct={};const Ot=/flac|opus|mp4a\.40\.34/i;function xt(t,e=!0){return t.replace(Ot,(t=>function(t,e=!0){if(Ct[t])return Ct[t];const i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[t];for(let s=0;s<i.length;s++){var r;if(_t(i[s],"audio",e))return Ct[t]=i[s],i[s];if("mp3"===i[s]&&null!=(r=w(e))&&r.isTypeSupported("audio/mpeg"))return""}return t}(t.toLowerCase(),e)))}function Mt(t,e){if(t&&(t.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(t))&&(Ft(t,"audio")||Ft(t,"video")))return t;if(e){const i=e.split(",");if(i.length>1){if(t)for(let e=i.length;e--;)if(i[e].substring(0,4)===t.substring(0,4))return i[e];return i[0]}}return e||t}function Ft(t,e){return Rt(t,e)&&_t(t,e)}function Nt(t){if(t.startsWith("av01.")){const e=t.split("."),i=["0","111","01","01","01","0"];for(let t=e.length;t>4&&t<10;t++)e[t]=i[t-4];return e.join(".")}return t}function Bt(t){const e=w(t)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Ut(t){return t.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const $t={supported:!1,smooth:!1,powerEfficient:!1},Gt={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function Ht(t,e){return{supported:!1,configurations:e,decodingInfoResults:[$t],error:t}}function Vt(t,e,i,s,n,a){const o=t.videoCodec,l=t.audioCodec?t.audioGroups:null,u=null==a?void 0:a.audioCodec,c=null==a?void 0:a.channels,d=c?parseInt(c):u?Infinity:2;let h=null;if(null!=l&&l.length)try{h=1===l.length&&l[0]?e.groups[l[0]].channels:l.reduce(((t,i)=>{if(i){const r=e.groups[i];if(!r)throw new Error(`Audio track group ${i} not found`);Object.keys(r.channels).forEach((e=>{t[e]=(t[e]||0)+r.channels[e]}))}return t}),{2:0})}catch(t){return!0}return void 0!==o&&(o.split(",").some((t=>yt(t)))||t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(s,30)||"SDR"!==t.videoRange&&t.videoRange!==i||t.bitrate>Math.max(n,8e6))||!!h&&r(d)&&Object.keys(h).some((t=>parseInt(t)>d))}function jt(t,e,i,r={}){const s=t.videoCodec;if(!s&&!t.audioCodec||!i)return Promise.resolve(Gt);const n=[],a=function(t){var e;const i=null==(e=t.videoCodec)?void 0:e.split(","),r=Wt(t),s=t.width||640,n=t.height||480,a=t.frameRate||30,o=t.videoRange.toLowerCase();return i?i.map((t=>{const e={contentType:wt(Nt(t),"video"),width:s,height:n,bitrate:r,framerate:a};return"sdr"!==o&&(e.transferFunction=o),e})):[]}(t),o=a.length,l=function(t,e,i){var r;const s=null==(r=t.audioCodec)?void 0:r.split(","),n=Wt(t);if(s&&t.audioGroups)return t.audioGroups.reduce(((t,r)=>{var a;const o=r?null==(a=e.groups[r])?void 0:a.tracks:null;return o?o.reduce(((t,e)=>{if(e.groupId===r){const r=parseFloat(e.channels||"");s.forEach((e=>{const s={contentType:wt(e,"audio"),bitrate:i?Kt(e,n):n};r&&(s.channels=""+r),t.push(s)}))}return t}),t):t}),[]);return[]}(t,e,o>0),u=l.length;for(let t=o||1*u||1;t--;){const e={type:"media-source"};if(o&&(e.video=a[t%o]),u){e.audio=l[t%u];const i=e.audio.bitrate;e.video&&i&&(e.video.bitrate-=i)}n.push(e)}if(s){const t=navigator.userAgent;if(s.split(",").some((t=>yt(t)))&&Lt())return Promise.resolve(Ht(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${t})`),n))}return Promise.all(n.map((t=>{const e=function(t){let e="";const{audio:i,video:r}=t;if(r){e+=`${Ut(r.contentType)}_r${r.height}x${r.width}f${Math.ceil(r.framerate)}${r.transferFunction||"sd"}_${Math.ceil(r.bitrate/1e5)}`}if(i){e+=`${r?"_":""}${Ut(i.contentType)}_c${i.channels}`}return e}(t);return r[e]||(r[e]=i.decodingInfo(t))}))).then((t=>({supported:!t.some((t=>!t.supported)),configurations:n,decodingInfoResults:t}))).catch((t=>({supported:!1,configurations:n,decodingInfoResults:[],error:t})))}function Kt(t,e){if(e<=1)return 1;let i=128e3;return"ec-3"===t?i=768e3:"ac-3"===t&&(i=64e4),Math.min(e/2,i)}function Wt(t){return 1e3*Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)/1e3)||1}const Yt=["NONE","TYPE-0","TYPE-1",null];const qt=["SDR","PQ","HLG"];var zt="",Xt="YES",Qt="v2";function Zt(t){const{canSkipUntil:e,canSkipDateRanges:i,age:r}=t;return e&&r<e/2?i?Qt:Xt:zt}class Jt{constructor(t,e,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=e,this.skip=i}addDirectives(t){const e=new self.URL(t);return void 0!==this.msn&&e.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&e.searchParams.set("_HLS_part",this.part.toString()),this.skip&&e.searchParams.set("_HLS_skip",this.skip),e.href}}class te{constructor(t){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[t.url],this._attrs=[t.attrs],this.bitrate=t.bitrate,t.details&&(this.details=t.details),this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.frameRate=t.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=t.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,this.codecSet=[t.videoCodec,t.audioCodec].filter((t=>!!t)).map((t=>t.substring(0,4))).join(","),"supplemental"in t){var e;this.supplemental=t.supplemental;const i=null==(e=t.supplemental)?void 0:e.videoCodec;i&&i!==t.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(t){return ee(this._audioGroups,t)}hasSubtitleGroup(t){return ee(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,e){if(e)if("audio"===t){let t=this._audioGroups;t||(t=this._audioGroups=[]),-1===t.indexOf(e)&&t.push(e)}else if("text"===t){let t=this._subtitleGroups;t||(t=this._subtitleGroups=[]),-1===t.indexOf(e)&&t.push(e)}}get urlId(){return 0}set urlId(t){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var t;return null==(t=this.audioGroups)?void 0:t[0]}get textGroupId(){var t;return null==(t=this.subtitleGroups)?void 0:t[0]}addFallback(){}}function ee(t,e){return!(!e||!t)&&-1!==t.indexOf(e)}function ie(t,e){let i=!1,r=[];if(t&&(i="SDR"!==t,r=[t]),e){r=e.allowedVideoRanges||qt.slice(0);const t="SDR"!==r.join("")&&!e.videoCodec;i=void 0!==e.preferHDR?e.preferHDR:t&&function(){if("function"==typeof matchMedia){const t=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(t.media!==e.media)return!0===t.matches}return!1}(),i||(r=["SDR"])}return{preferHDR:i,allowedVideoRanges:r}}const re=(t,e)=>JSON.stringify(t,(t=>{const e=new WeakSet;return(i,r)=>{if(t&&(r=t(i,r)),"object"==typeof r&&null!==r){if(e.has(r))return;e.add(r)}return r}})(e));function se(t,e){_.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function ne(t){return t.reduce(((t,e)=>{let i=t.groups[e.groupId];i||(i=t.groups[e.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(e);const r=e.channels||"2";return i.channels[r]=(i.channels[r]||0)+1,i.hasDefault=i.hasDefault||e.default,i.hasAutoSelect=i.hasAutoSelect||e.autoselect,i.hasDefault&&(t.hasDefaultAudio=!0),i.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function ae(t){if(!t)return t;const{lang:e,assocLang:i,characteristics:r,channels:s,audioCodec:n}=t;return{lang:e,assocLang:i,characteristics:r,channels:s,audioCodec:n}}function oe(t,e,i){if("attrs"in t){const i=e.indexOf(t);if(-1!==i)return i}for(let r=0;r<e.length;r++){if(le(t,e[r],i))return r}return-1}function le(t,e,i){const{groupId:r,name:s,lang:n,assocLang:a,default:o}=t,l=t.forced;return(void 0===r||e.groupId===r)&&(void 0===s||e.name===s)&&(void 0===n||function(t,e="--"){if(t.length===e.length)return t===e;return t.startsWith(e)||e.startsWith(t)}(n,e.lang))&&(void 0===n||e.assocLang===a)&&(void 0===o||e.default===o)&&(void 0===l||e.forced===l)&&(!("characteristics"in t)||function(t,e=""){const i=t.split(","),r=e.split(",");return i.length===r.length&&!i.some((t=>-1===r.indexOf(t)))}(t.characteristics||"",e.characteristics))&&(void 0===i||i(t,e))}function ue(t,e){const{audioCodec:i,channels:r}=t;return!(void 0!==i&&(e.audioCodec||"").substring(0,4)!==i.substring(0,4)||void 0!==r&&r!==(e.channels||"2"))}function ce(t,e,i){for(let r=e;r>-1;r--)if(i(t[r]))return r;for(let r=e+1;r<t.length;r++)if(i(t[r]))return r;return-1}function de(t,e){var i;return!!t&&t!==(null==(i=e.loadLevelObj)?void 0:i.uri)}const he=function(t,e){let i=0,r=t.length-1,s=null,n=null;for(;i<=r;){s=(i+r)/2|0,n=t[s];const a=e(n);if(a>0)i=s+1;else{if(!(a<0))return n;r=s-1}}return null};function fe(t,e,i=0,r=0,s=.005){let n=null;if(t){n=e[1+t.sn-e[0].sn]||null;const r=t.endDTS-i;r>0&&r<15e-7&&(i+=15e-7),n&&t.level!==n.level&&n.end<=t.end&&(n=e[2+t.sn-e[0].sn]||null)}else 0===i&&0===e[0].start&&(n=e[0]);if(n&&((!t||t.level===n.level)&&0===ge(i,r,n)||function(t,e,i){if(e&&0===e.start&&e.level<t.level&&(e.endPTS||0)>0){const r=e.tagList.reduce(((t,e)=>("INF"===e[0]&&(t+=parseFloat(e[1])),t)),i);return t.start<=r}return!1}(n,t,Math.min(s,r))))return n;const a=he(e,ge.bind(null,i,r));return!a||a===t&&n?n:a}function ge(t=0,e=0,i){if(i.start<=t&&i.start+i.duration>t)return 0;const r=Math.min(e,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-r<=t?1:i.start-r>t&&i.start?-1:0}function me(t,e,i){const r=1e3*Math.min(e,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-r>t}function pe(t,e,i){if(t&&t.startCC<=e&&t.endCC>=e){let r=t.fragments;const{fragmentHint:s}=t;let n;return s&&(r=r.concat(s)),he(r,(t=>t.cc<e?1:t.cc>e?-1:(n=t,t.end<=i?1:t.start>i?-1:0))),n||null}return null}function ve(t){switch(t.details){case o.FRAG_LOAD_TIMEOUT:case o.KEY_LOAD_TIMEOUT:case o.LEVEL_LOAD_TIMEOUT:case o.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function ye(t){return t.details.startsWith("key")}function Ee(t){return ye(t)&&!!t.frag&&!t.frag.decryptdata}function Te(t,e){const i=ve(e);return t.default[(i?"timeout":"error")+"Retry"]}function be(t,e){const i="linear"===t.backoff?1:Math.pow(2,e);return Math.min(i*t.retryDelayMs,t.maxRetryDelayMs)}function Se(t){return b(b({},t),{errorRetry:null,timeoutRetry:null})}function Ae(t,e,i,r){if(!t)return!1;const s=null==r?void 0:r.code,n=e<t.maxNumRetry&&(function(t){return Le(t)||!!t&&(t<400||t>499)}(s)||!!i);return t.shouldRetry?t.shouldRetry(t,e,i,r,n):n}function Le(t){return 0===t&&!1===navigator.onLine}var ke=0,Re=2,Ie=3,_e=5,we=0,Pe=1,De=2,Ce=4;function Oe(t){const e={action:ke,flags:we};return t&&(e.resolved=!0),e}var xe="NOT_LOADED",Me="APPENDING",Fe="PARTIAL",Ne="OK";class Be{constructor(t){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=t,this._registerListeners()}_registerListeners(){const{hls:t}=this;t&&(t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.BUFFER_APPENDED,this.onBufferAppended,this),t.on(l.FRAG_BUFFERED,this.onFragBuffered,this),t.on(l.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.BUFFER_APPENDED,this.onBufferAppended,this),t.off(l.FRAG_BUFFERED,this.onFragBuffered,this),t.off(l.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(t,e){const i=this.activePartLists[e];if(i)for(let e=i.length;e--;){const r=i[e];if(!r)break;if(r.start<=t&&t<=r.end&&r.loaded)return r}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){return this.getFragAtPos(t,e,!0)}getFragAtPos(t,e,i){const{fragments:r}=this,s=Object.keys(r);for(let n=s.length;n--;){const a=r[s[n]];if((null==a?void 0:a.body.type)===e&&(!i||a.buffered)){const e=a.body;if(e.start<=t&&t<=e.end)return e}}return null}detectEvictedFragments(t,e,i,r,s){this.timeRanges&&(this.timeRanges[t]=e);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||s))return void(a.body.type===i&&this.removeFragment(a.body));const o=a.range[t];o&&(0!==o.time.length?o.time.some((t=>{const i=!this.isTimeBuffered(t.startPTS,t.endPTS,e);return i&&this.removeFragment(a.body),i})):this.removeFragment(a.body))}))}detectPartialFragments(t){const e=this.timeRanges;if(!e||"initSegment"===t.frag.sn)return;const i=t.frag,r=$e(i),s=this.fragments[r];if(!s||s.buffered&&i.gap)return;const n=!i.relurl;Object.keys(e).forEach((r=>{const a=i.elementaryStreams[r];if(!a)return;const o=e[r],l=n||!0===a.partial;s.range[r]=this.getBufferedTimes(i,t.part,l,o)})),s.loaded=null,Object.keys(s.range).length?(this.bufferedEnd(s,i),Ue(s)||this.removeParts(i.sn-1,i.type)):this.removeFragment(s.body)}bufferedEnd(t,e){t.buffered=!0;(t.body.endList=e.endList||t.body.endList)&&(this.endListFragments[t.body.type]=t)}removeParts(t,e){const i=this.activePartLists[e];i&&(this.activePartLists[e]=Ge(i,(e=>e.fragment.sn>=t)))}fragBuffered(t,e){const i=$e(t);let r=this.fragments[i];!r&&e&&(r=this.fragments[i]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,this.bufferedEnd(r,t))}getBufferedTimes(t,e,i,r){const s={time:[],partial:i},n=t.start,a=t.end,o=t.minEndPTS||a,l=t.maxStartPTS||n;for(let t=0;t<r.length;t++){const e=r.start(t)-this.bufferPadding,i=r.end(t)+this.bufferPadding;if(l>=e&&o<=i){s.time.push({startPTS:Math.max(n,r.start(t)),endPTS:Math.min(a,r.end(t))});break}if(n<i&&a>e){const e=Math.max(n,r.start(t)),i=Math.min(a,r.end(t));i>e&&(s.partial=!0,s.time.push({startPTS:e,endPTS:i}))}else if(a<=e)break}return s}getPartialFragment(t){let e,i,r,s=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach((l=>{const u=o[l];u&&Ue(u)&&(i=u.body.start-a,r=u.body.end+a,t>=i&&t<=r&&(e=Math.min(t-i,r-t),n<=e&&(s=u.body,n=e)))})),s}isEndListAppended(t){const e=this.endListFragments[t];return void 0!==e&&(e.buffered||Ue(e))}getState(t){const e=$e(t),i=this.fragments[e];return i?i.buffered?Ue(i)?Fe:Ne:Me:xe}isTimeBuffered(t,e,i){let r,s;for(let n=0;n<i.length;n++){if(r=i.start(n)-this.bufferPadding,s=i.end(n)+this.bufferPadding,t>=r&&e<=s)return!0;if(e<=r)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(t,e){if("initSegment"===e.frag.sn||e.frag.bitrateTest)return;const i=e.frag,r=e.part?null:e,s=$e(i);this.fragments[s]={body:i,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:i,part:r,timeRanges:s,type:n}=e;if("initSegment"===i.sn)return;const a=i.type;if(r){let t=this.activePartLists[a];t||(this.activePartLists[a]=t=[]),t.push(r)}this.timeRanges=s;const o=s[n];this.detectEvictedFragments(n,o,a,r)}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=$e(t);return!!this.fragments[e]}hasFragments(t){const{fragments:e}=this,i=Object.keys(e);if(!t)return i.length>0;for(let r=i.length;r--;){const s=e[i[r]];if((null==s?void 0:s.body.type)===t)return!0}return!1}hasParts(t){var e;return!(null==(e=this.activePartLists[t])||!e.length)}removeFragmentsInRange(t,e,i,r,s){r&&!this.hasGaps||Object.keys(this.fragments).forEach((n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==i||r&&!o.gap||o.start<e&&o.end>t&&(a.buffered||s)&&this.removeFragment(o)}))}removeFragment(t){const e=$e(t);t.clearElementaryStreamInfo();const i=this.activePartLists[t.type];if(i){const e=t.sn;this.activePartLists[t.type]=Ge(i,(t=>t.fragment.sn!==e))}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){var t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const e=null==(t=this.hls)||null==(t=t.latestLevelDetails)?void 0:t.partList;e&&e.forEach((t=>t.clearElementaryStreamInfo()))}}function Ue(t){var e,i,r;return t.buffered&&!!(t.body.gap||null!=(e=t.range.video)&&e.partial||null!=(i=t.range.audio)&&i.partial||null!=(r=t.range.audiovideo)&&r.partial)}function $e(t){return`${t.type}_${t.level}_${t.sn}`}function Ge(t,e){return t.filter((t=>{const i=e(t);return i||t.clearElementaryStreamInfo(),i}))}var He=0,Ve=1;class je{constructor(t,e,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=e,this.aesMode=i}decrypt(t,e){switch(this.aesMode){case He:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t);case Ve:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},e,t);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}class Ke{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(t){const e=new DataView(t),i=new Uint32Array(4);for(let t=0;t<4;t++)i[t]=e.getUint32(4*t);return i}initTable(){const t=this.sBox,e=this.invSBox,i=this.subMix,r=i[0],s=i[1],n=i[2],a=i[3],o=this.invSubMix,l=o[0],u=o[1],c=o[2],d=o[3],h=new Uint32Array(256);let f=0,g=0,m=0;for(m=0;m<256;m++)h[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){let i=g^g<<1^g<<2^g<<3^g<<4;i=i>>>8^255&i^99,t[f]=i,e[i]=f;const o=h[f],m=h[o],p=h[m];let v=257*h[i]^16843008*i;r[f]=v<<24|v>>>8,s[f]=v<<16|v>>>16,n[f]=v<<8|v>>>24,a[f]=v,v=16843009*p^65537*m^257*o^16843008*f,l[i]=v<<24|v>>>8,u[i]=v<<16|v>>>16,c[i]=v<<8|v>>>24,d[i]=v,f?(f=o^h[h[h[p^o]]],g^=h[h[g]]):f=g=1}}expandKey(t){const e=this.uint8ArrayToUint32Array_(t);let i=!0,r=0;for(;r<e.length&&i;)i=e[r]===this.key[r],r++;if(i)return;this.key=e;const s=this.keySize=e.length;if(4!==s&&6!==s&&8!==s)throw new Error("Invalid aes key size="+s);const n=this.ksRows=4*(s+6+1);let a,o;const l=this.keySchedule=new Uint32Array(n),u=this.invKeySchedule=new Uint32Array(n),c=this.sBox,d=this.rcon,h=this.invSubMix,f=h[0],g=h[1],m=h[2],p=h[3];let v,y;for(a=0;a<n;a++)a<s?v=l[a]=e[a]:(y=v,a%s==0?(y=y<<8|y>>>24,y=c[y>>>24]<<24|c[y>>>16&255]<<16|c[y>>>8&255]<<8|c[255&y],y^=d[a/s|0]<<24):s>6&&a%s==4&&(y=c[y>>>24]<<24|c[y>>>16&255]<<16|c[y>>>8&255]<<8|c[255&y]),l[a]=v=(l[a-s]^y)>>>0);for(o=0;o<n;o++)a=n-o,y=3&o?l[a]:l[a-4],u[o]=o<4||a<=4?y:f[c[y>>>24]]^g[c[y>>>16&255]]^m[c[y>>>8&255]]^p[c[255&y]],u[o]=u[o]>>>0}networkToHostOrderSwap(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24}decrypt(t,e,i){const r=this.keySize+6,s=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],u=a[2],c=a[3],d=this.uint8ArrayToUint32Array_(i);let h=d[0],f=d[1],g=d[2],m=d[3];const p=new Int32Array(t),v=new Int32Array(p.length);let y,E,T,b,S,A,L,k,R,I,_,w,P,D;const C=this.networkToHostOrderSwap;for(;e<p.length;){for(R=C(p[e]),I=C(p[e+1]),_=C(p[e+2]),w=C(p[e+3]),S=R^s[0],A=w^s[1],L=_^s[2],k=I^s[3],P=4,D=1;D<r;D++)y=o[S>>>24]^l[A>>16&255]^u[L>>8&255]^c[255&k]^s[P],E=o[A>>>24]^l[L>>16&255]^u[k>>8&255]^c[255&S]^s[P+1],T=o[L>>>24]^l[k>>16&255]^u[S>>8&255]^c[255&A]^s[P+2],b=o[k>>>24]^l[S>>16&255]^u[A>>8&255]^c[255&L]^s[P+3],S=y,A=E,L=T,k=b,P+=4;y=n[S>>>24]<<24^n[A>>16&255]<<16^n[L>>8&255]<<8^n[255&k]^s[P],E=n[A>>>24]<<24^n[L>>16&255]<<16^n[k>>8&255]<<8^n[255&S]^s[P+1],T=n[L>>>24]<<24^n[k>>16&255]<<16^n[S>>8&255]<<8^n[255&A]^s[P+2],b=n[k>>>24]<<24^n[S>>16&255]<<16^n[A>>8&255]<<8^n[255&L]^s[P+3],v[e]=C(y^h),v[e+1]=C(b^f),v[e+2]=C(T^g),v[e+3]=C(E^m),h=R,f=I,g=_,m=w,e+=4}return v.buffer}}class We{constructor(t,e,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=t,this.key=e,this.aesMode=i}expandKey(){const t=function(t){switch(t){case He:return"AES-CBC";case Ve:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${t}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:t},!1,["encrypt","decrypt"])}}class Ye{constructor(t,{removePKCS7Padding:e=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=t.enableSoftwareAES,this.removePKCS7Padding=e,e)try{const t=self.crypto;t&&(this.subtle=t.subtle||t.webkitSubtle)}catch(t){}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:t,remainderData:e}=this;if(!t||e)return this.reset(),null;const i=new Uint8Array(t);return this.reset(),this.removePKCS7Padding?function(t){const e=t.byteLength,i=e&&new DataView(t.buffer).getUint8(e-1);return i?t.slice(0,e-i):t}(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,e,i,r){return this.useSoftware?new Promise(((s,n)=>{const a=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(a,e,i,r);const o=this.flush();o?s(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(t),e,i,r)}softwareDecrypt(t,e,i,r){const{currentIV:s,currentResult:n,remainderData:a}=this;if(r!==He||16!==e.byteLength)return _.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(t=pt(a,t),this.remainderData=null);const o=this.getValidChunk(t);if(!o.length)return null;s&&(i=s);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Ke),l.expandKey(e);const u=n;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=o.slice(-16).buffer,u||null}webCryptoDecrypt(t,e,i,r){if(this.key!==e||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,e,i,r));this.key=e,this.fastAesKey=new We(this.subtle,e,r)}return this.fastAesKey.expandKey().then((e=>{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new je(this.subtle,new Uint8Array(i),r).decrypt(t.buffer,e)})).catch((s=>(_.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${s.name}: ${s.message}`),this.onWebCryptoError(t,e,i,r))))}onWebCryptoError(t,e,i,r){const s=this.enableSoftwareAES;if(s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,i,r);const s=this.flush();if(s)return s.buffer}throw new Error("WebCrypto"+(s?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(t){let e=t;const i=t.length-t.length%16;return i!==t.length&&(e=t.slice(0,i),this.remainderData=t.slice(i)),e}logOnce(t){this.logEnabled&&(_.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const qe=Math.pow(2,17);class ze{constructor(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(t,e){const i=t.url;if(!i)return Promise.reject(new Ze({type:a.NETWORK_ERROR,details:o.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error("Fragment does not have a "+(i?"part list":"url")),networkDetails:null}));this.abort();const r=this.config,s=r.fLoader,n=r.loader;return new Promise(((l,u)=>{if(this.loader&&this.loader.destroy(),t.gap){if(t.tagList.some((t=>"GAP"===t[0])))return void u(Qe(t));t.gap=!1}const c=this.loader=s?new s(r):new n(r),d=Xe(t);t.loader=c;const h=Se(r.fragLoadPolicy.default),f={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?Infinity:qe};t.stats=c.stats;const g={onSuccess:(e,i,r,s)=>{this.resetLoader(t,c);let n=e.data;r.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),l({frag:t,part:null,payload:n,networkDetails:s})},onError:(e,r,s,n)=>{this.resetLoader(t,c),u(new Ze({type:a.NETWORK_ERROR,details:o.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:b({url:i,data:void 0},e),error:new Error(`HTTP Error ${e.code} ${e.text}`),networkDetails:s,stats:n}))},onAbort:(e,i,r)=>{this.resetLoader(t,c),u(new Ze({type:a.NETWORK_ERROR,details:o.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:r,stats:e}))},onTimeout:(e,i,r)=>{this.resetLoader(t,c),u(new Ze({type:a.NETWORK_ERROR,details:o.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${f.timeout}ms`),networkDetails:r,stats:e}))}};e&&(g.onProgress=(i,r,s,n)=>e({frag:t,part:null,payload:s,networkDetails:n})),c.load(d,f,g)}))}loadPart(t,e,i){this.abort();const r=this.config,s=r.fLoader,n=r.loader;return new Promise(((l,u)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap)return void u(Qe(t,e));const c=this.loader=s?new s(r):new n(r),d=Xe(t,e);t.loader=c;const h=Se(r.fragLoadPolicy.default),f={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:qe};e.stats=c.stats,c.load(d,f,{onSuccess:(r,s,n,a)=>{this.resetLoader(t,c),this.updateStatsFromPart(t,e);const o={frag:t,part:e,payload:r.data,networkDetails:a};i(o),l(o)},onError:(i,r,s,n)=>{this.resetLoader(t,c),u(new Ze({type:a.NETWORK_ERROR,details:o.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:b({url:d.url,data:void 0},i),error:new Error(`HTTP Error ${i.code} ${i.text}`),networkDetails:s,stats:n}))},onAbort:(i,r,s)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,c),u(new Ze({type:a.NETWORK_ERROR,details:o.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:s,stats:i}))},onTimeout:(i,r,s)=>{this.resetLoader(t,c),u(new Ze({type:a.NETWORK_ERROR,details:o.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${f.timeout}ms`),networkDetails:s,stats:i}))}})}))}updateStatsFromPart(t,e){const i=t.stats,r=e.stats,s=r.total;if(i.loaded+=r.loaded,s){const r=Math.round(t.duration/e.duration),n=Math.min(Math.round(i.loaded/s),r),a=(r-n)*Math.round(i.loaded/n);i.total=i.loaded+a}else i.total=Math.max(i.loaded,i.total);const n=i.loading,a=r.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()}}function Xe(t,e=null){const i=e||t,s={frag:t,part:e,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},n=i.byteRangeStartOffset,a=i.byteRangeEndOffset;if(r(n)&&r(a)){var o;let e=n,i=a;if("initSegment"===t.sn&&("AES-128"===(l=null==(o=t.decryptdata)?void 0:o.method)||"AES-256"===l)){const t=a-n;t%16&&(i=a+(16-t%16)),0!==n&&(s.resetIV=!0,e=n-16)}s.rangeStart=e,s.rangeEnd=i}var l;return s}function Qe(t,e){const i=new Error(`GAP ${t.gap?"tag":"attribute"} found`),r={type:a.MEDIA_ERROR,details:o.FRAG_GAP,fatal:!1,frag:t,error:i,networkDetails:null};return e&&(r.part=e),(e||t).stats.aborted=!0,new Ze(r)}class Ze extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class Je extends S{constructor(t,e){super(t,e),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(t){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class ti{constructor(t,e,i,r=0,s=-1,n=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=t,this.sn=e,this.id=i,this.size=r,this.part=s,this.partial=n}}const ei={length:0,start:()=>0,end:()=>0};class ii{static isBuffered(t,e){if(t){const i=ii.getBuffered(t);for(let t=i.length;t--;)if(e>=i.start(t)&&e<=i.end(t))return!0}return!1}static bufferedRanges(t){if(t){const e=ii.getBuffered(t);return ii.timeRangesToArray(e)}return[]}static timeRangesToArray(t){const e=[];for(let i=0;i<t.length;i++)e.push({start:t.start(i),end:t.end(i)});return e}static bufferInfo(t,e,i){if(t){const r=ii.bufferedRanges(t);if(r.length)return ii.bufferedInfo(r,e,i)}return{len:0,start:e,end:e,bufferedIndex:-1}}static bufferedInfo(t,e,i){e=Math.max(0,e),t.length>1&&t.sort(((t,e)=>t.start-e.start||e.end-t.end));let r=-1,s=[];if(i)for(let n=0;n<t.length;n++){e>=t[n].start&&e<=t[n].end&&(r=n);const a=s.length;if(a){const e=s[a-1].end;t[n].start-e<i?t[n].end>e&&(s[a-1].end=t[n].end):s.push(t[n])}else s.push(t[n])}else s=t;let n,a=0,o=e,l=e;for(let t=0;t<s.length;t++){const u=s[t].start,c=s[t].end;if(-1===r&&e>=u&&e<=c&&(r=t),e+i>=u&&e<c)o=u,l=c,a=l-e;else if(e+i<u){n=u;break}}return{len:a,start:o||0,end:l||0,nextStart:n,buffered:t,bufferedIndex:r}}static getBuffered(t){try{return t.buffered||ei}catch(t){return _.log("failed to get media.buffered",t),ei}}}const ri=/\{\$([a-zA-Z0-9-_]+)\}/g;function si(t){return ri.test(t)}function ni(t,e){if(null!==t.variableList||t.hasVariableRefs){const i=t.variableList;return e.replace(ri,(e=>{const r=e.substring(2,e.length-1),s=null==i?void 0:i[r];return void 0===s?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),e):s}))}return e}function ai(t,e,i){let r,s,n=t.variableList;if(n||(t.variableList=n={}),"QUERYPARAM"in e){r=e.QUERYPARAM;try{const t=new self.URL(i).searchParams;if(!t.has(r))throw new Error(`"${r}" does not match any query parameter in URI: "${i}"`);s=t.get(r)}catch(e){t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${e.message}`))}}else r=e.NAME,s=e.VALUE;r in n?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):n[r]=s||""}function oi(t,e,i){const r=e.IMPORT;if(i&&r in i){let e=t.variableList;e||(t.variableList=e={}),e[r]=i[r]}else t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`))}const li=/^(\d+)x(\d+)$/,ui=/(.+?)=(".*?"|.*?)(?:,|$)/g;class ci{constructor(t,e){"string"==typeof t&&(t=ci.parseAttrList(t,e)),E(this,t)}get clientAttrs(){return Object.keys(this).filter((t=>"X-"===t.substring(0,2)))}decimalInteger(t){const e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?Infinity:e}hexadecimalInteger(t){if(this[t]){let e=(this[t]||"0x").slice(2);e=(1&e.length?"0":"")+e;const i=new Uint8Array(e.length/2);for(let t=0;t<e.length/2;t++)i[t]=parseInt(e.slice(2*t,2*t+2),16);return i}return null}hexadecimalIntegerAsNumber(t){const e=parseInt(this[t],16);return e>Number.MAX_SAFE_INTEGER?Infinity:e}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,e){const i=this[t];return i?parseFloat(i):e}enumeratedString(t){return this[t]}enumeratedStringList(t,e){const i=this[t];return(i?i.split(/[ ,]+/):[]).reduce(((t,e)=>(t[e.toLowerCase()]=!0,t)),e)}bool(t){return"YES"===this[t]}decimalResolution(t){const e=li.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t,e){let i;const r={};for(ui.lastIndex=0;null!==(i=ui.exec(t));){const s=i[1].trim();let n=i[2];const a=0===n.indexOf('"')&&n.lastIndexOf('"')===n.length-1;let o=!1;if(a)n=n.slice(1,-1);else switch(s){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(e&&(a||o))n=ni(e,n);else if(!o&&!a)switch(s){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":_.warn(`${t}: attribute ${s} is missing quotes`)}r[s]=n}return r}}function di(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t||"SCTE35-CMD"===t}class hi{constructor(t,e,i=0){var s;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==e?void 0:e.tagAnchor)||null,this.tagOrder=null!=(s=null==e?void 0:e.tagOrder)?s:i,e){const i=e.attr;for(const e in i)if(Object.prototype.hasOwnProperty.call(t,e)&&t[e]!==i[e]){_.warn(`DATERANGE tag attribute: "${e}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=e;break}t=E(new ci({}),i,t)}if(this.attr=t,e?(this._startDate=e._startDate,this._cue=e._cue,this._endDate=e._endDate,this._dateAtEnd=e._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){const t=(null==e?void 0:e.endDate)||new Date(this.attr["END-DATE"]);r(t.getTime())&&(this._endDate=t)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const t=this._cue;return void 0===t?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):t}get startTime(){const{tagAnchor:t}=this;return null===t||null===t.programDateTime?(_.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${t}`),NaN):t.start+(this.startDate.getTime()-t.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const t=this._endDate||this._dateAtEnd;if(t)return t;const e=this.duration;return null!==e?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*e):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(r(t))return t}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&r(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}class fi{constructor(t){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t}reloaded(t){if(!t)return this.advanced=!0,void(this.updated=!0);const e=this.lastPartSn-t.lastPartSn,i=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!i||!!e||!this.live,this.advanced=this.endSN>t.endSN||e>0||0===e&&i>0,this.updated||this.advanced?this.misses=Math.floor(.6*t.misses):this.misses=t.misses+1}hasKey(t){return this.encryptedFragments.some((e=>{let i=e.decryptdata;return i||(e.setKeyFormat(t.keyFormat),i=e.decryptdata),!!i&&t.matches(i)}))}get hasProgramDateTime(){return!!this.fragments.length&&r(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const t=this.driftEndTime-this.driftStartTime;if(t>0){return 1e3*(this.driftEnd-this.driftStart)/t}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const t=this.partList;if(t){const e=this.lastPartIndex;if(-1!==e){for(let i=t.length;i--;)if(t[i].index>e)return t[i].index;return e}}return 0}get lastPartSn(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const t=this.partEnd-this.fragmentStart;return this.age>Math.max(t,this.totalduration)+this.levelTargetDuration}return!1}}function gi(t,e){return t.length===e.length&&!t.some(((t,i)=>t!==e[i]))}function mi(t,e){return!t&&!e||!(!t||!e)&&gi(t,e)}function pi(t){return"AES-128"===t||"AES-256"===t||"AES-256-CTR"===t}function vi(t){switch(t){case"AES-128":case"AES-256":return He;case"AES-256-CTR":return Ve;default:throw new Error(`invalid full segment method ${t}`)}}function yi(t){return Uint8Array.from(atob(t),(t=>t.charCodeAt(0)))}function Ei(t){return Uint8Array.from(unescape(encodeURIComponent(t)),(t=>t.charCodeAt(0)))}function Ti(t){const e=function(t,e,i){const r=t[e];t[e]=t[i],t[i]=r};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}function bi(t){const e=t.split(":");let i=null;if("data"===e[0]&&2===e.length){const t=e[1].split(";"),r=t[t.length-1].split(",");if(2===r.length){const e="base64"===r[0],s=r[1];e?(t.splice(-1,1),i=yi(s)):i=function(t){const e=Ei(t).subarray(0,16),i=new Uint8Array(16);return i.set(e,16-e.length),i}(s)}}return i}const Si="undefined"!=typeof self?self:void 0;var Ai={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Li="org.w3.clearkey",ki="com.apple.streamingkeydelivery",Ri="com.microsoft.playready",Ii="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function _i(t){switch(t){case ki:return Ai.FAIRPLAY;case Ri:return Ai.PLAYREADY;case Ii:return Ai.WIDEVINE;case Li:return Ai.CLEARKEY}}function wi(t){switch(t){case Ai.FAIRPLAY:return ki;case Ai.PLAYREADY:return Ri;case Ai.WIDEVINE:return Ii;case Ai.CLEARKEY:return Li}}function Pi(t){const{drmSystems:e,widevineLicenseUrl:i}=t,r=e?[Ai.FAIRPLAY,Ai.WIDEVINE,Ai.PLAYREADY,Ai.CLEARKEY].filter((t=>!!e[t])):[];return!r[Ai.WIDEVINE]&&i&&r.push(Ai.WIDEVINE),r}const Di=null!=Si&&null!=(Ci=Si.navigator)&&Ci.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var Ci;function Oi(t){const e=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),i=String.fromCharCode.apply(null,Array.from(e)),r=i.substring(i.indexOf("<"),i.length),s=(new DOMParser).parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(s){const t=s.childNodes[0]?s.childNodes[0].nodeValue:s.getAttribute("VALUE");if(t){const e=yi(t).subarray(0,16);return Ti(e),e}}return null}let xi={};class Mi{static clearKeyUriToKeyIdMap(){xi={}}static setKeyIdForUri(t,e){xi[t]=e}static addKeyIdForUri(t){const e=Object.keys(xi).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,e),xi[t]=i,i}constructor(t,e,i,r=[1],s=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=t,this.uri=e,this.keyFormat=i,this.keyFormatVersions=r,this.iv=s,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&!pi(t),null!=n&&n.startsWith("0x")&&(this.keyId=new Uint8Array(O(n)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&gi(t.keyFormatVersions,this.keyFormatVersions)&&mi(t.iv,this.iv)&&mi(t.keyId,this.keyId)}isSupported(){if(this.method){if(pi(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case ki:case Ii:case Ri:case Li:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(t,e){if(!this.encrypted||!this.uri)return null;if(pi(this.method)){let e=this.iv;e||("number"!=typeof t&&(_.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),e=function(t){const e=new Uint8Array(16);for(let i=12;i<16;i++)e[i]=t>>8*(15-i)&255;return e}(t));return new Mi(this.method,this.uri,"identity",this.keyFormatVersions,e)}if(this.keyId){const t=xi[this.uri];if(t&&!gi(this.keyId,t)&&Mi.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const i=bi(this.uri);if(i)switch(this.keyFormat){case Ii:if(this.pssh=i,!this.keyId){const t=function(t){const e=[];if(t instanceof ArrayBuffer){const i=t.byteLength;let r=0;for(;r+32<i;){const i=At(new DataView(t,r));e.push(i),r+=i.size}}return e}(i.buffer);if(t.length){var r;const e=t[0];this.keyId=null!=(r=e.kids)&&r.length?e.kids[0]:null}}this.keyId||(this.keyId=Fi(e));break;case Ri:{const t=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=St(t,0,i),this.keyId=Oi(i);break}default:{let t=i.subarray(0,16);if(16!==t.length){const e=new Uint8Array(16);e.set(t,16-t.length),t=e}this.keyId=t;break}}if(!this.keyId||16!==this.keyId.byteLength){let t;t=function(t){const e=null==t?void 0:t[Ii];if(e)return e.keyId;return null}(e),t||(t=Fi(e),t||(t=xi[this.uri])),t&&(this.keyId=t,Mi.setKeyIdForUri(this.uri,t))}return this}}function Fi(t){const e=null==t?void 0:t[Ri];if(e){const t=bi(e.uri);if(t)return Oi(t)}return null}const Ni=/#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,Bi=/#EXT-X-MEDIA:(.*)/g,Ui=/^#EXT(?:INF|-X-TARGETDURATION):/m,$i=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Gi=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 Hi{static findGroup(t,e){for(let i=0;i<t.length;i++){const r=t[i];if(r.id===e)return r}}static resolve(t,e){return H.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return Ui.test(t)}static parseMasterPlaylist(t,e){const i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:si(t)},r=[];if(Ni.lastIndex=0,!t.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let s;for(;null!=(s=Ni.exec(t));)if(s[1]){var n;const t=new ci(s[1],i),a=ni(i,s[2]),o={attrs:t,bitrate:t.decimalInteger("BANDWIDTH")||t.decimalInteger("AVERAGE-BANDWIDTH"),name:t.NAME,url:Hi.resolve(a,e)},l=t.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),Yi(t.CODECS,o);const u=t["SUPPLEMENTAL-CODECS"];u&&(o.supplemental={},Yi(u,o.supplemental)),null!=(n=o.unknownCodecs)&&n.length||r.push(o),i.levels.push(o)}else if(s[3]){const t=s[3],r=s[4];switch(t){case"SESSION-DATA":{const t=new ci(r,i),e=t["DATA-ID"];e&&(null===i.sessionData&&(i.sessionData={}),i.sessionData[e]=t);break}case"SESSION-KEY":{const t=Ki(r,e,i);t.encrypted&&t.isSupported()?(null===i.sessionKeys&&(i.sessionKeys=[]),i.sessionKeys.push(t)):_.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${r}"`);break}case"DEFINE":ai(i,new ci(r,i),e);break;case"CONTENT-STEERING":{const t=new ci(r,i);i.contentSteering={uri:Hi.resolve(t["SERVER-URI"],e),pathwayId:t["PATHWAY-ID"]||"."};break}case"START":i.startTimeOffset=Wi(r)}}const a=r.length>0&&r.length<i.levels.length;return i.levels=a?r:i.levels,0===i.levels.length&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(t,e,i){let r;const s={},n=i.levels,a={AUDIO:n.map((t=>({id:t.attrs.AUDIO,audioCodec:t.audioCodec}))),SUBTITLES:n.map((t=>({id:t.attrs.SUBTITLES,textCodec:t.textCodec}))),"CLOSED-CAPTIONS":[]};let o=0;for(Bi.lastIndex=0;null!==(r=Bi.exec(t));){const t=new ci(r[1],i),n=t.TYPE;if(n){const i=a[n],r=s[n]||[];s[n]=r;const l=t.LANGUAGE,u=t["ASSOC-LANGUAGE"],c=t.CHANNELS,d=t.CHARACTERISTICS,h=t["INSTREAM-ID"],f={attrs:t,bitrate:0,id:o++,groupId:t["GROUP-ID"]||"",name:t.NAME||l||"",type:n,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:l,url:t.URI?Hi.resolve(t.URI,e):""};if(u&&(f.assocLang=u),c&&(f.channels=c),d&&(f.characteristics=d),h&&(f.instreamId=h),null!=i&&i.length){const t=Hi.findGroup(i,f.groupId)||i[0];qi(f,t,"audioCodec"),qi(f,t,"textCodec")}r.push(f)}}return s}static parseLevelPlaylist(t,e,i,s,n,a){var o;const l={url:e},u=new fi(e),c=u.fragments,d=[];let h,f,g,m,p=null,v=0,y=0,T=0,b=0,S=0,A=null,L=new z(s,l),k=-1,R=!1,I=null;if($i.lastIndex=0,u.m3u8=t,u.hasVariableRefs=si(t),"#EXTM3U"!==(null==(o=$i.exec(t))?void 0:o[0]))return u.playlistParsingError=new Error("Missing format identifier #EXTM3U"),u;for(;null!==(h=$i.exec(t));){R&&(R=!1,L=new z(s,l),L.playlistOffset=T,L.setStart(T),L.sn=v,L.cc=b,S&&(L.bitrate=S),L.level=i,p&&(L.initSegment=p,p.rawProgramDateTime&&(L.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null),I&&(L.setByteRange(I),I=null)));const t=h[1];if(t){L.duration=parseFloat(t);const e=(" "+h[2]).slice(1);L.title=e||null,L.tagList.push(e?["INF",t,e]:["INF",t])}else if(h[3]){if(r(L.duration)){L.playlistOffset=T,L.setStart(T),g&&Qi(L,g,u),L.sn=v,L.level=i,L.cc=b,c.push(L);const t=(" "+h[3]).slice(1);L.relurl=ni(u,t),zi(L,A,d),A=L,T+=L.duration,v++,y=0,R=!0}}else{if(h=h[0].match(Gi),!h){_.warn("No matches on slow regex match for level playlist!");continue}for(f=1;f<h.length&&void 0===h[f];f++);const t=(" "+h[f]).slice(1),n=(" "+h[f+1]).slice(1),o=h[f+2]?(" "+h[f+2]).slice(1):null;switch(t){case"BYTERANGE":A?L.setByteRange(n,A):L.setByteRange(n);break;case"PROGRAM-DATE-TIME":L.rawProgramDateTime=n,L.tagList.push(["PROGRAM-DATE-TIME",n]),-1===k&&(k=c.length);break;case"PLAYLIST-TYPE":u.type&&Zi(u,t,h),u.type=n.toUpperCase();break;case"MEDIA-SEQUENCE":0!==u.startSN?Zi(u,t,h):c.length>0&&Ji(u,t,h),v=u.startSN=parseInt(n);break;case"SKIP":{u.skippedSegments&&Zi(u,t,h);const e=new ci(n,u),i=e.decimalInteger("SKIPPED-SEGMENTS");if(r(i)){u.skippedSegments+=i;for(let t=i;t--;)c.push(null);v+=i}const s=e.enumeratedString("RECENTLY-REMOVED-DATERANGES");s&&(u.recentlyRemovedDateranges=(u.recentlyRemovedDateranges||[]).concat(s.split("\t")));break}case"TARGETDURATION":0!==u.targetduration&&Zi(u,t,h),u.targetduration=Math.max(parseInt(n),1);break;case"VERSION":null!==u.version&&Zi(u,t,h),u.version=parseInt(n);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":u.live||Zi(u,t,h),u.live=!1;break;case"#":(n||o)&&L.tagList.push(o?[n,o]:[n]);break;case"DISCONTINUITY":b++,L.tagList.push(["DIS"]);break;case"GAP":L.gap=!0,L.tagList.push([t]);break;case"BITRATE":L.tagList.push([t,n]),S=1e3*parseInt(n),r(S)?L.bitrate=S:S=0;break;case"DATERANGE":{const t=new ci(n,u),e=new hi(t,u.dateRanges[t.ID],u.dateRangeTagCount);u.dateRangeTagCount++,e.isValid||u.skippedSegments?u.dateRanges[e.id]=e:_.warn(`Ignoring invalid DATERANGE tag: "${n}"`),L.tagList.push(["EXT-X-DATERANGE",n]);break}case"DEFINE":{const t=new ci(n,u);"IMPORT"in t?oi(u,t,a):ai(u,t,e)}break;case"DISCONTINUITY-SEQUENCE":0!==u.startCC?Zi(u,t,h):c.length>0&&Ji(u,t,h),u.startCC=b=parseInt(n);break;case"KEY":{const t=Ki(n,e,u);if(t.isSupported()){if("NONE"===t.method){g=void 0;break}g||(g={});const e=g[t.keyFormat];null!=e&&e.matches(t)||(e&&(g=E({},g)),g[t.keyFormat]=t)}else _.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${n}"`);break}case"START":u.startTimeOffset=Wi(n);break;case"MAP":{const t=new ci(n,u);if(L.duration){const e=new z(s,l);Xi(e,t,i,g),p=e,L.initSegment=p,p.rawProgramDateTime&&!L.rawProgramDateTime&&(L.rawProgramDateTime=p.rawProgramDateTime)}else{const e=L.byteRangeEndOffset;if(e){const t=L.byteRangeStartOffset;I=`${e-t}@${t}`}else I=null;Xi(L,t,i,g),p=L,R=!0}p.cc=b;break}case"SERVER-CONTROL":m&&Zi(u,t,h),m=new ci(n),u.canBlockReload=m.bool("CAN-BLOCK-RELOAD"),u.canSkipUntil=m.optionalFloat("CAN-SKIP-UNTIL",0),u.canSkipDateRanges=u.canSkipUntil>0&&m.bool("CAN-SKIP-DATERANGES"),u.partHoldBack=m.optionalFloat("PART-HOLD-BACK",0),u.holdBack=m.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{u.partTarget&&Zi(u,t,h);const e=new ci(n);u.partTarget=e.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=u.partList;t||(t=u.partList=[]);const e=y>0?t[t.length-1]:void 0,i=y++,r=new ci(n,u),s=new X(r,L,l,i,e);t.push(s),L.duration+=s.duration;break}case"PRELOAD-HINT":{const t=new ci(n,u);u.preloadHint=t;break}case"RENDITION-REPORT":{const t=new ci(n,u);u.renditionReports=u.renditionReports||[],u.renditionReports.push(t);break}default:_.warn(`line parsed but not handled: ${h}`)}}}A&&!A.relurl?(c.pop(),T-=A.duration,u.partList&&(u.fragmentHint=A)):u.partList&&(zi(L,A,d),L.cc=b,u.fragmentHint=L,g&&Qi(L,g,u)),u.targetduration||(u.playlistParsingError=new Error("Missing Target Duration"));const w=c.length,P=c[0],D=c[w-1];if(T+=u.skippedSegments*u.targetduration,T>0&&w&&D){u.averagetargetduration=T/w;const t=D.sn;u.endSN="initSegment"!==t?t:0,u.live||(D.endList=!0),k>0&&(!function(t,e){let i=t[e];for(let r=e;r--;){const e=t[r];if(!e)return;e.programDateTime=i.programDateTime-1e3*e.duration,i=e}}(c,k),P&&d.unshift(P))}return u.fragmentHint&&(T+=u.fragmentHint.duration),u.totalduration=T,d.length&&u.dateRangeTagCount&&P&&Vi(d,u),u.endCC=b,u}}function Vi(t,e){let i=t.length;if(!i){if(!e.hasProgramDateTime)return;{const r=e.fragments[e.fragments.length-1];t.push(r),i++}}const r=t[i-1],s=e.live?Infinity:e.totalduration,n=Object.keys(e.dateRanges);for(let o=n.length;o--;){const l=e.dateRanges[n[o]],u=l.startDate.getTime();l.tagAnchor=r.ref;for(let r=i;r--;){var a;if((null==(a=t[r])?void 0:a.sn)<e.startSN)break;const i=ji(e,u,t,r,s);if(-1!==i){l.tagAnchor=e.fragments[i].ref;break}}}}function ji(t,e,i,r,s){const n=i[r];if(n){const o=n.programDateTime;if(e>=o||0===r){var a;if(e<=o+1e3*(((null==(a=i[r+1])?void 0:a.start)||s)-n.start)){const s=i[r].sn-t.startSN;if(s<0)return-1;const n=t.fragments;if(n.length>i.length){for(let a=(i[r+1]||n[n.length-1]).sn-t.startSN;a>s;a--){const t=n[a].programDateTime;if(e>=t&&e<t+1e3*n[a].duration)return a}}return s}}}return-1}function Ki(t,e,i){var r,s;const n=new ci(t,i),a=null!=(r=n.METHOD)?r:"",o=n.URI,l=n.hexadecimalInteger("IV"),u=n.KEYFORMATVERSIONS,c=null!=(s=n.KEYFORMAT)?s:"identity";o&&n.IV&&!l&&_.error(`Invalid IV: ${n.IV}`);const d=o?Hi.resolve(o,e):"",h=(u||"1").split("/").map(Number).filter(Number.isFinite);return new Mi(a,d,c,h,l,n.KEYID)}function Wi(t){const e=new ci(t).decimalFloatingPoint("TIME-OFFSET");return r(e)?e:null}function Yi(t,e){let i=(t||"").split(/[ ,]+/).filter((t=>t));["video","audio","text"].forEach((t=>{const r=i.filter((e=>Rt(e,t)));r.length&&(e[`${t}Codec`]=r.map((t=>t.split("/")[0])).join(","),i=i.filter((t=>-1===r.indexOf(t))))})),e.unknownCodecs=i}function qi(t,e,i){const r=e[i];r&&(t[i]=r)}function zi(t,e,i){t.rawProgramDateTime?i.push(t):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime)}function Xi(t,e,i,r){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=i,t.sn="initSegment",r&&(t.levelkeys=r),t.initSegment=null}function Qi(t,e,i){t.levelkeys=e;const{encryptedFragments:r}=i;r.length&&r[r.length-1].levelkeys===e||!Object.keys(e).some((t=>e[t].isCommonEncryption))||r.push(t)}function Zi(t,e,i){t.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${i[0]})`)}function Ji(t,e,i){t.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${i[0]})`)}function tr(t,e){const i=e.startPTS;if(r(i)){let r,s=0;e.sn>t.sn?(s=i-t.start,r=t):(s=t.start-i,r=e),r.duration!==s&&r.setDuration(s)}else if(e.sn>t.sn){t.cc===e.cc&&t.minEndPTS?e.setStart(t.start+(t.minEndPTS-t.start)):e.setStart(t.start+t.duration)}else e.setStart(Math.max(t.start-e.duration,0))}function er(t,e,i,s,n,a,o){s-i<=0&&(o.warn("Fragment should have a positive duration",e),s=i+e.duration,a=n+e.duration);let l=i,u=s;const c=e.startPTS,d=e.endPTS;if(r(c)){const h=Math.abs(c-i);t&&h>t.totalduration?o.warn(`media timestamps and playlist times differ by ${h}s for level ${e.level} ${t.url}`):r(e.deltaPTS)?e.deltaPTS=Math.max(h,e.deltaPTS):e.deltaPTS=h,l=Math.max(i,c),i=Math.min(i,c),n=void 0!==e.startDTS?Math.min(n,e.startDTS):n,u=Math.min(s,d),s=Math.max(s,d),a=void 0!==e.endDTS?Math.max(a,e.endDTS):a}const h=i-e.start;0!==e.start&&e.setStart(i),e.setDuration(s-e.start),e.startPTS=i,e.maxStartPTS=l,e.startDTS=n,e.endPTS=s,e.minEndPTS=u,e.endDTS=a;const f=e.sn;if(!t||f<t.startSN||f>t.endSN)return 0;let g;const m=f-t.startSN,p=t.fragments;for(p[m]=e,g=m;g>0;g--)tr(p[g],p[g-1]);for(g=m;g<p.length-1;g++)tr(p[g],p[g+1]);return t.fragmentHint&&tr(p[p.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,h}function ir(t,e,i){if(t===e)return;let s=null;const n=t.fragments;for(let t=n.length-1;t>=0;t--){const e=n[t].initSegment;if(e){s=e;break}}let a;t.fragmentHint&&delete t.fragmentHint.endPTS,function(t,e,i){const r=e.skippedSegments,s=Math.max(t.startSN,e.startSN)-e.startSN,n=(t.fragmentHint?1:0)+(r?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,a=e.startSN-t.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments;for(let u=s;u<=n;u++){const s=l[a+u];let n=o[u];if(r&&!n&&s&&(n=e.fragments[u]=s),s&&n){i(s,n,u,o);const r=s.relurl,a=n.relurl;if(r&&dr(r,a))return void(e.playlistParsingError=rr(`media sequence mismatch ${n.sn}:`,t,e,s,n));if(s.cc!==n.cc)return void(e.playlistParsingError=rr(`discontinuity sequence mismatch (${s.cc}!=${n.cc})`,t,e,s,n))}}}(t,e,((t,i,n,o)=>{if((!e.startCC||e.skippedSegments)&&i.cc!==t.cc){const r=t.cc-i.cc;for(let t=n;t<o.length;t++)o[t].cc+=r;e.endCC=o[o.length-1].cc}r(t.startPTS)&&r(t.endPTS)&&(i.setStart(i.startPTS=t.startPTS),i.startDTS=t.startDTS,i.maxStartPTS=t.maxStartPTS,i.endPTS=t.endPTS,i.endDTS=t.endDTS,i.minEndPTS=t.minEndPTS,i.setDuration(t.endPTS-t.startPTS),i.duration&&(a=i),e.PTSKnown=e.alignedSliding=!0),t.hasStreams&&(i.elementaryStreams=t.elementaryStreams),i.loader=t.loader,t.hasStats&&(i.stats=t.stats),t.initSegment&&(i.initSegment=t.initSegment,s=t.initSegment)}));const o=e.fragments,l=e.fragmentHint?o.concat(e.fragmentHint):o;if(s&&l.forEach((t=>{var e;!t||t.initSegment&&t.initSegment.relurl!==(null==(e=s)?void 0:e.relurl)||(t.initSegment=s)})),e.skippedSegments){if(e.deltaUpdateFailed=o.some((t=>!t)),e.deltaUpdateFailed){i.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let t=e.skippedSegments;t--;)o.shift();e.startSN=o[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=function(t,e,i){const{dateRanges:r,recentlyRemovedDateranges:s}=e,n=E({},t);s&&s.forEach((t=>{delete n[t]}));const a=Object.keys(n).length;if(!a)return r;return Object.keys(r).forEach((t=>{const e=n[t],s=new hi(r[t].attr,e);s.isValid?(n[t]=s,e||(s.tagOrder+=a)):i.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${re(r[t].attr)}"`)})),n}(t.dateRanges,e,i));const r=t.fragments.filter((t=>t.rawProgramDateTime));if(t.hasProgramDateTime&&!e.hasProgramDateTime)for(let t=1;t<l.length;t++)null===l[t].programDateTime&&zi(l[t],l[t-1],r);Vi(r,e)}e.endCC=o[o.length-1].cc}if(!e.startCC){var u;const i=or(t,e.startSN-1);e.startCC=null!=(u=null==i?void 0:i.cc)?u:o[0].cc}!function(t,e,i){if(t&&e){let r=0;for(let s=0,n=t.length;s<=n;s++){const n=t[s],a=e[s+r];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?i(n,a):r--}}}(t.partList,e.partList,((t,e)=>{e.elementaryStreams=t.elementaryStreams,e.stats=t.stats})),a?er(e,a,a.startPTS,a.endPTS,a.startDTS,a.endDTS,i):sr(t,e),o.length&&(e.totalduration=e.edge-o[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;const c=e.advancedDateTime;if(e.advanced&&c){const t=e.edge;e.driftStart||(e.driftStartTime=c,e.driftStart=t),e.driftEndTime=c,e.driftEnd=t}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime;-1===e.requestScheduled&&(e.requestScheduled=t.requestScheduled)}function rr(t,e,i,r,s){return new Error(`${t} ${s.url}\nPlaylist starting @${e.startSN}\n${e.m3u8}\n\nPlaylist starting @${i.startSN}\n${i.m3u8}`)}function sr(t,e,i=!0){const r=e.startSN+e.skippedSegments-t.startSN,s=t.fragments,n=r>=0;let a=0;if(n&&r<s.length)a=s[r].start;else if(n&&e.startSN===t.endSN+1)a=t.fragmentEnd;else if(n&&i)a=t.fragmentStart+r*e.levelTargetDuration;else{if(e.skippedSegments||0!==e.fragmentStart)return;a=t.fragmentStart}nr(e,a)}function nr(t,e){if(e){const i=t.fragments;for(let r=t.skippedSegments;r<i.length;r++)i[r].addStart(e);t.fragmentHint&&t.fragmentHint.addStart(e)}}function ar(t,e=Infinity){let i=1e3*t.targetduration;if(t.updated){const r=t.fragments,s=4;if(r.length&&i*s>e){const t=1e3*r[r.length-1].duration;t<i&&(i=t)}}else i/=2;return Math.round(i)}function or(t,e,i){if(!t)return null;let r=t.fragments[e-t.startSN];return r||(r=t.fragmentHint,r&&r.sn===e?r:e<t.startSN&&i&&i.sn===e?i:null)}function lr(t,e,i){return t?ur(t.partList,e,i):null}function ur(t,e,i){if(t)for(let r=t.length;r--;){const s=t[r];if(s.index===i&&s.fragment.sn===e)return s}return null}function cr(t){t.forEach(((t,e)=>{var i;null==(i=t.details)||i.fragments.forEach((t=>{t.level=e,t.initSegment&&(t.initSegment.level=e)}))}))}function dr(t,e){return!(t===e||!e)&&hr(t)!==hr(e)}function hr(t){return t.replace(/\?[^?]*$/,"")}function fr(t,e){for(let r=0,s=t.length;r<s;r++){var i;if((null==(i=t[r])?void 0:i.cc)===e)return t[r]}return null}function gr(t,e){const i=t.start+e;t.startPTS=i,t.setStart(i),t.endPTS=i+t.duration}function mr(t,e){const i=e.fragments;for(let e=0,r=i.length;e<r;e++)gr(i[e],t);e.fragmentHint&&gr(e.fragmentHint,t),e.alignedSliding=!0}function pr(t,e){if(!function(t,e){return!!(t&&e.startCC<t.endCC&&e.endCC>t.startCC)}(e,t))return;const i=Math.min(e.endCC,t.endCC),r=fr(e.fragments,i),s=fr(t.fragments,i);if(!r||!s)return;_.log(`Aligning playlist at start of dicontinuity sequence ${i}`);mr(r.start-s.start,t)}function vr(t,e){if(!t.hasProgramDateTime||!e.hasProgramDateTime)return;const i=t.fragments,r=e.fragments;if(!i.length||!r.length)return;let s,n;const a=Math.min(e.endCC,t.endCC);e.startCC<a&&t.startCC<a&&(s=fr(r,a),n=fr(i,a)),s&&n||(s=r[Math.floor(r.length/2)],n=fr(i,s.cc)||i[Math.floor(i.length/2)]);const o=s.programDateTime,l=n.programDateTime;if(!o||!l)return;mr((l-o)/1e3-(n.start-s.start),t)}function yr(t,e,i){Er(t,e,i),t.addEventListener(e,i)}function Er(t,e,i){t.removeEventListener(e,i)}const Tr=function(t){let e="";const i=t.length;for(let r=0;r<i;r++)e+=`[${t.start(r).toFixed(3)}-${t.end(r).toFixed(3)}]`;return e},br="STOPPED",Sr="IDLE",Ar="KEY_LOADING",Lr="FRAG_LOADING",kr="FRAG_LOADING_WAITING_RETRY",Rr="WAITING_TRACK",Ir="PARSING",_r="PARSED",wr="ENDED",Pr="ERROR",Dr="WAITING_INIT_PTS",Cr="WAITING_LEVEL";class Or extends Je{constructor(t,e,i,s,n){super(s,t.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=br,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:t,fragCurrent:e,media:i,mediaBuffer:s,state:n}=this,a=i?i.currentTime:0,o=ii.bufferInfo(s||i,a,t.maxBufferHole),l=!o.len;if(this.log(`Media seeking to ${r(a)?a.toFixed(3):a}, state: ${n}, ${l?"out of":"in"} buffer`),this.state===wr)this.resetLoadingState();else if(e){const i=t.maxFragLookUpTolerance,r=e.start-i,s=e.start+e.duration+i;if(l||s<o.start||r>o.end){const t=a>s;(a<r||t)&&(t&&e.loader&&(this.log(`Cancelling fragment load for seek (sn: ${e.sn})`),e.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(i){this.fragmentTracker.removeFragmentsInRange(a,Infinity,this.playlistType,!0);if(a>this.lastCurrentTime&&(this.lastCurrentTime=a),!this.loadingParts){const t=Math.max(o.end,a),e=this.shouldLoadParts(this.getLevelDetails(),t);e&&(this.log(`LL-Part loading ON after seeking to ${a.toFixed(2)} with buffer @${t.toFixed(2)}`),this.loadingParts=e)}}this.hls.hasEnoughToStart||(this.log(`Setting ${l?"startPosition":"nextLoadPosition"} to ${a} for seek without enough to start`),this.nextLoadPosition=a,l&&(this.startPosition=a)),l&&this.state===Sr&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=n,this.hls=t,this.fragmentLoader=new ze(t.config),this.keyLoader=i,this.fragmentTracker=e,this.config=t.config,this.decrypter=new Ye(t.config)}registerListeners(){const{hls:t}=this;t.on(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(l.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(l.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===br)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const t=this.fragCurrent;null!=t&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=br}get startPositionValue(){const{nextLoadPosition:t,startPosition:e}=this;return-1===e&&t?t:e}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(t,e){if(e.live||!this.media)return!1;const i=t.end||0,r=this.config.timelineOffset||0;if(i<=r)return!1;const s=t.buffered;this.config.maxBufferHole&&s&&s.length>1&&(t=ii.bufferedInfo(s,t.start,0));const n=t.nextStart;if(n&&n>r&&n<e.edge)return!1;if(this.media.currentTime<t.start)return!1;const a=e.partList;if(null!=a&&a.length){const t=a[a.length-1];return ii.isBuffered(this.media,t.start+t.duration/2)}const o=e.fragments[e.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(o)}getLevelDetails(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}get timelineOffset(){const t=this.config.timelineOffset;var e;return t?(null==(e=this.getLevelDetails())?void 0:e.appliedTimelineOffset)||t:0}onMediaAttached(t,e){const i=this.media=this.mediaBuffer=e.media;yr(i,"seeking",this.onMediaSeeking),yr(i,"ended",this.onMediaEnded);const r=this.config;this.levels&&r.autoStartLoad&&this.state===br&&this.startLoad(r.startPosition)}onMediaDetaching(t,e){const i=!!e.transferMedia,r=this.media;if(null!==r){if(r.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Er(r,"seeking",this.onMediaSeeking),Er(r,"ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(t,e){}onManifestLoaded(t,e){this.startTimeOffset=e.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=br,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(t,e,i){this.startFragRequested=!0,this._loadFragForPlayback(t,e,i)}_loadFragForPlayback(t,e,i){this._doFragLoad(t,e,i,(t=>{const e=t.frag;if(this.fragContextChanged(e))return this.warn(`${e.type} sn: ${e.sn}${t.part?" part: "+t.part.index:""} of ${this.fragInfo(e,!1,t.part)}) was dropped during download.`),void this.fragmentTracker.removeFragment(e);e.stats.chunkCount++,this._handleFragmentLoadProgress(t)})).then((t=>{if(!t)return;const e=this.state,i=t.frag;this.fragContextChanged(i)?(e===Lr||!this.fragCurrent&&e===Ir)&&(this.fragmentTracker.removeFragment(i),this.state=Sr):("payload"in t&&(this.log(`Loaded ${i.type} sn: ${i.sn} of ${this.playlistLabel()} ${i.level}`),this.hls.trigger(l.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t))})).catch((e=>{this.state!==br&&this.state!==Pr&&(this.warn(`Frag error: ${(null==e?void 0:e.message)||e}`),this.resetFragmentLoading(t))}))}clearTrackerIfNeeded(t){var e;const{fragmentTracker:i}=this;if(i.getState(t)===Me){const e=t.type,r=this.getFwdBufferInfo(this.mediaBuffer,e),s=Math.max(t.duration,r?r.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?t.sn-n.sn:0)||this.reduceMaxBufferLength(s,t.duration))&&i.removeFragment(t)}else 0===(null==(e=this.mediaBuffer)?void 0:e.buffered.length)?i.removeAllFragments():i.hasParts(t.type)&&(i.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),i.getState(t)===Fe&&i.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const e=t.fragments[t.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}waitForLive(t){const e=t.details;return(null==e?void 0:e.live)&&"EVENT"!==e.type&&(this.levelLastLoaded!==t||e.expired)}flushMainBuffer(t,e,i=null){if(!(t-e))return;const r={startOffset:t,endOffset:e,type:i};this.hls.trigger(l.BUFFER_FLUSHING,r)}_loadInitSegment(t,e){this._doFragLoad(t,e).then((t=>{const e=null==t?void 0:t.frag;if(!e||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return t})).then((t=>{const{hls:e}=this,{frag:i,payload:r}=t,s=i.decryptdata;if(r&&r.byteLength>0&&null!=s&&s.key&&s.iv&&pi(s.method)){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),s.key.buffer,s.iv.buffer,vi(s.method)).catch((t=>{throw e.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:i}),t})).then((r=>{const s=self.performance.now();return e.trigger(l.FRAG_DECRYPTED,{frag:i,payload:r,stats:{tstart:n,tdecrypt:s}}),t.payload=r,this.completeInitSegmentLoad(t)}))}return this.completeInitSegmentLoad(t)})).catch((e=>{this.state!==br&&this.state!==Pr&&(this.warn(e),this.resetFragmentLoading(t))}))}completeInitSegmentLoad(t){const{levels:e}=this;if(!e)throw new Error("init load aborted, missing levels");const i=t.frag.stats;this.state!==br&&(this.state=Sr),t.frag.data=new Uint8Array(t.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(t,e){var i,r;const s=t.tracks;if(s&&!e.encrypted&&(null!=(i=s.audio)&&i.encrypted||null!=(r=s.video)&&r.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const t=this.media,i=new Error(`Encrypted track with no key in ${this.fragInfo(e)} (media ${t?"attached mediaKeys: "+t.mediaKeys:"detached"})`);return this.warn(i.message),!t||t.mediaKeys?!1:(this.hls.trigger(l.ERROR,{type:a.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_NO_KEYS,fatal:!1,error:i,frag:e}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(t){const{fragCurrent:e}=this;return!t||!e||t.sn!==e.sn||t.level!==e.level}fragBufferedComplete(t,e){const i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)} > buffer:${i?Tr(ii.getBuffered(i)):"(detached)"})`),q(t)){var r;if(t.type!==m){const e=t.elementaryStreams;if(!Object.keys(e).some((t=>!!e[t])))return void(this.state=Sr)}const e=null==(r=this.levels)?void 0:r[t.level];null!=e&&e.fragmentError&&(this.log(`Resetting level fragment error count of ${e.fragmentError} on frag buffered`),e.fragmentError=0)}this.state=Sr}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const{frag:i,part:r,partsLoaded:s}=t,n=!s||0===s.length||s.some((t=>!t)),a=new ti(i.level,i.sn,i.stats.chunkCount+1,0,r?r.index:-1,!n);e.flush(a)}_handleFragmentLoadProgress(t){}_doFragLoad(t,e,i=null,s){var n;this.fragCurrent=t;const a=e.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;if(!t.encrypted||null!=(n=t.decryptdata)&&n.key)t.encrypted||(o=this.keyLoader.loadClear(t,a.encryptedFragments,this.startFragRequested),o&&this.log("[eme] blocking frag load until media-keys acquired"));else if(this.log(`Loading key for ${t.sn} of [${a.startSN}-${a.endSN}], ${this.playlistLabel()} ${t.level}`),this.state=Ar,this.fragCurrent=t,o=this.keyLoader.load(t).then((t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(l.KEY_LOADED,t),this.state===Ar&&(this.state=Sr),t})),this.hls.trigger(l.KEY_LOADING,{frag:t}),null===this.fragCurrent)return this.log("context changed in KEY_LOADING"),Promise.resolve(null);const u=this.fragPrevious;if(q(t)&&(!u||t.sn!==u.sn)){const i=this.shouldLoadParts(e.details,t.end);i!==this.loadingParts&&(this.log(`LL-Part loading ${i?"ON":"OFF"} loading sn ${null==u?void 0:u.sn}->${t.sn}`),this.loadingParts=i)}if(i=Math.max(t.start,i||0),this.loadingParts&&q(t)){const r=a.partList;if(r&&s){i>a.fragmentEnd&&a.fragmentHint&&(t=a.fragmentHint);const n=this.getNextPart(r,t,i);if(n>-1){const u=r[n];let c;return t=this.fragCurrent=u.fragment,this.log(`Loading ${t.type} sn: ${t.sn} part: ${u.index} (${n}/${r.length-1}) of ${this.fragInfo(t,!1,u)}) cc: ${t.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=u.start+u.duration,this.state=Lr,c=o?o.then((i=>!i||this.fragContextChanged(i.frag)?null:this.doFragPartsLoad(t,u,e,s))).catch((t=>this.handleFragLoadError(t))):this.doFragPartsLoad(t,u,e,s).catch((t=>this.handleFragLoadError(t))),this.hls.trigger(l.FRAG_LOADING,{frag:t,part:u,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):c}if(!t.url||this.loadedEndOfParts(r,i))return Promise.resolve(null)}}var c;if(q(t)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)} Check buffer at sn: ${t.sn} loaded parts: ${null==(c=a.partList)?void 0:c.filter((t=>t.loaded)).map((t=>`[${t.start}-${t.end}]`))}`),this.loadingParts=!1;else if(!t.url)return Promise.resolve(null);this.log(`Loading ${t.type} sn: ${t.sn} of ${this.fragInfo(t,!1)}) cc: ${t.cc} ${"["+a.startSN+"-"+a.endSN+"]"}, target: ${parseFloat(i.toFixed(3))}`),r(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=Lr;const d=this.config.progressive&&t.type!==m;let h;return h=d&&o?o.then((e=>!e||this.fragContextChanged(e.frag)?null:this.fragmentLoader.load(t,s))).catch((t=>this.handleFragLoadError(t))):Promise.all([this.fragmentLoader.load(t,d?s:void 0),o]).then((([t])=>(!d&&s&&s(t),t))).catch((t=>this.handleFragLoadError(t))),this.hls.trigger(l.FRAG_LOADING,{frag:t,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):h}doFragPartsLoad(t,e,i,r){return new Promise(((s,n)=>{var a;const o=[],u=null==(a=i.details)?void 0:a.partList,c=e=>{this.fragmentLoader.loadPart(t,e,r).then((r=>{o[e.index]=r;const n=r.part;this.hls.trigger(l.FRAG_LOADED,r);const a=lr(i.details,t.sn,e.index+1)||ur(u,t.sn,e.index+1);if(!a)return s({frag:t,part:n,partsLoaded:o});c(a)})).catch(n)};c(e)}))}handleFragLoadError(t){if("data"in t){const e=t.data;e.frag&&e.details===o.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):e.frag&&e.type===a.KEY_SYSTEM_ERROR?(e.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(e.frag)):this.hls.trigger(l.ERROR,e)}else this.hls.trigger(l.ERROR,{type:a.OTHER_ERROR,details:o.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==Ir)return void(this.fragCurrent||this.state===br||this.state===Pr||(this.state=Sr));const{frag:i,part:r,level:s}=e,n=self.performance.now();i.stats.parsing.end=n,r&&(r.stats.parsing.end=n);const a=this.getLevelDetails(),o=a&&i.sn>a.endSN||this.shouldLoadParts(a,i.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${i.end.toFixed(2)}`),this.loadingParts=o),this.updateLevelTiming(i,r,s,t.partial)}shouldLoadParts(t,e){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(t.partList){var i;const s=t.partList[0];if(s.fragment.type===m)return!1;if(e>=s.end+((null==(i=t.fragmentHint)?void 0:i.duration)||0)){var r;if((this.hls.hasEnoughToStart?(null==(r=this.media)?void 0:r.currentTime)||this.lastCurrentTime:this.getLoadPosition())>s.start-s.fragment.duration)return!0}}}return!1}getCurrentContext(t){const{levels:e,fragCurrent:i}=this,{level:r,sn:s,part:n}=t;if(null==e||!e[r])return this.warn(`Levels object was unset while buffering fragment ${s} of ${this.playlistLabel()} ${r}. The current chunk will not be buffered.`),null;const a=e[r],o=a.details,l=n>-1?lr(o,s,n):null,u=l?l.fragment:or(o,s,i);return u?(i&&i!==u&&(u.stats=i.stats),{frag:u,part:l,level:a}):null}bufferFragmentData(t,e,i,r,s){if(this.state!==Ir)return;const{data1:n,data2:a}=t;let o=n;if(a&&(o=pt(n,a)),!o.length)return;const u=this.initPTS[e.cc],c=u?-u.baseTime/u.timescale:void 0,d={type:t.type,frag:e,part:i,chunkMeta:r,offset:c,parent:e.type,data:o};if(this.hls.trigger(l.BUFFER_APPENDING,d),t.dropped&&t.independent&&!i){if(s)return;this.flushBufferGap(e)}}flushBufferGap(t){const e=this.media;if(!e)return;if(!ii.isBuffered(e,e.currentTime))return void this.flushMainBuffer(0,t.start);const i=e.currentTime,r=ii.bufferInfo(e,i,0),s=t.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*s),a=Math.max(Math.min(t.start-n,r.end-n),i+n);t.start-a>n&&this.flushMainBuffer(a,t.start)}getFwdBufferInfo(t,e){var i;const s=this.getLoadPosition();if(!r(s))return null;const n=this.lastCurrentTime>s||null!=(i=this.media)&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,s,e,n)}getFwdBufferInfoAtPos(t,e,i,r){const s=ii.bufferInfo(t,e,r);if(0===s.len&&void 0!==s.nextStart){const n=this.fragmentTracker.getBufferedFrag(e,i);if(n&&(s.nextStart<=n.end||n.gap)){const i=Math.max(Math.min(s.nextStart,n.end)-e,r);return ii.bufferInfo(t,e,i)}}return s}getMaxBufferLength(t){const{config:e}=this;let i;return i=t?Math.max(8*e.maxBufferSize/t,e.maxBufferLength):e.maxBufferLength,Math.min(i,e.maxMaxBufferLength)}reduceMaxBufferLength(t,e){const i=this.config,r=Math.max(Math.min(t-e,i.maxBufferLength),e),s=Math.max(t-3*e,i.maxMaxBufferLength/2,r);return s>=r&&(i.maxMaxBufferLength=s,this.warn(`Reduce max buffer length to ${s}s`),!0)}getAppendedFrag(t,e=f){const i=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(t,e):null;return i&&"fragment"in i?i.fragment:i}getNextFragment(t,e){const i=e.fragments,r=i.length;if(!r)return null;const{config:s}=this,n=i[0].start,a=s.lowLatencyMode&&!!e.partList;let o=null;if(e.live){const i=s.initialLiveManifestSize;if(r<i)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${i})`),null;if(!e.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||t<n){var l;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(e);const i=this.hls.startPosition,r=this.hls.liveSyncPosition,s=o?(-1!==i&&i>=n?i:r)||o.start:t;this.log(`Setting startPosition to ${s} to match start frag at live edge. mainStart: ${i} liveSyncPosition: ${r} frag.start: ${null==(l=o)?void 0:l.start}`),this.startPosition=this.nextLoadPosition=s}}else t<=n&&(o=i[0]);if(!o){const i=this.loadingParts?e.partEnd:e.fragmentEnd;o=this.getFragmentAtPosition(t,i,e)}let u=this.filterReplacedPrimary(o,e);if(!u&&o){const t=o.sn-e.startSN;u=this.filterReplacedPrimary(i[t+1]||null,e)}return this.mapToInitFragWhenRequired(u)}isLoopLoading(t,e){const i=this.fragmentTracker.getState(t);return(i===Ne||i===Fe&&!!t.gap)&&this.nextLoadPosition>e}getNextFragmentLoopLoading(t,e,i,r,s){let n=null;if(t.gap&&(n=this.getNextFragment(this.nextLoadPosition,e),n&&!n.gap&&i.nextStart)){const t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,r,0);if(null!==t&&i.len+t.len>=s){const t=n.sn;return this.loopSn!==t&&(this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${t}`),this.loopSn=t),null}}return this.loopSn=void 0,n}get primaryPrefetch(){if(xr(this.config)){var t;if(null==(t=this.hls.interstitialsManager)||null==(t=t.playingItem)?void 0:t.event)return!0}return!1}filterReplacedPrimary(t,e){if(!t)return t;if(xr(this.config)&&t.type!==m){const i=this.hls.interstitialsManager,r=null==i?void 0:i.bufferingItem;if(r){const i=r.event;if(i){if(i.appendInPlace||Math.abs(t.start-r.start)>1||0===r.start)return null}else{if(t.end<=r.start&&!1===(null==e?void 0:e.live))return null;if(t.start>r.end&&r.nextEvent&&(r.nextEvent.appendInPlace||t.start-r.end>1))return null}}const s=null==i?void 0:i.playerQueue;if(s)for(let e=s.length;e--;){const i=s[e].interstitial;if(i.appendInPlace&&t.start>=i.startTime&&t.end<=i.resumeTime)return null}}return t}mapToInitFragWhenRequired(t){return null==t||!t.initSegment||t.initSegment.data||this.bitrateTest?t:t.initSegment}getNextPart(t,e,i){let r=-1,s=!1,n=!0;for(let a=0,o=t.length;a<o;a++){const o=t[a];if(n=n&&!o.independent,r>-1&&i<o.start)break;const l=o.loaded;l?r=-1:(s||(o.independent||n)&&o.fragment===e)&&(o.fragment!==e&&this.warn(`Need buffer at ${i} but next unloaded part starts at ${o.start}`),r=a),s=l}return r}loadedEndOfParts(t,e){let i;for(let r=t.length;r--;){if(i=t[r],!i.loaded)return!1;if(e>i.start)return!0}return!1}getInitialLiveFragment(t){const e=t.fragments,i=this.fragPrevious;let s=null;if(i){if(t.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),s=function(t,e,i){if(null===e||!Array.isArray(t)||!t.length||!r(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;for(let r=0;r<t.length;++r){const s=t[r];if(me(e,i,s))return s}return null}(e,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!s){const r=i.sn+1;if(r>=t.startSN&&r<=t.endSN){const n=e[r-t.startSN];i.cc===n.cc&&(s=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}s||(s=pe(t,i.cc,i.end),s&&this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`))}}else{const e=this.hls.liveSyncPosition;null!==e&&(s=this.getFragmentAtPosition(e,this.bitrateTest?t.fragmentEnd:t.edge,t))}return s}getFragmentAtPosition(t,e,i){const{config:r}=this;let{fragPrevious:s}=this,{fragments:n,endSN:a}=i;const{fragmentHint:o}=i,{maxFragLookUpTolerance:l}=r,u=i.partList,c=!!(this.loadingParts&&null!=u&&u.length&&o);let d;if(c&&!this.bitrateTest&&u[u.length-1].fragment.sn===o.sn&&(n=n.concat(o),a=o.sn),t<e){var h;d=fe(s,n,t,t<this.lastCurrentTime||t>e-l||null!=(h=this.media)&&h.paused||!this.startFragRequested?0:l)}else d=n[n.length-1];if(d){const t=d.sn-i.startSN,e=this.fragmentTracker.getState(d);if((e===Ne||e===Fe&&d.gap)&&(s=d),s&&d.sn===s.sn&&(!c||u[0].fragment.sn>d.sn||!i.live)){if(d.level===s.level){const e=n[t+1];d=d.sn<a&&this.fragmentTracker.getState(e)!==Ne?e:null}}}return d}alignPlaylists(t,e,i){const s=t.fragments.length;if(!s)return this.warn("No fragments in live playlist"),0;const n=t.fragmentStart,a=!e,o=t.alignedSliding&&r(n);if(a||!o&&!n){!function(t,e){t&&(pr(e,t),e.alignedSliding||vr(e,t),e.alignedSliding||e.skippedSegments||sr(t,e,!1))}(i,t);const r=t.fragmentStart;return this.log(`Live playlist sliding: ${r.toFixed(2)} start-sn: ${e?e.startSN:"na"}->${t.startSN} fragments: ${s}`),r}return n}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)}setStartPosition(t,e){let i=this.startPosition;i<e&&(i=-1);const s=this.timelineOffset;if(-1===i){const n=null!==this.startTimeOffset,a=n?this.startTimeOffset:t.startTimeOffset;null!==a&&r(a)?(i=e+a,a<0&&(i+=t.edge),i=Math.min(Math.max(e,i),e+t.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${a} found in ${n?"multivariant":"media"} playlist`),this.startPosition=i):t.live?(i=this.hls.liveSyncPosition||e,this.log(`Setting startPosition to -1 to start at live edge ${i}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+s}this.nextLoadPosition=i+s}getLoadPosition(){var t;const{media:e}=this;let i=0;return null!=(t=this.hls)&&t.hasEnoughToStart&&e?i=e.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(t,e){this.transmuxer&&t.type===this.playlistType&&q(t)&&t.stats.aborted&&(this.log(`Fragment ${t.sn}${e?" part "+e.index:""} of ${this.playlistLabel()} ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){this.fragCurrent&&(this.fragContextChanged(t)||this.state===kr)||(this.state=Sr)}onFragmentOrKeyLoadError(t,e){var i;if(e.chunkMeta&&!e.frag){const t=this.getCurrentContext(e.chunkMeta);t&&(e.frag=t.frag)}const r=e.frag;if(!r||r.type!==t||!this.levels)return;var s;if(this.fragContextChanged(r))return void this.warn(`Frag load error must match current frag to retry ${r.url} > ${null==(s=this.fragCurrent)?void 0:s.url}`);const n=e.details===o.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(r,!0);const a=e.errorAction;if(!a)return void(this.state=Pr);const{action:l,flags:u,retryCount:c=0,retryConfig:d}=a,h=!!d,f=h&&l===_e,g=h&&!a.resolved&&u===Pe,m=null==(i=this.hls.latestLevelDetails)?void 0:i.live;if(!f&&g&&q(r)&&!r.endList&&m&&!Ee(e))this.resetFragmentErrors(t),this.treatAsGap(r),a.resolved=!0;else if((f||g)&&c<d.maxNumRetry){var p;const i=Le(null==(p=e.response)?void 0:p.code),s=be(d,c);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+s,this.state=kr,a.resolved=!0,i)return this.log("Waiting for connection (offline)"),this.retryDate=Infinity,void(e.reason="offline");this.warn(`Fragment ${r.sn} of ${t} ${r.level} errored with ${e.details}, retrying loading ${c+1}/${d.maxNumRetry} in ${s}ms`)}else if(d){if(this.resetFragmentErrors(t),!(c<d.maxNumRetry))return void this.warn(`${e.details} reached or exceeded max retry (${c})`);n||l===Ie||(a.resolved=!0)}else this.state=l===Re?Cr:Pr;this.tickImmediate()}checkRetryDate(){const t=self.performance.now(),e=this.retryDate,i=Infinity===e;(!e||t>=e||i&&!Le(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=Sr)}reduceLengthAndFlushBuffer(t){if(this.state===Ir||this.state===_r){const e=t.frag,i=t.parent,r=this.getFwdBufferInfo(this.mediaBuffer,i),s=r&&r.len>.5;s&&this.reduceMaxBufferLength(r.len,(null==e?void 0:e.duration)||10);const n=!s;return n&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${i} buffer`),e&&(this.fragmentTracker.removeFragment(e),this.nextLoadPosition=e.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(t){t===g&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==br&&(this.state=Sr)}afterBufferFlushed(t,e,i){if(!t)return;const r=ii.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,r,i),this.state===wr&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==br&&(this.state=Sr)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=this.levelLastLoaded,e=t?t.details:null;null!=e&&e.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(e,e.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.log(`Loading context changed while buffering sn ${t.sn} of ${this.playlistLabel()} ${-1===t.level?"<removed>":t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,Infinity,this.playlistType,!1,!0)}updateLevelTiming(t,e,i,r){const s=i.details;if(!s)return void this.warn("level.details undefined");if(!Object.keys(t.elementaryStreams).reduce(((e,n)=>{const a=t.elementaryStreams[n];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${t.sn} ${n} duration reliably (${o})`),e||!1;const u=r?0:er(s,t,a.startPTS,a.endPTS,a.startDTS,a.endDTS,this);return this.hls.trigger(l.LEVEL_PTS_UPDATED,{details:s,level:i,drift:u,type:n,frag:t,start:a.startPTS,end:a.endPTS}),!0}return e}),!1)){var n;const e=null===(null==(n=this.transmuxer)?void 0:n.error);if((0===i.fragmentError||e&&(i.fragmentError<2||t.endList))&&this.treatAsGap(t,i),e){const e=new Error(`Found no media in fragment ${t.sn} of ${this.playlistLabel()} ${t.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(e.message),this.hls.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.FRAG_PARSING_ERROR,fatal:!1,error:e,frag:t,reason:`Found no media in msn ${t.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=_r,this.log(`Parsed ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)})`),this.hls.trigger(l.FRAG_PARSED,{frag:t,part:e})}playlistLabel(){return this.playlistType===f?"level":"track"}fragInfo(t,e=!0,i){var r,s;return`${this.playlistLabel()} ${t.level} (${i?"part":"frag"}:[${(null!=(r=e&&!i?t.startPTS:(i||t).start)?r:NaN).toFixed(3)}-${(null!=(s=e&&!i?t.endPTS:(i||t).end)?s:NaN).toFixed(3)}]${i&&"main"===t.type?"INDEPENDENT="+(i.independent?"YES":"NO"):""}`}treatAsGap(t,e){e&&e.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)}resetTransmuxer(){var t;null==(t=this.transmuxer)||t.reset()}recoverWorkerError(t){"demuxerWorker"===t.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`))}get state(){return this._state}}function xr(t){return!!t.interstitialsController&&!1!==t.enableInterstitialPlayback}class Mr{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:e}=this;let i;return t.length?(i=1===t.length?t[0]:function(t,e){const i=new Uint8Array(e);let r=0;for(let e=0;e<t.length;e++){const s=t[e];i.set(s,r),r+=s.length}return i}(t,e),this.reset(),i):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}var Fr,Nr={exports:{}};var Br=(Fr||(Fr=1,function(t){var e=Object.prototype.hasOwnProperty,i="~";function r(){}function s(t,e,i){this.fn=t,this.context=e,this.once=i||!1}function n(t,e,r,n,a){if("function"!=typeof r)throw new TypeError("The listener must be a function");var o=new s(r,n||t,a),l=i?i+e:e;return t._events[l]?t._events[l].fn?t._events[l]=[t._events[l],o]:t._events[l].push(o):(t._events[l]=o,t._eventsCount++),t}function a(t,e){0==--t._eventsCount?t._events=new r:delete t._events[e]}function o(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(i=!1)),o.prototype.eventNames=function(){var t,r,s=[];if(0===this._eventsCount)return s;for(r in t=this._events)e.call(t,r)&&s.push(i?r.slice(1):r);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(t)):s},o.prototype.listeners=function(t){var e=i?i+t:t,r=this._events[e];if(!r)return[];if(r.fn)return[r.fn];for(var s=0,n=r.length,a=new Array(n);s<n;s++)a[s]=r[s].fn;return a},o.prototype.listenerCount=function(t){var e=i?i+t:t,r=this._events[e];return r?r.fn?1:r.length:0},o.prototype.emit=function(t,e,r,s,n,a){var o=i?i+t:t;if(!this._events[o])return!1;var l,u,c=this._events[o],d=arguments.length;if(c.fn){switch(c.once&&this.removeListener(t,c.fn,void 0,!0),d){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,r),!0;case 4:return c.fn.call(c.context,e,r,s),!0;case 5:return c.fn.call(c.context,e,r,s,n),!0;case 6:return c.fn.call(c.context,e,r,s,n,a),!0}for(u=1,l=new Array(d-1);u<d;u++)l[u-1]=arguments[u];c.fn.apply(c.context,l)}else{var h,f=c.length;for(u=0;u<f;u++)switch(c[u].once&&this.removeListener(t,c[u].fn,void 0,!0),d){case 1:c[u].fn.call(c[u].context);break;case 2:c[u].fn.call(c[u].context,e);break;case 3:c[u].fn.call(c[u].context,e,r);break;case 4:c[u].fn.call(c[u].context,e,r,s);break;default:if(!l)for(h=1,l=new Array(d-1);h<d;h++)l[h-1]=arguments[h];c[u].fn.apply(c[u].context,l)}}return!0},o.prototype.on=function(t,e,i){return n(this,t,e,i,!1)},o.prototype.once=function(t,e,i){return n(this,t,e,i,!0)},o.prototype.removeListener=function(t,e,r,s){var n=i?i+t:t;if(!this._events[n])return this;if(!e)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn!==e||s&&!o.once||r&&o.context!==r||a(this,n);else{for(var l=0,u=[],c=o.length;l<c;l++)(o[l].fn!==e||s&&!o[l].once||r&&o[l].context!==r)&&u.push(o[l]);u.length?this._events[n]=1===u.length?u[0]:u:a(this,n)}return this},o.prototype.removeAllListeners=function(t){var e;return t?(e=i?i+t:t,this._events[e]&&a(this,e)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=i,o.EventEmitter=o,t.exports=o}(Nr)),Nr.exports),Ur=x(Br);const $r="1.6.15",Gr={};function Hr(t,e){return e+10<=t.length&&51===t[e]&&68===t[e+1]&&73===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128}function Vr(t,e){return e+10<=t.length&&73===t[e]&&68===t[e+1]&&51===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128}function jr(t,e){let i=0;return i=(127&t[e])<<21,i|=(127&t[e+1])<<14,i|=(127&t[e+2])<<7,i|=127&t[e+3],i}function Kr(t,e){const i=e;let r=0;for(;Vr(t,e);){r+=10;r+=jr(t,e+6),Hr(t,e+10)&&(r+=10),e+=r}if(r>0)return t.subarray(i,i+r)}function Wr(t,e){return 255===t[e]&&240==(246&t[e+1])}function Yr(t,e){return 1&t[e+1]?7:9}function qr(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function zr(t,e){return e+1<t.length&&Wr(t,e)}function Xr(t,e){if(zr(t,e)){const i=Yr(t,e);if(e+i>=t.length)return!1;const r=qr(t,e);if(r<=i)return!1;const s=e+r;return s===t.length||zr(t,s)}return!1}function Qr(t,e,i,r,s){if(!t.samplerate){const n=function(t,e,i,r){const s=e[i+2],n=s>>2&15;if(n>12){const e=new Error(`invalid ADTS sampling index:${n}`);return void t.emit(l.ERROR,l.ERROR,{type:a.MEDIA_ERROR,details:o.FRAG_PARSING_ERROR,fatal:!0,error:e,reason:e.message})}const u=1+(s>>6&3),c=e[i+3]>>6&3|(1&s)<<2,d="mp4a.40."+u,h=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][n];let f=n;5!==u&&29!==u||(f-=3);const g=[u<<3|(14&f)>>1,(1&f)<<7|c<<3];return _.log(`manifest codec:${r}, parsed codec:${d}, channels:${c}, rate:${h} (ADTS object type:${u} sampling index:${n})`),{config:g,samplerate:h,channelCount:c,codec:d,parsedCodec:d,manifestCodec:r}}(e,i,r,s);if(!n)return;E(t,n)}}function Zr(t){return 9216e4/t}function Jr(t,e,i,r,s){const n=r+s*Zr(t.samplerate),a=function(t,e){const i=Yr(t,e);if(e+i<=t.length){const r=qr(t,e)-i;if(r>0)return{headerLength:i,frameLength:r}}}(e,i);let o;if(a){const{frameLength:r,headerLength:s}=a,l=s+r,u=Math.max(0,i+l-e.length);u?(o=new Uint8Array(l-s),o.set(e.subarray(i+s,e.length),0)):o=e.subarray(i+s,i+l);const c={unit:o,pts:n};return u||t.samples.push(c),{sample:c,length:l,missing:u}}const l=e.length-i;o=new Uint8Array(l),o.set(e.subarray(i,e.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}function ts(t,e){return Vr(t,e)&&jr(t,e+6)+10<=t.length-e}function es(t,e=0,i=Infinity){return function(t,e,i,r){const s=function(t){return t instanceof ArrayBuffer?t:t.buffer}(t);let n=1;"BYTES_PER_ELEMENT"in r&&(n=r.BYTES_PER_ELEMENT);const a=(d=t,d&&d.buffer instanceof ArrayBuffer&&void 0!==d.byteLength&&void 0!==d.byteOffset?t.byteOffset:0),o=(a+t.byteLength)/n,l=(a+e)/n,u=Math.floor(Math.max(0,Math.min(l,o))),c=Math.floor(Math.min(u+Math.max(i,0),o));var d;return new r(s,u,c-u)}(t,e,i,Uint8Array)}function is(t){const e={key:t.type,description:"",data:"",mimeType:null,pictureType:null};if(t.size<2)return;if(3!==t.data[0])return void console.log("Ignore frame with unrecognized character encoding");const i=t.data.subarray(1).indexOf(0);if(-1===i)return;const r=D(es(t.data,1,i)),s=t.data[2+i],n=t.data.subarray(3+i).indexOf(0);if(-1===n)return;const a=D(es(t.data,3+i,n));let o;return o="--\x3e"===r?D(es(t.data,4+i+n)):function(t){return t instanceof ArrayBuffer?t:0==t.byteOffset&&t.byteLength==t.buffer.byteLength?t.buffer:new Uint8Array(t).buffer}(t.data.subarray(4+i+n)),e.mimeType=r,e.pictureType=s,e.description=a,e.data=o,e}function rs(t){return"PRIV"===t.type?function(t){if(t.size<2)return;const e=D(t.data,!0),i=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:i.buffer}}(t):"W"===t.type[0]?function(t){if("WXXX"===t.type){if(t.size<2)return;let e=1;const i=D(t.data.subarray(e),!0);e+=i.length+1;const r=D(t.data.subarray(e));return{key:t.type,info:i,data:r}}const e=D(t.data);return{key:t.type,info:"",data:e}}(t):"APIC"===t.type?is(t):function(t){if(t.size<2)return;if("TXXX"===t.type){let e=1;const i=D(t.data.subarray(e),!0);e+=i.length+1;const r=D(t.data.subarray(e));return{key:t.type,info:i,data:r}}const e=D(t.data.subarray(1));return{key:t.type,info:"",data:e}}(t)}function ss(t){const e=String.fromCharCode(t[0],t[1],t[2],t[3]),i=jr(t,4);return{type:e,size:i,data:t.subarray(10,10+i)}}function ns(t){let e=0;const i=[];for(;Vr(t,e);){const r=jr(t,e+6);t[e+5]>>6&1&&(e+=10),e+=10;const s=e+r;for(;e+10<s;){const r=ss(t.subarray(e)),s=rs(r);s&&i.push(s),e+=r.size+10}Hr(t,e)&&(e+=10)}return i}function as(t){return t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info}function os(t){if(8===t.data.byteLength){const e=new Uint8Array(t.data),i=1&e[3];let r=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return r/=45,i&&(r+=47721858.84),Math.round(r)}}function ls(t){const e=ns(t);for(let t=0;t<e.length;t++){const i=e[t];if(as(i))return os(i)}}let us=function(t){return t.audioId3="org.id3",t.dateRange="com.apple.quicktime.HLS",t.emsg="https://aomedia.org/emsg/ID3",t.misbklv="urn:misb:KLV:bin:1910.1",t}({});function cs(t="",e=9e4){return{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class ds{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(t,e,i,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(t){this.initPTS=t,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(t,e){return!1}appendFrame(t,e,i){}demux(t,e){this.cachedData&&(t=pt(this.cachedData,t),this.cachedData=null);let i,s=Kr(t,0),n=s?s.length:0;const a=this._audioTrack,o=this._id3Track,l=s?ls(s):void 0,u=t.length;for((null===this.basePTS||0===this.frameIndex&&r(l))&&(this.basePTS=hs(l,e,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),s&&s.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:us.audioId3,duration:Number.POSITIVE_INFINITY});n<u;){if(this.canParse(t,n)){const e=this.appendFrame(a,t,n);e?(this.frameIndex++,this.lastPTS=e.sample.pts,n+=e.length,i=n):n=u}else ts(t,n)?(s=Kr(t,n),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:us.audioId3,duration:Number.POSITIVE_INFINITY}),n+=s.length,i=n):n++;if(n===u&&i!==u){const e=t.slice(i);this.cachedData?this.cachedData=pt(this.cachedData,e):this.cachedData=e}}return{audioTrack:a,videoTrack:cs(),id3Track:o,textTrack:cs()}}demuxSampleAes(t,e,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(t){const e=this.cachedData;return e&&(this.cachedData=null,this.demux(e,0)),{audioTrack:this._audioTrack,videoTrack:cs(),id3Track:this._id3Track,textTrack:cs()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const hs=(t,e,i)=>{if(r(t))return 90*t;return 9e4*e+(i?9e4*i.baseTime/i.timescale:0)};let fs=null;const gs=[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],ms=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],ps=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],vs=[0,1,1,4];function ys(t,e,i,r,s){if(i+24>e.length)return;const n=Es(e,i);if(n&&i+n.frameLength<=e.length){const a=r+s*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:e.subarray(i,i+n.frameLength),pts:a,dts:a};return t.config=[],t.channelCount=n.channelCount,t.samplerate=n.sampleRate,t.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function Es(t,e){const i=t[e+1]>>3&3,r=t[e+1]>>1&3,s=t[e+2]>>4&15,n=t[e+2]>>2&3;if(1!==i&&0!==s&&15!==s&&3!==n){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*gs[14*(3===i?3-r:3===r?3:4)+s-1],u=ms[3*(3===i?0:2===i?1:2)+n],c=3===o?1:2,d=ps[i][r],h=vs[r],f=8*d*h,g=Math.floor(d*l/u+a)*h;if(null===fs){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);fs=t?parseInt(t[1]):0}return!!fs&&fs<=87&&2===r&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:u,channelCount:c,frameLength:g,samplesPerFrame:f}}}function Ts(t,e){return!(255!==t[e]||224&~t[e+1]||!(6&t[e+1]))}function bs(t,e){return e+1<t.length&&Ts(t,e)}function Ss(t,e){if(e+1<t.length&&Ts(t,e)){const i=4,r=Es(t,e);let s=i;null!=r&&r.frameLength&&(s=r.frameLength);const n=e+s;return n===t.length||bs(t,n)}return!1}const As=(t,e)=>{let i=0,r=5;e+=r;const s=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;r>0;){a[0]=t[e];const o=Math.min(r,8),l=8-o;n[0]=4278190080>>>24+l<<l,s[0]=(a[0]&n[0])>>l,i=i?i<<o|s[0]:s[0],e+=1,r-=o}return i};class Ls extends ds{constructor(t){super(),this.observer=void 0,this.observer=t}resetInitSegment(t,e,i,r){super.resetInitSegment(t,e,i,r),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:e,duration:r,inputTimeScale:9e4,dropped:0}}canParse(t,e){return e+64<t.length}appendFrame(t,e,i){const r=ks(t,e,i,this.basePTS,this.frameIndex);if(-1!==r){return{sample:t.samples[t.samples.length-1],length:r,missing:0}}}static probe(t){if(!t)return!1;const e=Kr(t,0);if(!e)return!1;const i=e.length;return 11===t[i]&&119===t[i+1]&&void 0!==ls(e)&&As(t,i)<16}}function ks(t,e,i,r,s){if(i+8>e.length)return-1;if(11!==e[i]||119!==e[i+1])return-1;const n=e[i+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&e[i+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+n];if(i+l>e.length)return-1;const u=e[i+6]>>5;let c=0;2===u?c+=2:(1&u&&1!==u&&(c+=2),4&u&&(c+=2));const d=(e[i+6]<<8|e[i+7])>>12-c&1,h=[2,1,2,3,3,4,4,5][u]+d,f=e[i+5]>>3,g=7&e[i+5],m=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|u<<3|d<<2|o>>4,o<<4&224]),p=r+s*(1536/a*9e4),v=e.subarray(i,i+l);return t.config=m,t.channelCount=h,t.samplerate=a,t.samples.push({unit:v,pts:p}),l}const Rs=/\/emsg[-/]ID3/i;function Is(t,e){return r(t.presentationTime)?t.presentationTime/t.timeScale:e+t.presentationTimeDelta/t.timeScale}class _s{constructor(t,e,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Ye(e,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,He)}decryptAacSample(t,e,i){const r=t[e].unit;if(r.length<=16)return;const s=r.subarray(16,r.length-r.length%16),n=s.buffer.slice(s.byteOffset,s.byteOffset+s.length);this.decryptBuffer(n).then((s=>{const n=new Uint8Array(s);r.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(t,e+1,i)})).catch(i)}decryptAacSamples(t,e,i){for(;;e++){if(e>=t.length)return void i();if(!(t[e].unit.length<32)&&(this.decryptAacSample(t,e,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const e=16*Math.floor((t.length-48)/160)+16,i=new Int8Array(e);let r=0;for(let e=32;e<t.length-16;e+=160,r+=16)i.set(t.subarray(e,e+16),r);return i}getAvcDecryptedUnit(t,e){const i=new Uint8Array(e);let r=0;for(let e=32;e<t.length-16;e+=160,r+=16)t.set(i.subarray(r,r+16),e);return t}decryptAvcSample(t,e,i,r,s){const n=bt(s.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then((a=>{s.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(t,e,i+1,r)})).catch(r)}decryptAvcSamples(t,e,i,r){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,i=0){if(e>=t.length)return void r();const s=t[e].units;for(;!(i>=s.length);i++){const n=s[i];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(t,e,i,r,n),this.decrypter.isSync())))return}}}}class ws{constructor(){this.VideoSample=null}createVideoSample(t,e,i){return{key:t,frame:!1,pts:e,dts:i,units:[],length:0}}getLastNalUnit(t){var e;let i,r=this.VideoSample;if(r&&0!==r.units.length||(r=t[t.length-1]),null!=(e=r)&&e.units){const t=r.units;i=t[t.length-1]}return i}pushAccessUnit(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){const i=e.samples,r=i.length;if(!r)return void e.dropped++;{const e=i[r-1];t.pts=e.pts,t.dts=e.dts}}e.samples.push(t)}}parseNALu(t,e,i){const r=e.byteLength;let s=t.naluState||0;const n=s,a=[];let o,l,u,c=0,d=-1,h=0;for(-1===s&&(d=0,h=this.getNALuType(e,0),s=0,c=1);c<r;)if(o=e[c++],s)if(1!==s)if(o)if(1===o){if(l=c-s-1,d>=0){const t={data:e.subarray(d,l),type:h};a.push(t)}else{const i=this.getLastNalUnit(t.samples);i&&(n&&c<=4-n&&i.state&&(i.data=i.data.subarray(0,i.data.byteLength-n)),l>0&&(i.data=pt(i.data,e.subarray(0,l)),i.state=0))}c<r?(u=this.getNALuType(e,c),d=c,h=u,s=0):s=-1}else s=0;else s=3;else s=o?0:2;else s=o?0:1;if(d>=0&&s>=0){const t={data:e.subarray(d,r),type:h,state:s};a.push(t)}if(0===a.length){const i=this.getLastNalUnit(t.samples);i&&(i.data=pt(i.data,e))}return t.naluState=s,a}}class Ps{constructor(t){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const t=this.data,e=this.bytesAvailable,i=t.byteLength-e,r=new Uint8Array(4),s=Math.min(4,e);if(0===s)throw new Error("no bytes available");r.set(t.subarray(i,i+s)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=8*s,this.bytesAvailable-=s}skipBits(t){let e;t=Math.min(t,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(e=(t-=this.bitsAvailable)>>3,t-=e<<3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)}readBits(t){let e=Math.min(this.bitsAvailable,t);const i=this.word>>>32-e;if(t>32&&_.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0)this.word<<=e;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return e=t-e,e>0&&this.bitsAvailable?i<<e|this.readBits(e):i}skipLZ(){let t;for(t=0;t<this.bitsAvailable;++t)if(this.word&2147483648>>>t)return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const t=this.skipLZ();return this.readBits(t+1)-1}readEG(){const t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class Ds extends ws{parsePES(t,e,i,r){const s=this.parseNALu(t,i.data,r);let n,a=this.VideoSample,o=!1;i.data=null,a&&s.length&&!t.audFound&&(this.pushAccessUnit(a,t),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),s.forEach((r=>{var s,l;switch(r.type){case 1:{let e=!1;n=!0;const s=r.data;if(o&&s.length>4){const t=this.readSliceType(s);2!==t&&4!==t&&7!==t&&9!==t||(e=!0)}var u;if(e)null!=(u=a)&&u.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.frame=!0,a.key=e;break}case 5:n=!0,null!=(s=a)&&s.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 6:n=!0,Tt(r.data,1,i.pts,e.samples);break;case 7:{var c,d;n=!0,o=!0;const e=r.data,i=this.readSPS(e);if(!t.sps||t.width!==i.width||t.height!==i.height||(null==(c=t.pixelRatio)?void 0:c[0])!==i.pixelRatio[0]||(null==(d=t.pixelRatio)?void 0:d[1])!==i.pixelRatio[1]){t.width=i.width,t.height=i.height,t.pixelRatio=i.pixelRatio,t.sps=[e];const r=e.subarray(1,4);let s="avc1.";for(let t=0;t<3;t++){let e=r[t].toString(16);e.length<2&&(e="0"+e),s+=e}t.codec=s}break}case 8:n=!0,t.pps=[r.data];break;case 9:n=!0,t.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,t),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:n=!0;break;default:n=!1}if(a&&n){a.units.push(r)}})),r&&a&&(this.pushAccessUnit(a,t),this.VideoSample=null)}getNALuType(t,e){return 31&t[e]}readSliceType(t){const e=new Ps(t);return e.readUByte(),e.readUEG(),e.readUEG()}skipScalingList(t,e){let i,r=8,s=8;for(let n=0;n<t;n++)0!==s&&(i=e.readEG(),s=(r+i+256)%256),r=0===s?r:s}readSPS(t){const e=new Ps(t);let i,r,s,n=0,a=0,o=0,l=0;const u=e.readUByte.bind(e),c=e.readBits.bind(e),d=e.readUEG.bind(e),h=e.readBoolean.bind(e),f=e.skipBits.bind(e),g=e.skipEG.bind(e),m=e.skipUEG.bind(e),p=this.skipScalingList.bind(this);u();const v=u();if(c(5),f(3),u(),m(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){const t=d();if(3===t&&f(1),m(),m(),f(1),h())for(r=3!==t?8:12,s=0;s<r;s++)h()&&p(s<6?16:64,e)}m();const y=d();if(0===y)d();else if(1===y)for(f(1),g(),g(),i=d(),s=0;s<i;s++)g();m(),f(1);const E=d(),T=d(),b=c(1);0===b&&f(1),f(1),h()&&(n=d(),a=d(),o=d(),l=d());let S=[1,1];if(h()&&h()){switch(u()){case 1:S=[1,1];break;case 2:S=[12,11];break;case 3:S=[10,11];break;case 4:S=[16,11];break;case 5:S=[40,33];break;case 6:S=[24,11];break;case 7:S=[20,11];break;case 8:S=[32,11];break;case 9:S=[80,33];break;case 10:S=[18,11];break;case 11:S=[15,11];break;case 12:S=[64,33];break;case 13:S=[160,99];break;case 14:S=[4,3];break;case 15:S=[3,2];break;case 16:S=[2,1];break;case 255:S=[u()<<8|u(),u()<<8|u()]}}return{width:Math.ceil(16*(E+1)-2*n-2*a),height:(2-b)*(T+1)*16-(b?2:4)*(o+l),pixelRatio:S}}}class Cs extends ws{constructor(...t){super(...t),this.initVPS=null}parsePES(t,e,i,r){const s=this.parseNALu(t,i.data,r);let n,a=this.VideoSample,o=!1;i.data=null,a&&s.length&&!t.audFound&&(this.pushAccessUnit(a,t),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),s.forEach((r=>{var s,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,i.pts,i.dts)),a.frame=!0,n=!0;break;case 16:case 17:case 18:case 21:var u;if(n=!0,o)null!=(u=a)&&u.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:n=!0,null!=(s=a)&&s.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 39:n=!0,Tt(r.data,2,i.pts,e.samples);break;case 32:n=!0,t.vps||("object"!=typeof t.params&&(t.params={}),t.params=E(t.params,this.readVPS(r.data)),this.initVPS=r.data),t.vps=[r.data];break;case 33:if(n=!0,o=!0,void 0===t.vps||t.vps[0]===this.initVPS||void 0===t.sps||this.matchSPS(t.sps[0],r.data)||(this.initVPS=t.vps[0],t.sps=t.pps=void 0),!t.sps){const e=this.readSPS(r.data);t.width=e.width,t.height=e.height,t.pixelRatio=e.pixelRatio,t.codec=e.codecString,t.sps=[],"object"!=typeof t.params&&(t.params={});for(const i in e.params)t.params[i]=e.params[i]}this.pushParameterSet(t.sps,r.data,t.vps),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0;break;case 34:if(n=!0,"object"==typeof t.params){if(!t.pps){t.pps=[];const e=this.readPPS(r.data);for(const i in e)t.params[i]=e[i]}this.pushParameterSet(t.pps,r.data,t.vps)}break;case 35:n=!0,t.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,t),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;default:n=!1}if(a&&n){a.units.push(r)}})),r&&a&&(this.pushAccessUnit(a,t),this.VideoSample=null)}pushParameterSet(t,e,i){(i&&i[0]===this.initVPS||!i&&!t.length)&&t.push(e)}getNALuType(t,e){return(126&t[e])>>>1}ebsp2rbsp(t){const e=new Uint8Array(t.byteLength);let i=0;for(let r=0;r<t.byteLength;r++)r>=2&&3===t[r]&&0===t[r-1]&&0===t[r-2]||(e[i]=t[r],i++);return new Uint8Array(e.buffer,0,i)}pushAccessUnit(t,e){super.pushAccessUnit(t,e),this.initVPS&&(this.initVPS=null)}readVPS(t){const e=new Ps(t);e.readUByte(),e.readUByte(),e.readBits(4),e.skipBits(2),e.readBits(6);return{numTemporalLayers:e.readBits(3)+1,temporalIdNested:e.readBoolean()}}readSPS(t){const e=new Ps(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.readBits(4);const i=e.readBits(3);e.readBoolean();const r=e.readBits(2),s=e.readBoolean(),n=e.readBits(5),a=e.readUByte(),o=e.readUByte(),l=e.readUByte(),u=e.readUByte(),c=e.readUByte(),d=e.readUByte(),h=e.readUByte(),f=e.readUByte(),g=e.readUByte(),m=e.readUByte(),p=e.readUByte(),v=[],y=[];for(let t=0;t<i;t++)v.push(e.readBoolean()),y.push(e.readBoolean());if(i>0)for(let t=i;t<8;t++)e.readBits(2);for(let t=0;t<i;t++)v[t]&&(e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte()),y[t]&&e.readUByte();e.readUEG();const E=e.readUEG();3==E&&e.skipBits(1);const T=e.readUEG(),b=e.readUEG(),S=e.readBoolean();let A=0,L=0,k=0,R=0;S&&(A+=e.readUEG(),L+=e.readUEG(),k+=e.readUEG(),R+=e.readUEG());const I=e.readUEG(),_=e.readUEG(),w=e.readUEG();for(let t=e.readBoolean()?0:i;t<=i;t++)e.skipUEG(),e.skipUEG(),e.skipUEG();e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG();if(e.readBoolean()){if(e.readBoolean())for(let t=0;t<4;t++)for(let i=0;i<(3===t?2:6);i++){if(e.readBoolean()){const i=Math.min(64,1<<4+(t<<1));t>1&&e.readEG();for(let t=0;t<i;t++)e.readEG()}else e.readUEG()}}e.readBoolean(),e.readBoolean();e.readBoolean()&&(e.readUByte(),e.skipUEG(),e.skipUEG(),e.readBoolean());const P=e.readUEG();let D=0;for(let t=0;t<P;t++){let i=!1;if(0!==t&&(i=e.readBoolean()),i){t===P&&e.readUEG(),e.readBoolean(),e.readUEG();let i=0;for(let t=0;t<=D;t++){const t=e.readBoolean();let r=!1;t||(r=e.readBoolean()),(t||r)&&i++}D=i}else{const t=e.readUEG(),i=e.readUEG();D=t+i;for(let i=0;i<t;i++)e.readUEG(),e.readBoolean();for(let t=0;t<i;t++)e.readUEG(),e.readBoolean()}}if(e.readBoolean()){const t=e.readUEG();for(let i=0;i<t;i++){for(let t=0;t<w+4;t++)e.readBits(1);e.readBits(1)}}let C=0,O=1,x=1,M=!0,F=1,N=0;e.readBoolean(),e.readBoolean();let B=!1;if(e.readBoolean()){if(e.readBoolean()){const t=e.readUByte();t>0&&t<16?(O=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][t-1],x=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][t-1]):255===t&&(O=e.readBits(16),x=e.readBits(16))}e.readBoolean()&&e.readBoolean();if(e.readBoolean()){e.readBits(3),e.readBoolean();e.readBoolean()&&(e.readUByte(),e.readUByte(),e.readUByte())}e.readBoolean()&&(e.readUEG(),e.readUEG()),e.readBoolean(),e.readBoolean(),e.readBoolean(),B=e.readBoolean(),B&&(e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG());if(e.readBoolean()){F=e.readBits(32),N=e.readBits(32);e.readBoolean()&&e.readUEG();if(e.readBoolean()){const t=e.readBoolean(),r=e.readBoolean();let s=!1;(t||r)&&(s=e.readBoolean(),s&&(e.readUByte(),e.readBits(5),e.readBoolean(),e.readBits(5)),e.readBits(4),e.readBits(4),s&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let n=0;n<=i;n++){M=e.readBoolean();let i=!1;M||e.readBoolean()?e.readEG():i=e.readBoolean();const n=i?1:e.readUEG()+1;if(t)for(let t=0;t<n;t++)e.readUEG(),e.readUEG(),s&&(e.readUEG(),e.readUEG()),e.skipBits(1);if(r)for(let t=0;t<n;t++)e.readUEG(),e.readUEG(),s&&(e.readUEG(),e.readUEG()),e.skipBits(1)}}}e.readBoolean()&&(e.readBoolean(),e.readBoolean(),e.readBoolean(),C=e.readUEG())}let U=T,$=b;if(S){let t=1,e=1;1===E?t=e=2:2==E&&(t=2),U=T-t*L-t*A,$=b-e*R-e*k}const G=r?["A","B","C"][r]:"",H=a<<24|o<<16|l<<8|u;let V=0;for(let t=0;t<32;t++)V=(V|(H>>t&1)<<31-t)>>>0;let j=V.toString(16);1===n&&"2"===j&&(j="6");return{codecString:`hvc1.${G}${n}.${j}.${s?"H":"L"}${p}.B0`,params:{general_tier_flag:s,general_profile_idc:n,general_profile_space:r,general_profile_compatibility_flags:[a,o,l,u],general_constraint_indicator_flags:[c,d,h,f,g,m],general_level_idc:p,bit_depth:I+8,bit_depth_luma_minus8:I,bit_depth_chroma_minus8:_,min_spatial_segmentation_idc:C,chroma_format_idc:E,frame_rate:{fixed:M,fps:N/F}},width:U,height:$,pixelRatio:[O,x]}}readPPS(t){const e=new Ps(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.skipUEG(),e.skipUEG(),e.skipBits(2),e.skipBits(3),e.skipBits(2),e.skipUEG(),e.skipUEG(),e.skipEG(),e.skipBits(2);e.readBoolean()&&e.skipUEG(),e.skipEG(),e.skipEG(),e.skipBits(4);const i=e.readBoolean(),r=e.readBoolean();let s=1;return r&&i?s=0:r?s=3:i&&(s=2),{parallelismType:s}}matchSPS(t,e){return String.fromCharCode.apply(null,t).substr(3)===String.fromCharCode.apply(null,e).substr(3)}}const Os=188;class xs{constructor(t,e,i,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=t,this.config=e,this.typeSupported=i,this.logger=r,this.videoParser=null}static probe(t,e){const i=xs.syncOffset(t);return i>0&&e.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),-1!==i}static syncOffset(t){const e=t.length;let i=Math.min(940,e-Os)+1,r=0;for(;r<i;){let s=!1,n=-1,a=0;for(let o=r;o<e;o+=Os){if(71!==t[o]||e-o!==Os&&71!==t[o+Os]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(i=Math.min(n+18612,t.length-Os)+1)),s||(s=0===Ms(t,o)),s&&a>1&&(0===n&&a>2||o+Os>i))return n}r++}return-1}static createTrack(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:tt[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}}resetInitSegment(t,e,i,r){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=xs.createTrack("video"),this._videoTrack.duration=r,this._audioTrack=xs.createTrack("audio",r),this._id3Track=xs.createTrack("id3"),this._txtTrack=xs.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=i}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:e,_id3Track:i}=this;t&&(t.pesData=null),e&&(e.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,e,i=!1,r=!1){let s;i||(this.sampleAes=null);const n=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let u=n.pid,c=n.pesData,d=a.pid,h=o.pid,f=a.pesData,g=o.pesData,m=null,p=this.pmtParsed,v=this._pmtId,y=t.length;if(this.remainderData&&(y=(t=pt(this.remainderData,t)).length,this.remainderData=null),y<Os&&!r)return this.remainderData=t,{audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};const E=Math.max(0,xs.syncOffset(t));y-=(y-E)%Os,y<t.byteLength&&!r&&(this.remainderData=new Uint8Array(t.buffer,y,t.buffer.byteLength-y));let T=0;for(let e=E;e<y;e+=Os)if(71===t[e]){const r=!!(64&t[e+1]),y=Ms(t,e);let T;if((48&t[e+3])>>4>1){if(T=e+5+t[e+4],T===e+Os)continue}else T=e+4;switch(y){case u:r&&(c&&(s=$s(c,this.logger))&&(this.readyVideoParser(n.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(n,l,s,!1)),c={data:[],size:0}),c&&(c.data.push(t.subarray(T,e+Os)),c.size+=e+Os-T);break;case d:if(r){if(f&&(s=$s(f,this.logger)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,s);break;case"mp3":this.parseMPEGPES(a,s);break;case"ac3":this.parseAC3PES(a,s)}f={data:[],size:0}}f&&(f.data.push(t.subarray(T,e+Os)),f.size+=e+Os-T);break;case h:r&&(g&&(s=$s(g,this.logger))&&this.parseID3PES(o,s),g={data:[],size:0}),g&&(g.data.push(t.subarray(T,e+Os)),g.size+=e+Os-T);break;case 0:r&&(T+=t[T]+1),v=this._pmtId=Fs(t,T);break;case v:{r&&(T+=t[T]+1);const s=Ns(t,T,this.typeSupported,i,this.observer,this.logger);u=s.videoPid,u>0&&(n.pid=u,n.segmentCodec=s.segmentVideoCodec),d=s.audioPid,d>0&&(a.pid=d,a.segmentCodec=s.segmentAudioCodec),h=s.id3Pid,h>0&&(o.pid=h),null===m||p||(this.logger.warn(`MPEG-TS PMT found at ${e} after unknown PID '${m}'. Backtracking to sync byte @${E} to parse all TS packets.`),m=null,e=E-188),p=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=y}}else T++;T>0&&Bs(this.observer,new Error(`Found ${T} TS packet/s that do not start with 0x47`),void 0,this.logger),n.pesData=c,a.pesData=f,o.pesData=g;const b={audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};return r&&this.extractRemainingSamples(b),b}flush(){const{remainderData:t}=this;let e;return this.remainderData=null,e=t?this.demux(t,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e}extractRemainingSamples(t){const{audioTrack:e,videoTrack:i,id3Track:r,textTrack:s}=t,n=i.pesData,a=e.pesData,o=r.pesData;let l;if(n&&(l=$s(n,this.logger))?(this.readyVideoParser(i.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(i,s,l,!0),i.pesData=null)):i.pesData=n,a&&(l=$s(a,this.logger))){switch(e.segmentCodec){case"aac":this.parseAACPES(e,l);break;case"mp3":this.parseMPEGPES(e,l);break;case"ac3":this.parseAC3PES(e,l)}e.pesData=null}else null!=a&&a.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),e.pesData=a;o&&(l=$s(o,this.logger))?(this.parseID3PES(r,l),r.pesData=null):r.pesData=o}demuxSampleAes(t,e,i){const r=this.demux(t,i,!0,!this.config.progressive),s=this.sampleAes=new _s(this.observer,this.config,e);return this.decrypt(r,s)}readyVideoParser(t){null===this.videoParser&&("avc"===t?this.videoParser=new Ds:"hevc"===t&&(this.videoParser=new Cs))}decrypt(t,e){return new Promise((i=>{const{audioTrack:r,videoTrack:s}=t;r.samples&&"aac"===r.segmentCodec?e.decryptAacSamples(r.samples,0,(()=>{s.samples?e.decryptAvcSamples(s.samples,0,0,(()=>{i(t)})):i(t)})):s.samples&&e.decryptAvcSamples(s.samples,0,0,(()=>{i(t)}))}))}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(t,e){let i=0;const r=this.aacOverFlow;let s,n,a,o=e.data;if(r){this.aacOverFlow=null;const e=r.missing,s=r.sample.unit.byteLength;if(-1===e)o=pt(r.sample.unit,o);else{const n=s-e;r.sample.unit.set(o.subarray(0,e),n),t.samples.push(r.sample),i=r.missing}}for(s=i,n=o.length;s<n-1&&!zr(o,s);s++);if(s!==i){let t;const e=s<n-1;if(t=e?`AAC PES did not start with ADTS header,offset:${s}`:"No ADTS header found in AAC PES",Bs(this.observer,new Error(t),e,this.logger),!e)return}if(Qr(t,this.observer,o,s,this.audioCodec),void 0!==e.pts)a=e.pts;else{if(!r)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const e=Zr(t.samplerate);a=r.sample.pts+e}}let l,u=0;for(;s<n;){if(l=Jr(t,o,s,a,u),s+=l.length,l.missing){this.aacOverFlow=l;break}for(u++;s<n-1&&!zr(o,s);s++);}}parseMPEGPES(t,e){const i=e.data,r=i.length;let s=0,n=0;const a=e.pts;if(void 0!==a)for(;n<r;)if(bs(i,n)){const e=ys(t,i,n,a,s);if(!e)break;n+=e.length,s++}else n++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(t,e){{const i=e.data,r=e.pts;if(void 0===r)return void this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");const s=i.length;let n,a=0,o=0;for(;o<s&&(n=ks(t,i,o,r,a++))>0;)o+=n}}parseID3PES(t,e){if(void 0===e.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const i=E({},e,{type:this._videoTrack?us.emsg:us.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(i)}}function Ms(t,e){return((31&t[e+1])<<8)+t[e+2]}function Fs(t,e){return(31&t[e+10])<<8|t[e+11]}function Ns(t,e,i,r,s,n){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=e+3+((15&t[e+1])<<8|t[e+2])-4;for(e+=12+((15&t[e+10])<<8|t[e+11]);e<o;){const o=Ms(t,e),l=(15&t[e+3])<<8|t[e+4];switch(t[e]){case 207:if(!r){Us("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){Us("H.264",n);break}case 27:-1===a.videoPid&&(a.videoPid=o);break;case 3:case 4:i.mpeg||i.mp3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="mp3"):n.log("MPEG audio found, not supported in this browser");break;case 193:if(!r){Us("AC-3",n);break}case 129:i.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=e+5,s=l;for(;s>2;){if(106===t[r])!0!==i.ac3?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=o,a.segmentAudioCodec="ac3");const e=t[r+1]+2;r+=e,s-=e}}break;case 194:case 135:return Bs(s,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"))}e+=l+5}return a}function Bs(t,e,i,r){r.warn(`parsing error: ${e.message}`),t.emit(l.ERROR,l.ERROR,{type:a.MEDIA_ERROR,details:o.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,error:e,reason:e.message})}function Us(t,e){e.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function $s(t,e){let i,r,s,n,a,o=0;const l=t.data;if(!t||0===t.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=pt(l[0],l[1]),l.splice(1,1);i=l[0];if(1===(i[0]<<16)+(i[1]<<8)+i[2]){if(r=(i[4]<<8)+i[5],r&&r>t.size-6)return null;const u=i[7];192&u&&(n=536870912*(14&i[9])+4194304*(255&i[10])+16384*(254&i[11])+128*(255&i[12])+(254&i[13])/2,64&u?(a=536870912*(14&i[14])+4194304*(255&i[15])+16384*(254&i[16])+128*(255&i[17])+(254&i[18])/2,n-a>54e5&&(e.warn(`${Math.round((n-a)/9e4)}s delta between PTS and DTS, align them`),n=a)):a=n),s=i[8];let c=s+9;if(t.size<=c)return null;t.size-=c;const d=new Uint8Array(t.size);for(let t=0,e=l.length;t<e;t++){i=l[t];let e=i.byteLength;if(c){if(c>e){c-=e;continue}i=i.subarray(c),e-=c,c=0}d.set(i,o),o+=e}return r&&(r-=s+3),{data:d,pts:n,dts:a,len:r}}return null}class Gs{static getSilentFrame(t,e){if("mp4a.40.2"===t){if(1===e)return new Uint8Array([0,200,0,128,35,128]);if(2===e)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===e)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===e)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===e)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}const Hs=Math.pow(2,32)-1;class Vs{static init(){let t;for(t in Vs.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:[]},Vs.types)Vs.types.hasOwnProperty(t)&&(Vs.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);const e=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);Vs.HDLR_TYPES={video:e,audio:i};const r=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),s=new Uint8Array([0,0,0,0,0,0,0,0]);Vs.STTS=Vs.STSC=Vs.STCO=s,Vs.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Vs.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Vs.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Vs.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]);Vs.FTYP=Vs.box(Vs.types.ftyp,n,o,n,a),Vs.DINF=Vs.box(Vs.types.dinf,Vs.box(Vs.types.dref,r))}static box(t,...e){let i=8,r=e.length;const s=r;for(;r--;)i+=e[r].byteLength;const n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=255&i,n.set(t,4),r=0,i=8;r<s;r++)n.set(e[r],i),i+=e[r].byteLength;return n}static hdlr(t){return Vs.box(Vs.types.hdlr,Vs.HDLR_TYPES[t])}static mdat(t){return Vs.box(Vs.types.mdat,t)}static mdhd(t,e){e*=t;const i=Math.floor(e/(Hs+1)),r=Math.floor(e%(Hs+1));return Vs.box(Vs.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,r>>24,r>>16&255,r>>8&255,255&r,85,196,0,0]))}static mdia(t){return Vs.box(Vs.types.mdia,Vs.mdhd(t.timescale||0,t.duration||0),Vs.hdlr(t.type),Vs.minf(t))}static mfhd(t){return Vs.box(Vs.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}static minf(t){return"audio"===t.type?Vs.box(Vs.types.minf,Vs.box(Vs.types.smhd,Vs.SMHD),Vs.DINF,Vs.stbl(t)):Vs.box(Vs.types.minf,Vs.box(Vs.types.vmhd,Vs.VMHD),Vs.DINF,Vs.stbl(t))}static moof(t,e,i){return Vs.box(Vs.types.moof,Vs.mfhd(t),Vs.traf(i,e))}static moov(t){let e=t.length;const i=[];for(;e--;)i[e]=Vs.trak(t[e]);return Vs.box.apply(null,[Vs.types.moov,Vs.mvhd(t[0].timescale||0,t[0].duration||0)].concat(i).concat(Vs.mvex(t)))}static mvex(t){let e=t.length;const i=[];for(;e--;)i[e]=Vs.trex(t[e]);return Vs.box.apply(null,[Vs.types.mvex,...i])}static mvhd(t,e){e*=t;const i=Math.floor(e/(Hs+1)),r=Math.floor(e%(Hs+1)),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,r>>24,r>>16&255,r>>8&255,255&r,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return Vs.box(Vs.types.mvhd,s)}static sdtp(t){const e=t.samples||[],i=new Uint8Array(4+e.length);let r,s;for(r=0;r<e.length;r++)s=e[r].flags,i[r+4]=s.dependsOn<<4|s.isDependedOn<<2|s.hasRedundancy;return Vs.box(Vs.types.sdtp,i)}static stbl(t){return Vs.box(Vs.types.stbl,Vs.stsd(t),Vs.box(Vs.types.stts,Vs.STTS),Vs.box(Vs.types.stsc,Vs.STSC),Vs.box(Vs.types.stsz,Vs.STSZ),Vs.box(Vs.types.stco,Vs.STCO))}static avc1(t){let e,i,r,s=[],n=[];for(e=0;e<t.sps.length;e++)i=t.sps[e],r=i.byteLength,s.push(r>>>8&255),s.push(255&r),s=s.concat(Array.prototype.slice.call(i));for(e=0;e<t.pps.length;e++)i=t.pps[e],r=i.byteLength,n.push(r>>>8&255),n.push(255&r),n=n.concat(Array.prototype.slice.call(i));const a=Vs.box(Vs.types.avcC,new Uint8Array([1,s[3],s[4],s[5],255,224|t.sps.length].concat(s).concat([t.pps.length]).concat(n))),o=t.width,l=t.height,u=t.pixelRatio[0],c=t.pixelRatio[1];return Vs.box(Vs.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,Vs.box(Vs.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Vs.box(Vs.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,255&u,c>>24,c>>16&255,c>>8&255,255&c])))}static esds(t){const e=t.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...e,6,1,2])}static audioStsd(t){const e=t.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount||0,0,16,0,0,0,0,e>>8&255,255&e,0,0])}static mp4a(t){return Vs.box(Vs.types.mp4a,Vs.audioStsd(t),Vs.box(Vs.types.esds,Vs.esds(t)))}static mp3(t){return Vs.box(Vs.types[".mp3"],Vs.audioStsd(t))}static ac3(t){return Vs.box(Vs.types["ac-3"],Vs.audioStsd(t),Vs.box(Vs.types.dac3,t.config))}static stsd(t){const{segmentCodec:e}=t;if("audio"===t.type){if("aac"===e)return Vs.box(Vs.types.stsd,Vs.STSD,Vs.mp4a(t));if("ac3"===e&&t.config)return Vs.box(Vs.types.stsd,Vs.STSD,Vs.ac3(t));if("mp3"===e&&"mp3"===t.codec)return Vs.box(Vs.types.stsd,Vs.STSD,Vs.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===e)return Vs.box(Vs.types.stsd,Vs.STSD,Vs.avc1(t));if("hevc"===e&&t.vps)return Vs.box(Vs.types.stsd,Vs.STSD,Vs.hvc1(t))}throw new Error(`unsupported ${t.type} segment codec (${e}/${t.codec})`)}static tkhd(t){const e=t.id,i=(t.duration||0)*(t.timescale||0),r=t.width||0,s=t.height||0,n=Math.floor(i/(Hs+1)),a=Math.floor(i%(Hs+1));return Vs.box(Vs.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,r>>8&255,255&r,0,0,s>>8&255,255&s,0,0]))}static traf(t,e){const i=Vs.sdtp(t),r=t.id,s=Math.floor(e/(Hs+1)),n=Math.floor(e%(Hs+1));return Vs.box(Vs.types.traf,Vs.box(Vs.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r])),Vs.box(Vs.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,n>>24,n>>16&255,n>>8&255,255&n])),Vs.trun(t,i.length+16+20+8+16+8+8),i)}static trak(t){return t.duration=t.duration||4294967295,Vs.box(Vs.types.trak,Vs.tkhd(t),Vs.mdia(t))}static trex(t){const e=t.id;return Vs.box(Vs.types.trex,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,e){const i=t.samples||[],r=i.length,s=12+16*r,n=new Uint8Array(s);let a,o,l,u,c,d;for(e+=8+s,n.set(["video"===t.type?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,255&r,e>>>24&255,e>>>16&255,e>>>8&255,255&e],0),a=0;a<r;a++)o=i[a],l=o.duration,u=o.size,c=o.flags,d=o.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,u>>>24&255,u>>>16&255,u>>>8&255,255&u,c.isLeading<<2|c.dependsOn,c.isDependedOn<<6|c.hasRedundancy<<4|c.paddingValue<<1|c.isNonSync,61440&c.degradPrio,15&c.degradPrio,d>>>24&255,d>>>16&255,d>>>8&255,255&d],12+16*a);return Vs.box(Vs.types.trun,n)}static initSegment(t){Vs.types||Vs.init();const e=Vs.moov(t);return pt(Vs.FTYP,e)}static hvc1(t){const e=t.params,i=[t.vps,t.sps,t.pps],r=new Uint8Array([1,e.general_profile_space<<6|(e.general_tier_flag?32:0)|e.general_profile_idc,e.general_profile_compatibility_flags[0],e.general_profile_compatibility_flags[1],e.general_profile_compatibility_flags[2],e.general_profile_compatibility_flags[3],e.general_constraint_indicator_flags[0],e.general_constraint_indicator_flags[1],e.general_constraint_indicator_flags[2],e.general_constraint_indicator_flags[3],e.general_constraint_indicator_flags[4],e.general_constraint_indicator_flags[5],e.general_level_idc,240|e.min_spatial_segmentation_idc>>8,255&e.min_spatial_segmentation_idc,252|e.parallelismType,252|e.chroma_format_idc,248|e.bit_depth_luma_minus8,248|e.bit_depth_chroma_minus8,0,parseInt(e.frame_rate.fps),3|e.temporal_id_nested<<2|e.num_temporal_layers<<3|(e.frame_rate.fixed?64:0),i.length]);let s=r.length;for(let t=0;t<i.length;t+=1){s+=3;for(let e=0;e<i[t].length;e+=1)s+=2+i[t][e].length}const n=new Uint8Array(s);n.set(r,0),s=r.length;const a=i.length-1;for(let t=0;t<i.length;t+=1){n.set(new Uint8Array([32+t|(t===a?128:0),0,i[t].length]),s),s+=3;for(let e=0;e<i[t].length;e+=1)n.set(new Uint8Array([i[t][e].length>>8,255&i[t][e].length]),s),s+=2,n.set(i[t][e],s),s+=i[t][e].length}const o=Vs.box(Vs.types.hvcC,n),l=t.width,u=t.height,c=t.pixelRatio[0],d=t.pixelRatio[1];return Vs.box(Vs.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,u>>8&255,255&u,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,Vs.box(Vs.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Vs.box(Vs.types.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,255&c,d>>24,d>>16&255,d>>8&255,255&d])))}}Vs.types=void 0,Vs.HDLR_TYPES=void 0,Vs.STTS=void 0,Vs.STSC=void 0,Vs.STCO=void 0,Vs.STSZ=void 0,Vs.VMHD=void 0,Vs.SMHD=void 0,Vs.STSD=void 0,Vs.FTYP=void 0,Vs.DINF=void 0;function js(t,e,i=1,r=!1){const s=t*e*i;return r?Math.round(s):s}function Ks(t,e=!1){return js(t,1e3,1/9e4,e)}function Ws(t){const{baseTime:e,timescale:i,trackId:r}=t;return`${e/i} (${e}/${i}) trackId: ${r}`}let Ys,qs=null,zs=null;function Xs(t,e,i,r){return{duration:e,size:i,cts:r,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1}}}class Qs extends S{constructor(t,e,i,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=t,this.config=e,this.typeSupported=i,this.ISGenerated=!1,null===qs){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);qs=t?parseInt(t[1]):0}if(null===zs){const t=navigator.userAgent.match(/Safari\/(\d+)/i);zs=t?parseInt(t[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){const e=this._initPTS;e&&t&&t.trackId===e.trackId&&t.baseTime===e.baseTime&&t.timescale===e.timescale||this.log(`Reset initPTS: ${e?Ws(e):e} > ${t?Ws(t):t}`),this._initPTS=this._initDTS=t}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let e=!1;const i=t[0].pts,r=t.reduce(((t,r)=>{let s=r.pts,n=s-t;return n<-4294967296&&(e=!0,s=Zs(s,i),n=s-t),n>0?t:s}),i);return e&&this.debug("PTS rollover detected"),r}remux(t,e,i,r,s,n,a,o){let l,u,c,d,h,f,m=s,p=s;const v=t.pid>-1,y=e.pid>-1,E=e.samples.length,T=t.samples.length>0,b=a&&E>0||E>1;if((!v||T)&&(!y||b)||this.ISGenerated||a){if(this.ISGenerated){var S,A,L,k;const t=this.videoTrackConfig;(t&&(e.width!==t.width||e.height!==t.height||(null==(S=e.pixelRatio)?void 0:S[0])!==(null==(A=t.pixelRatio)?void 0:A[0])||(null==(L=e.pixelRatio)?void 0:L[1])!==(null==(k=t.pixelRatio)?void 0:k[1]))||!t&&b||null===this.nextAudioTs&&T)&&this.resetInitSegment()}this.ISGenerated||(c=this.generateIS(t,e,s,n));const i=this.isVideoContiguous;let r,a=-1;if(b&&(a=function(t){for(let e=0;e<t.length;e++)if(t[e].key)return e;return-1}(e.samples),!i&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,a>0){this.warn(`Dropped ${a} out of ${E} video samples due to a missing keyframe`);const t=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(a),e.dropped+=a,p+=(e.samples[0].pts-t)/e.inputTimeScale,r=p}else-1===a&&(this.warn(`No keyframe found out of ${E} video samples`),f=!1);if(this.ISGenerated){if(T&&b){const i=this.getVideoStartPts(e.samples),r=(Zs(t.samples[0].pts,i)-i)/e.inputTimeScale;m+=Math.max(0,r),p+=Math.max(0,-r)}if(T){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),c=this.generateIS(t,e,s,n)),u=this.remuxAudio(t,m,this.isAudioContiguous,n,y||b||o===g?p:void 0),b){const r=u?u.endPTS-u.startPTS:0;e.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),c=this.generateIS(t,e,s,n)),l=this.remuxVideo(e,p,i,r)}}else b&&(l=this.remuxVideo(e,p,i,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=r)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(h=Js(i,s,this._initPTS,this._initDTS)),r.samples.length&&(d=tn(r,s,this._initPTS))),{audio:u,video:l,initSegment:c,independent:f,text:d,id3:h}}computeInitPts(t,e,i,r){const s=Math.round(i*e);let n=Zs(t,s);if(n<s+e)for(this.log(`Adjusting PTS for rollover in timeline near ${(s-n)/e} ${r}`);n<s+e;)n+=8589934592;return n-s}generateIS(t,e,i,r){const s=t.samples,n=e.samples,a=this.typeSupported,o={},l=this._initPTS;let u,c,d,h=!l||r,f="audio/mp4",g=-1;if(h&&(u=c=Infinity),t.config&&s.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",t.codec=""):a.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3"}o.audio={id:"audio",container:f,codec:t.codec,initSegment:"mp3"===t.segmentCodec&&a.mpeg?new Uint8Array(0):Vs.initSegment([t]),metadata:{channelCount:t.channelCount}},h&&(g=t.id,d=t.inputTimeScale,l&&d===l.timescale?h=!1:u=c=this.computeInitPts(s[0].pts,d,i,"audio"))}if(e.sps&&e.pps&&n.length){if(e.timescale=e.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:Vs.initSegment([e]),metadata:{width:e.width,height:e.height}},h)if(g=e.id,d=e.inputTimeScale,l&&d===l.timescale)h=!1;else{const t=this.getVideoStartPts(n),e=Zs(n[0].dts,t),r=this.computeInitPts(e,d,i,"video"),s=this.computeInitPts(t,d,i,"video");c=Math.min(c,r),u=Math.min(u,s)}this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,h?(l&&this.warn(`Timestamps at playlist time: ${r?"":"~"}${i} ${u/d} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${u/d} (${u}/${d}) trackId: ${g}`),this._initPTS={baseTime:u,timescale:d,trackId:g},this._initDTS={baseTime:c,timescale:d,trackId:g}):u=d=void 0,{tracks:o,initPTS:u,timescale:d,trackId:g}}remuxVideo(t,e,i,r){const s=t.inputTimeScale,n=t.samples,u=[],c=n.length,d=this._initPTS,h=d.baseTime*s/d.timescale;let f,g,m=this.nextVideoTs,p=8,v=this.videoSampleDuration,y=Number.POSITIVE_INFINITY,T=Number.NEGATIVE_INFINITY,b=!1;if(!i||null===m){const t=h+e*s,r=n[0].pts-Zs(n[0].dts,n[0].pts);qs&&null!==m&&Math.abs(t-r-(m+h))<15e3?i=!0:m=t-r-h}const S=m+h;for(let t=0;t<c;t++){const e=n[t];e.pts=Zs(e.pts,S),e.dts=Zs(e.dts,S),e.dts<n[t>0?t-1:t].dts&&(b=!0)}b&&n.sort((function(t,e){const i=t.dts-e.dts,r=t.pts-e.pts;return i||r})),f=n[0].dts,g=n[n.length-1].dts;const A=g-f,L=A?Math.round(A/(c-1)):v||t.inputTimeScale/30;if(i){const i=f-S,r=i>L,s=i<-1;if((r||s)&&(r?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${Ks(i,!0)} ms (${i}dts) hole between fragments detected at ${e.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${Ks(-i,!0)} ms (${i}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!s||S>=n[0].pts||qs)){f=S;const t=n[0].pts-i;if(r)n[0].dts=f,n[0].pts=t;else{let e=!0;for(let r=0;r<n.length&&!(n[r].dts>t&&e);r++){const t=n[r].pts;if(n[r].dts-=i,n[r].pts-=i,r<n.length-1){const i=n[r+1].pts;e=i<=n[r].pts==i<=t}}}this.log(`Video: Initial PTS/DTS adjusted: ${Ks(t,!0)}/${Ks(f,!0)}, delta: ${Ks(i,!0)} ms`)}}f=Math.max(0,f);let k=0,R=0,I=f;for(let t=0;t<c;t++){const e=n[t],i=e.units,r=i.length;let s=0;for(let t=0;t<r;t++)s+=i[t].data.length;R+=s,k+=r,e.length=s,e.dts<I?(e.dts=I,I+=L/4|0||1):I=e.dts,y=Math.min(e.pts,y),T=Math.max(e.pts,T)}g=n[c-1].dts;const _=R+4*k+8;let w;try{w=new Uint8Array(_)}catch(t){return void this.observer.emit(l.ERROR,l.ERROR,{type:a.MUX_ERROR,details:o.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:_,reason:`fail allocating video mdat ${_}`})}const P=new DataView(w.buffer);P.setUint32(0,_),w.set(Vs.types.mdat,4);let D=!1,C=Number.POSITIVE_INFINITY,O=Number.POSITIVE_INFINITY,x=Number.NEGATIVE_INFINITY,M=Number.NEGATIVE_INFINITY;for(let t=0;t<c;t++){const e=n[t],i=e.units;let a,o=0;for(let t=0,e=i.length;t<e;t++){const e=i[t],r=e.data,s=e.data.byteLength;P.setUint32(p,s),p+=4,w.set(r,p),p+=s,o+=4+s}if(t<c-1)v=n[t+1].dts-e.dts,a=n[t+1].pts-e.pts;else{const i=this.config,o=t>0?e.dts-n[t-1].dts:L;if(a=t>0?e.pts-n[t-1].pts:L,i.stretchShortVideoTrack&&null!==this.nextAudioTs){const t=Math.floor(i.maxBufferHole*s),n=(r?y+r*s:this.nextAudioTs+h)-e.pts;n>t?(v=n-o,v<0?v=o:D=!0,this.log(`It is approximately ${n/90} ms to the next segment; using duration ${v/90} ms for the last video frame.`)):v=o}else v=o}const l=Math.round(e.pts-e.dts);C=Math.min(C,v),x=Math.max(x,v),O=Math.min(O,a),M=Math.max(M,a),u.push(Xs(e.key,v,o,l))}if(u.length)if(qs){if(qs<70){const t=u[0].flags;t.dependsOn=2,t.isNonSync=0}}else if(zs&&M-O<x-C&&L/x<.025&&0===u[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let t=f;for(let e=0,i=u.length;e<i;e++){const r=t+u[e].duration,s=t+u[e].cts;if(e<i-1){const t=r+u[e+1].cts;u[e].duration=t-s}else u[e].duration=e?u[e-1].duration:L;u[e].cts=0,t=r}}v=D||!v?L:v;const F=g+v;this.nextVideoTs=m=F-h,this.videoSampleDuration=v,this.isVideoContiguous=!0;const N={data1:Vs.moof(t.sequenceNumber++,f,E(t,{samples:u})),data2:w,startPTS:(y-h)/s,endPTS:(T+v-h)/s,startDTS:(f-h)/s,endDTS:m/s,type:"video",hasAudio:!1,hasVideo:!0,nb:u.length,dropped:t.dropped};return t.samples=[],t.dropped=0,N}getSamplesPerFrame(t){switch(t.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(t,e,i,r,s){const n=t.inputTimeScale,u=n/(t.samplerate?t.samplerate:n),c=this.getSamplesPerFrame(t),d=c*u,h=this._initPTS,f="mp3"===t.segmentCodec&&this.typeSupported.mpeg,g=[],m=void 0!==s;let p=t.samples,v=f?0:8,y=this.nextAudioTs||-1;const T=h.baseTime*n/h.timescale,b=T+e*n;if(this.isAudioContiguous=i=i||p.length&&y>0&&(r&&Math.abs(b-(y+T))<9e3||Math.abs(Zs(p[0].pts,b)-(y+T))<20*d),p.forEach((function(t){t.pts=Zs(t.pts,b)})),!i||y<0){const t=p.length;if(p=p.filter((t=>t.pts>=0)),t!==p.length&&this.warn(`Removed ${p.length-t} of ${t} samples (initPTS ${T} / ${n})`),!p.length)return;y=0===s?0:r&&!m?Math.max(0,b-T):p[0].pts-T}if("aac"===t.segmentCodec){const e=this.config.maxAudioFramesDrift;for(let i=0,r=y+T;i<p.length;i++){const s=p[i],a=s.pts,o=a-r,l=Math.abs(1e3*o/n);if(o<=-e*d&&m)0===i&&(this.warn(`Audio frame @ ${(a/n).toFixed(3)}s overlaps marker by ${Math.round(1e3*o/n)} ms.`),this.nextAudioTs=y=a-T,r=a);else if(o>=e*d&&l<1e4&&m){let e=Math.round(o/d);for(r=a-e*d;r<0&&e&&d;)e--,r+=d;0===i&&(this.nextAudioTs=y=r-T),this.warn(`Injecting ${e} audio frames @ ${((r-T)/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n<e;n++){let e=Gs.getSilentFrame(t.parsedCodec||t.manifestCodec||t.codec,t.channelCount);e||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),e=s.unit.subarray()),p.splice(i,0,{unit:e,pts:r}),r+=d,i++}}s.pts=r,r+=d}}let S,A=null,L=null,k=0,R=p.length;for(;R--;)k+=p[R].unit.byteLength;for(let e=0,r=p.length;e<r;e++){const r=p[e],s=r.unit;let n=r.pts;if(null!==L){g[e-1].duration=Math.round((n-L)/u)}else{if(i&&"aac"===t.segmentCodec&&(n=y+T),A=n,!(k>0))return;k+=v;try{S=new Uint8Array(k)}catch(t){return void this.observer.emit(l.ERROR,l.ERROR,{type:a.MUX_ERROR,details:o.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:k,reason:`fail allocating audio mdat ${k}`})}if(!f){new DataView(S.buffer).setUint32(0,k),S.set(Vs.types.mdat,4)}}S.set(s,v);const d=s.byteLength;v+=d,g.push(Xs(!0,c,d,0)),L=n}const I=g.length;if(!I)return;const _=g[g.length-1];y=L-T,this.nextAudioTs=y+u*_.duration;const w=f?new Uint8Array(0):Vs.moof(t.sequenceNumber++,A/u,E({},t,{samples:g}));t.samples=[];const P=(A-T)/n,D=this.nextAudioTs/n,C={data1:w,data2:S,startPTS:P,endPTS:D,startDTS:P,endDTS:D,type:"audio",hasAudio:!0,hasVideo:!1,nb:I};return this.isAudioContiguous=!0,C}}function Zs(t,e){let i;if(null===e)return t;for(i=e<t?-8589934592:8589934592;Math.abs(t-e)>4294967296;)t+=i;return t}function Js(t,e,i,r){const s=t.samples.length;if(!s)return;const n=t.inputTimeScale;for(let a=0;a<s;a++){const s=t.samples[a];s.pts=Zs(s.pts-i.baseTime*n/i.timescale,e*n)/n,s.dts=Zs(s.dts-r.baseTime*n/r.timescale,e*n)/n}const a=t.samples;return t.samples=[],{samples:a}}function tn(t,e,i){const r=t.samples.length;if(!r)return;const s=t.inputTimeScale;for(let n=0;n<r;n++){const r=t.samples[n];r.pts=Zs(r.pts-i.baseTime*s/i.timescale,e*s)/s}t.samples.sort(((t,e)=>t.pts-e.pts));const n=t.samples;return t.samples=[],{samples:n}}function en(t,e,i=!1){return void 0!==(null==t?void 0:t.start)?(t.start+(i?t.duration:0))/t.timescale:e}function rn(t,e,i){const r=t.codec;if(r&&r.length>4)return r;if(e===j){if("ec-3"===r||"ac-3"===r||"alac"===r)return r;if("fLaC"===r||"Opus"===r){return xt(r,!1)}return i.warn(`Unhandled audio codec "${r}" in mp4 MAP`),r||"mp4a"}return i.warn(`Unhandled video codec "${r}" in mp4 MAP`),r||"avc1"}try{Ys=self.performance.now.bind(self.performance)}catch(t){Ys=Date.now}const sn=[{demux:class{constructor(t,e){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=e}resetTimeStamp(){}resetInitSegment(t,e,i,r){const s=this.videoTrack=cs("video",1),n=this.audioTrack=cs("audio",1),a=this.txtTrack=cs("text",1);if(this.id3Track=cs("id3",1),this.timeOffset=0,null==t||!t.byteLength)return;const o=lt(t);if(o.video){const{id:t,timescale:e,codec:i,supplemental:r}=o.video;s.id=t,s.timescale=a.timescale=e,s.codec=i,s.supplemental=r}if(o.audio){const{id:t,timescale:e,codec:i}=o.audio;n.id=t,n.timescale=e,n.codec=i}a.id=tt.text,s.sampleDuration=0,s.duration=n.duration=r}resetContiguity(){this.remainderData=null}static probe(t){return function(t){const e=t.byteLength;for(let i=0;i<e;){const r=rt(t,i);if(r>8&&109===t[i+4]&&111===t[i+5]&&111===t[i+6]&&102===t[i+7])return!0;i=r>1?i+r:e}return!1}(t)}demux(t,e){this.timeOffset=e;let i=t;const r=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=pt(this.remainderData,t));const e=function(t){const e={valid:null,remainder:null},i=at(t,["moof"]);if(i.length<2)return e.remainder=t,e;const r=i[i.length-1];return e.valid=t.slice(0,r.byteOffset-8),e.remainder=t.slice(r.byteOffset-8),e}(i);this.remainderData=e.remainder,r.samples=e.valid||new Uint8Array}else r.samples=i;const n=this.extractID3Track(r,e);return s.samples=vt(e,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const t=this.timeOffset,e=this.videoTrack,i=this.txtTrack;e.samples=this.remainderData||new Uint8Array,this.remainderData=null;const r=this.extractID3Track(e,this.timeOffset);return i.samples=vt(t,e),{videoTrack:e,audioTrack:cs(),id3Track:r,textTrack:cs()}}extractID3Track(t,e){const i=this.id3Track;if(t.samples.length){const r=at(t.samples,["emsg"]);r&&r.forEach((t=>{const r=function(t){const e=t[0];let i="",r="",n=0,a=0,o=0,l=0,u=0,c=0;if(0===e){for(;"\0"!==et(t.subarray(c,c+1));)i+=et(t.subarray(c,c+1)),c+=1;for(i+=et(t.subarray(c,c+1)),c+=1;"\0"!==et(t.subarray(c,c+1));)r+=et(t.subarray(c,c+1)),c+=1;r+=et(t.subarray(c,c+1)),c+=1,n=rt(t,12),a=rt(t,16),l=rt(t,20),u=rt(t,24),c=28}else if(1===e){c+=4,n=rt(t,c),c+=4;const e=rt(t,c);c+=4;const a=rt(t,c);for(c+=4,o=2**32*e+a,s(o)||(o=Number.MAX_SAFE_INTEGER,_.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),l=rt(t,c),c+=4,u=rt(t,c),c+=4;"\0"!==et(t.subarray(c,c+1));)i+=et(t.subarray(c,c+1)),c+=1;for(i+=et(t.subarray(c,c+1)),c+=1;"\0"!==et(t.subarray(c,c+1));)r+=et(t.subarray(c,c+1)),c+=1;r+=et(t.subarray(c,c+1)),c+=1}return{schemeIdUri:i,value:r,timeScale:n,presentationTime:o,presentationTimeDelta:a,eventDuration:l,id:u,payload:t.subarray(c,t.byteLength)}}(t);if(Rs.test(r.schemeIdUri)){const t=Is(r,e);let s=4294967295===r.eventDuration?Number.POSITIVE_INFINITY:r.eventDuration/r.timeScale;s<=.001&&(s=Number.POSITIVE_INFINITY);const n=r.payload;i.samples.push({data:n,len:n.byteLength,dts:t,pts:t,type:us.emsg,duration:s})}else if(this.config.enableEmsgKLVMetadata&&r.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const t=Is(r,e);i.samples.push({data:r.payload,len:r.payload.byteLength,dts:t,pts:t,type:us.misbklv,duration:Number.POSITIVE_INFINITY})}}))}return i}demuxSampleAes(t,e,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}},remux:class extends S{constructor(t,e,i,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(t){this.lastEndTime=null;const e=this.initPTS;e&&t&&e.baseTime===t.baseTime&&e.timescale===t.timescale||(this.initPTS=t)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(t,e,i,r){this.audioCodec=e,this.videoCodec=i,this.generateInitSegment(t,r),this.emitInitSegment=!0}generateInitSegment(t,e){let{audioCodec:i,videoCodec:r}=this;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const{audio:s,video:n}=this.initData=lt(t);if(e)!function(t,e){if(!t||!e)return;const i=e.keyId;i&&e.isCommonEncryption&&gt(t,((t,e)=>{const r=t.subarray(8,24);r.some((t=>0!==t))||(_.log(`[eme] Patching keyId in 'enc${e?"a":"v"}>sinf>>tenc' box: ${C(r)} -> ${C(i)}`),t.set(i,8))}))}(t,e);else{const t=s||n;null!=t&&t.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${t.codec}")!`)}s&&(i=rn(s,j,this)),n&&(r=rn(n,K,this));const a={};s&&n?a.audiovideo={container:"video/mp4",codec:i+","+r,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:t,id:"main"}:s?a.audio={container:"audio/mp4",codec:i,encrypted:s.encrypted,initSegment:t,id:"audio"}:n?a.video={container:"video/mp4",codec:r,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:t,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=a}remux(t,e,i,s,n,a){var o,l;let{initPTS:u,lastEndTime:c}=this;const d={audio:void 0,video:void 0,text:s,id3:i,initSegment:void 0};r(c)||(c=this.lastEndTime=n||0);const h=e.samples;if(!h.length)return d;const f={initPTS:void 0,timescale:void 0,trackId:void 0};let g=this.initData;if(null!=(o=g)&&o.length||(this.generateInitSegment(h),g=this.initData),null==(l=g)||!l.length)return this.warn("Failed to generate initSegment."),d;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const m=function(t,e,i){const s={},n=at(t,["moof","traf"]);for(let t=0;t<n.length;t++){const a=n[t],o=at(a,["tfhd"])[0],l=rt(o,4),u=e[l];if(!u)continue;s[l]||(s[l]={start:NaN,duration:0,sampleCount:0,timescale:u.timescale,type:u.type});const c=s[l],d=at(a,["tfdt"])[0];if(d){const t=d[0];let e=rt(d,4);1===t&&(e===Z?i.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(e*=Z+1,e+=rt(d,8))),r(e)&&(!r(c.start)||e<c.start)&&(c.start=e)}const h=u.default,f=rt(o,0)|(null==h?void 0:h.flags);let g=(null==h?void 0:h.duration)||0;8&f&&(g=rt(o,2&f?12:8));const m=at(a,["trun"]);let p=c.start||0,v=0,y=g;for(let t=0;t<m.length;t++){const e=m[t],i=rt(e,4),r=c.sampleCount;c.sampleCount+=i;const s=1&e[3],n=4&e[3],a=1&e[2],o=2&e[2],l=4&e[2],u=8&e[2];let d=8,h=i;for(s&&(d+=4),n&&i&&(1&e[d+1]||void 0!==c.keyFrameIndex||(c.keyFrameIndex=r),d+=4,a?(y=rt(e,d),d+=4):y=g,o&&(d+=4),u&&(d+=4),p+=y,v+=y,h--);h--;)a?(y=rt(e,d),d+=4):y=g,o&&(d+=4),l&&(1&e[d+1]||void 0===c.keyFrameIndex&&(c.keyFrameIndex=c.sampleCount-(h+1),c.keyFrameStart=p),d+=4),u&&(d+=4),p+=y,v+=y;!v&&g&&(v+=g*i)}c.duration+=v}if(!Object.keys(s).some((t=>s[t].duration))){let e=Infinity,i=0;const n=at(t,["sidx"]);for(let t=0;t<n.length;t++){const r=ot(n[t]);if(null!=r&&r.references){e=Math.min(e,r.earliestPresentationTime/r.timescale);const t=r.references.reduce(((t,e)=>t+e.info.duration||0),0);i=Math.max(i,t+r.earliestPresentationTime/r.timescale)}}i&&r(i)&&Object.keys(s).forEach((t=>{s[t].duration||(s[t].duration=i*s[t].timescale-s[t].start)}))}return s}(h,g,this),p=g.audio?m[g.audio.id]:null,v=g.video?m[g.video.id]:null,y=en(v,Infinity),E=en(p,Infinity),T=en(v,0,!0),b=en(p,0,!0);let S=n,A=0;const L=p&&(!v||!u&&E<y||u&&u.trackId===g.audio.id),k=L?p:v;if(k){const t=k.timescale,e=k.start-n*t,i=L?g.audio.id:g.video.id;S=k.start/t,A=L?b-E:T-y,!a&&u||!function(t,e,i,r){if(null===t)return!0;const s=Math.max(r,1),n=e-t.baseTime/t.timescale;return Math.abs(n-i)>s}(u,S,n,A)&&t===u.timescale||(u&&this.warn(`Timestamps at playlist time: ${a?"":"~"}${n} ${e/t} != initPTS: ${u.baseTime/u.timescale} (${u.baseTime}/${u.timescale}) trackId: ${u.trackId}`),this.log(`Found initPTS at playlist time: ${n} offset: ${S-n} (${e}/${t}) trackId: ${i}`),u=null,f.initPTS=e,f.timescale=t,f.trackId=i)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${n}`);u?(f.initPTS=u.baseTime,f.timescale=u.timescale,f.trackId=u.trackId):(f.timescale&&void 0!==f.trackId&&void 0!==f.initPTS||(this.warn("Could not set initPTS"),f.initPTS=S,f.timescale=1,f.trackId=-1),this.initPTS=u={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});const R=S-u.baseTime/u.timescale,I=R+A;A>0?this.lastEndTime=I:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const _=!!g.audio,w=!!g.video;let P="";_&&(P+="audio"),w&&(P+="video");const D={data1:h,startPTS:R,startDTS:R,endPTS:I,endDTS:I,type:P,hasAudio:_,hasVideo:w,nb:1,dropped:0,encrypted:!!g.audio&&g.audio.encrypted||!!g.video&&g.video.encrypted};d.audio=_&&!w?D:void 0,d.video=w?D:void 0;const C=null==v?void 0:v.sampleCount;if(C){const t=v.keyFrameIndex,e=-1!==t;D.nb=C,D.dropped=0===t||this.isVideoContiguous?0:e?t:C,D.independent=e,D.firstKeyFrame=t,e&&v.keyFrameStart&&(D.firstKeyFramePTS=(v.keyFrameStart-u.baseTime)/u.timescale),this.isVideoContiguous||(d.independent=e),this.isVideoContiguous||(this.isVideoContiguous=e),D.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${t}/${C} dropped: ${D.dropped} start: ${D.firstKeyFramePTS||"NA"}`)}return d.initSegment=f,d.id3=Js(i,n,u,u),s.samples.length&&(d.text=tn(s,n,u)),d}}},{demux:xs,remux:Qs},{demux:class extends ds{constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.observer=t,this.config=e}resetInitSegment(t,e,i,r){super.resetInitSegment(t,e,i,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:r,inputTimeScale:9e4,dropped:0}}static probe(t,e){if(!t)return!1;const i=Kr(t,0);let r=(null==i?void 0:i.length)||0;if(Ss(t,r))return!1;for(let i=t.length;r<i;r++)if(Xr(t,r))return e.log("ADTS sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return function(t,e){return e+5<t.length}(t,e)&&Wr(t,e)&&qr(t,e)<=t.length-e}(t,e)}appendFrame(t,e,i){Qr(t,this.observer,e,i,t.manifestCodec);const r=Jr(t,e,i,this.basePTS,this.frameIndex);if(r&&0===r.missing)return r}},remux:Qs},{demux:class extends ds{resetInitSegment(t,e,i,r){super.resetInitSegment(t,e,i,r),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:r,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=Kr(t,0);let i=(null==e?void 0:e.length)||0;if(e&&11===t[i]&&119===t[i+1]&&void 0!==ls(e)&&As(t,i)<=16)return!1;for(let e=t.length;i<e;i++)if(Ss(t,i))return _.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return Ts(t,e)&&4<=t.length-e}(t,e)}appendFrame(t,e,i){if(null!==this.basePTS)return ys(t,e,i,this.basePTS,this.frameIndex)}},remux:Qs}];sn.splice(2,0,{demux:Ls,remux:Qs});class nn{constructor(t,e,i,r,s,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=t,this.typeSupported=e,this.config=i,this.id=s,this.logger=n}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,i,r){const s=i.transmuxing;s.executeStart=Ys();let n=new Uint8Array(t);const{currentTransmuxState:u,transmuxConfig:c}=this;r&&(this.currentTransmuxState=r);const{contiguous:d,discontinuity:h,trackSwitch:f,accurateTimeOffset:g,timeOffset:m,initSegmentChange:p}=r||u,{audioCodec:v,videoCodec:y,defaultInitPts:E,duration:T,initSegmentData:b}=c,S=function(t,e){let i=null;t.byteLength>0&&null!=(null==e?void 0:e.key)&&null!==e.iv&&null!=e.method&&(i=e);return i}(n,e);if(S&&pi(S.method)){const t=this.getDecrypter(),e=vi(S.method);if(!t.isSync())return this.asyncResult=!0,this.decryptionPromise=t.webCryptoDecrypt(n,S.key.buffer,S.iv.buffer,e).then((t=>{const e=this.push(t,null,i);return this.decryptionPromise=null,e})),this.decryptionPromise;{let r=t.softwareDecrypt(n,S.key.buffer,S.iv.buffer,e);if(i.part>-1){const e=t.flush();r=e?e.buffer:e}if(!r)return s.executeEnd=Ys(),an(i);n=new Uint8Array(r)}}const A=this.needsProbing(h,f);if(A){const t=this.configureTransmuxer(n);if(t)return this.logger.warn(`[transmuxer] ${t.message}`),this.observer.emit(l.ERROR,l.ERROR,{type:a.MEDIA_ERROR,details:o.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),s.executeEnd=Ys(),an(i)}(h||f||p||A)&&this.resetInitSegment(b,v,y,T,e),(h||p||A)&&this.resetInitialTimestamp(E),d||this.resetContiguity();const L=this.transmux(n,S,m,g,i);this.asyncResult=on(L);const k=this.currentTransmuxState;return k.contiguous=!0,k.discontinuity=!1,k.trackSwitch=!1,s.executeEnd=Ys(),L}flush(t){const e=t.transmuxing;e.executeStart=Ys();const{decrypter:i,currentTransmuxState:r,decryptionPromise:s}=this;if(s)return this.asyncResult=!0,s.then((()=>this.flush(t)));const n=[],{timeOffset:a}=r;if(i){const e=i.flush();e&&n.push(this.push(e.buffer,null,t))}const{demuxer:o,remuxer:l}=this;if(!o||!l){e.executeEnd=Ys();const i=[an(t)];return this.asyncResult?Promise.resolve(i):i}const u=o.flush(a);return on(u)?(this.asyncResult=!0,u.then((e=>(this.flushRemux(n,e,t),n)))):(this.flushRemux(n,u,t),this.asyncResult?Promise.resolve(n):n)}flushRemux(t,e,i){const{audioTrack:r,videoTrack:s,id3Track:n,textTrack:a}=e,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id===f?"level":"track"} ${i.level}`);const u=this.remuxer.remux(r,s,n,a,l,o,!0,this.id);t.push({remuxResult:u,chunkMeta:i}),i.transmuxing.executeEnd=Ys()}resetInitialTimestamp(t){const{demuxer:e,remuxer:i}=this;e&&i&&(e.resetTimeStamp(t),i.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:e}=this;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())}resetInitSegment(t,e,i,r,s){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(t,e,i,r),a.resetInitSegment(t,e,i,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,e,i,r,s){let n;return n=e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,i,r,s):this.transmuxUnencrypted(t,i,r,s),n}transmuxUnencrypted(t,e,i,r){const{audioTrack:s,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(t,e,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,n,a,o,e,i,!1,this.id),chunkMeta:r}}transmuxSampleAes(t,e,i,r,s){return this.demuxer.demuxSampleAes(t,e,i).then((t=>({remuxResult:this.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,i,r,!1,this.id),chunkMeta:s})))}configureTransmuxer(t){const{config:e,observer:i,typeSupported:r}=this;let s;for(let e=0,i=sn.length;e<i;e++){var n;if(null!=(n=sn[e].demux)&&n.probe(t,this.logger)){s=sn[e];break}}if(!s)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=s.remux,u=s.demux;o&&o instanceof l||(this.remuxer=new l(i,e,r,this.logger)),a&&a instanceof u||(this.demuxer=new u(i,e,r,this.logger),this.probe=u.probe)}needsProbing(t,e){return!this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new Ye(this.config)),t}}const an=t=>({remuxResult:{},chunkMeta:t});function on(t){return"then"in t&&t.then instanceof Function}class ln{constructor(t,e,i,r,s){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=e,this.initSegmentData=i,this.duration=r,this.defaultInitPts=s||null}}class un{constructor(t,e,i,r,s,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=t,this.contiguous=e,this.accurateTimeOffset=i,this.trackSwitch=r,this.timeOffset=s,this.initSegmentChange=n}}let cn=0;class dn{constructor(t,e,i,r){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=cn++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=t=>{const e=t.data,i=this.hls;if(i&&null!=e&&e.event&&e.instanceNo===this.instanceNo)switch(e.event){case"init":{var r;const t=null==(r=this.workerContext)?void 0:r.objectURL;t&&self.URL.revokeObjectURL(t);break}case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;case"workerLog":i.logger[e.data.logType]&&i.logger[e.data.logType](e.data.message);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.part=this.part,e.data.id=this.id,i.trigger(e.event,e.data)}},this.onWorkerError=t=>{if(!this.hls)return;const e=new Error(`${t.message}  (${t.filename}:${t.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(l.ERROR,{type:a.OTHER_ERROR,details:o.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:e})};const s=t.config;this.hls=t,this.id=e,this.useWorker=!!s.enableWorker,this.onTransmuxComplete=i,this.onFlush=r;const n=(t,e)=>{(e=e||{}).frag=this.frag||void 0,t===l.ERROR&&(e.parent=this.id,e.part=this.part,this.error=e.error),this.hls.trigger(t,e)};this.observer=new Ur,this.observer.on(l.FRAG_DECRYPTED,n),this.observer.on(l.ERROR,n);const u=Bt(s.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const i=this.hls.logger;if(s.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{s.workerPath?(i.log(`loading Web Worker ${s.workerPath} for "${e}"`),this.workerContext=function(t){const e=Gr[t];if(e)return e.clientCount++,e;const i=new self.URL(t,self.location.href).href,r={worker:new self.Worker(i),scriptURL:i,clientCount:1};return Gr[t]=r,r}(s.workerPath)):(i.log(`injecting Web Worker for "${e}"`),this.workerContext=function(){const t=Gr[$r];if(t)return t.clientCount++,t;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),i=self.URL.createObjectURL(e),r={worker:new self.Worker(i),objectURL:i,clientCount:1};return Gr[$r]=r,r}());const{worker:t}=this.workerContext;t.addEventListener("message",this.onWorkerMessage),t.addEventListener("error",this.onWorkerError),t.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:u,id:e,config:re(s)})}catch(r){i.warn(`Error setting up "${e}" Web Worker, fallback to inline`,r),this.terminateWorker(),this.error=null,this.transmuxer=new nn(this.observer,u,s,"",e,t.logger)}return}}this.transmuxer=new nn(this.observer,u,s,"",e,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=cn++;const e=this.hls.config,i=Bt(e.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:i,id:this.id,config:re(e)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),function(t){const e=Gr[t||$r];if(e&&1==e.clientCount--){const{worker:i,objectURL:r}=e;delete Gr[t||$r],r&&self.URL.revokeObjectURL(r),i.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(t,e,i,r,s,n,a,o,l,u){var c,d;l.transmuxing.start=self.performance.now();const{instanceNo:h,transmuxer:g}=this,m=n?n.start:s.start,p=s.decryptdata,v=this.frag,y=!(v&&s.cc===v.cc),E=!(v&&l.level===v.level),T=v?l.sn-v.sn:-1,b=this.part?l.part-this.part.index:-1,S=0===T&&l.id>1&&l.id===(null==v?void 0:v.stats.chunkCount),A=!E&&(1===T||0===T&&(1===b||S&&b<=0)),L=self.performance.now();(E||T||0===s.stats.parsing.start)&&(s.stats.parsing.start=L),!n||!b&&A||(n.stats.parsing.start=L);const k=!(v&&(null==(c=s.initSegment)?void 0:c.url)===(null==(d=v.initSegment)?void 0:d.url)),R=new un(y,A,o,E,m,k);if(!A||y||k){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${s.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===f?"level":"track"}: ${l.level} id: ${l.id}\n        discontinuity: ${y}\n        trackSwitch: ${E}\n        contiguous: ${A}\n        accurateTimeOffset: ${o}\n        timeOffset: ${m}\n        initSegmentChange: ${k}`);const t=new ln(i,r,e,a,u);this.configureTransmuxer(t)}if(this.frag=s,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:h,cmd:"demux",data:t,decryptdata:p,chunkMeta:l,state:R},t instanceof ArrayBuffer?[t]:[]);else if(g){const e=g.push(t,p,l,R);on(e)?e.then((t=>{this.handleTransmuxComplete(t)})).catch((t=>{this.transmuxerError(t,l,"transmuxer-interface push error")})):this.handleTransmuxComplete(e)}}flush(t){t.transmuxing.start=self.performance.now();const{instanceNo:e,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:e,cmd:"flush",chunkMeta:t});else if(i){const e=i.flush(t);on(e)?e.then((e=>{this.handleFlushResult(e,t)})).catch((e=>{this.transmuxerError(e,t,"transmuxer-interface flush error")})):this.handleFlushResult(e,t)}}transmuxerError(t,e,i){this.hls&&(this.error=t,this.hls.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.FRAG_PARSING_ERROR,chunkMeta:e,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:t,err:t,reason:i}))}handleFlushResult(t,e){t.forEach((t=>{this.handleTransmuxComplete(t)})),this.onFlush(e)}configureTransmuxer(t){const{instanceNo:e,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:e,cmd:"configure",config:t}):i&&i.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}class hn extends S{constructor(t,e){super(e,t.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=t}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,e,i){const r=null==e?void 0:e.renditionReports;if(r){let s=-1;for(let i=0;i<r.length;i++){const n=r[i];let a;try{a=new self.URL(n.URI,e.url).href}catch(t){this.warn(`Could not construct new URL for Rendition Report: ${t}`),a=n.URI||""}if(a===t){s=i;break}a===t.substring(0,a.length)&&(s=i)}if(-1!==s){const t=r[s],n=parseInt(t["LAST-MSN"])||e.lastPartSn;let a=parseInt(t["LAST-PART"])||e.lastPartIndex;if(this.hls.config.lowLatencyMode){const t=Math.min(e.age-e.partTarget,e.targetduration);a>=0&&t>e.partTarget&&(a+=1)}const o=i&&Zt(i);return new Jt(n,a>=0?a:void 0,o)}}}loadPlaylist(t){this.clearTimer()}loadingPlaylist(t,e){this.clearTimer()}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}getUrlWithDirectives(t,e){if(e)try{return e.addDirectives(t)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}return t}playlistLoaded(t,e,i){const{details:r,stats:s}=e,n=self.performance.now(),u=s.loading.first?Math.max(0,n-s.loading.first):0;r.advancedDateTime=Date.now()-u;const c=this.hls.config.timelineOffset;if(c!==r.appliedTimelineOffset){const t=Math.max(c||0,0);r.appliedTimelineOffset=t,r.fragments.forEach((e=>{e.setStart(e.playlistOffset+t)}))}if(r.live||null!=i&&i.live){const c="levelInfo"in e?e.levelInfo:e.track;if(r.reloaded(i),i&&r.fragments.length>0){ir(i,r,this);const t=r.playlistParsingError;if(t){this.warn(t);const i=this.hls;if(!i.config.ignorePlaylistParsingErrors){var d;const{networkDetails:n}=e;return void i.trigger(l.ERROR,{type:a.NETWORK_ERROR,details:o.LEVEL_PARSING_ERROR,fatal:!1,url:r.url,error:t,reason:t.message,level:e.level||void 0,parent:null==(d=r.fragments[0])?void 0:d.type,networkDetails:n,stats:s})}r.playlistParsingError=null}}-1===r.requestScheduled&&(r.requestScheduled=s.loading.start);const h=this.hls.mainForwardBufferInfo,f=h?h.end-h.len:0,g=ar(r,1e3*(r.edge-f));if(r.requestScheduled+g<n?r.requestScheduled=n:r.requestScheduled+=g,this.log(`live playlist ${t} ${r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED"}`),!this.canLoad||!r.live)return;let m,p,v;if(r.canBlockReload&&r.endSN&&r.advanced){const t=this.hls.config.lowLatencyMode,s=r.lastPartSn,a=r.endSN,o=r.lastPartIndex,l=s===a;-1!==o?l?(p=a+1,v=t?0:o):(p=s,v=t?o+1:r.maxPartIndex):p=a+1;const u=r.age,d=u+r.ageHeader;let h=Math.min(d-r.partTarget,1.5*r.targetduration);if(h>0){if(d>3*r.targetduration)this.log(`Playlist last advanced ${u.toFixed(2)}s ago. Omitting segment and part directives.`),p=void 0,v=void 0;else if(null!=i&&i.tuneInGoal&&d-r.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${h} with playlist age: ${r.age}`),h=0;else{const t=Math.floor(h/r.targetduration);if(p+=t,void 0!==v){v+=Math.round(h%r.targetduration/r.partTarget)}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${u.toFixed(2)}s goal: ${h} skip sn ${t} to part ${v}`)}r.tuneInGoal=h}if(m=this.getDeliveryDirectives(r,e.deliveryDirectives,p,v),t||!l)return r.requestScheduled=n,void this.loadingPlaylist(c,m)}else(r.canBlockReload||r.canSkipUntil)&&(m=this.getDeliveryDirectives(r,e.deliveryDirectives,p,v));m&&void 0!==p&&r.canBlockReload&&(r.requestScheduled=s.loading.first+Math.max(g-2*u,g/2)),this.scheduleLoading(c,m,r)}else this.clearTimer()}scheduleLoading(t,e,i){const r=i||t.details;if(!r)return void this.loadingPlaylist(t,e);const s=self.performance.now(),n=r.requestScheduled;if(s>=n)return void this.loadingPlaylist(t,e);const a=n-s;this.log(`reload live playlist ${t.name||t.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout((()=>this.loadingPlaylist(t,e)),a)}getDeliveryDirectives(t,e,i,r){let s=Zt(t);return null!=e&&e.skip&&t.deltaUpdateFailed&&(i=e.msn,r=e.part,s=zt),new Jt(i,r,s)}checkRetry(t){const e=t.details,i=ve(t),r=t.errorAction,{action:s,retryCount:n=0,retryConfig:a}=r||{},o=!!r&&!!a&&(s===_e||!r.resolved&&s===Re);if(o){var l;if(n>=a.maxNumRetry)return!1;if(i&&null!=(l=t.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{const t=be(a,n);this.clearTimer(),this.timer=self.setTimeout((()=>this.loadPlaylist()),t),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" in ${t}ms`)}t.levelRetry=!0,r.resolved=!0}return o}}function fn(t,e){if(t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(!gn(t[i].attrs,e[i].attrs))return!1;return!0}function gn(t,e,i){const r=t["STABLE-RENDITION-ID"];return r&&!i?r===e["STABLE-RENDITION-ID"]:!(i||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some((i=>t[i]!==e[i]))}function mn(t,e){return e.label.toLowerCase()===t.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(t.lang||"").toLowerCase())}class pn{constructor(t){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=t}destroy(){this.tracks=this.queues=null}append(t,e,i){if(null===this.queues||null===this.tracks)return;const r=this.queues[e];r.push(t),1!==r.length||i||this.executeNext(e)}appendBlocker(t){return new Promise((e=>{const i={label:"async-blocker",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,t)}))}prependBlocker(t){return new Promise((e=>{if(this.queues){const i={label:"async-blocker-prepend",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[t].unshift(i)}}))}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach((t=>{var e;const i=null==(e=t[0])?void 0:e.label;"async-blocker"!==i&&"async-blocker-prepend"!==i||(t[0].execute(),t.splice(0,1))}))}unblockAudio(t){if(null===this.queues)return;this.queues.audio[0]===t&&this.shiftAndExecuteNext("audio")}executeNext(t){if(null===this.queues||null===this.tracks)return;const e=this.queues[t];if(e.length){const r=e[0];try{r.execute()}catch(e){var i;if(r.onError(e),null===this.queues||null===this.tracks)return;const s=null==(i=this.tracks[t])?void 0:i.buffer;null!=s&&s.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){null!==this.queues&&(this.queues[t].shift(),this.executeNext(t))}current(t){var e;return(null==(e=this.queues)?void 0:e[t][0])||null}toString(){const{queues:t,tracks:e}=this;return null===t||null===e?"<destroyed>":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(t){var e,i;return null!=(e=this.queues)&&e[t]||null!=(i=this.tracks)&&i[t]?`${t}: (${this.listSbInfo(t)}) ${this.listOps(t)}`:""}listSbInfo(t){var e;const i=null==(e=this.tracks)?void 0:e[t],r=null==i?void 0:i.buffer;return r?`SourceBuffer${r.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(t){var e;return(null==(e=this.queues)?void 0:e[t].map((t=>t.label)).join(", "))||""}}const vn=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,yn="HlsJsTrackRemovedError";class En extends Error{constructor(t){super(t),this.name=yn}}function Tn(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach((e=>{t.removeChild(e)}))}function bn(t){return"audio"===t?1:0}class Sn{constructor(t){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:t}=this;t.on(l.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(l.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(l.MANIFEST_PARSED,this.onManifestParsed,this),t.on(l.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(l.BUFFER_CODECS,this.onBufferCodecs,this),t.on(l.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(l.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(l.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(l.MANIFEST_PARSED,this.onManifestParsed,this),t.off(l.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(l.BUFFER_CODECS,this.onBufferCodecs,this),t.off(l.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,e){const i=this.hls.levels[e.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(t,e){this.media=e.media instanceof HTMLVideoElement?e.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(t,e){const i=this.hls;this.restrictedLevels=[],this.firstLevel=e.firstLevel,i.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onLevelsUpdated(t,e){this.timer&&r(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,e){this.hls.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const t=this.hls.levels;if(t.length){const e=this.hls,i=this.getMaxLevel(t.length-1);i!==this.autoLevelCapping&&e.logger.log(`Setting autoLevelCapping to ${i}: ${t[i].height}p@${t[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),e.autoLevelCapping=i,e.autoLevelEnabled&&e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}}getMaxLevel(t){const e=this.hls.levels;if(!e.length)return-1;const i=e.filter(((e,i)=>this.isLevelAllowed(e)&&i<=t));return this.clientRect=null,Sn.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const t=this.media,e={width:0,height:0};if(t){const i=t.getBoundingClientRect();e.width=i.width,e.height=i.height,e.width||e.height||(e.width=i.right-i.left||t.width||0,e.height=i.bottom-i.top||t.height||0)}return this.clientRect=e,e}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch(t){}return Math.min(t,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(t){return!this.restrictedLevels.some((e=>t.bitrate===e.bitrate&&t.width===e.width&&t.height===e.height))}static getMaxLevelByMediaSize(t,e,i){if(null==t||!t.length)return-1;let r=t.length-1;const s=Math.max(e,i);for(let e=0;e<t.length;e+=1){const i=t[e];if((i.width>=s||i.height>=s)&&(n=i,!(a=t[e+1])||n.width!==a.width||n.height!==a.height)){r=e;break}}var n,a;return r}}const An={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Ln={HLS:"h"};class kn{constructor(t,e){Array.isArray(t)&&(t=t.map((t=>t instanceof kn?t:new kn(t)))),this.value=t,this.params=e}}function Rn(t,e,i,r){return new Error(`failed to ${t} "${s=e,Array.isArray(s)?JSON.stringify(s):s instanceof Map?"Map{}":s instanceof Set?"Set{}":"object"==typeof s?JSON.stringify(s):String(s)}" as ${i}`,{cause:r});var s}function In(t,e,i){return Rn("serialize",t,e,i)}class _n{constructor(t){this.description=t}}const wn="Bare Item";function Pn(t){if(!1===ArrayBuffer.isView(t))throw In(t,"Byte Sequence");return`:${e=t,btoa(String.fromCharCode(...e))}:`;var e}function Dn(t){if(function(t){return t<-999999999999999||999999999999999<t}(t))throw In(t,"Integer");return t.toString()}function Cn(t,e){if(t<0)return-Cn(-t,e);const i=Math.pow(10,e);if(Math.abs(t*i%1-.5)<Number.EPSILON){const e=Math.floor(t*i);return(e%2==0?e:e+1)/i}return Math.round(t*i)/i}function On(t){const e=Cn(t,3);if(Math.floor(Math.abs(e)).toString().length>12)throw In(t,"Decimal");const i=e.toString();return i.includes(".")?i:`${i}.0`}const xn=/[\x00-\x1f\x7f]+/;function Mn(t){const e=(i=t).description||i.toString().slice(7,-1);var i;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e))throw In(e,"Token");return e}function Fn(t){switch(typeof t){case"number":if(!r(t))throw In(t,wn);return Number.isInteger(t)?Dn(t):On(t);case"string":return function(t){if(xn.test(t))throw In(t,"String");return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(t);case"symbol":return Mn(t);case"boolean":return function(t){if("boolean"!=typeof t)throw In(t,"Boolean");return t?"?1":"?0"}(t);case"object":if(t instanceof Date)return function(t){return`@${Dn(t.getTime()/1e3)}`}(t);if(t instanceof Uint8Array)return Pn(t);if(t instanceof _n)return Mn(t);default:throw In(t,wn)}}function Nn(t){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(t))throw In(t,"Key");return t}function Bn(t){return null==t?"":Object.entries(t).map((([t,e])=>!0===e?`;${Nn(t)}`:`;${Nn(t)}=${Fn(e)}`)).join("")}function Un(t){return t instanceof kn?`${Fn(t.value)}${Bn(t.params)}`:Fn(t)}function $n(t,e={whitespace:!0}){if("object"!=typeof t||null==t)throw In(t,"Dict");const i=t instanceof Map?t.entries():Object.entries(t),r=(null==e?void 0:e.whitespace)?" ":"";return Array.from(i).map((([t,e])=>{e instanceof kn==!1&&(e=new kn(e));let i=Nn(t);var r;return!0===e.value?i+=Bn(e.params):(i+="=",Array.isArray(e.value)?i+=`(${(r=e).value.map(Un).join(" ")})${Bn(r.params)}`:i+=Un(e)),i})).join(`,${r}`)}function Gn(t,e){return $n(t,e)}const Hn="CMCD-Object",Vn="CMCD-Request",jn="CMCD-Session",Kn="CMCD-Status",Wn={br:Hn,ab:Hn,d:Hn,ot:Hn,tb:Hn,tpb:Hn,lb:Hn,tab:Hn,lab:Hn,url:Hn,pb:Vn,bl:Vn,tbl:Vn,dl:Vn,ltc:Vn,mtp:Vn,nor:Vn,nrr:Vn,rc:Vn,sn:Vn,sta:Vn,su:Vn,ttfb:Vn,ttfbb:Vn,ttlb:Vn,cmsdd:Vn,cmsds:Vn,smrt:Vn,df:Vn,cs:Vn,ts:Vn,cid:jn,pr:jn,sf:jn,sid:jn,st:jn,v:jn,msd:jn,bs:Kn,bsd:Kn,cdn:Kn,rtp:Kn,bg:Kn,pt:Kn,ec:Kn,e:Kn},Yn=Vn;function qn(t,e){const i={};if(!t)return i;const r=Object.keys(t),s=e?(n=e,Object.keys(n).reduce(((t,e)=>{var i;return null===(i=n[e])||void 0===i||i.forEach((i=>t[i]=e)),t}),{})):{};var n;return r.reduce(((e,i)=>{var r;const n=Wn[i]||s[i]||Yn;return(null!==(r=e[n])&&void 0!==r?r:e[n]={})[i]=t[i],e}),i)}const zn="event";const Xn=t=>Math.round(t),Qn=(t,e)=>Array.isArray(t)?t.map((t=>Qn(t,e))):t instanceof kn&&"string"==typeof t.value?new kn(Qn(t.value,e),t.params):(e.baseUrl&&(t=function(t,e){const i=new URL(t),r=new URL(e);if(i.origin!==r.origin)return t;const s=i.pathname.split("/").slice(1),n=r.pathname.split("/").slice(1,-1);for(;s[0]===n[0];)s.shift(),n.shift();for(;n.length;)n.shift(),s.unshift("..");return s.join("/")+i.search+i.hash}(t,e.baseUrl)),1===e.version?encodeURIComponent(t):t),Zn=t=>100*Xn(t/100),Jn={br:Xn,d:Xn,bl:Zn,dl:Zn,mtp:Zn,nor:(t,e)=>{let i=t;return e.version>=2&&(t instanceof kn&&"string"==typeof t.value?i=new kn([t]):"string"==typeof t&&(i=[t])),Qn(i,e)},rtp:Zn,tb:Xn},ta="request",ea="response",ia=["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"],ra=["e"],sa=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function na(t){return sa.test(t)}const aa=["d","dl","nor","ot","rtp","su"];const oa=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];const la=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function ua(t){return la.includes(t)||na(t)}const ca={[ea]:function(t){return ia.includes(t)||aa.includes(t)||oa.includes(t)||na(t)},[zn]:function(t){return ia.includes(t)||ra.includes(t)||na(t)},[ta]:function(t){return ia.includes(t)||aa.includes(t)||na(t)}};function da(t,e={}){const i={};if(null==t||"object"!=typeof t)return i;const s=e.version||t.v||1,n=e.reportingMode||ta,a=1===s?ua:ca[n];let o=Object.keys(t).filter(a);const l=e.filter;"function"==typeof l&&(o=o.filter(l));const u=n===ea||n===zn;u&&!o.includes("ts")&&o.push("ts"),s>1&&!o.includes("v")&&o.push("v");const c=E({},Jn,e.formatters),d={version:s,reportingMode:n,baseUrl:e.baseUrl};return o.sort().forEach((e=>{let n=t[e];const a=c[e];if("function"==typeof a&&(n=a(n,d)),"v"===e){if(1===s)return;n=s}"pr"==e&&1===n||(u&&"ts"===e&&!r(n)&&(n=Date.now()),function(t){return"number"==typeof t?r(t):null!=t&&""!==t&&!1!==t}(n)&&(function(t){return["ot","sf","st","e","sta"].includes(t)}(e)&&"string"==typeof n&&(n=new _n(n)),i[e]=n))})),i}function ha(t,e,i){return E(t,function(t,e={}){const i={};if(!t)return i;const r=qn(da(t,e),null==e?void 0:e.customHeaderMap);return Object.entries(r).reduce(((t,[e,i])=>{const r=Gn(i,{whitespace:!1});return r&&(t[e]=r),t}),i)}(e,i))}function fa(t,e={}){if(!t)return"";const i=function(t,e={}){return t?Gn(da(t,e),{whitespace:!1}):""}(t,e);return encodeURIComponent(i)}const ga=/CMCD=[^&#]+/;function ma(t,e,i){const r=function(t,e={}){return t?`CMCD=${fa(t,e)}`:""}(e,i);if(!r)return t;if(ga.test(t))return t.replace(ga,r);const s=t.includes("?")?"&":"?";return`${t}${s}${r}`}function pa(t,e,i,r){t&&Object.keys(e).forEach((s=>{const n=t.filter((t=>t.groupId===s)).map((t=>{const n=E({},t);return n.details=void 0,n.attrs=new ci(n.attrs),n.url=n.attrs.URI=va(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),n.groupId=n.attrs["GROUP-ID"]=e[s],n.attrs["PATHWAY-ID"]=r,n}));t.push(...n)}))}function va(t,e,i,r){const{HOST:s,PARAMS:n,[i]:a}=r;let o;e&&(o=null==a?void 0:a[e],o&&(t=o));const l=new self.URL(t);return s&&!o&&(l.host=s),n&&Object.keys(n).sort().forEach((t=>{t&&l.searchParams.set(t,n[t])})),l.href}class ya extends S{constructor(t){super("eme",t.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=ya.CDMCleanupPromise?[ya.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{const{initDataType:e,initData:i}=t,r=`"${t.type}" event: init data type: "${e}"`;if(this.debug(r),null!==i){if(!this.keyFormatPromise){let t=Object.keys(this.keySystemAccessPromises);t.length||(t=Pi(this.config));const e=t.map(wi).filter((t=>!!t));this.keyFormatPromise=this.getKeyFormatPromise(e)}this.keyFormatPromise.then((s=>{const n=_i(s);if("sinf"!==e||n!==Ai.FAIRPLAY)return void this.log(`Ignoring "${t.type}" event with init data type: "${e}" for selected key-system ${n}`);let a;try{const t=et(new Uint8Array(i)),e=mt(yi(JSON.parse(t).sinf));if(!e)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");a=new Uint8Array(e.subarray(8,24))}catch(t){return void this.warn(`${r} Failed to parse sinf: ${t}`)}const o=C(a),{keyIdToKeySessionPromise:l,mediaKeySessions:u}=this;let c=l[o];for(let t=0;t<u.length;t++){const r=u[t],s=r.decryptdata;if(!s.keyId)continue;const n=C(s.keyId);if(gi(a,s.keyId)||-1!==s.uri.replace(/-/g,"").indexOf(o)){if(c=l[n],!c)continue;if(s.pssh)break;delete l[n],s.pssh=new Uint8Array(i),s.keyId=a,c=l[o]=c.then((()=>this.generateRequestWithPreferredKeySession(r,e,i,"encrypted-event-key-match"))),c.catch((t=>this.handleError(t)));break}}c||this.handleError(new Error(`Key ID ${o} not encountered in playlist. Key-system sessions ${u.length}.`))})).catch((t=>this.handleError(t)))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(l.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(l.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(l.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(l.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(l.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(l.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(l.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(l.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(l.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(l.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(t){const{drmSystems:e,widevineLicenseUrl:i}=this.config,r=null==e?void 0:e[t];return r?r.licenseUrl:t===Ai.WIDEVINE&&i?i:void 0}getLicenseServerUrlOrThrow(t){const e=this.getLicenseServerUrl(t);if(void 0===e)throw new Error(`no license server URL configured for key-system "${t}"`);return e}getServerCertificateUrl(t){const{drmSystems:e}=this.config,i=null==e?void 0:e[t];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const e=this.hls.levels,i=(t,e,i)=>!!t&&i.indexOf(t)===e,r=e.map((t=>t.audioCodec)).filter(i),s=e.map((t=>t.videoCodec)).filter(i);return r.length+s.length===0&&s.push("avc1.42e01e"),new Promise(((e,i)=>{const n=t=>{const l=t.shift();this.getMediaKeysPromise(l,r,s).then((t=>e({keySystem:l,mediaKeys:t}))).catch((e=>{t.length?n(t):i(e instanceof ba?e:new ba({type:a.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_NO_ACCESS,error:e,fatal:!0},e.message))}))};n(t)}))}requestMediaKeySystemAccess(t,e){const{requestMediaKeySystemAccessFunc:i}=this.config;if("function"!=typeof i){let t=`Configured requestMediaKeySystemAccess is not a function ${i}`;return null===Di&&"http:"===self.location.protocol&&(t=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(t))}return i(t,e)}getMediaKeysPromise(t,e,i){var r;const s=function(t,e,i,r){let s;switch(t){case Ai.FAIRPLAY:s=["cenc","sinf"];break;case Ai.WIDEVINE:case Ai.PLAYREADY:s=["cenc"];break;case Ai.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${t}`)}return function(t,e,i,r){return[{initDataTypes:t,persistentState:r.persistentState||"optional",distinctiveIdentifier:r.distinctiveIdentifier||"optional",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:e.map((t=>({contentType:`audio/mp4; codecs=${t}`,robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null}))),videoCapabilities:i.map((t=>({contentType:`video/mp4; codecs=${t}`,robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null})))}]}(s,e,i,r)}(t,e,i,this.config.drmSystemOptions||{});let n=this.keySystemAccessPromises[t],a=null==(r=n)?void 0:r.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${t}" key-system access with config: ${re(s)}`),a=this.requestMediaKeySystemAccess(t,s);const e=n=this.keySystemAccessPromises[t]={keySystemAccess:a};return a.catch((e=>{this.log(`Failed to obtain access to key-system "${t}": ${e}`)})),a.then((i=>{this.log(`Access for key-system "${i.keySystem}" obtained`);const r=this.fetchServerCertificate(t);this.log(`Create media-keys for "${t}"`);const s=e.mediaKeys=i.createMediaKeys().then((i=>(this.log(`Media-keys created for "${t}"`),e.hasMediaKeys=!0,r.then((e=>e?this.setMediaKeysServerCertificate(i,t,e):i)))));return s.catch((e=>{this.error(`Failed to create media-keys for "${t}"}: ${e}`)})),s}))}return a.then((()=>n.mediaKeys))}createMediaKeySessionContext({decryptdata:t,keySystem:e,mediaKeys:i}){this.log(`Creating key-system session "${e}" keyId: ${C(t.keyId||[])} keyUri: ${t.uri}`);const r=i.createSession(),s={decryptdata:t,keySystem:e,mediaKeys:i,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(s),s}renewKeySession(t){const e=t.decryptdata;if(e.pssh){const i=this.createMediaKeySessionContext(t),r=Ea(e),s="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(i,s,e.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}updateKeySession(t,e){const i=t.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyId ${C(t.decryptdata.keyId||[])}\n      } (data length: ${e.byteLength})`),i.update(e)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map((t=>({keySystem:t,hasMediaKeys:this.keySystemAccessPromises[t].hasMediaKeys}))).filter((({hasMediaKeys:t})=>!!t)).map((({keySystem:t})=>wi(t))).filter((t=>!!t))}getKeySystemAccess(t){return this.getKeySystemSelectionPromise(t).then((({keySystem:t,mediaKeys:e})=>this.attemptSetMediaKeys(t,e)))}selectKeySystem(t){return new Promise(((e,i)=>{this.getKeySystemSelectionPromise(t).then((({keySystem:t})=>{const r=wi(t);r?e(r):i(new Error(`Unable to find format for key-system "${t}"`))})).catch(i)}))}selectKeySystemFormat(t){const e=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)),this.keyFormatPromise}getKeyFormatPromise(t){const e=Pi(this.config),i=t.map(_i).filter((t=>!!t&&-1!==e.indexOf(t)));return this.selectKeySystem(i)}getKeyStatus(t){const{mediaKeySessions:e}=this;for(let i=0;i<e.length;i++){const r=Ta(t,e[i]);if(r)return r}}loadKey(t){const e=t.keyInfo.decryptdata,i=Ea(e),r=this.bannedKeyIds[i];if(r||"internal-error"===this.getKeyStatus(e)){const i=Sa(r||"internal-error",e);return this.handleError(i,t.frag),Promise.reject(i)}const s=`(keyId: ${i} format: "${e.keyFormat}" method: ${e.method} uri: ${e.uri})`;this.log(`Starting session for key ${s}`);const n=this.keyIdToKeySessionPromise[i];if(!n){const r=this.getKeySystemForKeyPromise(e).then((({keySystem:i,mediaKeys:r})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${s}`),this.attemptSetMediaKeys(i,r).then((()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:i,mediaKeys:r,decryptdata:e}))))))).then((t=>{const i=e.pssh?e.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(t,"cenc",i,"playlist-key")}));return r.catch((e=>this.handleError(e,t.frag))),this.keyIdToKeySessionPromise[i]=r,r}return n.catch((i=>{if(i instanceof ba){const r=b({},i.data);"internal-error"===this.getKeyStatus(e)&&(r.decryptdata=e);const s=new ba(r,i.message);this.handleError(s,t.frag)}})),n}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t,e){if(this.hls)if(t instanceof ba){e&&(t.data.frag=e);const i=t.data.decryptdata;this.error(`${t.message}${i?` (${C(i.keyId||[])})`:""}`),this.hls.trigger(l.ERROR,t.data)}else this.error(t.message),this.hls.trigger(l.ERROR,{type:a.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0})}getKeySystemForKeyPromise(t){const e=Ea(t),i=this.keyIdToKeySessionPromise[e];if(!i){const e=_i(t.keyFormat),i=e?[e]:Pi(this.config);return this.attemptKeySystemAccess(i)}return i}getKeySystemSelectionPromise(t){if(t.length||(t=Pi(this.config)),0===t.length)throw new ba({type:a.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${re({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}attemptSetMediaKeys(t,e){if(this.mediaResolved=void 0,this.mediaKeys===e)return Promise.resolve();const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const r=Promise.all(i).then((()=>this.media?this.media.setMediaKeys(e):new Promise(((t,i)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return i(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=e,this.media.setMediaKeys(e).then(t).catch(i)}}))));return this.mediaKeys=e,this.setMediaKeysQueue.push(r),r.then((()=>{this.log(`Media-keys set for "${t}"`),i.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter((t=>-1===i.indexOf(t)))}))}generateRequestWithPreferredKeySession(t,e,i,r){var s;const n=null==(s=this.config.drmSystems)||null==(s=s[t.keySystem])?void 0:s.generateRequest;if(n)try{const r=n.call(this.hls,e,i,t);if(!r)throw new Error("Invalid response from configured generateRequest filter");e=r.initDataType,i=r.initData?r.initData:null,t.decryptdata.pssh=i?new Uint8Array(i):null}catch(t){if(this.warn(t.message),this.hls&&this.hls.config.debug)throw t}if(null===i)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(t);const l=Ea(t.decryptdata),u=t.decryptdata.uri;this.log(`Generating key-session request for "${r}" keyId: ${l} URI: ${u} (init data type: ${e} length: ${i.byteLength})`);const c=new Ur,d=t._onmessage=e=>{const i=t.mediaKeysSession;if(!i)return void c.emit("error",new Error("invalid state"));const{messageType:r,message:s}=e;this.log(`"${r}" message event for session "${i.sessionId}" message size: ${s.byteLength}`),"license-request"===r||"license-renewal"===r?this.renewLicense(t,s).catch((t=>{c.eventNames().length?c.emit("error",t):this.handleError(t)})):"license-release"===r?t.keySystem===Ai.FAIRPLAY&&this.updateKeySession(t,Ei("acknowledged")).then((()=>this.removeSession(t))).catch((t=>this.handleError(t))):this.warn(`unhandled media key message type "${r}"`)},h=(t,e)=>{let i;e.keyStatus=t,t.startsWith("usable")?c.emit("resolved"):"internal-error"===t||"output-restricted"===t||"output-downscaled"===t?i=Sa(t,e.decryptdata):"expired"===t?i=new Error(`key expired (keyId: ${l})`):"released"===t?i=new Error("key released"):"status-pending"===t||this.warn(`unhandled key status change "${t}" (keyId: ${l})`),i&&(c.eventNames().length?c.emit("error",i):this.handleError(i))},f=t._onkeystatuseschange=e=>{if(!t.mediaKeysSession)return void c.emit("error",new Error("invalid state"));const i=this.getKeyStatuses(t);if(!Object.keys(i).some((t=>"status-pending"!==i[t])))return;if("expired"===i[l])return this.log(`Expired key ${re(i)} in key-session "${t.mediaKeysSession.sessionId}"`),void this.renewKeySession(t);let r=i[l];if(r)h(r,t);else{var s;const e=1e3;t.keyStatusTimeouts||(t.keyStatusTimeouts={}),(s=t.keyStatusTimeouts)[l]||(s[l]=self.setTimeout((()=>{if(!t.mediaKeysSession||!this.mediaKeys)return;const i=this.getKeyStatus(t.decryptdata);if(i&&"status-pending"!==i)return this.log(`No status for keyId ${l} in key-session "${t.mediaKeysSession.sessionId}". Using session key-status ${i} from other session.`),h(i,t);this.log(`key status for ${l} in key-session "${t.mediaKeysSession.sessionId}" timed out after ${e}ms`),r="internal-error",h(r,t)}),e)),this.log(`No status for keyId ${l} (${re(i)}).`)}};yr(t.mediaKeysSession,"message",d),yr(t.mediaKeysSession,"keystatuseschange",f);const g=new Promise(((t,e)=>{c.on("error",e),c.on("resolved",t)}));return t.mediaKeysSession.generateRequest(e,i).then((()=>{this.log(`Request generated for key-session "${t.mediaKeysSession.sessionId}" keyId: ${l} URI: ${u}`)})).catch((e=>{throw new ba({type:a.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_NO_SESSION,error:e,decryptdata:t.decryptdata,fatal:!1},`Error generating key-session request: ${e}`)})).then((()=>g)).catch((e=>(c.removeAllListeners(),this.removeSession(t).then((()=>{throw e}))))).then((()=>(c.removeAllListeners(),t)))}getKeyStatuses(t){const e={};return t.mediaKeysSession.keyStatuses.forEach(((i,r)=>{if("string"==typeof r&&"object"==typeof i){const t=r;r=i,i=t}const s="buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);if(t.keySystem===Ai.PLAYREADY&&16===s.length){const t=C(s);e[t]=i,Ti(s)}const n=C(s);"internal-error"===i&&(this.bannedKeyIds[n]=i),this.log(`key status change "${i}" for keyStatuses keyId: ${n} key-session "${t.mediaKeysSession.sessionId}"`),e[n]=i})),e}fetchServerCertificate(t){const e=this.config,i=new(0,e.loader)(e),r=this.getServerCertificateUrl(t);return r?(this.log(`Fetching server certificate for "${t}"`),new Promise(((s,n)=>{const l={responseType:"arraybuffer",url:r},u=e.certLoadPolicy.default,c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(t,e,i,r)=>{s(t.data)},onError:(e,i,s,u)=>{n(new ba({type:a.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:b({url:l.url,data:void 0},e)},`"${t}" certificate request failed (${r}). Status: ${e.code} (${e.text})`))},onTimeout:(e,i,s)=>{n(new ba({type:a.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:{url:l.url,data:void 0}},`"${t}" certificate request timed out (${r})`))},onAbort:(t,e,i)=>{n(new Error("aborted"))}};i.load(l,c,d)}))):Promise.resolve()}setMediaKeysServerCertificate(t,e,i){return new Promise(((r,s)=>{t.setServerCertificate(i).then((s=>{this.log(`setServerCertificate ${s?"success":"not supported by CDM"} (${i.byteLength}) on "${e}"`),r(t)})).catch((t=>{s(new ba({type:a.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:t,fatal:!0},t.message))}))}))}renewLicense(t,e){return this.requestLicense(t,new Uint8Array(e)).then((e=>this.updateKeySession(t,new Uint8Array(e)).catch((e=>{throw new ba({type:a.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t.decryptdata,error:e,fatal:!1},e.message)}))))}unpackPlayReadyKeyMessage(t,e){const i=String.fromCharCode.apply(null,new Uint16Array(e.buffer));if(!i.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),e;const r=(new DOMParser).parseFromString(i,"application/xml"),s=r.querySelectorAll("HttpHeader");if(s.length>0){let e;for(let i=0,r=s.length;i<r;i++){var n,a;e=s[i];const r=null==(n=e.querySelector("name"))?void 0:n.textContent,o=null==(a=e.querySelector("value"))?void 0:a.textContent;r&&o&&t.setRequestHeader(r,o)}}const o=r.querySelector("Challenge"),l=null==o?void 0:o.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return Ei(atob(l))}setupLicenseXHR(t,e,i,r){const s=this.config.licenseXhrSetup;return s?Promise.resolve().then((()=>{if(!i.decryptdata)throw new Error("Key removed");return s.call(this.hls,t,e,i,r)})).catch((n=>{if(!i.decryptdata)throw n;return t.open("POST",e,!0),s.call(this.hls,t,e,i,r)})).then((i=>{t.readyState||t.open("POST",e,!0);return{xhr:t,licenseChallenge:i||r}})):(t.open("POST",e,!0),Promise.resolve({xhr:t,licenseChallenge:r}))}requestLicense(t,e){const i=this.config.keyLoadPolicy.default;return new Promise(((r,s)=>{const n=this.getLicenseServerUrlOrThrow(t.keySystem);this.log(`Sending license request to URL: ${n}`);const l=new XMLHttpRequest;l.responseType="arraybuffer",l.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return s(new Error("invalid state"));if(4===l.readyState)if(200===l.status){this._requestLicenseFailureCount=0;let e=l.response;this.log(`License received ${e instanceof ArrayBuffer?e.byteLength:e}`);const i=this.config.licenseResponseCallback;if(i)try{e=i.call(this.hls,l,n,t)}catch(t){this.error(t)}r(e)}else{const u=i.errorRetry,c=u?u.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>c||l.status>=400&&l.status<500)s(new ba({type:a.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t.decryptdata,fatal:!0,networkDetails:l,response:{url:n,data:void 0,code:l.status,text:l.statusText}},`License Request XHR failed (${n}). Status: ${l.status} (${l.statusText})`));else{const i=c-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${i} attempts left`),this.requestLicense(t,e).then(r,s)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=l,this.setupLicenseXHR(l,n,t,e).then((({xhr:e,licenseChallenge:i})=>{t.keySystem==Ai.PLAYREADY&&(i=this.unpackPlayReadyKeyMessage(e,i)),e.send(i)})).catch(s)}))}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(t,e){if(!this.config.emeEnabled)return;const i=e.media;this.media=i,yr(i,"encrypted",this.onMediaEncrypted),yr(i,"waitingforkey",this.onWaitingForKey);const r=this.mediaResolved;r?r():this.mediaKeys=i.mediaKeys}onMediaDetached(){const t=this.media;t&&(Er(t,"encrypted",this.onMediaEncrypted),Er(t,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var t;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const e=this.mediaResolved;if(e&&e(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const i=this.media,r=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Mi.clearKeyUriToKeyIdMap();const s=r.length;ya.CDMCleanupPromise=Promise.all(r.map((t=>this.removeSession(t))).concat((null==i||null==(t=i.setMediaKeys(null))?void 0:t.catch((t=>{this.log(`Could not clear media keys: ${t}`),this.hls&&this.hls.trigger(l.ERROR,{type:a.OTHER_ERROR,details:o.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${t}`)})})))||Promise.resolve())).catch((t=>{this.log(`Could not close sessions and clear media keys: ${t}`),this.hls&&this.hls.trigger(l.ERROR,{type:a.OTHER_ERROR,details:o.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${t}`)})})).then((()=>{s&&this.log("finished closing key sessions and clearing media keys")}))}onManifestLoading(){this._clear()}onManifestLoaded(t,{sessionKeys:e}){if(e&&this.config.emeEnabled&&!this.keyFormatPromise){const t=e.reduce(((t,e)=>(-1===t.indexOf(e.keyFormat)&&t.push(e.keyFormat),t)),[]);this.log(`Selecting key-system from session-keys ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)}}removeSession(t){const{mediaKeysSession:e,licenseXhr:i,decryptdata:r}=t;if(e){this.log(`Remove licenses and keys and close session "${e.sessionId}" keyId: ${C((null==r?void 0:r.keyId)||[])}`),t._onmessage&&(e.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(e.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const s=this.mediaKeySessions.indexOf(t);s>-1&&this.mediaKeySessions.splice(s,1);const{keyStatusTimeouts:n}=t;n&&Object.keys(n).forEach((t=>self.clearTimeout(n[t])));const{drmSystemOptions:u}=this.config,c=function(t){var e;return!(!t||"persistent-license"!==t.sessionType&&(null==(e=t.sessionTypes)||!e.some((t=>"persistent-license"===t))))}(u)?new Promise(((t,i)=>{self.setTimeout((()=>i(new Error("MediaKeySession.remove() timeout"))),8e3),e.remove().then(t).catch(i)})):Promise.resolve();return c.catch((t=>{this.log(`Could not remove session: ${t}`),this.hls&&this.hls.trigger(l.ERROR,{type:a.OTHER_ERROR,details:o.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${t}`)})})).then((()=>e.close())).catch((t=>{this.log(`Could not close session: ${t}`),this.hls&&this.hls.trigger(l.ERROR,{type:a.OTHER_ERROR,details:o.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${t}`)})}))}return Promise.resolve()}}function Ea(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(null===t.keyId)throw new Error("keyId is null");return C(t.keyId)}function Ta(t,e){return t.keyId&&e.mediaKeysSession.keyStatuses.has(t.keyId)?e.mediaKeysSession.keyStatuses.get(t.keyId):t.matches(e.decryptdata)?e.keyStatus:void 0}ya.CDMCleanupPromise=void 0;class ba extends Error{constructor(t,e){super(e),this.data=void 0,t.error||(t.error=new Error(e)),this.data=t,t.err=t.error}}function Sa(t,e){const i="output-restricted"===t,r=i?o.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:o.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new ba({type:a.KEY_SYSTEM_ERROR,details:r,fatal:!1,decryptdata:e},i?"HDCP level output restricted":`key status changed to "${t}"`)}function Aa(t,e){let i;try{i=new Event("addtrack")}catch(t){i=document.createEvent("Event"),i.initEvent("addtrack",!1,!1)}i.track=t,e.dispatchEvent(i)}function La(t,e){const i=t.mode;if("disabled"===i&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(e.id))try{if(t.addCue(e),!t.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){_.debug(`[texttrack-utils]: ${i}`);try{const i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,t.addCue(i)}catch(t){_.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${t}`)}}"disabled"===i&&(t.mode=i)}function ka(t,e){const i=t.mode;if("disabled"===i&&(t.mode="hidden"),t.cues)for(let i=t.cues.length;i--;)e&&t.cues[i].removeEventListener("enter",e),t.removeCue(t.cues[i]);"disabled"===i&&(t.mode=i)}function Ra(t,e,i,r){const s=t.mode;if("disabled"===s&&(t.mode="hidden"),t.cues&&t.cues.length>0){const s=function(t,e,i){const r=[],s=function(t,e){if(e<=t[0].startTime)return 0;const i=t.length-1;if(e>t[i].endTime)return-1;let r,s=0,n=i;for(;s<=n;)if(r=Math.floor((n+s)/2),e<t[r].startTime)n=r-1;else{if(!(e>t[r].startTime&&s<i))return r;s=r+1}return t[s].startTime-e<e-t[n].startTime?s:n}(t,e);if(s>-1)for(let n=s,a=t.length;n<a;n++){const s=t[n];if(s.startTime>=e&&s.endTime<=i)r.push(s);else if(s.startTime>i)return r}return r}(t.cues,e,i);for(let e=0;e<s.length;e++)r&&!r(s[e])||t.removeCue(s[e])}"disabled"===s&&(t.mode=s)}function Ia(t){const e=[];for(let i=0;i<t.length;i++){const r=t[i];"subtitles"!==r.kind&&"captions"!==r.kind||!r.label||e.push(t[i])}return e}function _a(t){let e=5381,i=t.length;for(;i;)e=33*e^t.charCodeAt(--i);return(e>>>0).toString()}const wa=.025;let Pa=function(t){return t[t.Point=0]="Point",t[t.Range=1]="Range",t}({});function Da(t,e,i){return`${t.identifier}-${i+1}-${_a(e)}`}class Ca{constructor(t,e){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=e,this.dateRange=t,this.setDateRange(t)}setDateRange(t){this.dateRange=t,this.resumeOffset=t.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=t.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=t.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=t.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var t;this.appendInPlaceStarted=!1,null==(t=this.assetListLoader)||t.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(t){var e;if(t>0&&t>=this.assetList.length)return!0;const i=this.playoutLimit;if(t<=0||isNaN(i))return!1;if(0===i)return!0;return((null==(e=this.assetList[t])?void 0:e.startOffset)||0)>i}findAssetIndex(t){return this.assetList.indexOf(t)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const t=this.dateRange.startTime;if(this.snapOptions.out){const e=this.dateRange.tagAnchor;if(e)return Oa(t,e)}return t}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(0===this.startTime||this.snapOptions.out)return!0;const t=this.dateRange.tagAnchor;if(t){const e=this.dateRange.startTime;return e-Oa(e,t)<.1}return!1}get resumptionOffset(){const t=this.resumeOffset,e=r(t)?t:this.duration;return this.cumulativeDuration+e}get resumeTime(){const t=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const e=this.resumeAnchor;if(e)return Oa(t,e)}return t}get appendInPlace(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<wa))}set appendInPlace(t){this.appendInPlaceStarted?this.resetOnResume=!t:this.appendInPlaceDisabled=!t}get timelineStart(){return null!==this._timelineStart?this._timelineStart:this.startTime}set timelineStart(t){this._timelineStart=t}get duration(){const t=this.playoutLimit;let e;return e=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(t)&&t<e&&(e=t),e}set duration(t){this._duration=t}get cue(){return this.dateRange.cue}get timelineOccupancy(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?Pa.Range:Pa.Point}get supplementsPrimary(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}get contentMayVary(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||null!==this.assetListResponse}toString(){return`["${(t=this).identifier}" ${t.cue.pre?"<pre>":t.cue.post?"<post>":""}${t.timelineStart.toFixed(2)}-${t.resumeTime.toFixed(2)}]`;var t}}function Oa(t,e){return t-e.start<e.duration/2&&!(Math.abs(t-(e.start+e.duration))<wa)?e.start:e.start+e.duration}function xa(t,e,i){const r=new self.URL(t,i);return"data:"!==r.protocol&&r.searchParams.set("_HLS_primary_id",e),r}function Ma(t,e){for(;null!=(i=t.assetList[++e])&&i.error;)var i;return e}function Fa(t){const e=t.timelineStart,i=t.duration||0;return`["${t.identifier}" ${e.toFixed(2)}-${(e+i).toFixed(2)}]`}class Na{constructor(t,e,i,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(l.PLAYOUT_LIMIT_REACHED,{})};const s=this.hls=new t(e);this.interstitial=i,this.assetItem=r;const n=()=>{this.hasDetails=!0};s.once(l.LEVEL_LOADED,n),s.once(l.AUDIO_TRACK_LOADED,n),s.once(l.SUBTITLE_TRACK_LOADED,n),s.on(l.MEDIA_ATTACHING,((t,{media:e})=>{this.removeMediaListeners(),this.mediaAttached=e;this.interstitial.playoutLimit&&(e.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&s.on(l.BUFFER_APPENDED,(()=>{const t=this.bufferedEnd;this.reachedPlayout(t)&&(this._bufferedEosTime=t,s.trigger(l.BUFFERED_TO_END,void 0))})))}))}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const t=this.hls;if(t)if(t.url)t.levels.length&&!t.started&&t.startLoad(-1,!0);else{let e=this.assetItem.uri;try{e=xa(e,t.config.primarySessionId||"").href}catch(t){}t.loadSource(e)}}bufferedInPlaceToEnd(t){var e;if(!this.appendInPlace)return!1;if(null!=(e=this.hls)&&e.bufferedToEnd)return!0;if(!t)return!1;const i=Math.min(this._bufferedEosTime||Infinity,this.duration),r=this.timelineOffset,s=ii.bufferInfo(t,r,0);return this.getAssetTime(s.end)>=i-.02}reachedPlayout(t){const e=this.interstitial.playoutLimit;return this.startOffset+t>=e}get destroyed(){var t;return!(null!=(t=this.hls)&&t.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var t;return(null==(t=this.hls)?void 0:t.media)||null}get bufferedEnd(){const t=this.media||this.mediaAttached;if(!t)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const e=ii.bufferInfo(t,t.currentTime,.001);return this.getAssetTime(e.end)}get currentTime(){const t=this.media||this.mediaAttached;return t?this.getAssetTime(t.currentTime):this._currentTime||0}get duration(){const t=this.assetItem.duration;if(!t)return 0;const e=this.interstitial.playoutLimit;if(e){const i=e-this.startOffset;if(i>0&&i<t)return i}return t}get remaining(){const t=this.duration;return t?Math.max(0,t-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var t;return(null==(t=this.hls)?void 0:t.config.timelineOffset)||0}set timelineOffset(t){const e=this.timelineOffset;if(t!==e){const i=t-e;if(Math.abs(i)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=t}}}getAssetTime(t){const e=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,t-e),i)}removeMediaListeners(){const t=this.mediaAttached;t&&(this._currentTime=t.currentTime,this.bufferSnapShot(),t.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){var t;this.mediaAttached&&(null!=(t=this.hls)&&t.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd))}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(t){var e;this.loadSource(),null==(e=this.hls)||e.attachMedia(t)}detachMedia(){var t;this.removeMediaListeners(),this.mediaAttached=null,null==(t=this.hls)||t.detachMedia()}resumeBuffering(){var t;null==(t=this.hls)||t.resumeBuffering()}pauseBuffering(){var t;null==(t=this.hls)||t.pauseBuffering()}transferMedia(){var t;return this.bufferSnapShot(),(null==(t=this.hls)?void 0:t.transferMedia())||null}resetDetails(){const t=this.hls;if(t&&this.hasDetails){t.stopLoad();const e=t=>delete t.details;t.levels.forEach(e),t.allAudioTracks.forEach(e),t.allSubtitleTracks.forEach(e),this.hasDetails=!1}}on(t,e,i){var r;null==(r=this.hls)||r.on(t,e)}once(t,e,i){var r;null==(r=this.hls)||r.once(t,e)}off(t,e,i){var r;null==(r=this.hls)||r.off(t,e)}toString(){var t;return`HlsAssetPlayer: ${Fa(this.assetItem)} ${null==(t=this.hls)?void 0:t.sessionId} ${this.appendInPlace?"append-in-place":""}`}}class Ba extends S{constructor(t,e){super("interstitials-sched",e),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=t}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach((t=>t.reset())),this.events=this.items=null}resetErrorsInRange(t,e){return this.events?this.events.reduce(((i,r)=>t<=r.startOffset&&e>r.startOffset?(delete r.error,i+1):i),0):0}get duration(){const t=this.items;return t?t[t.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(t){return t&&this.eventMap[t]||null}hasEvent(t){return t in this.eventMap}findItemIndex(t,e){if(t.event)return this.findEventIndex(t.event.identifier);let i=-1;t.nextEvent?i=this.findEventIndex(t.nextEvent.identifier)-1:t.previousEvent&&(i=this.findEventIndex(t.previousEvent.identifier)+1);const r=this.items;if(r)for(r[i]||(void 0===e&&(e=t.start),i=this.findItemIndexAtTime(e));i>=0&&null!=(s=r[i])&&s.event;){var s;i--}return i}findItemIndexAtTime(t,e){const i=this.items;if(i)for(let r=0;r<i.length;r++){let s=i[r];if(e&&"primary"!==e&&(s=s[e]),t===s.start||t>s.start&&t<s.end)return r}return-1}findJumpRestrictedIndex(t,e){const i=this.items;if(i)for(let r=t;r<=e&&i[r];r++){const t=i[r].event;if(null!=t&&t.restrictions.jump&&!t.appendInPlace)return r}return-1}findEventIndex(t){const e=this.items;if(e)for(let r=e.length;r--;){var i;if((null==(i=e[r].event)?void 0:i.identifier)===t)return r}return-1}findAssetIndex(t,e){const i=t.assetList,r=i.length;if(r>1)for(let t=0;t<r;t++){const s=i[t];if(!s.error){const i=s.timelineStart;if(e===i||e>i&&(e<i+(s.duration||0)||t===r-1))return t}}return 0}get assetIdAtEnd(){var t;const e=null==(t=this.items)||null==(t=t[this.length-1])?void 0:t.event;if(e){const t=e.assetList,i=t[t.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(t,e){const i=t.main.details,{dateRanges:r}=i,s=this.events,n=this.parseDateRanges(r,{url:i.url},e),a=Object.keys(r),o=s?s.filter((t=>!a.includes(t.identifier))):[];n.length&&n.sort(((t,e)=>{const i=t.cue.pre,r=t.cue.post,s=e.cue.pre,n=e.cue.post;if(i&&!s)return-1;if(s&&!i)return 1;if(r&&!n)return 1;if(n&&!r)return-1;if(!(i||s||r||n)){const i=t.startTime,r=e.startTime;if(i!==r)return i-r}return t.dateRange.tagOrder-e.dateRange.tagOrder})),this.events=n,o.forEach((t=>{this.removeEvent(t)})),this.updateSchedule(t,o)}updateSchedule(t,e=[],i=!1){const r=this.events||[];if(r.length||e.length||this.length<2){const s=this.items,n=this.parseSchedule(r,t);(i||e.length||(null==s?void 0:s.length)!==n.length||n.some(((t,e)=>Math.abs(t.playout.start-s[e].playout.start)>.005||Math.abs(t.playout.end-s[e].playout.end)>.005)))&&(this.items=n,this.onScheduleUpdate(e,s))}}parseDateRanges(t,e,i){const r=[],s=Object.keys(t);for(let n=0;n<s.length;n++){const a=s[n],o=t[a];if(o.isInterstitial){let t=this.eventMap[a];t?t.setDateRange(o):(t=new Ca(o,e),this.eventMap[a]=t,!1===i&&(t.appendInPlace=i)),r.push(t)}}return r}parseSchedule(t,e){const i=[],r=e.main.details,s=r.live?Infinity:r.edge;let n=0;if((t=t.filter((t=>!(t.error||t.cue.once&&t.hasPlayed)))).length){this.resolveOffsets(t,e);let r=0,o=0;if(t.forEach(((e,a)=>{const l=e.cue.pre,u=e.cue.post,c=t[a-1]||null,d=e.appendInPlace,h=u?s:e.startOffset,f=e.duration,g=e.timelineOccupancy===Pa.Range?f:0,m=e.resumptionOffset,p=(null==c?void 0:c.startTime)===h,v=h+e.cumulativeDuration;let y=d?v+f:h+m;if(l||!u&&h<=0){const t=o;o+=g,e.timelineStart=v;const r=n;n+=f,i.push({event:e,start:v,end:y,playout:{start:r,end:n},integrated:{start:t,end:o}})}else{if(!(h<=s))return;{if(!p){const s=h-r;if(s>.033){const l=r,u=o;o+=s;const c=n;n+=s;const d={previousEvent:t[a-1]||null,nextEvent:e,start:l,end:l+s,playout:{start:c,end:n},integrated:{start:u,end:o}};i.push(d)}else s>0&&c&&(c.cumulativeDuration+=s,i[i.length-1].end=h)}u&&(y=v),e.timelineStart=v;const s=o;o+=g;const l=n;n+=f,i.push({event:e,start:v,end:y,playout:{start:l,end:n},integrated:{start:s,end:o}})}}const E=e.resumeTime;r=u||E>s?s:E})),r<s){var a;const t=r,e=o,l=s-r;o+=l;const u=n;n+=l,i.push({previousEvent:(null==(a=i[i.length-1])?void 0:a.event)||null,nextEvent:null,start:r,end:t+l,playout:{start:u,end:n},integrated:{start:e,end:o}})}this.setDurations(s,n,o)}else{const t=0;i.push({previousEvent:null,nextEvent:null,start:t,end:s,playout:{start:t,end:s},integrated:{start:t,end:s}}),this.setDurations(s,s,s)}return i}setDurations(t,e,i){this.durations={primary:t,playout:e,integrated:i}}resolveOffsets(t,e){const i=e.main.details,s=i.live?Infinity:i.edge;let n=0,a=-1;t.forEach(((o,l)=>{const u=o.cue.pre,c=o.cue.post,d=u?0:c?s:o.startTime;this.updateAssetDurations(o);if(a===d?o.cumulativeDuration=n:(n=0,a=d),!c&&o.snapOptions.in&&(o.resumeAnchor=fe(null,i.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted){this.primaryCanResumeInPlaceAt(o,e)||(o.appendInPlace=!1)}if(!o.appendInPlace&&l+1<t.length){t[l+1].startTime-t[l].resumeTime<.033&&(t[l+1].appendInPlace=!1,t[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`))}const h=r(o.resumeOffset)?o.resumeOffset:o.duration;n+=h}))}primaryCanResumeInPlaceAt(t,e){const i=t.resumeTime,r=t.startTime+t.resumptionOffset;if(Math.abs(i-r)>wa)return this.log(`"${t.identifier}" resumption ${i} not aligned with estimated timeline end ${r}`),!1;return!Object.keys(e).some((r=>{const s=e[r].details,n=s.edge;if(i>=n)return this.log(`"${t.identifier}" resumption ${i} past ${r} playlist end ${n}`),!1;const a=fe(null,s.fragments,i);if(!a)return this.log(`"${t.identifier}" resumption ${i} does not align with any fragments in ${r} playlist (${s.fragStart}-${s.fragmentEnd})`),!0;const o="audio"===r?.175:0;return!(Math.abs(a.start-i)<wa+o||Math.abs(a.end-i)<wa+o)&&(this.log(`"${t.identifier}" resumption ${i} not aligned with ${r} fragment bounds (${a.start}-${a.end} sn: ${a.sn} cc: ${a.cc})`),!0)}))}updateAssetDurations(t){if(!t.assetListLoaded)return;const e=t.timelineStart;let i=0,r=!1,s=!1;for(let n=0;n<t.assetList.length;n++){const a=t.assetList[n],o=e+i;a.startOffset=i,a.timelineStart=o,r||(r=null===a.duration),s||(s=!!a.error);i+=a.error?0:a.duration||0}t.duration=r&&!s?Math.max(i,t.duration):i}removeEvent(t){t.reset(),delete this.eventMap[t.identifier]}}function Ua(t){return`[${t.event?'"'+t.event.identifier+'"':"primary"}: ${t.start.toFixed(2)}-${t.end.toFixed(2)}]`}class $a{constructor(t){this.hls=void 0,this.hls=t}destroy(){this.hls=null}loadAssetList(t,e){const i=t.assetListUrl;let r;try{r=xa(i,this.hls.sessionId,t.baseUrl)}catch(e){const r=this.assignAssetListError(t,o.ASSET_LIST_LOAD_ERROR,e,i);return void this.hls.trigger(l.ERROR,r)}e&&"data:"!==r.protocol&&r.searchParams.set("_HLS_start_offset",""+e);const s=this.hls.config,n=new(0,s.loader)(s),a={responseType:"json",url:r.href},u=s.interstitialAssetListLoadPolicy.default,c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(e,i,r,s)=>{const n=e.data,a=null==n?void 0:n.ASSETS;if(Array.isArray(a))t.assetListResponse=n,this.hls.trigger(l.ASSET_LIST_LOADED,{event:t,assetListResponse:n,networkDetails:s});else{const e=this.assignAssetListError(t,o.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),r.url,i,s);this.hls.trigger(l.ERROR,e)}},onError:(e,i,r,s)=>{const n=this.assignAssetListError(t,o.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${e.code} ${e.text} (${i.url})`),i.url,s,r);this.hls.trigger(l.ERROR,n)},onTimeout:(e,i,r)=>{const s=this.assignAssetListError(t,o.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${i.url})`),i.url,e,r);this.hls.trigger(l.ERROR,s)}};return n.load(a,c,d),this.hls.trigger(l.ASSET_LIST_LOADING,{event:t}),n}assignAssetListError(t,e,i,r,s,n){return t.error=i,{type:a.NETWORK_ERROR,details:e,fatal:!1,interstitial:t,url:r,error:i,networkDetails:n,stats:s}}}function Ga(t){var e;null==t||null==(e=t.play())||e.catch((()=>{}))}function Ha(t,e){return`[${t}] Advancing timeline position to ${e}`}class Va{constructor(t){this.buffered=void 0;const e=(e,i,r)=>{if((i>>>=0)>r-1)throw new DOMException(`Failed to execute '${e}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${r})`);return t[i][e]};this.buffered={get length(){return t.length},end:i=>e("end",i,t.length),start:i=>e("start",i,t.length)}}}const ja={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},Ka=t=>String.fromCharCode(ja[t]||t),Wa=15,Ya=100,qa={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},za={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Xa={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Qa={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Za=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Ja{constructor(){this.time=null,this.verboseLevel=0}log(t,e){if(this.verboseLevel>=t){const i="function"==typeof e?e():e;_.log(`${this.time} [${t}] ${i}`)}}}const to=function(t){const e=[];for(let i=0;i<t.length;i++)e.push(t[i].toString(16));return e};class eo{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(t){const e=["foreground","underline","italics","background","flash"];for(let i=0;i<e.length;i++){const r=e[i];t.hasOwnProperty(r)&&(this[r]=t[r])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(t){return this.foreground===t.foreground&&this.underline===t.underline&&this.italics===t.italics&&this.background===t.background&&this.flash===t.flash}copy(t){this.foreground=t.foreground,this.underline=t.underline,this.italics=t.italics,this.background=t.background,this.flash=t.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class io{constructor(){this.uchar=" ",this.penState=new eo}reset(){this.uchar=" ",this.penState.reset()}setChar(t,e){this.uchar=t,this.penState.copy(e)}setPenState(t){this.penState.copy(t)}equals(t){return this.uchar===t.uchar&&this.penState.equals(t.penState)}copy(t){this.uchar=t.uchar,this.penState.copy(t.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}}class ro{constructor(t){this.chars=[],this.pos=0,this.currPenState=new eo,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Ya;t++)this.chars.push(new io);this.logger=t}equals(t){for(let e=0;e<Ya;e++)if(!this.chars[e].equals(t.chars[e]))return!1;return!0}copy(t){for(let e=0;e<Ya;e++)this.chars[e].copy(t.chars[e])}isEmpty(){let t=!0;for(let e=0;e<Ya;e++)if(!this.chars[e].isEmpty()){t=!1;break}return t}setCursor(t){this.pos!==t&&(this.pos=t),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Ya&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Ya)}moveCursor(t){const e=this.pos+t;if(t>1)for(let t=this.pos+1;t<e+1;t++)this.chars[t].setPenState(this.currPenState);this.setCursor(e)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(t){t>=144&&this.backSpace();const e=Ka(t);this.pos>=Ya?this.logger.log(0,(()=>"Cannot insert "+t.toString(16)+" ("+e+") at position "+this.pos+". Skipping it!")):(this.chars[this.pos].setChar(e,this.currPenState),this.moveCursor(1))}clearFromPos(t){let e;for(e=t;e<Ya;e++)this.chars[e].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const t=[];let e=!0;for(let i=0;i<Ya;i++){const r=this.chars[i].uchar;" "!==r&&(e=!1),t.push(r)}return e?"":t.join("")}setPenStyles(t){this.currPenState.setStyles(t);this.chars[this.pos].setPenState(this.currPenState)}}class so{constructor(t){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let e=0;e<Wa;e++)this.rows.push(new ro(t));this.logger=t}reset(){for(let t=0;t<Wa;t++)this.rows[t].clear();this.currRow=14}equals(t){let e=!0;for(let i=0;i<Wa;i++)if(!this.rows[i].equals(t.rows[i])){e=!1;break}return e}copy(t){for(let e=0;e<Wa;e++)this.rows[e].copy(t.rows[e])}isEmpty(){let t=!0;for(let e=0;e<Wa;e++)if(!this.rows[e].isEmpty()){t=!1;break}return t}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(t){this.rows[this.currRow].insertChar(t)}setPen(t){this.rows[this.currRow].setPenStyles(t)}moveCursor(t){this.rows[this.currRow].moveCursor(t)}setCursor(t){this.logger.log(2,"setCursor: "+t);this.rows[this.currRow].setCursor(t)}setPAC(t){this.logger.log(2,(()=>"pacData = "+re(t)));let e=t.row-1;if(this.nrRollUpRows&&e<this.nrRollUpRows-1&&(e=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==e){for(let t=0;t<Wa;t++)this.rows[t].clear();const t=this.currRow+1-this.nrRollUpRows,i=this.lastOutputScreen;if(i){const r=i.rows[t].cueStartTime,s=this.logger.time;if(null!==r&&null!==s&&r<s)for(let r=0;r<this.nrRollUpRows;r++)this.rows[e-this.nrRollUpRows+r+1].copy(i.rows[t+r])}}this.currRow=e;const i=this.rows[this.currRow];if(null!==t.indent){const e=t.indent,r=Math.max(e-1,0);i.setCursor(t.indent),t.color=i.chars[r].penState.foreground}const r={foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:!1};this.setPen(r)}setBkgData(t){this.logger.log(2,(()=>"bkgData = "+re(t))),this.backSpace(),this.setPen(t),this.insertChar(32)}setRollUpRows(t){this.nrRollUpRows=t}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,(()=>this.getDisplayText()));const t=this.currRow+1-this.nrRollUpRows,e=this.rows.splice(t,1)[0];e.clear(),this.rows.splice(this.currRow,0,e),this.logger.log(2,"Rolling up")}getDisplayText(t){t=t||!1;const e=[];let i="",r=-1;for(let i=0;i<Wa;i++){const s=this.rows[i].getTextString();s&&(r=i+1,t?e.push("Row "+r+": '"+s+"'"):e.push(s.trim()))}return e.length>0&&(i=t?"["+e.join(" | ")+"]":e.join("\n")),i}getTextAndFormat(){return this.rows}}class no{constructor(t,e,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=e,this.mode=null,this.verbose=0,this.displayedMemory=new so(i),this.nonDisplayedMemory=new so(i),this.lastOutputScreen=new so(i),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(t){this.outputFilter=t}setPAC(t){this.writeScreen.setPAC(t)}setBkgData(t){this.writeScreen.setBkgData(t)}setMode(t){t!==this.mode&&(this.mode=t,this.logger.log(2,(()=>"MODE="+t)),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=t)}insertChars(t){for(let e=0;e<t.length;e++)this.writeScreen.insertChar(t[e]);const e=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,(()=>e+": "+this.writeScreen.getDisplayText(!0))),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,(()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0))),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(t){this.logger.log(2,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){const t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,(()=>"DISP: "+this.displayedMemory.getDisplayText()))}this.outputDataUpdate(!0)}ccTO(t){this.logger.log(2,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)}ccMIDROW(t){const e={flash:!1};if(e.underline=t%2==1,e.italics=t>=46,e.italics)e.foreground="white";else{const i=Math.floor(t/2)-16,r=["white","green","blue","cyan","red","yellow","magenta"];e.foreground=r[i]}this.logger.log(2,"MIDROW: "+re(e)),this.writeScreen.setPen(e)}outputDataUpdate(t=!1){const e=this.logger.time;null!==e&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:e):this.cueStartTime=e,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))}}class ao{constructor(t,e,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const r=this.logger=new Ja;this.channels=[null,new no(t,e,r),new no(t+1,i,r)]}getHandler(t){return this.channels[t].getHandler()}setHandler(t,e){this.channels[t].setHandler(e)}addData(t,e){this.logger.time=t;for(let t=0;t<e.length;t+=2){const i=127&e[t],r=127&e[t+1];let s=!1,n=null;if(0===i&&0===r)continue;this.logger.log(3,(()=>"["+to([e[t],e[t+1]])+"] -> ("+to([i,r])+")"));const a=this.cmdHistory;if(i>=16&&i<=31){if(lo(i,r,a)){oo(null,null,a),this.logger.log(3,(()=>"Repeated command ("+to([i,r])+") is dropped"));continue}oo(i,r,this.cmdHistory),s=this.parseCmd(i,r),s||(s=this.parseMidrow(i,r)),s||(s=this.parsePAC(i,r)),s||(s=this.parseBackgroundAttributes(i,r))}else oo(null,null,a);if(!s&&(n=this.parseChars(i,r),n)){const t=this.currentChannel;if(t&&t>0){this.channels[t].insertChars(n)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}s||n||this.logger.log(2,(()=>"Couldn't parse cleaned data "+to([i,r])+" orig: "+to([e[t],e[t+1]])))}}parseCmd(t,e){if(!((20===t||28===t||21===t||29===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=33&&e<=35))return!1;const i=20===t||21===t||23===t?1:2,r=this.channels[i];return 20===t||21===t||28===t||29===t?32===e?r.ccRCL():33===e?r.ccBS():34===e?r.ccAOF():35===e?r.ccAON():36===e?r.ccDER():37===e?r.ccRU(2):38===e?r.ccRU(3):39===e?r.ccRU(4):40===e?r.ccFON():41===e?r.ccRDC():42===e?r.ccTR():43===e?r.ccRTD():44===e?r.ccEDM():45===e?r.ccCR():46===e?r.ccENM():47===e&&r.ccEOC():r.ccTO(e-32),this.currentChannel=i,!0}parseMidrow(t,e){let i=0;if((17===t||25===t)&&e>=32&&e<=47){if(i=17===t?1:2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const r=this.channels[i];return!!r&&(r.ccMIDROW(e),this.logger.log(3,(()=>"MIDROW ("+to([t,e])+")")),!0)}return!1}parsePAC(t,e){let i;if(!((t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127)&&!((16===t||24===t)&&e>=64&&e<=95))return!1;const r=t<=23?1:2;i=e>=64&&e<=95?1===r?qa[t]:Xa[t]:1===r?za[t]:Qa[t];const s=this.channels[r];return!!s&&(s.setPAC(this.interpretPAC(i,e)),this.currentChannel=r,!0)}interpretPAC(t,e){let i;const r={color:null,italics:!1,indent:null,underline:!1,row:t};return i=e>95?e-96:e-64,r.underline=!(1&~i),i<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(r.italics=!0,r.color="white"):r.indent=4*Math.floor((i-16)/2),r}parseChars(t,e){let i,r=null,s=null;if(t>=25?(i=2,s=t-8):(i=1,s=t),s>=17&&s<=19){let t;t=17===s?e+80:18===s?e+112:e+144,this.logger.log(2,(()=>"Special char '"+Ka(t)+"' in channel "+i)),r=[t]}else t>=32&&t<=127&&(r=0===e?[t]:[t,e]);return r&&this.logger.log(3,(()=>"Char codes =  "+to(r).join(","))),r}parseBackgroundAttributes(t,e){if(!((16===t||24===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=45&&e<=47))return!1;let i;const r={};16===t||24===t?(i=Math.floor((e-32)/2),r.background=Za[i],e%2==1&&(r.background=r.background+"_semi")):45===e?r.background="transparent":(r.foreground="black",47===e&&(r.underline=!0));const s=t<=23?1:2;return this.channels[s].setBkgData(r),!0}reset(){for(let t=0;t<Object.keys(this.channels).length;t++){const e=this.channels[t];e&&e.reset()}oo(null,null,this.cmdHistory)}cueSplitAtTime(t){for(let e=0;e<this.channels.length;e++){const i=this.channels[e];i&&i.cueSplitAtTime(t)}}}function oo(t,e,i){i.a=t,i.b=e}function lo(t,e,i){return i.a===t&&i.b===e}var uo=function(){if(null!=Si&&Si.VTTCue)return self.VTTCue;const t=["","lr","rl"],e=["start","middle","end","left","right"];function i(t,e){if("string"!=typeof e)return!1;if(!Array.isArray(t))return!1;const i=e.toLowerCase();return!!~t.indexOf(i)&&i}function r(t){return i(e,t)}function s(t,...e){let i=1;for(;i<arguments.length;i++){const e=arguments[i];for(const i in e)t[i]=e[i]}return t}function n(e,n,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let u="",c=!1,d=e,h=n,f=a,g=null,m="",p=!0,v="auto",y="start",E=50,T="middle",b=50,S="middle";Object.defineProperty(o,"id",s({},l,{get:function(){return u},set:function(t){u=""+t}})),Object.defineProperty(o,"pauseOnExit",s({},l,{get:function(){return c},set:function(t){c=!!t}})),Object.defineProperty(o,"startTime",s({},l,{get:function(){return d},set:function(t){if("number"!=typeof t)throw new TypeError("Start time must be set to a number.");d=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",s({},l,{get:function(){return h},set:function(t){if("number"!=typeof t)throw new TypeError("End time must be set to a number.");h=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",s({},l,{get:function(){return f},set:function(t){f=""+t,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",s({},l,{get:function(){return g},set:function(t){g=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",s({},l,{get:function(){return m},set:function(e){const r=function(e){return i(t,e)}(e);if(!1===r)throw new SyntaxError("An invalid or illegal string was specified.");m=r,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",s({},l,{get:function(){return p},set:function(t){p=!!t,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",s({},l,{get:function(){return v},set:function(t){if("number"!=typeof t&&"auto"!==t)throw new SyntaxError("An invalid number or illegal string was specified.");v=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",s({},l,{get:function(){return y},set:function(t){const e=r(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");y=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",s({},l,{get:function(){return E},set:function(t){if(t<0||t>100)throw new Error("Position must be between 0 and 100.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",s({},l,{get:function(){return T},set:function(t){const e=r(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",s({},l,{get:function(){return b},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");b=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",s({},l,{get:function(){return S},set:function(t){const e=r(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");S=e,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class co{decode(t,e){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function ho(t){function e(t,e,i,r){return 3600*(0|t)+60*(0|e)+(0|i)+parseFloat(r||0)}const i=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?e(i[2],i[3],0,i[4]):e(i[1],i[2],i[3],i[4]):null}class fo{constructor(){this.values=Object.create(null)}set(t,e){this.get(t)||""===e||(this.values[t]=e)}get(t,e,i){return i?this.has(t)?this.values[t]:e[i]:this.has(t)?this.values[t]:e}has(t){return t in this.values}alt(t,e,i){for(let r=0;r<i.length;++r)if(e===i[r]){this.set(t,e);break}}integer(t,e){/^-?\d+$/.test(e)&&this.set(t,parseInt(e,10))}percent(t,e){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(e)){const i=parseFloat(e);if(i>=0&&i<=100)return this.set(t,i),!0}return!1}}function go(t,e,i,r){const s=r?t.split(r):[t];for(const t in s){if("string"!=typeof s[t])continue;const r=s[t].split(i);if(2!==r.length)continue;e(r[0],r[1])}}const mo=new uo(0,0,""),po="middle"===mo.align?"middle":"center";function vo(t,e,i){const r=t;function s(){const e=ho(t);if(null===e)throw new Error("Malformed timestamp: "+r);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function n(){t=t.replace(/^\s+/,"")}if(n(),e.startTime=s(),n(),"--\x3e"!==t.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+r);t=t.slice(3),n(),e.endTime=s(),n(),function(t,e){const r=new fo;go(t,(function(t,e){let s;switch(t){case"region":for(let s=i.length-1;s>=0;s--)if(i[s].id===e){r.set(t,i[s].region);break}break;case"vertical":r.alt(t,e,["rl","lr"]);break;case"line":s=e.split(","),r.integer(t,s[0]),r.percent(t,s[0])&&r.set("snapToLines",!1),r.alt(t,s[0],["auto"]),2===s.length&&r.alt("lineAlign",s[1],["start",po,"end"]);break;case"position":s=e.split(","),r.percent(t,s[0]),2===s.length&&r.alt("positionAlign",s[1],["start",po,"end","line-left","line-right","auto"]);break;case"size":r.percent(t,e);break;case"align":r.alt(t,e,["start",po,"end","left","right"])}}),/:/,/\s/),e.region=r.get("region",null),e.vertical=r.get("vertical","");let s=r.get("line","auto");"auto"===s&&-1===mo.line&&(s=-1),e.line=s,e.lineAlign=r.get("lineAlign","start"),e.snapToLines=r.get("snapToLines",!0),e.size=r.get("size",100),e.align=r.get("align",po);let n=r.get("position","auto");"auto"===n&&50===mo.position&&(n="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=n}(t,e)}function yo(t){return t.replace(/<br(?: \/)?>/gi,"\n")}class Eo{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new co,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(t){const e=this;function i(){let t=e.buffer,i=0;for(t=yo(t);i<t.length&&"\r"!==t[i]&&"\n"!==t[i];)++i;const r=t.slice(0,i);return"\r"===t[i]&&++i,"\n"===t[i]&&++i,e.buffer=t.slice(i),r}t&&(e.buffer+=e.decoder.decode(t,{stream:!0}));try{let t="";if("INITIAL"===e.state){if(!/\r\n|\n/.test(e.buffer))return this;t=i();const r=t.match(/^(ï»¿)?WEBVTT([ \t].*)?$/);if(null==r||!r[0])throw new Error("Malformed WebVTT signature.");e.state="HEADER"}let r=!1;for(;e.buffer;){if(!/\r\n|\n/.test(e.buffer))return this;switch(r?r=!1:t=i(),e.state){case"HEADER":/:/.test(t)?go(t,(function(t,e){}),/:/):t||(e.state="ID");continue;case"NOTE":t||(e.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(t)){e.state="NOTE";break}if(!t)continue;if(e.cue=new uo(0,0,""),e.state="CUE",-1===t.indexOf("--\x3e")){e.cue.id=t;continue}case"CUE":if(!e.cue){e.state="BADCUE";continue}try{vo(t,e.cue,e.regionList)}catch(t){e.cue=null,e.state="BADCUE";continue}e.state="CUETEXT";continue;case"CUETEXT":{const i=-1!==t.indexOf("--\x3e");if(!t||i&&(r=!0)){e.oncue&&e.cue&&e.oncue(e.cue),e.cue=null,e.state="ID";continue}if(null===e.cue)continue;e.cue.text&&(e.cue.text+="\n"),e.cue.text+=t}continue;case"BADCUE":t||(e.state="ID")}}}catch(t){"CUETEXT"===e.state&&e.cue&&e.oncue&&e.oncue(e.cue),e.cue=null,e.state="INITIAL"===e.state?"BADWEBVTT":"BADCUE"}return this}flush(){const t=this;try{if((t.cue||"HEADER"===t.state)&&(t.buffer+="\n\n",t.parse()),"INITIAL"===t.state||"BADWEBVTT"===t.state)throw new Error("Malformed WebVTT signature.")}catch(e){t.onparsingerror&&t.onparsingerror(e)}return t.onflush&&t.onflush(),this}}const To=/\r\n|\n\r|\n|\r/g,bo=function(t,e,i=0){return t.slice(i,i+e.length)===e};function So(t,e,i){return _a(t.toString())+_a(e.toString())+_a(i)}function Ao(t,e,i,s,n,a,o){const l=new Eo,u=D(new Uint8Array(t)).trim().replace(To,"\n").split("\n"),c=[],d=e?function(t,e=1){return js(t,9e4,1/e)}(e.baseTime,e.timescale):0;let h,f="00:00.000",g=0,m=0,p=!0;l.oncue=function(t){const r=i[s];let a=i.ccOffset;const o=(g-d)/9e4;if(null!=r&&r.new&&(void 0!==m?a=i.ccOffset=r.start:function(t,e,i){let r=t[e],s=t[r.prevCC];if(!s||!s.new&&r.new)return t.ccOffset=t.presentationOffset=r.start,void(r.new=!1);for(;null!=(n=s)&&n.new;){var n;t.ccOffset+=r.start-s.start,r.new=!1,r=s,s=t[r.prevCC]}t.presentationOffset=i}(i,s,o)),o){if(!e)return void(h=new Error("Missing initPTS for VTT MPEGTS"));a=o-i.presentationOffset}const l=t.endTime-t.startTime,u=Zs(9e4*(t.startTime+a-m),9e4*n)/9e4;t.startTime=Math.max(u,0),t.endTime=Math.max(u+l,0);const f=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(f)),t.id||(t.id=So(t.startTime,t.endTime,f)),t.endTime>0&&c.push(t)},l.onparsingerror=function(t){h=t},l.onflush=function(){h?o(h):a(c)},u.forEach((t=>{if(p){if(bo(t,"X-TIMESTAMP-MAP=")){p=!1,t.slice(16).split(",").forEach((t=>{bo(t,"LOCAL:")?f=t.slice(6):bo(t,"MPEGTS:")&&(g=parseInt(t.slice(7)))}));try{m=function(t){let e=parseInt(t.slice(-3));const i=parseInt(t.slice(-6,-4)),s=parseInt(t.slice(-9,-7)),n=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!(r(e)&&r(i)&&r(s)&&r(n)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return e+=1e3*i,e+=6e4*s,e+=36e5*n,e}(f)/1e3}catch(t){h=t}return}""===t&&(p=!1)}l.parse(t+"\n")})),l.flush()}const Lo="stpp.ttml.im1t",ko=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Ro=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Io={left:"start",center:"center",right:"end",start:"start",end:"end"};function _o(t,e,i,r){const s=at(new Uint8Array(t),["mdat"]);if(0===s.length)return void r(new Error("Could not parse IMSC1 mdat"));const n=s.map((t=>D(t))),a=function(t,e,i=1,r=!1){return js(t,e,1/i,r)}(e.baseTime,1,e.timescale);try{n.forEach((t=>i(function(t,e){const i=(new DOMParser).parseFromString(t,"text/xml"),r=i.getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");const s={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(s).reduce(((t,e)=>(t[e]=r.getAttribute(`ttp:${e}`)||s[e],t)),{}),a="preserve"!==r.getAttribute("xml:space"),o=Po(wo(r,"styling","style")),l=Po(wo(r,"layout","region")),u=wo(r,"body","[begin]");return[].map.call(u,(t=>{const i=Do(t,a);if(!i||!t.hasAttribute("begin"))return null;const r=xo(t.getAttribute("begin"),n),s=xo(t.getAttribute("dur"),n);let u=xo(t.getAttribute("end"),n);if(null===r)throw Oo(t);if(null===u){if(null===s)throw Oo(t);u=r+s}const c=new uo(r-e,u-e,i);c.id=So(c.startTime,c.endTime,c.text);const d=function(t,e,i){const r="http://www.w3.org/ns/ttml#styling";let s=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;a&&i.hasOwnProperty(a)&&(s=i[a]);return n.reduce(((i,n)=>{const a=Co(e,r,n)||Co(t,r,n)||Co(s,r,n);return a&&(i[n]=a),i}),{})}(l[t.getAttribute("region")],o[t.getAttribute("style")],o),{textAlign:h}=d;if(h){const t=Io[h];t&&(c.lineAlign=t),c.align=h}return E(c,d),c})).filter((t=>null!==t))}(t,a))))}catch(t){r(t)}}function wo(t,e,i){const r=t.getElementsByTagName(e)[0];return r?[].slice.call(r.querySelectorAll(i)):[]}function Po(t){return t.reduce(((t,e)=>{const i=e.getAttribute("xml:id");return i&&(t[i]=e),t}),{})}function Do(t,e){return[].slice.call(t.childNodes).reduce(((t,i,r)=>{var s;return"br"===i.nodeName&&r?t+"\n":null!=(s=i.childNodes)&&s.length?Do(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent}),"")}function Co(t,e,i){return t&&t.hasAttributeNS(e,i)?t.getAttributeNS(e,i):null}function Oo(t){return new Error(`Could not parse ttml timestamp ${t}`)}function xo(t,e){if(!t)return null;let i=ho(t);return null===i&&(ko.test(t)?i=function(t,e){const i=ko.exec(t),r=(0|i[4])+(0|i[5])/e.subFrameRate;return 3600*(0|i[1])+60*(0|i[2])+(0|i[3])+r/e.frameRate}(t,e):Ro.test(t)&&(i=function(t,e){const i=Ro.exec(t),r=Number(i[1]);switch(i[2]){case"h":return 3600*r;case"m":return 60*r;case"ms":return 1e3*r;case"f":return r/e.frameRate;case"t":return r/e.tickRate}return r}(t,e))),i}class Mo{constructor(t,e){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=e}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(t,e,i){(null===this.startTime||this.startTime>t)&&(this.startTime=t),this.endTime=e,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}function Fo(t){return t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles"}function No(t,e){return!!t&&t.kind===Fo(e)&&mn(e,t)}const Bo=/\s/,Uo={newCue(t,e,i,r){const s=[];let n,a,o,l,u;const c=self.VTTCue||self.TextTrackCue;for(let h=0;h<r.rows.length;h++)if(n=r.rows[h],o=!0,l=0,u="",!n.isEmpty()){var d;for(let t=0;t<n.chars.length;t++)Bo.test(n.chars[t].uchar)&&o?l++:(u+=n.chars[t].uchar,o=!1);n.cueStartTime=e,e===i&&(i+=1e-4),l>=16?l--:l++;const r=yo(u.trim()),f=So(e,i,r);null!=t&&null!=(d=t.cues)&&d.getCueById(f)||(a=new c(e,i,r),a.id=f,a.line=h+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),s.push(a))}return t&&s.length&&(s.sort(((t,e)=>"auto"===t.line||"auto"===e.line?0:t.line>8&&e.line>8?e.line-t.line:t.line-e.line)),s.forEach((e=>La(t,e)))),s}};const $o=/(\d+)-(\d+)\/(\d+)/;class Go{constructor(t){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=t.fetchSetup||Ho,this.controller=new self.AbortController,this.stats=new V}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(t,e,i){const s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now();const n=function(t,e){const i={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(E({},t.headers))};t.rangeEnd&&i.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1));return i}(t,this.controller.signal),a="arraybuffer"===t.responseType,o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:u}=e.loadPolicy;this.context=t,this.config=e,this.callbacks=i,this.request=this.fetchSetup(t,n),self.clearTimeout(this.requestTimeout),e.timeout=l&&r(l)?l:u,this.requestTimeout=self.setTimeout((()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,t,this.response))}),e.timeout);(on(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then((i=>{var n;this.response=this.loader=i;const o=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=u,this.requestTimeout=self.setTimeout((()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,t,this.response))}),u-(o-s.loading.start)),!i.ok){const{status:t,statusText:e}=i;throw new Vo(e||"fetch, bad network response",t,i)}s.loading.first=o,s.total=function(t){const e=t.get("Content-Range");if(e){const t=function(t){const e=$o.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}(e);if(r(t))return t}const i=t.get("Content-Length");if(i)return parseInt(i)}(i.headers)||s.total;const l=null==(n=this.callbacks)?void 0:n.onProgress;return l&&r(e.highWaterMark)?this.loadProgressively(i,s,t,e.highWaterMark,l):a?i.arrayBuffer():"json"===t.responseType?i.json():i.text()})).then((i=>{var n,a;const l=this.response;if(!l)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const u=i[o];u&&(s.loaded=s.total=u);const c={url:l.url,data:i,code:l.status},d=null==(n=this.callbacks)?void 0:n.onProgress;d&&!r(e.highWaterMark)&&d(s,t,i,l),null==(a=this.callbacks)||a.onSuccess(c,s,t,l)})).catch((e=>{var i;if(self.clearTimeout(this.requestTimeout),s.aborted)return;const r=e&&e.code||0,n=e?e.message:null;null==(i=this.callbacks)||i.onError({code:r,text:n},t,e?e.details:null,s)}))}getCacheAge(){let t=null;if(this.response){const e=this.response.headers.get("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,e,i,r=0,s){const n=new Mr,a=t.body.getReader(),o=()=>a.read().then((a=>{if(a.done)return n.dataLength&&s(e,i,n.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));const l=a.value,u=l.length;return e.loaded+=u,u<r||n.dataLength?(n.push(l),n.dataLength>=r&&s(e,i,n.flush().buffer,t)):s(e,i,l.buffer,t),o()})).catch((()=>Promise.reject()));return o()}}function Ho(t,e){return new self.Request(t.url,e)}class Vo extends Error{constructor(t,e,i){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=i}}const jo=/^age:\s*[\d.]+\s*$/im;class Ko{constructor(t){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=t&&t.xhrSetup||null,this.stats=new V,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,4!==t.readyState&&(this.stats.aborted=!0,t.abort()))}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(t,e,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=i,this.loadInternal()}loadInternal(){const{config:t,context:e}=this;if(!t||!e)return;const i=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;const s=this.xhrSetup;s?Promise.resolve().then((()=>{if(this.loader===i&&!this.stats.aborted)return s(i,e.url)})).catch((t=>{if(this.loader===i&&!this.stats.aborted)return i.open("GET",e.url,!0),s(i,e.url)})).then((()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,e,t)})).catch((t=>{var s;null==(s=this.callbacks)||s.onError({code:i.status,text:t.message},e,i,r)})):this.openAndSendXhr(i,e,t)}openAndSendXhr(t,e,i){t.readyState||t.open("GET",e.url,!0);const s=e.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=i.loadPolicy;if(s)for(const e in s)t.setRequestHeader(e,s[e]);e.rangeEnd&&t.setRequestHeader("Range","bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=e.responseType,self.clearTimeout(this.requestTimeout),i.timeout=n&&r(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),t.send()}readystatechange(){const{context:t,loader:e,stats:i}=this;if(!t||!e)return;const r=e.readyState,s=this.config;if(!i.aborted&&r>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),4===r)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;const r=e.status,l="text"===e.responseType?e.responseText:null;if(r>=200&&r<300){const s=null!=l?l:e.response;if(null!=s){var n,a;i.loading.end=Math.max(self.performance.now(),i.loading.first);const o="arraybuffer"===e.responseType?s.byteLength:s.length;i.loaded=i.total=o,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first);const l=null==(n=this.callbacks)?void 0:n.onProgress;l&&l(i,t,s,e);const u={url:e.responseURL,data:s,code:r};return void(null==(a=this.callbacks)||a.onSuccess(u,i,t,e))}}const u=s.loadPolicy.errorRetry;var o;if(Ae(u,i.retry,!1,{url:t.url,data:void 0,code:r}))this.retry(u);else _.error(`${r} while loading ${t.url}`),null==(o=this.callbacks)||o.onError({code:r,text:e.statusText},t,e,i)}}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry;if(Ae(t,this.stats.retry,!0))this.retry(t);else{var e;_.warn(`timeout while loading ${null==(e=this.context)?void 0:e.url}`);const t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.loader))}}retry(t){const{context:e,stats:i}=this;this.retryDelay=be(t,i.retry),i.retry++,_.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==e?void 0:e.url}, retrying ${i.retry}/${t.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(t){const e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)}getCacheAge(){let t=null;if(this.loader&&jo.test(this.loader.getAllResponseHeaders())){const e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.loader&&new RegExp(`^${t}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null}}const Wo=b(b({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:Infinity,frontBufferFlushThreshold:Infinity,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:Infinity,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:Ko,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class extends S{constructor(t){super("abr",t.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var e;const{fragCurrent:i,partCurrent:s,hls:n}=this,{autoLevelEnabled:a,media:o}=n;if(!i||!o)return;const u=performance.now(),c=s?s.stats:i.stats,d=s?s.duration:i.duration,h=u-c.loading.start,f=n.minAutoLevel,g=i.level,m=this._nextAutoLevel;if(c.aborted||c.loaded&&c.loaded===c.total||g<=f)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!a)return;const p=m>-1&&m!==g,v=!!t||p;if(!v&&(o.paused||!o.playbackRate||!o.readyState))return;const y=n.mainForwardBufferInfo;if(!v&&null===y)return;const E=this.bwEstimator.getEstimateTTFB(),T=Math.abs(o.playbackRate);if(h<=Math.max(E,d/(2*T)*1e3))return;const b=y?y.len/T:0,S=c.loading.first?c.loading.first-c.loading.start:-1,A=c.loaded&&S>-1,L=this.getBwEstimate(),k=n.levels,R=k[g],I=Math.max(c.loaded,Math.round(d*(i.bitrate||R.averageBitrate)/8));let _=A?h-S:h;_<1&&A&&(_=Math.min(h,8*c.loaded/L));const w=A?1e3*c.loaded/_:0,P=E/1e3,D=w?(I-c.loaded)/w:8*I/L+P;if(D<=b)return;const C=w?8*w:L,O=!0===(null==(e=(null==t?void 0:t.details)||this.hls.latestLevelDetails)?void 0:e.live),x=this.hls.config.abrBandWidthUpFactor;let M,F=Number.POSITIVE_INFINITY;for(M=g-1;M>f;M--){const t=k[M].maxBitrate,e=!k[M].details||O;if(F=this.getTimeToLoadFrag(P,C,d*t,e),F<Math.min(b,d+P))break}if(F>=D)return;if(F>10*d)return;A?this.bwEstimator.sample(h-Math.min(E,S),c.loaded):this.bwEstimator.sampleTTFB(h);const N=k[M].maxBitrate;this.getBwEstimate()*x>N&&this.resetEstimator(N);const B=this.findBestLevel(N,f,M,0,b,1,1);B>-1&&(M=B),this.warn(`Fragment ${i.sn}${s?" part "+s.index:""} of level ${g} is loading too slowly;\n      Fragment duration: ${i.duration.toFixed(3)}\n      Time to underbuffer: ${b.toFixed(3)} s\n      Estimated load time for current fragment: ${D.toFixed(3)} s\n      Estimated load time for down switch fragment: ${F.toFixed(3)} s\n      TTFB estimate: ${0|S} ms\n      Current BW estimate: ${r(L)?0|L:"Unknown"} bps\n      New BW estimate: ${0|this.getBwEstimate()} bps\n      Switching to level ${M} @ ${0|N} bps`),n.nextLoadLevel=n.nextAutoLevel=M,this.clearTimer();const U=()=>{if(this.clearTimer(),this.fragCurrent===i&&this.hls.loadLevel===M&&M>0){const t=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${M>0?"and switching down":""}\n      Fragment duration: ${i.duration.toFixed(3)} s\n      Time to underbuffer: ${t.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,M>f){let e=this.findBestLevel(this.hls.levels[f].bitrate,f,M,0,t,1,1);-1===e&&(e=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=e,this.resetEstimator(this.hls.levels[e].bitrate)}}};p||D>2*F?U():this.timer=self.setInterval(U,1e3*F),n.trigger(l.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:s,stats:c})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){t&&(this.log(`setting initial bwe to ${t}`),this.hls.config.abrEwmaDefaultEstimate=t),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const t=this.hls.config;return new v(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.FRAG_LOADING,this.onFragLoading,this),t.on(l.FRAG_LOADED,this.onFragLoaded,this),t.on(l.FRAG_BUFFERED,this.onFragBuffered,this),t.on(l.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(l.LEVEL_LOADED,this.onLevelLoaded,this),t.on(l.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(l.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(l.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.FRAG_LOADING,this.onFragLoading,this),t.off(l.FRAG_LOADED,this.onFragLoaded,this),t.off(l.FRAG_BUFFERED,this.onFragBuffered,this),t.off(l.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(l.LEVEL_LOADED,this.onLevelLoaded,this),t.off(l.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(l.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(l.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(t,e){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(t,e){const i=e.frag;if(!this.ignoreFragment(i)){var r;if(!i.bitrateTest)this.fragCurrent=i,this.partCurrent=null!=(r=e.part)?r:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(t,e){this.clearTimer()}onError(t,e){if(!e.fatal)switch(e.details){case o.BUFFER_ADD_CODEC_ERROR:case o.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case o.FRAG_LOAD_TIMEOUT:{const t=e.frag,{fragCurrent:i,partCurrent:r}=this;if(t&&i&&t.sn===i.sn&&t.level===i.level){const e=performance.now(),i=r?r.stats:t.stats,s=e-i.loading.start,n=i.loading.first?i.loading.first-i.loading.start:-1;if(i.loaded&&n>-1){const t=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(s-Math.min(t,n),i.loaded)}else this.bwEstimator.sampleTTFB(s)}break}}}getTimeToLoadFrag(t,e,i,r){return t+i/e+(r?t+this.lastLevelLoadSec:0)}onLevelLoaded(t,e){const i=this.hls.config,{loading:s}=e.stats,n=s.end-s.first;r(n)&&(this.lastLevelLoadSec=n/1e3),e.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(e.levelInfo)}onFragLoaded(t,{frag:e,part:i}){const r=i?i.stats:e.stats;if(e.type===f&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(e)){if(this.clearTimer(),e.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const t=i?i.duration:e.duration,s=this.hls.levels[e.level],n=(s.loaded?s.loaded.bytes:0)+r.loaded,a=(s.loaded?s.loaded.duration:0)+t;s.loaded={bytes:n,duration:a},s.realBitrate=Math.round(8*n/a)}if(e.bitrateTest){const t={stats:r,frag:e,part:i,id:e.type};this.onFragBuffered(l.FRAG_BUFFERED,t),e.bitrateTest=!1}else this.lastLoadedFragLevel=e.level}}onFragBuffered(t,e){const{frag:i,part:r}=e,s=null!=r&&r.stats.loaded?r.stats:i.stats;if(s.aborted)return;if(this.ignoreFragment(i))return;const n=s.parsing.end-s.loading.start-Math.min(s.loading.first-s.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,s.loaded),s.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==f||"initSegment"===t.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:t,minAutoLevel:e}=this.hls,i=this.getBwEstimate(),r=this.hls.config.maxStarvationDelay,s=this.findBestLevel(i,e,t,0,r,1,1);if(s>-1)return s;const n=this.hls.firstLevel,a=Math.min(Math.max(n,e),t);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 t=this.forcedAutoLevel,e=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(!(-1===t||e&&i&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return t;const r=e&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==t){const e=this.hls.levels;if(e.length>Math.max(t,r)&&e[t].loadError<=e[r].loadError)return t}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;const{maxAutoLevel:r,config:s,minAutoLevel:n}=i,a=e?e.duration:t?t.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let u=s.abrBandWidthFactor,c=s.abrBandWidthUpFactor;if(l){const t=this.findBestLevel(o,n,r,l,0,u,c);if(t>=0)return this.rebufferNotice=-1,t}let d=a?Math.min(a,s.maxStarvationDelay):s.maxStarvationDelay;if(!l){const t=this.bitrateTestDelay;if(t){d=(a?Math.min(a,s.maxLoadingDelay):s.maxLoadingDelay)-t,this.info(`bitrate test took ${Math.round(1e3*t)}ms, set first fragment max fetchDuration to ${Math.round(1e3*d)} ms`),u=c=1}}const h=this.findBestLevel(o,n,r,l,d,u,c);if(this.rebufferNotice!==h&&(this.rebufferNotice=h,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${h}`)),h>-1)return h;const f=i.levels[n],g=i.loadLevelObj;return g&&(null==f?void 0:f.bitrate)<g.bitrate?n:i.loadLevel}getStarvationDelay(){const t=this.hls,e=t.media;if(!e)return Infinity;const i=e&&0!==e.playbackRate?Math.abs(e.playbackRate):1,r=t.mainForwardBufferInfo;return(r?r.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(t,e,i,s,n,a,o){var l;const u=s+n,c=this.lastLoadedFragLevel,d=-1===c?this.hls.firstLevel:c,{fragCurrent:h,partCurrent:f}=this,{levels:g,allAudioTracks:m,loadLevel:p,config:v}=this.hls;if(1===g.length)return 0;const y=g[d],E=!(null==(l=this.hls.latestLevelDetails)||!l.live),T=-1===p||-1===c;let b,S="SDR",A=(null==y?void 0:y.frameRate)||0;const{audioPreference:L,videoPreference:k}=v,R=this.audioTracksByGroup||(this.audioTracksByGroup=ne(m));let I=-1;if(T){if(-1!==this.firstSelection)return this.firstSelection;const s=this.codecTiers||(this.codecTiers=function(t,e,i,r){return t.slice(i,r+1).reduce(((t,i,r)=>{if(!i.codecSet)return t;const s=i.audioGroups;let n=t[i.codecSet];n||(t[i.codecSet]=n={minBitrate:Infinity,minHeight:Infinity,minFramerate:Infinity,minIndex:r,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!s,fragmentError:0}),n.minBitrate=Math.min(n.minBitrate,i.bitrate);const a=Math.min(i.height,i.width);return n.minHeight=Math.min(n.minHeight,a),n.minFramerate=Math.min(n.minFramerate,i.frameRate),n.minIndex=Math.min(n.minIndex,r),n.maxScore=Math.max(n.maxScore,i.score),n.fragmentError+=i.fragmentError,n.videoRanges[i.videoRange]=(n.videoRanges[i.videoRange]||0)+1,s&&s.forEach((t=>{if(!t)return;const i=e.groups[t];i&&(n.hasDefaultAudio=n.hasDefaultAudio||e.hasDefaultAudio?i.hasDefault:i.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(i.channels).forEach((t=>{n.channels[t]=(n.channels[t]||0)+i.channels[t]})))})),t}),{})}(g,R,e,i)),n=function(t,e,i,s,n){const a=Object.keys(t),o=null==s?void 0:s.channels,l=null==s?void 0:s.audioCodec,u=null==n?void 0:n.videoCodec,c=o&&2===parseInt(o);let d=!1,h=!1,f=Infinity,g=Infinity,m=Infinity,p=Infinity,v=0,y=[];const{preferHDR:E,allowedVideoRanges:T}=ie(e,n);for(let e=a.length;e--;){const i=t[a[e]];d||(d=i.channels[2]>0),f=Math.min(f,i.minHeight),g=Math.min(g,i.minFramerate),m=Math.min(m,i.minBitrate),T.filter((t=>i.videoRanges[t]>0)).length>0&&(h=!0)}f=r(f)?f:0,g=r(g)?g:0;const b=Math.max(1080,f),S=Math.max(30,g);m=r(m)?m:i,i=Math.max(m,i),h||(e=void 0);const A=a.length>1;return{codecSet:a.reduce(((e,r)=>{const s=t[r];if(r===e)return e;if(y=h?T.filter((t=>s.videoRanges[t]>0)):[],A){if(s.minBitrate>i)return se(r,`min bitrate of ${s.minBitrate} > current estimate of ${i}`),e;if(!s.hasDefaultAudio)return se(r,"no renditions with default or auto-select sound found"),e;if(l&&r.indexOf(l.substring(0,4))%5!=0)return se(r,`audio codec preference "${l}" not found`),e;if(o&&!c){if(!s.channels[o])return se(r,`no renditions with ${o} channel sound found (channels options: ${Object.keys(s.channels)})`),e}else if((!l||c)&&d&&0===s.channels[2])return se(r,"no renditions with stereo sound found"),e;if(s.minHeight>b)return se(r,`min resolution of ${s.minHeight} > maximum of ${b}`),e;if(s.minFramerate>S)return se(r,`min framerate of ${s.minFramerate} > maximum of ${S}`),e;if(!y.some((t=>s.videoRanges[t]>0)))return se(r,`no variants with VIDEO-RANGE of ${re(y)} found`),e;if(u&&r.indexOf(u.substring(0,4))%5!=0)return se(r,`video codec preference "${u}" not found`),e;if(s.maxScore<v)return se(r,`max score of ${s.maxScore} < selected max of ${v}`),e}return e&&(Dt(r)>=Dt(e)||s.fragmentError>t[e].fragmentError)?e:(p=s.minIndex,v=s.maxScore,r)}),void 0),videoRanges:y,preferHDR:E,minFramerate:g,minBitrate:m,minIndex:p}}(s,S,t,L,k),{codecSet:a,videoRanges:o,minFramerate:l,minBitrate:u,minIndex:c,preferHDR:d}=n;I=c,b=a,S=d?o[o.length-1]:o[0],A=l,t=Math.max(t,u),this.log(`picked start tier ${re(n)}`)}else b=null==y?void 0:y.codecSet,S=null==y?void 0:y.videoRange;const _=f?f.duration:h?h.duration:0,w=this.bwEstimator.getEstimateTTFB()/1e3,P=[];for(let l=i;l>=e;l--){var D;const e=g[l],h=l>d;if(!e)continue;if(v.useMediaCapabilities&&!e.supportedResult&&!e.supportedPromise){const i=navigator.mediaCapabilities;"function"==typeof(null==i?void 0:i.decodingInfo)&&Vt(e,R,S,A,t,L)?(e.supportedPromise=jt(e,R,i,this.supportedCache),e.supportedPromise.then((t=>{if(!this.hls)return;e.supportedResult=t;const i=this.hls.levels,r=i.indexOf(e);t.error?this.warn(`MediaCapabilities decodingInfo error: "${t.error}" for level ${r} ${re(t)}`):t.supported?t.decodingInfoResults.some((t=>!1===t.smooth||!1===t.powerEfficient))&&this.log(`MediaCapabilities decodingInfo for level ${r} not smooth or powerEfficient: ${re(t)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${r} ${re(t)}`),r>-1&&i.length>1&&(this.log(`Removing unsupported level ${r}`),this.hls.removeLevel(r),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))})).catch((t=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${t}`)}))):e.supportedResult=Gt}if((b&&e.codecSet!==b||S&&e.videoRange!==S||h&&A>e.frameRate||!h&&A>0&&A<e.frameRate||null!=(D=e.supportedResult)&&null!=(D=D.decodingInfoResults)&&D.some((t=>!1===t.smooth)))&&(!T||l!==I)){P.push(l);continue}const m=e.details,y=(f?null==m?void 0:m.partTarget:null==m?void 0:m.averagetargetduration)||_;let k;k=h?o*t:a*t;const C=_&&s>=2*_&&0===n?e.averageBitrate:e.maxBitrate,O=this.getTimeToLoadFrag(w,k,C*y,void 0===m);if(k>=C&&(l===c||0===e.loadError&&0===e.fragmentError)&&(O<=w||!r(O)||E&&!this.bitrateTestDelay||O<u)){const t=this.forcedAutoLevel;return l===p||-1!==t&&t===p||(P.length&&this.trace(`Skipped level(s) ${P.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${g[P[0]].codecs}" ${g[P[0]].videoRange}; not compatible with "${b}" ${S}`),this.info(`switch candidate:${d}->${l} adjustedbw(${Math.round(k)})-bitrate=${Math.round(k-C)} ttfb:${w.toFixed(1)} avgDuration:${y.toFixed(1)} maxFetchDuration:${u.toFixed(1)} fetchDuration:${O.toFixed(1)} firstSelection:${T} codecSet:${e.codecSet} videoRange:${e.videoRange} hls.loadLevel:${p}`)),T&&(this.firstSelection=l),l}}return-1}set nextAutoLevel(t){const e=this.deriveNextAutoLevel(t);this._nextAutoLevel!==e&&(this.nextAutoLevelKey="",this._nextAutoLevel=e)}deriveNextAutoLevel(t){const{maxAutoLevel:e,minAutoLevel:i}=this.hls;return Math.min(Math.max(t,i),e)}},bufferController:class extends S{constructor(t,e){var i;super("buffer-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=t=>{var e;this.hls&&"open"===(null==(e=this.mediaSource)?void 0:e.readyState)&&this.hls.pauseBuffering()},this._onStartStreaming=t=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=t=>{const{media:e,mediaSource:i}=this;t&&this.log("Media source opened"),e&&i&&(i.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(l.MEDIA_ATTACHED,{media:e,mediaSource:i}),null!==this.mediaSource&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:t,_objectUrl:e}=this;t!==e&&this.error(`Media element src was set while attaching MediaSource (${e} > ${t})`)},this.hls=t,this.fragmentTracker=e,this.appendSource=(i=w(t.config.preferManagedMediaSource),"undefined"!=typeof self&&i===self.ManagedMediaSource),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:t}=this;t.on(l.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.MANIFEST_PARSED,this.onManifestParsed,this),t.on(l.BUFFER_RESET,this.onBufferReset,this),t.on(l.BUFFER_APPENDING,this.onBufferAppending,this),t.on(l.BUFFER_CODECS,this.onBufferCodecs,this),t.on(l.BUFFER_EOS,this.onBufferEos,this),t.on(l.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(l.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(l.FRAG_PARSED,this.onFragParsed,this),t.on(l.FRAG_CHANGED,this.onFragChanged,this),t.on(l.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(l.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.MANIFEST_PARSED,this.onManifestParsed,this),t.off(l.BUFFER_RESET,this.onBufferReset,this),t.off(l.BUFFER_APPENDING,this.onBufferAppending,this),t.off(l.BUFFER_CODECS,this.onBufferCodecs,this),t.off(l.BUFFER_EOS,this.onBufferEos,this),t.off(l.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(l.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(l.FRAG_PARSED,this.onFragParsed,this),t.off(l.FRAG_CHANGED,this.onFragChanged,this),t.off(l.ERROR,this.onError,this)}transferMedia(){const{media:t,mediaSource:e}=this;if(!t)return null;const i={};if(this.operationQueue){const t=this.isUpdating();t||this.operationQueue.removeBlockers();const e=this.isQueued();(t||e)&&this.warn(`Transfering MediaSource with${e?" operations in queue":""}${t?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const r=this.transferData;return!this.sourceBufferCount&&r&&r.mediaSource===e?E(i,r.tracks):this.sourceBuffers.forEach((t=>{const[e]=t;e&&(i[e]=E({},this.tracks[e]),this.removeBuffer(e)),t[0]=t[1]=null})),{media:t,mediaSource:e,tracks:i}}initTracks(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(t,e){var i;let r=2;(e.audio&&!e.video||!e.altAudio)&&(r=1),this.bufferCodecEventsTotal=r,this.log(`${r} bufferCodec event(s) expected.`),null!=(i=this.transferData)&&i.mediaSource&&this.sourceBufferCount&&r&&this.bufferCreated()}onMediaAttaching(t,e){const i=this.media=e.media;this.transferData=this.overrides=void 0;const r=w(this.appendSource);if(r){const t=!!e.mediaSource;(t||e.overrides)&&(this.transferData=e,this.overrides=e.overrides);const s=this.mediaSource=e.mediaSource||new r;if(this.assignMediaSource(s),t)this._objectUrl=i.src,this.attachTransferred();else{const t=this._objectUrl=self.URL.createObjectURL(s);if(this.appendSource)try{i.removeAttribute("src");const e=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||e&&s instanceof e,Tn(i),function(t,e){const i=self.document.createElement("source");i.type="video/mp4",i.src=e,t.appendChild(i)}(i,t),i.load()}catch(e){i.src=t}else i.src=t}i.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(t){var e,i;this.log(`${(null==(e=this.transferData)?void 0:e.mediaSource)===t?"transferred":"created"} media source: ${null==(i=t.constructor)?void 0:i.name}`),t.addEventListener("sourceopen",this._onMediaSourceOpen),t.addEventListener("sourceended",this._onMediaSourceEnded),t.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.addEventListener("startstreaming",this._onStartStreaming),t.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const t=this.media,e=this.transferData;if(!e||!t)return;const i=this.tracks,r=e.tracks,s=r?Object.keys(r):null,n=s?s.length:0,a=()=>{Promise.resolve().then((()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()}))};if(r&&s&&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: ${re(i,((t,e)=>"initSegment"===t?void 0:e))};\ntransfer tracks: ${re(r,((t,e)=>"initSegment"===t?void 0:e))}}`),!P(r,i)){e.mediaSource=null,e.tracks=void 0;const s=t.currentTime,n=this.details,a=Math.max(s,(null==n?void 0:n.fragments[0].start)||0);return a-s>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${s} -> ${a}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(r)}"->"${Object.keys(i)}") start time: ${a} currentTime: ${s}`),this.onMediaDetaching(l.MEDIA_DETACHING,{}),this.onMediaAttaching(l.MEDIA_ATTACHING,e),void(t.currentTime=a))}this.transferData=void 0,s.forEach((t=>{const e=t,i=r[e];if(i){const t=i.buffer;if(t){const r=this.fragmentTracker,s=i.id;if(r.hasFragments(s)||r.hasParts(s)){const i=ii.getBuffered(t);r.detectEvictedFragments(e,i,s,null,!0)}const n=bn(e),a=[e,t];this.sourceBuffers[n]=a,t.updating&&this.operationQueue&&this.operationQueue.prependBlocker(e),this.trackSourceBuffer(e,i)}}})),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var t;const e=null==(t=this.mediaSource)?void 0:t.readyState;return"open"===e||"ended"===e}onMediaDetaching(t,e){const i=!!e.transferMedia;this.transferData=this.overrides=void 0;const{media:r,mediaSource:s,_objectUrl:n}=this;if(s){if(this.log("media source "+(i?"transferring":"detaching")),i)this.sourceBuffers.forEach((([t])=>{t&&this.removeBuffer(t)})),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const t="open"===s.readyState;try{const e=s.sourceBuffers;for(let i=e.length;i--;)t&&e[i].abort(),s.removeSourceBuffer(e[i]);t&&s.endOfStream()}catch(t){this.warn(`onMediaDetaching: ${t.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}s.removeEventListener("sourceopen",this._onMediaSourceOpen),s.removeEventListener("sourceended",this._onMediaSourceEnded),s.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(s.removeEventListener("startstreaming",this._onStartStreaming),s.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}r&&(r.removeEventListener("emptied",this._onMediaEmptied),i||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(r.removeAttribute("src"),this.appendSource&&Tn(r),r.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(l.MEDIA_DETACHED,e)}onBufferReset(){this.sourceBuffers.forEach((([t])=>{t&&this.resetBuffer(t)})),this.initTracks()}resetBuffer(t){var e;const i=null==(e=this.tracks[t])?void 0:e.buffer;if(this.removeBuffer(t),i)try{var r;null!=(r=this.mediaSource)&&r.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(e){this.warn(`onBufferReset ${t}`,e)}delete this.tracks[t]}removeBuffer(t){this.removeBufferListeners(t),this.sourceBuffers[bn(t)]=[null,null];const e=this.tracks[t];e&&(e.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new pn(this.tracks)}onBufferCodecs(t,e){var i;const r=this.tracks,s=Object.keys(e);this.log(`BUFFER_CODECS: "${s}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in e&&(r.audio||r.video)||r.audiovideo&&("audio"in e||"video"in e),a=!n&&this.sourceBufferCount&&this.media&&s.some((t=>!r[t]));n||a?this.warn(`Unsupported transition between "${Object.keys(r)}" and "${s}" SourceBuffers`):(s.forEach((t=>{var i,s;const n=e[t],{id:a,codec:o,levelCodec:l,container:u,metadata:c,supplemental:d}=n;let h=r[t];const f=null==(i=this.transferData)||null==(i=i.tracks)?void 0:i[t],g=null!=f&&f.buffer?f:h,m=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),p=null==g?void 0:g.levelCodec;h||(h=r[t]={buffer:void 0,listeners:[],codec:o,supplemental:d,container:u,levelCodec:l,metadata:c,id:a});const v=Mt(m,p),y=null==v?void 0:v.replace(vn,"$1");let E=Mt(o,l);const T=null==(s=E)?void 0:s.replace(vn,"$1");E&&v&&y!==T&&("audio"===t.slice(0,5)&&(E=xt(E,this.appendSource)),this.log(`switching codec ${m} to ${E}`),E!==(h.pendingCodec||h.codec)&&(h.pendingCodec=E),h.container=u,this.appendChangeType(t,u,E))})),(this.tracksReady||this.sourceBufferCount)&&(e.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!e.video&&"main"===(null==(i=e.audio)?void 0:i.id)&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))}get sourceBufferTracks(){return Object.keys(this.tracks).reduce(((t,e)=>{const i=this.tracks[e];return t[e]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},t}),{})}appendChangeType(t,e,i){const r=`${e};codecs=${i}`,s={label:`change-type=${r}`,execute:()=>{const s=this.tracks[t];if(s){const n=s.buffer;null!=n&&n.changeType&&(this.log(`changing ${t} sourceBuffer type to ${r}`),n.changeType(r),s.codec=i,s.container=e)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn(`Failed to change ${t} SourceBuffer type`,e)}};this.append(s,t,this.isPending(this.tracks[t]))}blockAudio(t){var e;const i=t.start,r=i+.05*t.duration;if(!0===(null==(e=this.fragmentTracker.getAppendedFrag(i,f))?void 0:e.gap))return;const s={label:"block-audio",execute:()=>{var t;const e=this.tracks.video;(this.lastVideoAppendEnd>r||null!=e&&e.buffer&&ii.isBuffered(e.buffer,r)||!0===(null==(t=this.fragmentTracker.getAppendedFrag(r,f))?void 0:t.gap))&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn("Error executing block-audio operation",t)}};this.blockedAudioAppend={op:s,frag:t},this.append(s,"audio",!0)}unblockAudio(){const{blockedAudioAppend:t,operationQueue:e}=this;t&&e&&(this.blockedAudioAppend=null,e.unblockAudio(t.op))}onBufferAppending(t,e){const{tracks:i}=this,{data:s,type:n,parent:u,frag:c,part:d,chunkMeta:h,offset:g}=e,m=h.buffering[n],{sn:p,cc:v}=c,y=self.performance.now();m.start=y;const E=c.stats.buffering,T=d?d.stats.buffering:null;0===E.start&&(E.start=y),T&&0===T.start&&(T.start=y);const b=i.audio;let S=!1;"audio"===n&&"audio/mpeg"===(null==b?void 0:b.container)&&(S=!this.lastMpegAudioChunk||1===h.id||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);const A=i.video,L=null==A?void 0:A.buffer;if(L&&"initSegment"!==p){const t=d||c,e=this.blockedAudioAppend;if("audio"!==n||"main"===u||this.blockedAudioAppend||A.ending||A.ended){if("video"===n){const i=t.end;if(e){const t=e.frag.start;(i>t||i<this.lastVideoAppendEnd||ii.isBuffered(L,t))&&this.unblockAudio()}this.lastVideoAppendEnd=i}}else{const e=t.start+.05*t.duration,i=L.buffered,r=this.currentOp("video");i.length||r?!r&&!ii.isBuffered(L,e)&&this.lastVideoAppendEnd<e&&this.blockAudio(t):this.blockAudio(t)}}const k=(d||c).start,R={label:`append-${n}`,execute:()=>{var t;m.executeStart=self.performance.now();const e=null==(t=this.tracks[n])?void 0:t.buffer;e&&(S?this.updateTimestampOffset(e,k,.1,n,p,v):void 0!==g&&r(g)&&this.updateTimestampOffset(e,g,1e-6,n,p,v)),this.appendExecutor(s,n)},onStart:()=>{},onComplete:()=>{const t=self.performance.now();m.executeEnd=m.end=t,0===E.first&&(E.first=t),T&&0===T.first&&(T.first=t);const e={};this.sourceBuffers.forEach((([t,i])=>{t&&(e[t]=ii.getBuffered(i))})),this.appendErrors[n]=0,"audio"===n||"video"===n?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(l.BUFFER_APPENDED,{type:n,frag:c,part:d,chunkMeta:h,parent:c.type,timeRanges:e})},onError:t=>{var e;const i={type:a.MEDIA_ERROR,parent:c.type,details:o.BUFFER_APPEND_ERROR,sourceBufferName:n,frag:c,part:d,chunkMeta:h,error:t,err:t,fatal:!1},r=null==(e=this.media)?void 0:e.error;if(t.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==t.name||"quota"in t)i.details=o.BUFFER_FULL_ERROR;else if(t.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!r)i.errorAction=Oe(!0);else if(t.name===yn&&0===this.sourceBufferCount)i.errorAction=Oe(!0);else{const t=++this.appendErrors[n];this.warn(`Failed ${t}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${n}" sourceBuffer (${r||"no media error"})`),(t>=this.hls.config.appendErrorMaxRetry||r)&&(i.fatal=!0)}this.hls.trigger(l.ERROR,i)}};this.log(`queuing "${n}" append sn: ${p}${d?" p: "+d.index:""} of ${c.type===f?"level":"track"} ${c.level} cc: ${v}`),this.append(R,n,this.isPending(this.tracks[n]))}getFlushOp(t,e,i){return this.log(`queuing "${t}" remove ${e}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(t,e,i)},onStart:()=>{},onComplete:()=>{this.hls.trigger(l.BUFFER_FLUSHED,{type:t})},onError:r=>{this.warn(`Failed to remove ${e}-${i} from "${t}" SourceBuffer`,r)}}}onBufferFlushing(t,e){const{type:i,startOffset:r,endOffset:s}=e;i?this.append(this.getFlushOp(i,r,s),i):this.sourceBuffers.forEach((([t])=>{t&&this.append(this.getFlushOp(t,r,s),t)}))}onFragParsed(t,e){const{frag:i,part:r}=e,s=[],n=r?r.elementaryStreams:i.elementaryStreams;n[W]?s.push("audiovideo"):(n[j]&&s.push("audio"),n[K]&&s.push("video"));0===s.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers((()=>{const t=self.performance.now();i.stats.buffering.end=t,r&&(r.stats.buffering.end=t);const e=r?r.stats:i.stats;this.hls.trigger(l.FRAG_BUFFERED,{frag:i,part:r,stats:e,id:i.type})}),s).catch((t=>{this.warn(`Fragment buffered callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)}))}onFragChanged(t,e){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some((([t])=>{if(t){const e=this.tracks[t];if(e)return!e.ended||e.ending}return!1}))}onBufferEos(t,e){var i;this.sourceBuffers.forEach((([t])=>{if(t){const i=this.tracks[t];e.type&&e.type!==t||(i.ending=!0,i.ended||(i.ended=!0,this.log(`${t} buffer reached EOS`)))}}));const r=!1!==(null==(i=this.overrides)?void 0:i.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some((([t])=>{var e;return t&&!(null!=(e=this.tracks[t])&&e.ended)}))?r?(this.log("Queueing EOS"),this.blockUntilOpen((()=>{this.tracksEnded();const{mediaSource:t}=this;t&&"open"===t.readyState?(this.log("Calling mediaSource.endOfStream()"),t.endOfStream(),this.hls.trigger(l.BUFFERED_TO_END,void 0)):t&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${t.readyState}`)}))):(this.tracksEnded(),this.hls.trigger(l.BUFFERED_TO_END,void 0)):"video"===e.type&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach((([t])=>{if(null!==t){const e=this.tracks[t];e&&(e.ending=!1)}}))}onLevelUpdated(t,{details:e}){e.fragments.length&&(this.details=e,this.updateDuration())}updateDuration(){this.blockUntilOpen((()=>{const t=this.getDurationAndRange();t&&this.updateMediaSource(t)}))}onError(t,e){if(e.details===o.BUFFER_APPEND_ERROR&&e.frag){var i;const t=null==(i=e.errorAction)?void 0:i.nextAutoLevel;r(t)&&t!==e.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:t,details:e,media:i}=this;if(!i||null===e)return;if(!this.sourceBufferCount)return;const s=t.config,n=i.currentTime,a=e.levelTargetDuration,o=e.live&&null!==s.liveBackBufferLength?s.liveBackBufferLength:s.backBufferLength;if(r(o)&&o>=0){const t=Math.max(o,a),e=Math.floor(n/a)*a-t;this.flushBackBuffer(n,a,e)}const l=s.frontBufferFlushThreshold;if(r(l)&&l>0){const t=Math.max(s.maxBufferLength,l),e=Math.max(t,a),i=Math.floor(n/a)*a+e;this.flushFrontBuffer(n,a,i)}}flushBackBuffer(t,e,i){this.sourceBuffers.forEach((([t,e])=>{if(e){const s=ii.getBuffered(e);if(s.length>0&&i>s.start(0)){var r;this.hls.trigger(l.BACK_BUFFER_REACHED,{bufferEnd:i});const e=this.tracks[t];if(null!=(r=this.details)&&r.live)this.hls.trigger(l.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(null!=e&&e.ended)return void this.log(`Cannot flush ${t} back buffer while SourceBuffer is in ended state`);this.hls.trigger(l.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:t})}}}))}flushFrontBuffer(t,e,i){this.sourceBuffers.forEach((([e,r])=>{if(r){const s=ii.getBuffered(r),n=s.length;if(n<2)return;const a=s.start(n-1),o=s.end(n-1);if(i>a||t>=a&&t<=o)return;this.hls.trigger(l.BUFFER_FLUSHING,{startOffset:a,endOffset:Infinity,type:e})}}))}getDurationAndRange(){var t;const{details:e,mediaSource:i}=this;if(!e||!this.media||"open"!==(null==i?void 0:i.readyState))return null;const s=e.edge;if(e.live&&this.hls.config.liveDurationInfinity){if(e.fragments.length&&i.setLiveSeekableRange){const t=Math.max(0,e.fragmentStart);return{duration:Infinity,start:t,end:Math.max(t,s)}}return{duration:Infinity}}const n=null==(t=this.overrides)?void 0:t.duration;if(n)return r(n)?{duration:n}:null;const a=this.media.duration;return s>(r(i.duration)?i.duration:0)&&s>a||!r(a)?{duration:s}:null}updateMediaSource({duration:t,start:e,end:i}){const s=this.mediaSource;this.media&&s&&"open"===s.readyState&&(s.duration!==t&&(r(t)&&this.log(`Updating MediaSource duration to ${t.toFixed(3)}`),s.duration=t),void 0!==e&&void 0!==i&&(this.log(`MediaSource duration is set to ${s.duration}. Setting seekable range to ${e}-${i}.`),s.setLiveSeekableRange(e,i)))}get tracksReady(){const t=this.pendingTrackCount;return t>0&&(t>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:t,pendingTrackCount:e,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${e} codec events expected: ${t}) ${re(i)}`),this.tracksReady){var r;const t=null==(r=this.transferData)?void 0:r.tracks;t&&Object.keys(t).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const t={};this.sourceBuffers.forEach((([e,i])=>{if(e){const r=this.tracks[e];t[e]={buffer:i,container:r.container,codec:r.codec,supplemental:r.supplemental,levelCodec:r.levelCodec,id:r.id,metadata:r.metadata}}})),this.hls.trigger(l.BUFFER_CREATED,{tracks:t}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach((([t])=>{this.executeNext(t)}))}else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}createSourceBuffers(){const{tracks:t,sourceBuffers:e,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(const s in t){const n=s,u=t[n];if(this.isPending(u)){const t=this.getTrackCodec(u,n),s=`${u.container};codecs=${t}`;u.codec=t,this.log(`creating sourceBuffer(${s})${this.currentOp(n)?" Queued":""} ${re(u)}`);try{const t=i.addSourceBuffer(s),r=bn(n),a=[n,t];e[r]=a,u.buffer=t}catch(t){var r;return this.error(`error while trying to add sourceBuffer: ${t.message}`),this.shiftAndExecuteNext(n),null==(r=this.operationQueue)||r.removeBlockers(),delete this.tracks[n],void this.hls.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:n,mimeType:s,parent:u.id})}this.trackSourceBuffer(n,u)}}this.bufferCreated()}getTrackCodec(t,e){const i=t.supplemental;let r=t.codec;i&&("video"===e||"audiovideo"===e)&&It(i,"video")&&(r=function(t,e){const i=[];if(t){const e=t.split(",");for(let t=0;t<e.length;t++)Rt(e[t],"video")||i.push(e[t])}return e&&i.push(e),i.join(",")}(r,i));const s=Mt(r,t.levelCodec);return s?"audio"===e.slice(0,5)?xt(s,this.appendSource):s:""}trackSourceBuffer(t,e){const i=e.buffer;if(!i)return;const r=this.getTrackCodec(e,t);this.tracks[t]={buffer:i,codec:r,container:e.container,levelCodec:e.levelCodec,supplemental:e.supplemental,metadata:e.metadata,id:e.id,listeners:[]},this.removeBufferListeners(t),this.addBufferListener(t,"updatestart",this.onSBUpdateStart),this.addBufferListener(t,"updateend",this.onSBUpdateEnd),this.addBufferListener(t,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(t,"bufferedchange",((t,e)=>{const i=e.removedRanges;null!=i&&i.length&&this.hls.trigger(l.BUFFER_FLUSHED,{type:t})}))}get mediaSrc(){var t,e;const i=(null==(t=this.media)||null==(e=t.querySelector)?void 0:e.call(t,"source"))||this.media;return null==i?void 0:i.src}onSBUpdateStart(t){const e=this.currentOp(t);e&&e.onStart()}onSBUpdateEnd(t){var e;if("closed"===(null==(e=this.mediaSource)?void 0:e.readyState))return void this.resetBuffer(t);const i=this.currentOp(t);i&&(i.onComplete(),this.shiftAndExecuteNext(t))}onSBUpdateError(t,e){var i;const r=new Error(`${t} SourceBuffer error. MediaSource readyState: ${null==(i=this.mediaSource)?void 0:i.readyState}`);this.error(`${r}`,e),this.hls.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:r,fatal:!1});const s=this.currentOp(t);s&&s.onError(r)}updateTimestampOffset(t,e,i,r,s,n){const a=e-t.timestampOffset;Math.abs(a)>=i&&(this.log(`Updating ${r} SourceBuffer timestampOffset to ${e} (sn: ${s} cc: ${n})`),t.timestampOffset=e)}removeExecutor(t,e,i){const{media:s,mediaSource:n}=this,a=this.tracks[t],o=null==a?void 0:a.buffer;if(!s||!n||!o)return this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),void this.shiftAndExecuteNext(t);const l=r(s.duration)?s.duration:Infinity,u=r(n.duration)?n.duration:Infinity,c=Math.max(0,e),d=Math.min(i,l,u);d>c&&(!a.ending||a.ended)?(a.ended=!1,this.log(`Removing [${c},${d}] from the ${t} SourceBuffer`),o.remove(c,d)):this.shiftAndExecuteNext(t)}appendExecutor(t,e){const i=this.tracks[e],r=null==i?void 0:i.buffer;if(!r)throw new En(`Attempting to append to the ${e} SourceBuffer, but it does not exist`);i.ending=!1,i.ended=!1,r.appendBuffer(t)}blockUntilOpen(t){if(this.isUpdating()||this.isQueued())this.blockBuffers(t).catch((t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)}));else try{t()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some((([t,e])=>t&&e.updating))}isQueued(){return this.sourceBuffers.some((([t])=>t&&!!this.currentOp(t)))}isPending(t){return!!t&&!t.buffer}blockBuffers(t,e=this.sourceBufferTypes){if(!e.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);const{operationQueue:i}=this,r=e.map((t=>this.appendBlocker(t)));return e.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(r).then((e=>{i===this.operationQueue&&(t(),this.stepOperationQueue(this.sourceBufferTypes))}))}stepOperationQueue(t){t.forEach((t=>{var e;const i=null==(e=this.tracks[t])?void 0:e.buffer;i&&!i.updating&&this.shiftAndExecuteNext(t)}))}append(t,e,i){this.operationQueue&&this.operationQueue.append(t,e,i)}appendBlocker(t){if(this.operationQueue)return this.operationQueue.appendBlocker(t)}currentOp(t){return this.operationQueue?this.operationQueue.current(t):null}executeNext(t){t&&this.operationQueue&&this.operationQueue.executeNext(t)}shiftAndExecuteNext(t){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(t)}get pendingTrackCount(){return Object.keys(this.tracks).reduce(((t,e)=>t+(this.isPending(this.tracks[e])?1:0)),0)}get sourceBufferCount(){return this.sourceBuffers.reduce(((t,[e])=>t+(e?1:0)),0)}get sourceBufferTypes(){return this.sourceBuffers.map((([t])=>t)).filter((t=>!!t))}addBufferListener(t,e,i){const r=this.tracks[t];if(!r)return;const s=r.buffer;if(!s)return;const n=i.bind(this,t);r.listeners.push({event:e,listener:n}),s.addEventListener(e,n)}removeBufferListeners(t){const e=this.tracks[t];if(!e)return;const i=e.buffer;i&&(e.listeners.forEach((t=>{i.removeEventListener(t.event,t.listener)})),e.listeners.length=0)}},capLevelController:Sn,errorController:class extends S{constructor(t){super("error-controller",t.logger),this.hls=void 0,this.playlistError=0,this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(l.ERROR,this.onError,this),t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(l.ERROR,this.onError,this),t.off(l.ERROR,this.onErrorOut,this),t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){return(null==t?void 0:t.type)===f?t.level:this.getVariantIndex()}getVariantIndex(){var t;const e=this.hls,i=e.currentLevel;return null!=(t=e.loadLevelObj)&&t.details||-1===i?e.loadLevel:i}variantHasKey(t,e){if(t){var i;if(null!=(i=t.details)&&i.hasKey(e))return!0;const r=t.audioGroups;if(r){return this.hls.allAudioTracks.filter((t=>r.indexOf(t.groupId)>=0)).some((t=>{var i;return null==(i=t.details)?void 0:i.hasKey(e)}))}}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(t,e){var i;if(e.fatal)return;const r=this.hls,s=e.context;switch(e.details){case o.FRAG_LOAD_ERROR:case o.FRAG_LOAD_TIMEOUT:case o.KEY_LOAD_ERROR:case o.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case o.FRAG_PARSING_ERROR:if(null!=(i=e.frag)&&i.gap)return void(e.errorAction=Oe());case o.FRAG_GAP:case o.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=Re);case o.LEVEL_EMPTY_ERROR:case o.LEVEL_PARSING_ERROR:{var n;const t=e.parent===f?e.level:r.loadLevel;e.details===o.LEVEL_EMPTY_ERROR&&null!=(n=e.context)&&null!=(n=n.levelDetails)&&n.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,t):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t))}return;case o.LEVEL_LOAD_ERROR:case o.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==s?void 0:s.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,s.level)));case o.AUDIO_TRACK_LOAD_ERROR:case o.AUDIO_TRACK_LOAD_TIMEOUT:case o.SUBTITLE_LOAD_ERROR:case o.SUBTITLE_TRACK_LOAD_TIMEOUT:if(s){const t=r.loadLevelObj;if(t&&(s.type===d&&t.hasAudioGroup(s.groupId)||s.type===h&&t.hasSubtitleGroup(s.groupId)))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,r.loadLevel),e.errorAction.action=Re,void(e.errorAction.flags=Pe)}return;case o.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(e.errorAction={action:Re,flags:De});case o.KEY_SYSTEM_SESSION_UPDATE_FAILED:case o.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case o.KEY_SYSTEM_NO_SESSION:return void(e.errorAction={action:Re,flags:Ce});case o.BUFFER_ADD_CODEC_ERROR:case o.REMUX_ALLOC_ERROR:case o.BUFFER_APPEND_ERROR:var l;if(!e.errorAction)e.errorAction=this.getLevelSwitchAction(e,null!=(l=e.level)?l:r.loadLevel);return;case o.INTERNAL_EXCEPTION:case o.BUFFER_APPENDING_ERROR:case o.BUFFER_FULL_ERROR:case o.LEVEL_SWITCH_ERROR:case o.BUFFER_STALLED_ERROR:case o.BUFFER_SEEK_OVER_HOLE:case o.BUFFER_NUDGE_ON_STALL:return void(e.errorAction=Oe())}e.type===a.KEY_SYSTEM_ERROR&&(e.levelRetry=!1,e.errorAction=Oe())}getPlaylistRetryOrSwitchAction(t,e){const i=Te(this.hls.config.playlistLoadPolicy,t),r=this.playlistError++;if(Ae(i,r,ve(t),t.response))return{action:_e,flags:we,retryConfig:i,retryCount:r};const s=this.getLevelSwitchAction(t,e);return i&&(s.retryConfig=i,s.retryCount=r),s}getFragRetryOrSwitchAction(t){const e=this.hls,i=this.getVariantLevelIndex(t.frag),r=e.levels[i],{fragLoadPolicy:s,keyLoadPolicy:n}=e.config,a=Te(ye(t)?n:s,t),l=e.levels.reduce(((t,e)=>t+e.fragmentError),0);if(r&&(t.details!==o.FRAG_GAP&&r.fragmentError++,!Ee(t))){if(Ae(a,l,ve(t),t.response))return{action:_e,flags:we,retryConfig:a,retryCount:l}}const u=this.getLevelSwitchAction(t,i);return a&&(u.retryConfig=a,u.retryCount=l),u}getLevelSwitchAction(t,e){const i=this.hls;null==e&&(e=i.loadLevel);const r=this.hls.levels[e];if(r){var s,n;const e=t.details;r.loadError++,e===o.BUFFER_APPEND_ERROR&&r.fragmentError++;let u=-1;const{levels:c,loadLevel:p,minAutoLevel:v,maxAutoLevel:y}=i;i.autoLevelEnabled||i.config.preserveManualLevelOnError||(i.loadLevel=-1);const E=null==(s=t.frag)?void 0:s.type,T=(E===g&&e===o.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&(e===o.BUFFER_ADD_CODEC_ERROR||e===o.BUFFER_APPEND_ERROR))&&c.some((({audioCodec:t})=>r.audioCodec!==t)),b="video"===t.sourceBufferName&&(e===o.BUFFER_ADD_CODEC_ERROR||e===o.BUFFER_APPEND_ERROR)&&c.some((({codecSet:t,audioCodec:e})=>r.codecSet!==t&&r.audioCodec===e)),{type:S,groupId:A}=null!=(n=t.context)?n:{};for(let i=c.length;i--;){const s=(i+p)%c.length;if(s!==p&&s>=v&&s<=y&&0===c[s].loadError){var a,l;const i=c[s];if(e===o.FRAG_GAP&&E===f&&t.frag){const e=c[s].details;if(e){const i=fe(t.frag,e.fragments,t.frag.start);if(null!=i&&i.gap)continue}}else{if(S===d&&i.hasAudioGroup(A)||S===h&&i.hasSubtitleGroup(A))continue;if(E===g&&null!=(a=r.audioGroups)&&a.some((t=>i.hasAudioGroup(t)))||E===m&&null!=(l=r.subtitleGroups)&&l.some((t=>i.hasSubtitleGroup(t)))||T&&r.audioCodec===i.audioCodec||b&&r.codecSet===i.codecSet||!T&&r.codecSet!==i.codecSet)continue}u=s;break}}if(u>-1&&i.loadLevel!==u)return t.levelRetry=!0,this.playlistError=0,{action:Re,flags:we,nextAutoLevel:u}}return{action:Re,flags:Pe}}onErrorOut(t,e){var i;switch(null==(i=e.errorAction)?void 0:i.action){case ke:break;case Re:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===o.FRAG_GAP?/MediaSource readyState: ended/.test(e.error.message)&&(this.warn(`MediaSource ended after "${e.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):e.fatal=!0}e.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(t){const e=this.hls,i=t.errorAction;if(!i)return;const{flags:r}=i,s=i.nextAutoLevel;switch(r){case we:this.switchLevel(t,s);break;case De:{const r=this.getVariantLevelIndex(t.frag),s=e.levels[r],n=null==s?void 0:s.attrs["HDCP-LEVEL"];if(i.hdcpLevel=n,"NONE"===n)this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(n){e.maxHdcpLevel=Yt[Yt.indexOf(n)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`);break}}case Ce:{const e=t.decryptdata;if(e){const r=this.hls.levels,s=r.length;for(let i=s;i--;){var n,a;if(this.variantHasKey(r[i],e))this.log(`Banned key found in level ${i} (${r[i].bitrate}bps) or audio group "${null==(n=r[i].audioGroups)?void 0:n.join(",")}" (${null==(a=t.frag)?void 0:a.type} fragment) ${C(e.keyId||[])}`),r[i].fragmentError++,r[i].loadError++,this.log(`Removing level ${i} with key error (${t.error})`),this.hls.removeLevel(i)}const o=t.frag;if(this.hls.levels.length<s)i.resolved=!0;else if(o&&o.type!==f){const t=o.decryptdata;t&&!e.matches(t)&&(i.resolved=!0)}}break}}i.resolved||this.switchLevel(t,s)}switchLevel(t,e){if(void 0!==e&&t.errorAction&&(this.warn(`switching to level ${e} after ${t.details}`),this.hls.nextAutoLevel=e,t.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,t.details===o.BUFFER_ADD_CODEC_ERROR&&t.mimeType&&"audiovideo"!==t.sourceBufferName)){const e=Ut(t.mimeType),i=this.hls.levels;for(let r=i.length;r--;)i[r][`${t.sourceBufferName}Codec`]===e&&(this.log(`Removing level ${r} for ${t.details} ("${e}" not supported)`),this.hls.removeLevel(r))}}},fpsController:class{constructor(t){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners()}setStreamController(t){this.streamController=t}registerListeners(){this.hls.on(l.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(l.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(l.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(l.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,e){const i=this.hls.config;if(i.capLevelOnFPSDrop){const t=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=t,t&&"function"==typeof t.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(t,e,i){const r=performance.now();if(e){if(this.lastTime){const t=r-this.lastTime,s=i-this.lastDroppedFrames,n=e-this.lastDecodedFrames,a=1e3*s/t,o=this.hls;if(o.trigger(l.FPS_DROP,{currentDropped:s,currentDecoded:n,totalDroppedFrames:i}),a>0&&s>o.config.fpsDroppedMonitoringThreshold*n){let t=o.currentLevel;o.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=t)&&(t-=1,o.trigger(l.FPS_DROP_LEVEL_CAPPING,{level:t,droppedLevel:o.currentLevel}),o.autoLevelCapping=t,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=i,this.lastDecodedFrames=e}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)}},stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Di,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:Infinity,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:Uo,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:class extends Or{constructor(t,e,i){super(t,e,i,"subtitle-stream-controller",m),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(l.LEVEL_LOADED,this.onLevelLoaded,this),t.on(l.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(l.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(l.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(l.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(l.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(l.LEVEL_LOADED,this.onLevelLoaded,this),t.off(l.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(l.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(l.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(l.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(l.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(t,e){this.stopLoad(),this.state=Sr,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(t,e){this.tracksBuffered=[],super.onMediaDetaching(t,e)}onLevelLoaded(t,e){this.mainDetails=e.details}onSubtitleFragProcessed(t,e){const{frag:i,success:r}=e;if(this.fragContextChanged(i)||(q(i)&&(this.fragPrevious=i),this.state=Sr),!r)return;const s=this.tracksBuffered[this.currentTrackId];if(!s)return;let n;const a=i.start;for(let t=0;t<s.length;t++)if(a>=s[t].start&&a<=s[t].end){n=s[t];break}const o=i.start+i.duration;n?n.end=o:(n={start:a,end:o},s.push(n)),this.fragmentTracker.fragBuffered(i),this.fragBufferedComplete(i,null),this.media&&this.tick()}onBufferFlushing(t,e){const{startOffset:i,endOffset:r}=e;if(0===i&&r!==Number.POSITIVE_INFINITY){const t=r-1;if(t<=0)return;e.endOffsetSubtitles=Math.max(0,t),this.tracksBuffered.forEach((e=>{for(let i=0;i<e.length;)if(e[i].end<=t)e.shift();else{if(!(e[i].start<t))break;e[i].start=t,i++}})),this.fragmentTracker.removeFragmentsInRange(i,t,m)}}onError(t,e){const i=e.frag;(null==i?void 0:i.type)===m&&(e.details===o.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==br&&(this.state=Sr))}onSubtitleTracksUpdated(t,{subtitleTracks:e}){this.levels&&fn(this.levels,e)?this.levels=e.map((t=>new te(t))):(this.tracksBuffered=[],this.levels=e.map((t=>{const e=new te(t);return this.tracksBuffered[e.id]=[],e})),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,m),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(t,e){var i;if(this.currentTrackId=e.id,null==(i=this.levels)||!i.length||-1===this.currentTrackId)return void this.clearInterval();const r=this.levels[this.currentTrackId];null!=r&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.state!==br&&this.setInterval(500)}onSubtitleTrackLoaded(t,e){var i;const{currentTrackId:r,levels:s}=this,{details:n,id:a}=e;if(!s)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=s[a];if(a>=s.length||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let u=0;if(n.live||null!=(i=o.details)&&i.live){if(n.deltaUpdateFailed)return;const t=this.mainDetails;if(!t)return void(this.startFragRequested=!1);const e=t.fragments[0];var c;if(o.details)u=this.alignPlaylists(n,o.details,null==(c=this.levelLastLoaded)?void 0:c.details),0===u&&e&&(u=e.start,nr(n,u));else n.hasProgramDateTime&&t.hasProgramDateTime?(vr(n,t),u=n.fragmentStart):e&&(u=e.start,nr(n,u));t&&!this.startFragRequested&&this.setStartPosition(t,u)}if(o.details=n,this.levelLastLoaded=o,a===r&&(this.hls.trigger(l.SUBTITLE_TRACK_UPDATED,{details:n,id:a,groupId:e.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===Sr)){fe(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}_handleFragmentLoadComplete(t){const{frag:e,payload:i}=t,r=e.decryptdata,s=this.hls;if(!this.fragContextChanged(e)&&i&&i.byteLength>0&&null!=r&&r.key&&r.iv&&pi(r.method)){const t=performance.now();this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer,vi(r.method)).catch((t=>{throw s.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t})).then((i=>{const r=performance.now();s.trigger(l.FRAG_DECRYPTED,{frag:e,payload:i,stats:{tstart:t,tdecrypt:r}})})).catch((t=>{this.warn(`${t.name}: ${t.message}`),this.state=Sr}))}}doTick(){if(this.media){if(this.state===Sr){const{currentTrackId:t,levels:e}=this,i=null==e?void 0:e[t];if(!i||!e.length||!i.details)return;if(this.waitForLive(i))return;const{config:r}=this,s=this.getLoadPosition(),n=ii.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,r.maxBufferHole),{end:a,len:o}=n,l=i.details;if(o>this.hls.maxBufferLength+l.levelTargetDuration)return;const u=l.fragments,c=u.length,d=l.edge;let h=null;const f=this.fragPrevious;if(a<d){const t=r.maxFragLookUpTolerance,e=a>d-t?0:t;h=fe(f,u,Math.max(u[0].start,a),e),!h&&f&&f.start<u[0].start&&(h=u[0])}else h=u[c-1];if(h=this.filterReplacedPrimary(h,i.details),!h)return;const g=u[h.sn-l.startSN-1];if(g&&g.cc===h.cc&&this.fragmentTracker.getState(g)===xe&&(h=g),this.fragmentTracker.getState(h)===xe){const t=this.mapToInitFragWhenRequired(h);t&&this.loadFragment(t,i,a)}}}else this.state=Sr}loadFragment(t,e,i){q(t)?super.loadFragment(t,e,i):this._loadInitSegment(t,e)}get mediaBufferTimeRanges(){return new Va(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends hn{constructor(t){super(t,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const e=Ia(this.media.textTracks);for(let i=0;i<e.length;i++)if("hidden"===e[i].mode)t=e[i];else if("showing"===e[i].mode){t=e[i];break}const i=this.findTrackForTextTrack(t);this.subtitleTrack!==i&&this.setSubtitleTrack(i)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.MANIFEST_PARSED,this.onManifestParsed,this),t.on(l.LEVEL_LOADING,this.onLevelLoading,this),t.on(l.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(l.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(l.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.MANIFEST_PARSED,this.onManifestParsed,this),t.off(l.LEVEL_LOADING,this.onLevelLoading,this),t.off(l.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(l.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(l.ERROR,this.onError,this)}onMediaAttached(t,e){this.media=e.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,t)}onMediaDetaching(t,e){const i=this.media;if(!i)return;const r=!!e.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,r)return;Ia(i.textTracks).forEach((t=>{ka(t)}))}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.subtitleTracks}onSubtitleTrackLoaded(t,e){const{id:i,groupId:r,details:s}=e,n=this.tracksInGroup[i];if(!n||n.groupId!==r)return void this.warn(`Subtitle track with id:${i} and group:${r} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Subtitle track ${i} "${n.name}" lang:${n.lang} group:${r} loaded [${s.startSN}-${s.endSN}]`),i===this.trackId&&this.playlistLoaded(i,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const i=e.subtitleGroups||null,r=this.groupIds;let s=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some((t=>-1===(null==r?void 0:r.indexOf(t))))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter((t=>!i||-1!==i.indexOf(t.groupId)));if(t.length)this.selectDefaultTrack&&!t.some((t=>t.default))&&(this.selectDefaultTrack=!1),t.forEach(((t,e)=>{t.id=e}));else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.subtitlePreference;if(!s&&e){this.selectDefaultTrack=!1;const i=oe(e,t);if(i>-1)s=t[i];else{const t=oe(e,this.tracks);s=this.tracks[t]}}let r=this.findTrackId(s);-1===r&&s&&(r=this.findTrackId(null));const n={subtitleTracks:t};this.log(`Updating subtitle tracks, ${t.length} track(s) found in "${null==i?void 0:i.join(",")}" group-id`),this.hls.trigger(l.SUBTITLE_TRACKS_UPDATED,n),-1!==r&&-1===this.trackId&&this.setSubtitleTrack(r)}}findTrackId(t){const e=this.tracksInGroup,i=this.selectDefaultTrack;for(let r=0;r<e.length;r++){const s=e[r];if((!i||s.default)&&(i||t)&&(!t||le(s,t)))return r}if(t){for(let i=0;i<e.length;i++){const r=e[i];if(gn(t.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<e.length;i++){const r=e[i];if(gn(t.attrs,r.attrs,["LANGUAGE"]))return i}}return-1}findTrackForTextTrack(t){if(t){const e=this.tracksInGroup;for(let i=0;i<e.length;i++){if(mn(e[i],t))return i}}return-1}onError(t,e){!e.fatal&&e.context&&(e.context.type!==h||e.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||this.checkRetry(e))}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(t){this.selectDefaultTrack=!1,this.setSubtitleTrack(t)}setSubtitleOption(t){if(this.hls.config.subtitlePreference=t,t){if(-1===t.id)return this.setSubtitleTrack(-1),null;const e=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,e.length){const i=this.currentTrack;if(i&&le(t,i))return i;const r=oe(t,this.tracksInGroup);if(r>-1){const t=this.tracksInGroup[r];return this.setSubtitleTrack(r),t}if(i)return null;{const i=oe(t,e);if(i>-1)return e[i]}}}return null}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const i=t.id,r=t.groupId,s=this.getUrlWithDirectives(t.url,e),n=t.details,a=null==n?void 0:n.age;this.log(`Loading subtitle ${i} "${t.name}" lang:${t.lang} group:${r}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type?" "+n.type||0:""):""} ${s}`),this.hls.trigger(l.SUBTITLE_TRACK_LOADING,{url:s,id:i,groupId:r,deliveryDirectives:e||null,track:t})}toggleTrackModes(){const{media:t}=this;if(!t)return;const e=Ia(t.textTracks),i=this.currentTrack;let r;if(i&&(r=e.filter((t=>mn(i,t)))[0],r||this.warn(`Unable to find subtitle TextTrack with name "${i.name}" and language "${i.lang}"`)),[].slice.call(e).forEach((t=>{"disabled"!==t.mode&&t!==r&&(t.mode="disabled")})),r){const t=this.subtitleDisplay?"showing":"hidden";r.mode!==t&&(r.mode=t)}}setSubtitleTrack(t){const e=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=t);if(t<-1||t>=e.length||!r(t))return void this.warn(`Invalid subtitle track id: ${t}`);this.selectDefaultTrack=!1;const i=this.currentTrack,s=e[t]||null;if(this.trackId=t,this.currentTrack=s,this.toggleTrackModes(),!s)return void this.hls.trigger(l.SUBTITLE_TRACK_SWITCH,{id:t});const n=!!s.details&&!s.details.live;if(t===this.trackId&&s===i&&n)return;this.log(`Switching to subtitle-track ${t}`+(s?` "${s.name}" lang:${s.lang} group:${s.groupId}`:""));const{id:a,groupId:o="",name:u,type:c,url:d}=s;this.hls.trigger(l.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:u,type:c,url:d});const h=this.switchParams(s.url,null==i?void 0:i.details,s.details);this.loadPlaylist(h)}},timelineController:class{constructor(t){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},t.on(l.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(l.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(l.FRAG_LOADING,this.onFragLoading,this),t.on(l.FRAG_LOADED,this.onFragLoaded,this),t.on(l.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(l.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(l.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(l.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(l.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(l.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(l.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(l.FRAG_LOADING,this.onFragLoading,this),t.off(l.FRAG_LOADED,this.onFragLoaded,this),t.off(l.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(l.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(l.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(l.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(l.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const t=new Mo(this,"textTrack1"),e=new Mo(this,"textTrack2"),i=new Mo(this,"textTrack3"),r=new Mo(this,"textTrack4");this.cea608Parser1=new ao(1,t,e),this.cea608Parser2=new ao(3,i,r)}addCues(t,e,i,r,s){let n=!1;for(let t=s.length;t--;){const r=s[t],l=(a=r[0],o=r[1],u=e,c=i,Math.min(o,c)-Math.max(a,u));if(l>=0&&(r[0]=Math.min(r[0],e),r[1]=Math.max(r[1],i),n=!0,l/(i-e)>.5))return}var a,o,u,c;if(n||s.push([e,i]),this.config.renderTextTracksNatively){const s=this.captionsTracks[t];this.Cues.newCue(s,e,i,r)}else{const s=this.Cues.newCue(null,e,i,r);this.hls.trigger(l.CUES_PARSED,{type:"captions",cues:s,track:t})}}onInitPtsFound(t,{frag:e,id:i,initPTS:r,timescale:s,trackId:n}){const{unparsedVttFrags:a}=this;i===f&&(this.initPTS[e.cc]={baseTime:r,timescale:s,trackId:n}),a.length&&(this.unparsedVttFrags=[],a.forEach((t=>{this.initPTS[t.frag.cc]?this.onFragLoaded(l.FRAG_LOADED,t):this.hls.trigger(l.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t.frag,error:new Error("Subtitle discontinuity domain does not match main")})})))}getExistingTrack(t,e){const{media:i}=this;if(i)for(let r=0;r<i.textTracks.length;r++){const s=i.textTracks[r];if(No(s,{name:t,lang:e,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return s}return null}createCaptionsTrack(t){this.config.renderTextTracksNatively?this.createNativeTrack(t):this.createNonNativeTrack(t)}createNativeTrack(t){if(this.captionsTracks[t])return;const{captionsProperties:e,captionsTracks:i,media:r}=this,{label:s,languageCode:n}=e[t],a=this.getExistingTrack(s,n);if(a)i[t]=a,ka(i[t]),Aa(i[t],r);else{const e=this.createTextTrack("captions",s,n);e&&(e[t]=!0,i[t]=e)}}createNonNativeTrack(t){if(this.nonNativeCaptionsTracks[t])return;const e=this.captionsProperties[t];if(!e)return;const i={_id:t,label:e.label,kind:"captions",default:!!e.media&&!!e.media.default,closedCaptions:e.media};this.nonNativeCaptionsTracks[t]=i,this.hls.trigger(l.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(t,e,i){const r=this.media;if(r)return r.addTextTrack(t,e,i)}onMediaAttaching(t,e){this.media=e.media,e.mediaSource||this._cleanTracks()}onMediaDetaching(t,e){const i=!!e.transferMedia;if(this.media=null,i)return;const{captionsTracks:r}=this;Object.keys(r).forEach((t=>{ka(r[t]),delete r[t]})),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:t}=this;if(!t)return;const e=t.textTracks;if(e)for(let t=0;t<e.length;t++)ka(e[t])}onSubtitleTracksUpdated(t,e){const i=e.subtitleTracks||[],r=i.some((t=>t.textCodec===Lo));if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(fn(this.tracks,i))return void(this.tracks=i);if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const t=this.media,e=t?Ia(t.textTracks):null;if(this.tracks.forEach(((t,i)=>{let r;if(e){let i=null;for(let r=0;r<e.length;r++)if(e[r]&&No(e[r],t)){i=e[r],e[r]=null;break}i&&(r=i)}if(r)ka(r);else{const e=Fo(t);r=this.createTextTrack(e,t.name,t.lang),r&&(r.mode="disabled")}r&&this.textTracks.push(r)})),null!=e&&e.length){const t=e.filter((t=>null!==t)).map((t=>t.label));t.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${t.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const t=this.tracks.map((t=>({label:t.name,kind:t.type.toLowerCase(),default:t.default,subtitleTrack:t})));this.hls.trigger(l.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:t})}}}onManifestLoaded(t,e){this.config.enableCEA708Captions&&e.captions&&e.captions.forEach((t=>{const e=/(?:CC|SERVICE)([1-4])/.exec(t.instreamId);if(!e)return;const i=`textTrack${e[1]}`,r=this.captionsProperties[i];r&&(r.label=t.name,t.lang&&(r.languageCode=t.lang),r.media=t)}))}closedCaptionsForLevel(t){const e=this.hls.levels[t.level];return null==e?void 0:e.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,e){if(this.enabled&&e.frag.type===f){var i,r;const{cea608Parser1:t,cea608Parser2:s,lastSn:n}=this,{cc:a,sn:o}=e.frag,l=null!=(i=null==(r=e.part)?void 0:r.index)?i:-1;t&&s&&(o!==n+1||o===n&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(t.reset(),s.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(t,e){const{frag:i,payload:r}=e;if(i.type===m)if(r.byteLength){const t=i.decryptdata,s="stats"in e;if(null==t||!t.encrypted||s){const t=this.tracks[i.level],s=this.vttCCs;s[i.cc]||(s[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),t&&t.textCodec===Lo?this._parseIMSC1(i,r):this._parseVTTs(e)}}else this.hls.trigger(l.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,e){const i=this.hls;_o(e,this.initPTS[t.cc],(e=>{this._appendCues(e,t.level),i.trigger(l.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})}),(e=>{i.logger.log(`Failed to parse IMSC1: ${e}`),i.trigger(l.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:e})}))}_parseVTTs(t){var e;const{frag:i,payload:r}=t,{initPTS:s,unparsedVttFrags:n}=this,a=s.length-1;if(!s[i.cc]&&-1===a)return void n.push(t);const o=this.hls;Ao(null!=(e=i.initSegment)&&e.data?pt(i.initSegment.data,new Uint8Array(r)).buffer:r,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,(t=>{this._appendCues(t,i.level),o.trigger(l.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})}),(e=>{const s="Missing initPTS for VTT MPEGTS"===e.message;s?n.push(t):this._fallbackToIMSC1(i,r),o.logger.log(`Failed to parse VTT cue: ${e}`),s&&a>i.cc||o.trigger(l.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:e})}))}_fallbackToIMSC1(t,e){const i=this.tracks[t.level];i.textCodec||_o(e,this.initPTS[t.cc],(()=>{i.textCodec=Lo,this._parseIMSC1(t,e)}),(()=>{i.textCodec="wvtt"}))}_appendCues(t,e){const i=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[e];if(!i||"disabled"===i.mode)return;t.forEach((t=>La(i,t)))}else{const r=this.tracks[e];if(!r)return;const s=r.default?"default":"subtitles"+e;i.trigger(l.CUES_PARSED,{type:"subtitles",cues:t,track:s})}}onFragDecrypted(t,e){const{frag:i}=e;i.type===m&&this.onFragLoaded(l.FRAG_LOADED,e)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,e){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:i,samples:r}=e;if(i.type!==f||"NONE"!==this.closedCaptionsForLevel(i))for(let t=0;t<r.length;t++){const e=r[t].bytes;if(e){this.cea608Parser1||this.initCea608Parsers();const i=this.extractCea608Data(e);this.cea608Parser1.addData(r[t].pts,i[0]),this.cea608Parser2.addData(r[t].pts,i[1])}}}onBufferFlushing(t,{startOffset:e,endOffset:i,endOffsetSubtitles:r,type:s}){const{media:n}=this;if(n&&!(n.currentTime<i)){if(!s||"video"===s){const{captionsTracks:t}=this;Object.keys(t).forEach((r=>Ra(t[r],e,i)))}if(this.config.renderTextTracksNatively&&0===e&&void 0!==r){const{textTracks:t}=this;Object.keys(t).forEach((i=>Ra(t[i],e,r)))}}}extractCea608Data(t){const e=[[],[]],i=31&t[0];let r=2;for(let s=0;s<i;s++){const i=t[r++],s=127&t[r++],n=127&t[r++];if(0===s&&0===n)continue;if(!!(4&i)){const t=3&i;0!==t&&1!==t||(e[t].push(s),e[t].push(n))}}return e}},audioStreamController:class extends Or{constructor(t,e,i){super(t,e,i,"audio-stream-controller",g),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(l.LEVEL_LOADED,this.onLevelLoaded,this),t.on(l.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(l.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(l.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(l.BUFFER_RESET,this.onBufferReset,this),t.on(l.BUFFER_CREATED,this.onBufferCreated,this),t.on(l.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(l.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(l.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(l.FRAG_LOADING,this.onFragLoading,this),t.on(l.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:t}=this;t&&(super.unregisterListeners(),t.off(l.LEVEL_LOADED,this.onLevelLoaded,this),t.off(l.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(l.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(l.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(l.BUFFER_RESET,this.onBufferReset,this),t.off(l.BUFFER_CREATED,this.onBufferCreated,this),t.off(l.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(l.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(l.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(l.FRAG_LOADING,this.onFragLoading,this),t.off(l.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(t,{frag:e,id:i,initPTS:r,timescale:s,trackId:n}){if(i===f){const t=e.cc,i=this.fragCurrent;if(this.initPTS[t]={baseTime:r,timescale:s,trackId:n},this.log(`InitPTS for cc: ${t} found from main: ${r/s} (${r}/${s}) trackId: ${n}`),this.mainAnchor=e,this.state===Dr){const i=this.waitingData;(!i&&!this.loadingParts||i&&i.frag.cc!==t)&&this.syncWithAnchor(e,null==i?void 0:i.frag)}else!this.hls.hasEnoughToStart&&i&&i.cc!==t?(i.abortRequests(),this.syncWithAnchor(e,i)):this.state===Sr&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(t,e){var i;const r=(null==(i=this.mainFragLoading)?void 0:i.frag)||null;if(e&&(null==r?void 0:r.cc)===e.cc)return;const s=(r||t).cc,n=pe(this.getLevelDetails(),s,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===Sr&&this.doTickIdle())}startLoad(t,e){if(!this.levels)return this.startPosition=t,void(this.state=br);const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),i>0&&-1===t?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),t=i,this.state=Sr):this.state=Rr,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}doTick(){switch(this.state){case Sr:this.doTickIdle();break;case Rr:{const{levels:t,trackId:e}=this,i=null==t?void 0:t[e],r=null==i?void 0:i.details;if(r&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(r))break;this.state=Dr}break}case kr:this.checkRetryDate();break;case Dr:{const t=this.waitingData;if(t){const{frag:e,part:i,cache:r,complete:s}=t,n=this.mainAnchor;if(void 0!==this.initPTS[e.cc]){this.waitingData=null,this.state=Lr;const t={frag:e,part:i,payload:r.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(t),s&&super._handleFragmentLoadComplete(t)}else n&&n.cc!==t.frag.cc&&this.syncWithAnchor(n,t.frag)}else this.state=Sr}}this.onTickEnd()}resetLoadingState(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:t}=this;null!=t&&t.readyState&&(this.lastCurrentTime=t.currentTime)}doTickIdle(){var t;const{hls:e,levels:i,media:r,trackId:s}=this,n=e.config;if(!this.buffering||!r&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||null==i||!i[s])return;const a=i[s],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o))return this.state=Rr,void(this.startFragRequested=!1);const u=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&u&&(this.bufferFlushed=!1,this.afterBufferFlushed(u,j,g));const c=this.getFwdBufferInfo(u,g);if(null===c)return;if(!this.switchingTrack&&this._streamEnded(c,o))return e.trigger(l.BUFFER_EOS,{type:"audio"}),void(this.state=wr);const d=c.len,h=e.maxBufferLength,m=o.fragments,p=m[0].start,v=this.getLoadPosition(),y=this.flushing?v:c.end;if(this.switchingTrack&&r){const t=v;o.PTSKnown&&t<p&&(c.end>p||c.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),r.currentTime=p+.05)}if(d>=h&&!this.switchingTrack&&y<m[m.length-1].start)return;let E=this.getNextFragment(y,o);if(E&&this.isLoopLoading(E,y)&&(E=this.getNextFragmentLoopLoading(E,o,c,f,h)),!E)return void(this.bufferFlushed=!0);let T=(null==(t=this.mainFragLoading)?void 0:t.frag)||null;if(!this.audioOnly&&this.startFragRequested&&T&&q(E)&&!E.endList&&(!o.live||!this.loadingParts&&y<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(T)===Ne&&(this.mainFragLoading=T=null),T&&q(T))){if(E.start>T.end){const t=this.fragmentTracker.getFragAtPos(y,f);t&&t.end>T.end&&(T=t,this.mainFragLoading={frag:t,targetBufferTime:null})}if(E.start>T.end)return}this.loadFragment(E,a,y)}onMediaDetaching(t,e){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(t,e)}onAudioTracksUpdated(t,{audioTracks:e}){this.resetTransmuxer(),this.levels=e.map((t=>new te(t)))}onAudioTrackSwitching(t,e){const i=!!e.url;this.trackId=e.id;const{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),i?(this.switchingTrack=e,this.flushAudioIfNeeded(e),this.state!==br&&(this.setInterval(100),this.state=Sr,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=e,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(t,e){this.mainDetails=e.details;const i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(l.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(t,e){var i;const{levels:r}=this,{details:s,id:n,groupId:a,track:o}=e;if(!r)return void this.warn(`Audio tracks reset while loading track ${n} "${o.name}" of "${a}"`);const u=this.mainDetails;if(!u||s.endCC>u.endCC||u.expired)return this.cachedTrackLoadedData=e,void(this.state!==br&&(this.state=Rr));this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${o.name}" of "${a}" loaded [${s.startSN},${s.endSN}]${s.lastPartSn?`[part-${s.lastPartSn}-${s.lastPartIndex}]`:""},duration:${s.totalduration}`);const c=r[n];let d=0;if(s.live||null!=(i=c.details)&&i.live){if(this.checkLiveUpdate(s),s.deltaUpdateFailed)return;var h;if(c.details)d=this.alignPlaylists(s,c.details,null==(h=this.levelLastLoaded)?void 0:h.details);s.alignedSliding||(pr(s,u),s.alignedSliding||vr(s,u),d=s.fragmentStart)}c.details=s,this.levelLastLoaded=c,this.startFragRequested||this.setStartPosition(u,d),this.hls.trigger(l.AUDIO_TRACK_UPDATED,{details:s,id:n,groupId:e.groupId}),this.state!==Rr||this.waitForCdnTuneIn(s)||(this.state=Sr),this.tick()}_handleFragmentLoadProgress(t){var e;const i=t.frag,{part:r,payload:s}=t,{config:n,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const u=l.details;if(!u)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(i.start);const c=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let d=this.transmuxer;d||(d=this.transmuxer=new dn(this.hls,g,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const h=this.initPTS[i.cc],f=null==(e=i.initSegment)?void 0:e.data;if(void 0!==h){const t=!1,e=r?r.index:-1,n=-1!==e,a=new ti(i.level,i.sn,i.stats.chunkCount,s.byteLength,e,n);d.push(s,f,c,"",i,r,u.totalduration,t,a,h)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${u.startSN} ,${u.endSN}],track ${a}`);const{cache:t}=this.waitingData=this.waitingData||{frag:i,part:r,cache:new Mr,complete:!1};t.push(new Uint8Array(s)),this.state!==br&&(this.state=Dr)}}_handleFragmentLoadComplete(t){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(t,e){this.bufferFlushed=this.flushing=!1;const i=e.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(t,e){!this.audioOnly&&e.frag.type===f&&q(e.frag)&&(this.mainFragLoading=e,this.state===Sr&&this.tick())}onFragBuffered(t,e){const{frag:i,part:r}=e;if(i.type===g)if(this.fragContextChanged(i))this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if(q(i)){this.fragPrevious=i;const t=this.switchingTrack;t&&(this.bufferedTrack=t,this.switchingTrack=null,this.hls.trigger(l.AUDIO_TRACK_SWITCHED,b({},t)))}this.fragBufferedComplete(i,r),this.media&&this.tick()}else this.audioOnly||i.type!==f||i.elementaryStreams.video||i.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}onError(t,e){var i;if(e.fatal)this.state=Pr;else switch(e.details){case o.FRAG_GAP:case o.FRAG_PARSING_ERROR:case o.FRAG_DECRYPT_ERROR:case o.FRAG_LOAD_ERROR:case o.FRAG_LOAD_TIMEOUT:case o.KEY_LOAD_ERROR:case o.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(g,e);break;case o.AUDIO_TRACK_LOAD_ERROR:case o.AUDIO_TRACK_LOAD_TIMEOUT:case o.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==Rr||(null==(i=e.context)?void 0:i.type)!==d||(this.state=Sr);break;case o.BUFFER_ADD_CODEC_ERROR:case o.BUFFER_APPEND_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)||this.resetLoadingState();break;case o.BUFFER_FULL_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case o.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onBufferFlushing(t,{type:e}){e!==K&&(this.flushing=!0)}onBufferFlushed(t,{type:e}){if(e!==K){this.flushing=!1,this.bufferFlushed=!0,this.state===wr&&(this.state=Sr);const t=this.mediaBuffer||this.media;t&&(this.afterBufferFlushed(t,e,g),this.tick())}}_handleTransmuxComplete(t){var e;const i="audio",{hls:r}=this,{remuxResult:s,chunkMeta:n}=t,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:u,level:c}=a,{details:d}=c,{audio:h,text:f,id3:g,initSegment:m}=s;if(!this.fragContextChanged(o)&&d){if(this.state=Ir,this.switchingTrack&&h&&this.completeAudioSwitch(this.switchingTrack),null!=m&&m.tracks){const t=o.initSegment||o;if(this.unhandledEncryptionError(m,o))return;this._bufferInitSegment(c,m.tracks,t,n),r.trigger(l.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:i,tracks:m.tracks})}if(h){const{startPTS:t,endPTS:e,startDTS:i,endDTS:r}=h;u&&(u.elementaryStreams[j]={startPTS:t,endPTS:e,startDTS:i,endDTS:r}),o.setElementaryStreamInfo(j,t,e,i,r),this.bufferFragmentData(h,o,u,n)}if(null!=g&&null!=(e=g.samples)&&e.length){const t=E({id:i,frag:o,details:d},g);r.trigger(l.FRAG_PARSING_METADATA,t)}if(f){const t=E({id:i,frag:o,details:d},f);r.trigger(l.FRAG_PARSING_USERDATA,t)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(t,e,i,r){if(this.state!==Ir)return;if(e.video&&delete e.video,e.audiovideo&&delete e.audiovideo,!e.audio)return;const s=e.audio;s.id=g;const n=t.audioCodec;this.log(`Init audio buffer, container:${s.container}, codecs[level/parsed]=[${n}/${s.codec}]`),n&&1===n.split(",").length&&(s.levelCodec=n),this.hls.trigger(l.BUFFER_CODECS,e);const a=s.initSegment;if(null!=a&&a.byteLength){const t={type:"audio",frag:i,part:null,chunkMeta:r,parent:i.type,data:a};this.hls.trigger(l.BUFFER_APPENDING,t)}this.tickImmediate()}loadFragment(t,e,i){const r=this.fragmentTracker.getState(t);var s;if(this.switchingTrack||r===xe||r===Fe)if(q(t))if(null!=(s=e.details)&&s.live&&!this.initPTS[t.cc]){this.log(`Waiting for video PTS in continuity counter ${t.cc} of live stream before loading audio fragment ${t.sn} of level ${this.trackId}`),this.state=Dr;const i=this.mainDetails;i&&i.fragmentStart!==e.details.fragmentStart&&vr(e.details,i)}else super.loadFragment(t,e,i);else this._loadInitSegment(t,e);else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){if(this.media&&this.bufferedTrack){const{name:e,lang:i,assocLang:r,characteristics:s,audioCodec:n,channels:a}=this.bufferedTrack;le({name:e,lang:i,assocLang:r,characteristics:s,audioCodec:n,channels:a},t,ue)||(de(t.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=t)}}completeAudioSwitch(t){const{hls:e}=this;this.flushAudioIfNeeded(t),this.bufferedTrack=t,this.switchingTrack=null,e.trigger(l.AUDIO_TRACK_SWITCHED,b({},t))}},audioTrackController:class extends hn{constructor(t){super(t,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:t}=this;t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.MANIFEST_PARSED,this.onManifestParsed,this),t.on(l.LEVEL_LOADING,this.onLevelLoading,this),t.on(l.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(l.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(l.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.MANIFEST_PARSED,this.onManifestParsed,this),t.off(l.LEVEL_LOADING,this.onLevelLoading,this),t.off(l.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(l.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(l.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.audioTracks||[]}onAudioTrackLoaded(t,e){const{id:i,groupId:r,details:s}=e,n=this.tracksInGroup[i];if(!n||n.groupId!==r)return void this.warn(`Audio track with id:${i} and group:${r} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Audio track ${i} "${n.name}" lang:${n.lang} group:${r} loaded [${s.startSN}-${s.endSN}]`),i===this.trackId&&this.playlistLoaded(i,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const i=e.audioGroups||null,r=this.groupIds;let s=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some((t=>-1===(null==r?void 0:r.indexOf(t))))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter((t=>!i||-1!==i.indexOf(t.groupId)));if(t.length)this.selectDefaultTrack&&!t.some((t=>t.default))&&(this.selectDefaultTrack=!1),t.forEach(((t,e)=>{t.id=e}));else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.audioPreference;if(!s&&e){const i=oe(e,t,ue);if(i>-1)s=t[i];else{const t=oe(e,this.tracks);s=this.tracks[t]}}let r=this.findTrackId(s);-1===r&&s&&(r=this.findTrackId(null));const u={audioTracks:t};this.log(`Updating audio tracks, ${t.length} track(s) found in group(s): ${null==i?void 0:i.join(",")}`),this.hls.trigger(l.AUDIO_TRACKS_UPDATED,u);const c=this.trackId;if(-1!==r&&-1===c)this.setAudioTrack(r);else if(t.length&&-1===c){var n;const e=new Error(`No audio track selected for current audio group-ID(s): ${null==(n=this.groupIds)?void 0:n.join(",")} track count: ${t.length}`);this.warn(e.message),this.hls.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:e})}}}onError(t,e){!e.fatal&&e.context&&(e.context.type!==d||e.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||this.checkRetry(e))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}setAudioOption(t){const e=this.hls;if(e.config.audioPreference=t,t){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const r=this.currentTrack;if(r&&le(t,r,ue))return r;const s=oe(t,this.tracksInGroup,ue);if(s>-1){const t=this.tracksInGroup[s];return this.setAudioTrack(s),t}if(r){let r=e.loadLevel;-1===r&&(r=e.firstAutoLevel);const s=function(t,e,i,r,s){const n=e[r],a=e.reduce(((t,e,i)=>{const r=e.uri;return(t[r]||(t[r]=[])).push(i),t}),{})[n.uri];a.length>1&&(r=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,u=n.codecSet.substring(0,4),c=ce(e,r,(e=>{if(e.videoRange!==o||e.frameRate!==l||e.codecSet.substring(0,4)!==u)return!1;const r=e.audioGroups,n=i.filter((t=>!r||-1!==r.indexOf(t.groupId)));return oe(t,n,s)>-1}));return c>-1?c:ce(e,r,(e=>{const r=e.audioGroups,n=i.filter((t=>!r||-1!==r.indexOf(t.groupId)));return oe(t,n,s)>-1}))}(t,e.levels,i,r,ue);if(-1===s)return null;e.nextLoadLevel=s}if(t.channels||t.audioCodec){const e=oe(t,i);if(e>-1)return i[e]}}}return null}setAudioTrack(t){const e=this.tracksInGroup;if(t<0||t>=e.length)return void this.warn(`Invalid audio track id: ${t}`);this.selectDefaultTrack=!1;const i=this.currentTrack,r=e[t],s=r.details&&!r.details.live;if(t===this.trackId&&r===i&&s)return;if(this.log(`Switching to audio-track ${t} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=t,this.currentTrack=r,this.hls.trigger(l.AUDIO_TRACK_SWITCHING,b({},r)),s)return;const n=this.switchParams(r.url,null==i?void 0:i.details,r.details);this.loadPlaylist(n)}findTrackId(t){const e=this.tracksInGroup;for(let i=0;i<e.length;i++){const r=e[i];if((!this.selectDefaultTrack||r.default)&&(!t||le(t,r,ue)))return i}if(t){const{name:i,lang:r,assocLang:s,characteristics:n,audioCodec:a,channels:o}=t;for(let t=0;t<e.length;t++){if(le({name:i,lang:r,assocLang:s,characteristics:n,audioCodec:a,channels:o},e[t],ue))return t}for(let i=0;i<e.length;i++){const r=e[i];if(gn(t.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<e.length;i++){const r=e[i];if(gn(t.attrs,r.attrs,["LANGUAGE"]))return i}}return-1}loadPlaylist(t){super.loadPlaylist();const e=this.currentTrack;this.shouldLoadPlaylist(e)&&de(e.url,this.hls)&&this.scheduleLoading(e,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const i=t.id,r=t.groupId,s=this.getUrlWithDirectives(t.url,e),n=t.details,a=null==n?void 0:n.age;this.log(`Loading audio-track ${i} "${t.name}" lang:${t.lang} group:${r}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type?" "+n.type||0:""):""} ${s}`),this.hls.trigger(l.AUDIO_TRACK_LOADING,{url:s,id:i,groupId:r,deliveryDirectives:e||null,track:t})}},emeController:ya,cmcdController:class{constructor(t){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=t=>{try{this.apply(t,{ot:An.MANIFEST,su:!this.initialized})}catch(t){this.hls.logger.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=t=>{try{const{frag:e,part:i}=t,r=this.hls.levels[e.level],s=this.getObjectType(e),n={d:1e3*(i||e).duration,ot:s};s!==An.VIDEO&&s!==An.AUDIO&&s!=An.MUXED||(n.br=r.bitrate/1e3,n.tb=this.getTopBandwidth(s)/1e3,n.bl=this.getBufferLength(s));const a=i?this.getNextPart(i):this.getNextFrag(e);null!=a&&a.url&&a.url!==e.url&&(n.nor=a.url),this.apply(t,n)}catch(t){this.hls.logger.warn("Could not generate segment CMCD data.",t)}},this.hls=t;const e=this.config=t.config,{cmcd:i}=e;null!=i&&(e.pLoader=this.createPlaylistLoader(),e.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||t.sessionId,this.cid=i.contentId,this.useHeaders=!0===i.useHeaders,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){const t=this.hls;t.on(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(l.MEDIA_DETACHED,this.onMediaDetached,this),t.on(l.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(l.MEDIA_DETACHED,this.onMediaDetached,this),t.off(l.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(t,e){var i,r;this.audioBuffer=null==(i=e.tracks.audio)?void 0:i.buffer,this.videoBuffer=null==(r=e.tracks.video)?void 0:r.buffer}createData(){var t;return{v:1,sf:Ln.HLS,sid:this.sid,cid:this.cid,pr:null==(t=this.media)?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,e={}){E(e,this.createData());const i=e.ot===An.INIT||e.ot===An.VIDEO||e.ot===An.MUXED;this.starved&&i&&(e.bs=!0,e.su=!0,this.starved=!1),null==e.su&&(e.su=this.buffering);const{includeKeys:r}=this;r&&(e=Object.keys(e).reduce(((t,i)=>(r.includes(i)&&(t[i]=e[i]),t)),{}));const s={baseUrl:t.url};this.useHeaders?(t.headers||(t.headers={}),ha(t.headers,e,s)):t.url=ma(t.url,e,s)}getNextFrag(t){var e;const i=null==(e=this.hls.levels[t.level])?void 0:e.details;if(i){const e=t.sn-i.startSN;return i.fragments[e+1]}}getNextPart(t){var e;const{index:i,fragment:r}=t,s=null==(e=this.hls.levels[r.level])||null==(e=e.details)?void 0:e.partList;if(s){const{sn:t}=r;for(let e=s.length-1;e>=0;e--){const r=s[e];if(r.index===i&&r.fragment.sn===t)return s[e+1]}}}getObjectType(t){const{type:e}=t;return"subtitle"===e?An.TIMED_TEXT:"initSegment"===t.sn?An.INIT:"audio"===e?An.AUDIO:"main"===e?this.hls.audioTracks.length?An.VIDEO:An.MUXED:void 0}getTopBandwidth(t){let e,i=0;const r=this.hls;if(t===An.AUDIO)e=r.audioTracks;else{const t=r.maxAutoLevel,i=t>-1?t+1:r.levels.length;e=r.levels.slice(0,i)}return e.forEach((t=>{t.bitrate>i&&(i=t.bitrate)})),i>0?i:NaN}getBufferLength(t){const e=this.media,i=t===An.AUDIO?this.audioBuffer:this.videoBuffer;if(!i||!e)return NaN;return 1e3*ii.bufferInfo(i,e.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:t}=this.config,e=this.applyPlaylistData,i=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new i(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,i,r){e(t),this.loader.load(t,i,r)}}}createFragmentLoader(){const{fLoader:t}=this.config,e=this.applyFragmentData,i=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new i(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,i,r){e(t),this.loader.load(t,i,r)}}}},contentSteeringController:class extends S{constructor(t){super("content-steering",t.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(l.MANIFEST_PARSED,this.onManifestParsed,this),t.on(l.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(l.MANIFEST_PARSED,this.onManifestParsed,this),t.off(l.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce(((t,e)=>(-1===t.indexOf(e.pathwayId)&&t.push(e.pathwayId),t)),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(t){this.updatePathwayPriority(t)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const t=1e3*this.timeToLoad-(performance.now()-this.updated);if(t>0)return void this.scheduleRefresh(this.uri,t)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(t){const e=this.levels;e&&(this.levels=e.filter((e=>e!==t)))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(t,e){const{contentSteering:i}=e;null!==i&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks}onError(t,e){const{errorAction:i}=e;if((null==i?void 0:i.action)===Re&&i.flags===Pe){const t=this.levels;let r=this._pathwayPriority,s=this.pathwayId;if(e.context){const{groupId:i,pathwayId:r,type:n}=e.context;i&&t?s=this.getPathwayForGroupId(i,n,s):r&&(s=r)}s in this.penalizedPathways||(this.penalizedPathways[s]=performance.now()),!r&&t&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==s),e.details!==o.BUFFER_APPEND_ERROR||e.fatal?i.resolved||this.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${s} levels: ${t?t.length:t} priorities: ${re(r)} penalized: ${re(this.penalizedPathways)}`):i.resolved=!0}}filterParsedLevels(t){this.levels=t;let e=this.getLevelsForPathway(this.pathwayId);if(0===e.length){const i=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),e=this.getLevelsForPathway(i),this.pathwayId=i}return e.length!==t.length&&this.log(`Found ${e.length}/${t.length} levels in Pathway "${this.pathwayId}"`),e}getLevelsForPathway(t){return null===this.levels?[]:this.levels.filter((e=>t===e.pathwayId))}updatePathwayPriority(t){let e;this._pathwayPriority=t;const i=this.penalizedPathways,r=performance.now();Object.keys(i).forEach((t=>{r-i[t]>3e5&&delete i[t]}));for(let r=0;r<t.length;r++){const s=t[r];if(s in i)continue;if(s===this.pathwayId)return;const n=this.hls.nextLoadLevel,a=this.hls.levels[n];if(e=this.getLevelsForPathway(s),e.length>0){this.log(`Setting Pathway to "${s}"`),this.pathwayId=s,cr(e),this.hls.trigger(l.LEVELS_UPDATED,{levels:e});const t=this.hls.levels[n];a&&t&&this.levels&&(t.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&t.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${t.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(t,e,i){const r=this.getLevelsForPathway(i).concat(this.levels||[]);for(let i=0;i<r.length;i++)if(e===d&&r[i].hasAudioGroup(t)||e===h&&r[i].hasSubtitleGroup(t))return r[i].pathwayId;return i}clonePathways(t){const e=this.levels;if(!e)return;const i={},r={};t.forEach((t=>{const{ID:s,"BASE-ID":n,"URI-REPLACEMENT":a}=t;if(e.some((t=>t.pathwayId===s)))return;const o=this.getLevelsForPathway(n).map((t=>{const e=new ci(t.attrs);e["PATHWAY-ID"]=s;const n=e.AUDIO&&`${e.AUDIO}_clone_${s}`,o=e.SUBTITLES&&`${e.SUBTITLES}_clone_${s}`;n&&(i[e.AUDIO]=n,e.AUDIO=n),o&&(r[e.SUBTITLES]=o,e.SUBTITLES=o);const l=va(t.uri,e["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),u=new te({attrs:e,audioCodec:t.audioCodec,bitrate:t.bitrate,height:t.height,name:t.name,url:l,videoCodec:t.videoCodec,width:t.width});if(t.audioGroups)for(let e=1;e<t.audioGroups.length;e++)u.addGroupId("audio",`${t.audioGroups[e]}_clone_${s}`);if(t.subtitleGroups)for(let e=1;e<t.subtitleGroups.length;e++)u.addGroupId("text",`${t.subtitleGroups[e]}_clone_${s}`);return u}));e.push(...o),pa(this.audioTracks,i,a,s),pa(this.subtitleTracks,r,a,s)}))}loadSteeringManifest(t){const e=this.hls.config,i=e.loader;let r;this.loader&&this.loader.destroy(),this.loader=new i(e);try{r=new self.URL(t)}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${t}`)}if("data:"!==r.protocol){const t=0|(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate);r.searchParams.set("_HLS_pathway",this.pathwayId),r.searchParams.set("_HLS_throughput",""+t)}const s={responseType:"json",url:r.href},n=e.steeringManifestLoadPolicy.default,a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},u={onSuccess:(t,e,i,s)=>{this.log(`Loaded steering manifest: "${r}"`);const n=t.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":u}=n;if(a)try{this.uri=new self.URL(a,r).href}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||i.url),o&&this.clonePathways(o);const c={steeringManifest:n,url:r.toString()};this.hls.trigger(l.STEERING_MANIFEST_LOADED,c),u&&this.updatePathwayPriority(u)},onError:(t,e,i,r)=>{if(this.log(`Error loading steering manifest: ${t.code} ${t.text} (${e.url})`),this.stopLoad(),410===t.code)return this.enabled=!1,void this.log(`Steering manifest ${e.url} no longer available`);let s=1e3*this.timeToLoad;if(429!==t.code)this.scheduleRefresh(this.uri||e.url,s);else{const t=this.loader;if("function"==typeof(null==t?void 0:t.getResponseHeader)){const e=t.getResponseHeader("Retry-After");e&&(s=1e3*parseFloat(e))}this.log(`Steering manifest ${e.url} rate limited`)}},onTimeout:(t,e,i)=>{this.log(`Timeout loading steering manifest (${e.url})`),this.scheduleRefresh(this.uri||e.url)}};this.log(`Requesting steering manifest: ${r}`),this.loader.load(s,o,u)}scheduleRefresh(t,e=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout((()=>{var e;const i=null==(e=this.hls)?void 0:e.media;!i||i.ended?this.scheduleRefresh(t,1e3*this.timeToLoad):this.loadSteeringManifest(t)}),e)}},interstitialsController:class extends S{constructor(t,e){super("interstitials",t.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const t=this.currentTime;if(void 0===t||this.playbackDisabled||!this.schedule)return;const e=t-this.timelinePos;if(Math.abs(e)<1/7056e5)return;const i=e<=-.01;this.timelinePos=t,this.bufferedPos=t;const r=this.playingItem;if(!r)return void this.checkBuffer();if(i){this.schedule.resetErrorsInRange(t,t-e)&&this.updateSchedule(!0)}if(this.checkBuffer(),i&&t<r.start||t>=r.end){var s;const e=this.findItemIndex(r);let n=this.schedule.findItemIndexAtTime(t);if(-1===n&&(n=e+(i?-1:1),this.log(`seeked ${i?"back ":""}to position not covered by schedule ${t} (resolving from ${e} to ${n})`)),!this.isInterstitial(r)&&null!=(s=this.media)&&s.paused&&(this.shouldPlay=!1),!i&&n>e){const t=this.schedule.findJumpRestrictedIndex(e+1,n);if(t>e)return void this.setSchedulePosition(t)}return void this.setSchedulePosition(n)}const n=this.playingAsset;if(!n){if(this.playingLastItem&&this.isInterstitial(r)){const e=r.event.assetList[0];e&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(t,e))}return}const a=n.timelineStart,o=n.duration||0;var l;(i&&t<a||t>=a+o)&&(null!=(l=r.event)&&l.appendInPlace&&(this.clearAssetPlayers(r.event,r),this.flushFrontBuffer(t)),this.setScheduleToAssetAtTime(t,n))},this.onTimeupdate=()=>{const t=this.currentTime;if(void 0===t||this.playbackDisabled)return;if(!(t>this.timelinePos))return;this.timelinePos=t,t>this.bufferedPos&&this.checkBuffer();const e=this.playingItem;if(!e||this.playingLastItem)return;if(t>=e.end){this.timelinePos=e.end;const t=this.findItemIndex(e);this.setSchedulePosition(t+1)}const i=this.playingAsset;if(!i)return;t>=i.timelineStart+(i.duration||0)&&this.setScheduleToAssetAtTime(t,i)},this.onScheduleUpdate=(t,e)=>{const i=this.schedule;if(!i)return;const r=this.playingItem,s=i.events||[],n=i.items||[],a=i.durations,o=t.map((t=>t.identifier)),u=!(!s.length&&!o.length);(u||e)&&this.log(`INTERSTITIALS_UPDATED (${s.length}): ${s}\nSchedule: ${n.map((t=>Ua(t)))} pos: ${this.timelinePos}`),o.length&&this.log(`Removed events ${o}`);let c=null,d=null;r&&(c=this.updateItem(r,this.timelinePos),this.itemsMatch(r,c)?this.playingItem=c:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const h=this.bufferingItem;if(h&&(d=this.updateItem(h,this.bufferedPos),this.itemsMatch(h,d)?this.bufferingItem=d:h.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(h.event,null))),t.forEach((t=>{t.assetList.forEach((t=>{this.clearAssetPlayer(t.identifier,null)}))})),this.playerQueue.forEach((t=>{if(t.interstitial.appendInPlace){const e=t.assetItem.timelineStart,i=t.timelineOffset-e;if(i)try{t.timelineOffset=e}catch(r){Math.abs(i)>wa&&this.warn(`${r} ("${t.assetId}" ${t.timelineOffset}->${e})`)}}})),u||e){if(this.hls.trigger(l.INTERSTITIALS_UPDATED,{events:s.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(c,r),h&&d!==c&&this.trimInPlace(d,h),this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=e,this.assetListLoader=new $a(t),this.schedule=new Ba(this.onScheduleUpdate,t.logger),this.registerListeners()}registerListeners(){const t=this.hls;t&&(t.on(l.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(l.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(l.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on(l.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(l.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on(l.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on(l.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on(l.BUFFER_APPENDED,this.onBufferAppended,this),t.on(l.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(l.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on(l.MEDIA_ENDED,this.onMediaEnded,this),t.on(l.ERROR,this.onError,this),t.on(l.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off(l.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(l.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(l.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off(l.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(l.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off(l.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off(l.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off(l.BUFFER_CODECS,this.onBufferCodecs,this),t.off(l.BUFFER_APPENDED,this.onBufferAppended,this),t.off(l.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(l.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off(l.MEDIA_ENDED,this.onMediaEnded,this),t.off(l.ERROR,this.onError,this),t.off(l.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var t;null==(t=this.getBufferingPlayer())||t.resumeBuffering()}pauseBuffering(){var t;null==(t=this.getBufferingPlayer())||t.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const t=this.primaryMedia||this.media;t&&this.removeMediaListeners(t)}removeMediaListeners(t){Er(t,"play",this.onPlay),Er(t,"pause",this.onPause),Er(t,"seeking",this.onSeeking),Er(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,e){const i=this.media=e.media;yr(i,"seeking",this.onSeeking),yr(i,"timeupdate",this.onTimeupdate),yr(i,"play",this.onPlay),yr(i,"pause",this.onPause)}onMediaAttached(t,e){const i=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,null===i)this.checkStart();else if(!r){this.clearScheduleState();const t=this.findItemIndex(i);this.setSchedulePosition(t)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(t,e){const i=!!e.transferMedia,r=this.media;if(this.media=null,!i&&(r&&this.removeMediaListeners(r),this.detachedData)){const t=this.getBufferingPlayer();t&&(this.log(`Removing schedule state for detachedData and ${t}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,t.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const t=this,e=()=>t.bufferingItem||t.waitingItem,i=e=>e?t.getAssetPlayer(e.identifier):e,r=(e,r,n,a,o)=>{if(e){let l=e[r].start;const u=e.event;if(u){if("playout"===r||u.timelineOccupancy!==Pa.Point){const t=i(n);(null==t?void 0:t.interstitial)===u&&(l+=t.assetItem.startOffset+t[o])}}else{l+=("bufferedPos"===a?s():t[a])-e.start}return l}return 0},s=()=>{const e=t.bufferedPos;return e===Number.MAX_VALUE?n("primary"):Math.max(e,0)},n=e=>{var i,r;return null!=(i=t.primaryDetails)&&i.live?t.primaryDetails.edge:(null==(r=t.schedule)?void 0:r.durations[e])||0},a=(e,s)=>{var n,a;const o=t.effectivePlayingItem;if(null!=o&&null!=(n=o.event)&&n.restrictions.skip||!t.schedule)return;t.log(`seek to ${e} "${s}"`);const l=t.effectivePlayingItem,u=t.schedule.findItemIndexAtTime(e,s),c=null==(a=t.schedule.items)?void 0:a[u],d=t.getBufferingPlayer(),h=null==d?void 0:d.interstitial,f=null==h?void 0:h.appendInPlace,g=l&&t.itemsMatch(l,c);if(l&&(f||g)){const n=i(t.playingAsset),a=(null==n?void 0:n.media)||t.primaryMedia;if(a){const i="primary"===s?a.currentTime:r(l,s,t.playingAsset,"timelinePos","currentTime"),o=e-i,u=(f?i:a.currentTime)+o;if(u>=0&&(!n||f||u<=n.duration))return void(a.currentTime=u)}}if(c){let i=e;if("primary"!==s){const t=e-c[s].start;i=c.start+t}const r=!t.isInterstitial(c);if(t.isInterstitial(l)&&!l.event.appendInPlace||!r&&!c.event.appendInPlace){if(l){const n=t.findItemIndex(l);if(u>n){const e=t.schedule.findJumpRestrictedIndex(n+1,u);if(e>n)return void t.setSchedulePosition(e)}let a=0;if(r)t.timelinePos=i,t.checkBuffer();else{const t=c.event.assetList,i=e-(c[s]||c).start;for(let e=t.length;e--;){const r=t[e];if(r.duration&&i>=r.startOffset&&i<r.startOffset+r.duration){a=e;break}}}t.setSchedulePosition(u,a)}}else{const e=t.media||(f?null==d?void 0:d.media:null);e&&(e.currentTime=i)}}},o=()=>{const i=t.effectivePlayingItem;if(t.isInterstitial(i))return i;const r=e();return t.isInterstitial(r)?r:null},l={get bufferedEnd(){const i=e(),s=t.bufferingItem;var n;return s&&s===i&&(r(s,"playout",t.bufferingAsset,"bufferedPos","bufferedEnd")-s.playout.start||(null==(n=t.bufferingAsset)?void 0:n.startOffset))||0},get currentTime(){const e=o(),i=t.effectivePlayingItem;return i&&i===e?r(i,"playout",t.effectivePlayingAsset,"timelinePos","currentTime")-i.playout.start:0},set currentTime(e){const i=o(),r=t.effectivePlayingItem;r&&r===i&&a(e+r.playout.start,"playout")},get duration(){const t=o();return t?t.playout.end-t.playout.start:0},get assetPlayers(){var e;const i=null==(e=o())?void 0:e.event.assetList;return i?i.map((e=>t.getAssetPlayer(e.identifier))):[]},get playingIndex(){var e;const i=null==(e=o())?void 0:e.event;return i&&t.effectivePlayingAsset?i.findAssetIndex(t.effectivePlayingAsset):-1},get scheduleItem(){return o()}};return this.manager={get events(){var e;return(null==(e=t.schedule)||null==(e=e.events)?void 0:e.slice(0))||[]},get schedule(){var e;return(null==(e=t.schedule)||null==(e=e.items)?void 0:e.slice(0))||[]},get interstitialPlayer(){return o()?l:null},get playerQueue(){return t.playerQueue.slice(0)},get bufferingAsset(){return t.bufferingAsset},get bufferingItem(){return e()},get bufferingIndex(){const i=e();return t.findItemIndex(i)},get playingAsset(){return t.effectivePlayingAsset},get playingItem(){return t.effectivePlayingItem},get playingIndex(){const e=t.effectivePlayingItem;return t.findItemIndex(e)},primary:{get bufferedEnd(){return s()},get currentTime(){const e=t.timelinePos;return e>0?e:0},set currentTime(t){a(t,"primary")},get duration(){return n("primary")},get seekableStart(){var e;return(null==(e=t.primaryDetails)?void 0:e.fragmentStart)||0}},integrated:{get bufferedEnd(){return r(e(),"integrated",t.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return r(t.effectivePlayingItem,"integrated",t.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(t){a(t,"integrated")},get duration(){return n("integrated")},get seekableStart(){var e;return((e,i)=>{var r;if(0!==e&&"primary"!==i&&null!=(r=t.schedule)&&r.length){var s;const r=t.schedule.findItemIndexAtTime(e),n=null==(s=t.schedule.items)?void 0:s[r];if(n)return e+(n[i].start-n.start)}return e})((null==(e=t.primaryDetails)?void 0:e.fragmentStart)||0,"integrated")}},skip:()=>{const e=t.effectivePlayingItem,i=null==e?void 0:e.event;if(i&&!i.restrictions.skip){const r=t.findItemIndex(e);if(i.appendInPlace){const t=e.playout.start+e.event.duration;a(t+.001,"playout")}else t.advanceAfterAssetEnded(i,r,Infinity)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var t;const e=this.playingItem,i=null==(t=this.schedule)?void 0:t.items;return!!(this.playbackStarted&&e&&i)&&this.findItemIndex(e)===i.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var t,e;if(null===this.mediaSelection)return;const i=this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&!i.event.appendInPlace)return;let s=this.media;!s&&null!=(t=this.bufferingItem)&&null!=(t=t.event)&&t.appendInPlace&&(s=this.primaryMedia);const n=null==(e=s)?void 0:e.currentTime;return void 0!==n&&r(n)?n:void 0}get primaryMedia(){var t;return this.media||(null==(t=this.detachedData)?void 0:t.media)||null}isInterstitial(t){return!(null==t||!t.event)}retreiveMediaSource(t,e){const i=this.getAssetPlayer(t);i&&this.transferMediaFromPlayer(i,e)}transferMediaFromPlayer(t,e){const i=t.interstitial.appendInPlace,r=t.media;if(i&&r===this.primaryMedia){if(this.bufferingAsset=null,(!e||this.isInterstitial(e)&&!e.event.appendInPlace)&&e&&r)return void(this.detachedData={media:r});const i=t.transferMedia();this.log(`transfer MediaSource from ${t} ${re(i)}`),this.detachedData=i}else e&&r&&(this.shouldPlay||(this.shouldPlay=!r.paused))}transferMediaTo(t,e){var i,r;if(t.media===e)return;let s=null;const n=this.hls,a=t!==n,o=a&&t.interstitial.appendInPlace,l=null==(i=this.detachedData)?void 0:i.mediaSource;let u;if(n.media)o&&(s=n.transferMedia(),this.detachedData=s),u="Primary";else if(l){const t=this.getBufferingPlayer();t?(s=t.transferMedia(),u=`${t}`):u="detached MediaSource"}else u="detached media";if(!s)if(l)s=this.detachedData,this.log(`using detachedData: MediaSource ${re(s)}`);else if(!this.detachedData||n.media===e){const t=this.playerQueue;t.length>1&&t.forEach((t=>{if(a&&t.interstitial.appendInPlace!==o){const e=t.interstitial;this.clearInterstitial(t.interstitial,null),e.appendInPlace=!1,e.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${e}`)}})),this.hls.detachMedia(),this.detachedData={media:e}}const c=s&&"mediaSource"in s&&"closed"!==(null==(r=s.mediaSource)?void 0:r.readyState),d=c&&s?s:e;this.log(`${c?"transfering MediaSource":"attaching media"} to ${a?t:"Primary"} from ${u} (media.currentTime: ${e.currentTime})`);const h=this.schedule;if(d===s&&h){const e=a&&t.assetId===h.assetIdAtEnd;d.overrides={duration:h.duration,endOfStream:!a||e,cueRemoval:!a}}t.attachMedia(d)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const t=this.schedule,e=null==t?void 0:t.events;if(!e||this.playbackDisabled||!this.media)return;-1===this.bufferedPos&&(this.bufferedPos=0);const i=this.timelinePos,r=this.effectivePlayingItem;if(-1===i){const i=this.hls.startPosition;if(this.log(Ha("checkStart",i)),this.timelinePos=i,e.length&&e[0].cue.pre){const i=t.findEventIndex(e[0].identifier);this.setSchedulePosition(i)}else if(i>=0||!this.primaryLive){const e=this.timelinePos=i>0?i:0,r=t.findItemIndexAtTime(e);this.setSchedulePosition(r)}}else if(r&&!this.playingItem){const e=t.findItemIndex(r);this.setSchedulePosition(e)}}advanceAssetBuffering(t,e){const i=t.event,r=i.findAssetIndex(e),s=Ma(i,r);if(i.isAssetPastPlayoutLimit(s)){if(this.schedule){var n;const e=null==(n=this.schedule.items)?void 0:n[this.findItemIndex(t)+1];e&&this.bufferedToItem(e)}}else this.bufferedToEvent(t,s)}advanceAfterAssetEnded(t,e,i){const r=Ma(t,i);if(t.isAssetPastPlayoutLimit(r)){if(this.schedule){const i=this.schedule.items;if(i){const r=e+1;if(r>=i.length)return void this.setSchedulePosition(-1);const s=t.resumeTime;this.timelinePos<s&&(this.log(Ha("advanceAfterAssetEnded",s)),this.timelinePos=s,t.appendInPlace&&this.advanceInPlace(s),this.checkBuffer(this.bufferedPos<s)),this.setSchedulePosition(r)}}}else{if(t.appendInPlace){const e=t.assetList[r];e&&this.advanceInPlace(e.timelineStart)}this.setSchedulePosition(e,r)}}setScheduleToAssetAtTime(t,e){const i=this.schedule;if(!i)return;const r=e.parentIdentifier,s=i.getEvent(r);if(s){const e=i.findEventIndex(r),n=i.findAssetIndex(s,t);this.advanceAfterAssetEnded(s,e,n-1)}}setSchedulePosition(t,e){var i;const r=null==(i=this.schedule)?void 0:i.items;if(!r||this.playbackDisabled)return;const s=t>=0?r[t]:null;this.log(`setSchedulePosition ${t}, ${e} (${s?Ua(s):s}) pos: ${this.timelinePos}`);const n=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(n)){const i=n.event,c=this.playingAsset,d=null==c?void 0:c.identifier,h=d?this.getAssetPlayer(d):null;if(h&&d&&(!this.eventItemsMatch(n,s)||void 0!==e&&d!==i.assetList[e].identifier)){var o;const e=i.findAssetIndex(c);if(this.log(`INTERSTITIAL_ASSET_ENDED ${e+1}/${i.assetList.length} ${Fa(c)}`),this.endedAsset=c,this.playingAsset=null,this.hls.trigger(l.INTERSTITIAL_ASSET_ENDED,{asset:c,assetListIndex:e,event:i,schedule:r.slice(0),scheduleIndex:t,player:h}),n!==this.playingItem)return void(this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(i,this.findItemIndex(this.playingItem),e));this.retreiveMediaSource(d,s),!h.media||null!=(o=this.detachedData)&&o.mediaSource||h.detachMedia()}if(!this.eventItemsMatch(n,s)&&(this.endedItem=n,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${i} ${Ua(n)}`),i.hasPlayed=!0,this.hls.trigger(l.INTERSTITIAL_ENDED,{event:i,schedule:r.slice(0),scheduleIndex:t}),i.cue.once)){var u;this.updateSchedule();const t=null==(u=this.schedule)?void 0:u.items;if(s&&t){const i=this.findItemIndex(s);this.advanceSchedule(i,t,e,n,a)}return}}this.advanceSchedule(t,r,e,n,a)}advanceSchedule(t,e,i,r,s){const n=this.schedule;if(!n)return;const a=e[t]||null,o=this.primaryMedia,u=this.playerQueue;if(u.length&&u.forEach((e=>{const i=e.interstitial,r=n.findEventIndex(i.identifier);(r<t||r>t+1)&&this.clearInterstitial(i,a)})),this.isInterstitial(a)){this.timelinePos=Math.min(Math.max(this.timelinePos,a.start),a.end);const s=a.event;if(void 0===i){const e=Ma(s,(i=n.findAssetIndex(s,this.timelinePos))-1);if(s.isAssetPastPlayoutLimit(e)||s.appendInPlace&&this.timelinePos===a.end)return void this.advanceAfterAssetEnded(s,t,i);i=e}const u=this.waitingItem;this.assetsBuffered(a,o)||this.setBufferingItem(a);let c=this.preloadAssets(s,i);if(this.eventItemsMatch(a,u||r)||(this.waitingItem=a,this.log(`INTERSTITIAL_STARTED ${Ua(a)} ${s.appendInPlace?"append in place":""}`),this.hls.trigger(l.INTERSTITIAL_STARTED,{event:s,schedule:e.slice(0),scheduleIndex:t})),!s.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${s}`);if(s.assetListLoader&&(s.assetListLoader.destroy(),s.assetListLoader=void 0),!o)return void this.log(`Waiting for attachMedia to start Interstitial ${s}`);this.waitingItem=this.endedItem=null,this.playingItem=a;const d=s.assetList[i];if(!d)return void this.advanceAfterAssetEnded(s,t,i||0);if(c||(c=this.getAssetPlayer(d.identifier)),null===c||c.destroyed){const t=s.assetList.length;this.warn(`asset ${i+1}/${t} player destroyed ${s}`),c=this.createAssetPlayer(s,d,i),c.loadSource()}if(!this.eventItemsMatch(a,this.bufferingItem)&&s.appendInPlace&&this.isAssetBuffered(d))return;this.startAssetPlayer(c,i,e,t,o),this.shouldPlay&&Ga(c.media)}else a?(this.resumePrimary(a,t,r),this.shouldPlay&&Ga(this.hls.media)):s&&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 t;return null==(t=this.mediaSelection)?void 0:t.main.details}get primaryLive(){var t;return!(null==(t=this.primaryDetails)||!t.live)}resumePrimary(t,e,i){var r,s;if(this.playingItem=t,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(t),this.log(`resuming ${Ua(t)}`),null==(r=this.detachedData)||!r.mediaSource){let i=this.timelinePos;(i<t.start||i>=t.end)&&(i=this.getPrimaryResumption(t,e),this.log(Ha("resumePrimary",i)),this.timelinePos=i),this.attachPrimary(i,t)}if(!i)return;const n=null==(s=this.schedule)?void 0:s.items;n&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Ua(t)}`),this.hls.trigger(l.INTERSTITIALS_PRIMARY_RESUMED,{schedule:n.slice(0),scheduleIndex:e}),this.checkBuffer())}getPrimaryResumption(t,e){const i=t.start;if(this.primaryLive){const t=this.primaryDetails;if(0===e)return this.hls.startPosition;if(t&&(i<t.fragmentStart||i>t.edge))return this.hls.liveSyncPosition||-1}return i}isAssetBuffered(t){const e=this.getAssetPlayer(t.identifier);if(null!=e&&e.hls)return e.hls.bufferedToEnd;return ii.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=t.timelineStart+(t.duration||0)}attachPrimary(t,e,i){e?this.setBufferingItem(e):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const r=this.primaryMedia;if(!r)return;const s=this.hls;s.media?this.checkBuffer():(this.transferMediaTo(s,r),i&&this.startLoadingPrimaryAt(t,i)),i||(this.log(Ha("attachPrimary",t)),this.timelinePos=t,this.startLoadingPrimaryAt(t,i))}startLoadingPrimaryAt(t,e){var i;const r=this.hls;!r.loadingEnabled||!r.media||Math.abs(((null==(i=r.mainForwardBufferInfo)?void 0:i.start)||r.media.currentTime)-t)>.5?r.startLoad(t,e):r.bufferingEnabled||r.resumeBuffering()}onManifestLoading(){var t;this.stopLoad(),null==(t=this.schedule)||t.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(l.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(l.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(t,e){if(-1===e.level||!this.schedule)return;const i=this.hls.levels[e.level];if(!i.details)return;const r=b(b({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=r,this.schedule.parseInterstitialDateRanges(r,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(t,e){const i=this.hls.audioTracks[e.id],r=this.mediaSelection;if(!r)return void(this.altSelection=b(b({},this.altSelection),{},{audio:i}));const s=b(b({},r),{},{audio:i});this.mediaSelection=s}onSubtitleTrackUpdated(t,e){const i=this.hls.subtitleTracks[e.id],r=this.mediaSelection;if(!r)return void(this.altSelection=b(b({},this.altSelection),{},{subtitles:i}));const s=b(b({},r),{},{subtitles:i});this.mediaSelection=s}onAudioTrackSwitching(t,e){const i=ae(e);this.playerQueue.forEach((({hls:t})=>t&&(t.setAudioOption(e)||t.setAudioOption(i))))}onSubtitleTrackSwitch(t,e){const i=ae(e);this.playerQueue.forEach((({hls:t})=>t&&(t.setSubtitleOption(e)||-1!==e.id&&t.setSubtitleOption(i))))}onBufferCodecs(t,e){const i=e.tracks;i&&(this.requiredTracks=i)}onBufferAppended(t,e){this.checkBuffer()}onBufferFlushed(t,e){const i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){const t=this.timelinePos;this.bufferedPos=t,this.checkBuffer()}}onBufferedToEnd(t){if(!this.schedule)return;const e=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&e){for(let t=0;t<e.length;t++){const r=e[t];if(r.cue.post){var i;const t=this.schedule.findEventIndex(r.identifier),e=null==(i=this.schedule.items)?void 0:i[t];this.isInterstitial(e)&&this.eventItemsMatch(e,this.bufferingItem)&&this.bufferedToItem(e,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(t){const e=this.playingItem;if(!this.playingLastItem&&e){const t=this.findItemIndex(e);this.setSchedulePosition(t+1)}else this.shouldPlay=!1}updateItem(t,e){var i;const r=null==(i=this.schedule)?void 0:i.items;if(t&&r){return r[this.findItemIndex(t,e)]||null}return null}trimInPlace(t,e){if(this.isInterstitial(t)&&t.event.appendInPlace&&e.end-t.end>.25){t.event.assetList.forEach(((e,i)=>{t.event.isAssetPastPlayoutLimit(i)&&this.clearAssetPlayer(e.identifier,null)}));const i=t.end+.25,r=ii.bufferInfo(this.primaryMedia,i,0);if(r.end>i||(r.nextStart||0)>i){this.log(`trim buffered interstitial ${Ua(t)} (was ${Ua(e)})`);const r=!0;this.attachPrimary(i,null,r),this.flushFrontBuffer(i)}}}itemsMatch(t,e){return!!e&&(t===e||t.event&&e.event&&this.eventItemsMatch(t,e)||!t.event&&!e.event&&this.findItemIndex(t)===this.findItemIndex(e))}eventItemsMatch(t,e){var i;return!!e&&(t===e||t.event.identifier===(null==(i=e.event)?void 0:i.identifier))}findItemIndex(t,e){return t&&this.schedule?this.schedule.findItemIndex(t,e):-1}updateSchedule(t=!1){var e;const i=this.mediaSelection;i&&(null==(e=this.schedule)||e.updateSchedule(i,[],t))}checkBuffer(t){var e;const i=null==(e=this.schedule)?void 0:e.items;if(!i)return;const r=ii.bufferInfo(this.primaryMedia,this.timelinePos,0);t&&(this.bufferedPos=this.timelinePos),t||(t=r.len<1),this.updateBufferedPos(r.end,i,t)}updateBufferedPos(t,e,i){const r=this.schedule,s=this.bufferingItem;if(this.bufferedPos>t||!r)return;if(1===e.length&&this.itemsMatch(e[0],s))return void(this.bufferedPos=t);const n=this.playingItem,a=this.findItemIndex(n);let o=r.findItemIndexAtTime(t);if(this.bufferedPos<t){var l;const i=this.findItemIndex(s),r=Math.min(i+1,e.length-1),n=e[r];if((-1===o&&s&&t>=s.end||null!=(l=n.event)&&l.appendInPlace&&t+.01>=n.start)&&(o=r),this.isInterstitial(s)){const t=s.event;if(r-a>1&&!1===t.appendInPlace)return;if(0===t.assetList.length&&t.assetListLoader)return}if(this.bufferedPos=t,o>i&&o>a)this.bufferedToItem(n);else{const e=this.primaryDetails;this.primaryLive&&e&&t>e.edge-e.targetduration&&n.start<e.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(n)&&this.preloadAssets(n.event,0)}}else i&&n&&!this.itemsMatch(n,s)&&(o===a?this.bufferedToItem(n):o===a+1&&this.bufferedToItem(e[o]))}assetsBuffered(t,e){return 0!==t.event.assetList.length&&!t.event.assetList.some((t=>{const i=this.getAssetPlayer(t.identifier);return!(null!=i&&i.bufferedInPlaceToEnd(e))}))}setBufferingItem(t){const e=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(t,e)&&i){const{items:r,events:s}=i;if(!r||!s)return e;const n=this.isInterstitial(t),a=this.getBufferingPlayer();this.bufferingItem=t,this.bufferedPos=Math.max(t.start,Math.min(t.end,this.timelinePos));const o=a?a.remaining:e?e.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Ua(t)}`+(e?` (${o.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(n){const e=i.findAssetIndex(t.event,this.bufferedPos);t.event.assetList.forEach(((t,i)=>{const r=this.getAssetPlayer(t.identifier);r&&(i===e&&r.loadSource(),r.resumeBuffering())}))}else this.hls.resumeBuffering(),this.playerQueue.forEach((t=>t.pauseBuffering()));this.hls.trigger(l.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:s.slice(0),schedule:r.slice(0),bufferingIndex:this.findItemIndex(t),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==t&&(this.bufferingItem=t);return e}bufferedToItem(t,e=0){const i=this.setBufferingItem(t);if(!this.playbackDisabled)if(this.isInterstitial(t))this.bufferedToEvent(t,e);else if(null!==i){this.bufferingAsset=null;const e=this.detachedData;if(e)if(e.mediaSource){const e=!0;this.attachPrimary(t.start,t,e)}else this.preloadPrimary(t);else this.preloadPrimary(t)}}preloadPrimary(t){const e=this.findItemIndex(t),i=this.getPrimaryResumption(t,e);this.startLoadingPrimaryAt(i)}bufferedToEvent(t,e){const i=t.event,r=0===i.assetList.length&&!i.assetListLoader,s=i.cue.once;if(r||!s){const t=this.preloadAssets(i,e);if(null!=t&&t.interstitial.appendInPlace){const e=this.primaryMedia;e&&this.bufferAssetPlayer(t,e)}}}preloadAssets(t,e){const i=t.assetUrl,r=t.assetList.length,s=0===r&&!t.assetListLoader,n=t.cue.once;if(s){const s=t.timelineStart;if(t.appendInPlace){var a;const e=this.playingItem;this.isInterstitial(e)||(null==e||null==(a=e.nextEvent)?void 0:a.identifier)!==t.identifier||this.flushFrontBuffer(s+.25)}let n,o=0;if(!this.playingItem&&this.primaryLive&&(o=this.hls.startPosition,-1===o&&(o=this.hls.liveSyncPosition||0)),o&&!t.cue.pre&&!t.cue.post){const t=o-s;t>0&&(n=Math.round(1e3*t)/1e3)}if(this.log(`Load interstitial asset ${e+1}/${i?1:r} ${t}${n?` live-start: ${o} start-offset: ${n}`:""}`),i)return this.createAsset(t,0,0,s,t.duration,i);const l=this.assetListLoader.loadAssetList(t,n);l&&(t.assetListLoader=l)}else if(!n&&r){for(let i=e;i<r;i++){const e=t.assetList[i],r=this.getAssetPlayerQueueIndex(e.identifier);-1!==r&&!this.playerQueue[r].destroyed||e.error||this.createAssetPlayer(t,e,i)}const i=t.assetList[e];if(i){const t=this.getAssetPlayer(i.identifier);return t&&t.loadSource(),t}}return null}flushFrontBuffer(t){const e=this.requiredTracks;if(!e)return;this.log(`Removing front buffer starting at ${t}`);Object.keys(e).forEach((e=>{this.hls.trigger(l.BUFFER_FLUSHING,{startOffset:t,endOffset:Infinity,type:e})}))}getAssetPlayerQueueIndex(t){const e=this.playerQueue;for(let i=0;i<e.length;i++)if(t===e[i].assetId)return i;return-1}getAssetPlayer(t){const e=this.getAssetPlayerQueueIndex(t);return this.playerQueue[e]||null}getBufferingPlayer(){const{playerQueue:t,primaryMedia:e}=this;if(e)for(let i=0;i<t.length;i++)if(t[i].media===e)return t[i];return null}createAsset(t,e,i,r,s,n){const a={parentIdentifier:t.identifier,identifier:Da(t,n,e),duration:s,startOffset:i,timelineStart:r,uri:n};return this.createAssetPlayer(t,a,e)}createAssetPlayer(t,e,i){const r=this.hls,s=r.userConfig;let n=s.videoPreference;const u=r.loadLevelObj||r.levels[r.currentLevel];(n||u)&&(n=E({},n),u.videoCodec&&(n.videoCodec=u.videoCodec),u.videoRange&&(n.allowedVideoRanges=[u.videoRange]));const c=r.audioTracks[r.audioTrack],d=r.subtitleTracks[r.subtitleTrack];let h=0;if(this.primaryLive||t.appendInPlace){const t=this.timelinePos-e.timelineStart;if(t>1){const i=e.duration;i&&t<i&&(h=t)}}const f=e.identifier,g=b(b({},s),{},{maxMaxBufferLength:Math.min(180,r.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:r.sessionId,assetPlayerId:f,abrEwmaDefaultEstimate:r.bandwidthEstimate,interstitialsController:void 0,startPosition:h,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:n,audioPreference:c||s.audioPreference,subtitlePreference:d||s.subtitlePreference});t.appendInPlace&&(t.appendInPlaceStarted=!0,e.timelineStart&&(g.timelineOffset=e.timelineStart));const m=g.cmcd;null!=m&&m.sessionId&&m.contentId&&(g.cmcd=E({},m,{contentId:_a(e.uri)})),this.getAssetPlayer(f)&&this.warn(`Duplicate date range identifier ${t} and asset ${f}`);const p=new Na(this.HlsPlayerClass,g,t,e);this.playerQueue.push(p),t.assetList[i]=e;let v=!0;const y=r=>{if(r.live){var s;const e=new Error(`Interstitials MUST be VOD assets ${t}`),r={fatal:!0,type:a.OTHER_ERROR,details:o.INTERSTITIAL_ASSET_ITEM_ERROR,error:e},n=(null==(s=this.schedule)?void 0:s.findEventIndex(t.identifier))||-1;return void this.handleAssetItemError(r,t,n,i,e.message)}const n=r.edge-r.fragmentStart,l=e.duration;(v||null===l||n>l)&&(v=!1,this.log(`Interstitial asset "${f}" duration change ${l} > ${n}`),e.duration=n,this.updateSchedule())};p.on(l.LEVEL_UPDATED,((t,{details:e})=>y(e))),p.on(l.LEVEL_PTS_UPDATED,((t,{details:e})=>y(e))),p.on(l.EVENT_CUE_ENTER,(()=>this.onInterstitialCueEnter()));const T=(t,e)=>{const i=this.getAssetPlayer(f);if(i&&e.tracks){i.off(l.BUFFER_CODECS,T),i.tracks=e.tracks;const t=this.primaryMedia;this.bufferingAsset===i.assetItem&&t&&!i.media&&this.bufferAssetPlayer(i,t)}};p.on(l.BUFFER_CODECS,T);p.on(l.BUFFERED_TO_END,(()=>{var i;const r=this.getAssetPlayer(f);if(this.log(`buffered to end of asset ${r}`),!r||!this.schedule)return;const s=this.schedule.findEventIndex(t.identifier),n=null==(i=this.schedule.items)?void 0:i[s];this.isInterstitial(n)&&this.advanceAssetBuffering(n,e)}));const S=e=>()=>{if(!this.getAssetPlayer(f)||!this.schedule)return;this.shouldPlay=!0;const i=this.schedule.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,i,e)};return p.once(l.MEDIA_ENDED,S(i)),p.once(l.PLAYOUT_LIMIT_REACHED,S(Infinity)),p.on(l.ERROR,((e,r)=>{if(!this.schedule)return;const s=this.getAssetPlayer(f);if(r.details===o.BUFFER_STALLED_ERROR)return null!=s&&s.appendInPlace?void this.handleInPlaceStall(t):(this.onTimeupdate(),void this.checkBuffer(!0));this.handleAssetItemError(r,t,this.schedule.findEventIndex(t.identifier),i,`Asset player error ${r.error} ${t}`)})),p.on(l.DESTROYING,(()=>{if(!this.getAssetPlayer(f)||!this.schedule)return;const e=new Error(`Asset player destroyed unexpectedly ${f}`),r={fatal:!0,type:a.OTHER_ERROR,details:o.INTERSTITIAL_ASSET_ITEM_ERROR,error:e};this.handleAssetItemError(r,t,this.schedule.findEventIndex(t.identifier),i,e.message)})),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Fa(e)}`),this.hls.trigger(l.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:e,assetListIndex:i,event:t,player:p}),p}clearInterstitial(t,e){this.clearAssetPlayers(t,e),t.reset()}clearAssetPlayers(t,e){t.assetList.forEach((t=>{this.clearAssetPlayer(t.identifier,e)}))}resetAssetPlayer(t){const e=this.getAssetPlayerQueueIndex(t);if(-1!==e){this.log(`reset asset player "${t}" after error`);const i=this.playerQueue[e];this.transferMediaFromPlayer(i,null),i.resetDetails()}}clearAssetPlayer(t,e){const i=this.getAssetPlayerQueueIndex(t);if(-1!==i){const t=this.playerQueue[i];this.log(`clear ${t} toSegment: ${e?Ua(e):e}`),this.transferMediaFromPlayer(t,e),this.playerQueue.splice(i,1),t.destroy()}}emptyPlayerQueue(){let t;for(;t=this.playerQueue.pop();)t.destroy();this.playerQueue=[]}startAssetPlayer(t,e,i,r,s){const{interstitial:n,assetItem:a,assetId:o}=t,u=n.assetList.length,c=this.playingAsset;this.endedAsset=null,this.playingAsset=a,c&&c.identifier===o||(c&&(this.clearAssetPlayer(c.identifier,i[r]),delete c.error),this.log(`INTERSTITIAL_ASSET_STARTED ${e+1}/${u} ${Fa(a)}`),this.hls.trigger(l.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:e,event:n,schedule:i.slice(0),scheduleIndex:r,player:t})),this.bufferAssetPlayer(t,s)}bufferAssetPlayer(t,e){var i,r;if(!this.schedule)return;const{interstitial:s,assetItem:n}=t,l=this.schedule.findEventIndex(s.identifier),u=null==(i=this.schedule.items)?void 0:i[l];if(!u)return;t.loadSource(),this.setBufferingItem(u),this.bufferingAsset=n;const c=this.getBufferingPlayer();if(c===t)return;const d=s.appendInPlace;if(d&&!1===(null==c?void 0:c.interstitial.appendInPlace))return;const h=(null==c?void 0:c.tracks)||(null==(r=this.detachedData)?void 0:r.tracks)||this.requiredTracks;if(d&&n!==this.playingAsset){if(!t.tracks)return void this.log(`Waiting for track info before buffering ${t}`);if(h&&!P(h,t.tracks)){const e=new Error(`Asset ${Fa(n)} SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(h)}')`),i={fatal:!0,type:a.OTHER_ERROR,details:o.INTERSTITIAL_ASSET_ITEM_ERROR,error:e},r=s.findAssetIndex(n);return void this.handleAssetItemError(i,s,l,r,e.message)}}this.transferMediaTo(t,e)}handleInPlaceStall(t){const e=this.schedule,i=this.primaryMedia;if(!e||!i)return;const r=i.currentTime,s=e.findAssetIndex(t,r),n=t.assetList[s];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} ${t} (media.currentTime: ${r})`),o&&(l/i.playbackRate<.5||a.bufferedInPlaceToEnd(i))&&a.hls){const i=e.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,i,s)}}}}advanceInPlace(t){const e=this.primaryMedia;e&&e.currentTime<t&&(e.currentTime=t)}handleAssetItemError(t,e,i,r,s){if(t.details===o.BUFFER_STALLED_ERROR)return;const n=e.assetList[r]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${n?Fa(n):n} ${t.error}`),!this.schedule)return;const a=(null==n?void 0:n.identifier)||"",u=this.getAssetPlayerQueueIndex(a),c=this.playerQueue[u]||null,d=this.schedule.items,h=E({},t,{fatal:!1,errorAction:Oe(!0),asset:n,assetListIndex:r,event:e,schedule:d,scheduleIndex:i,player:c});if(this.hls.trigger(l.INTERSTITIAL_ASSET_ERROR,h),!t.fatal)return;const f=this.playingAsset,g=this.bufferingAsset,m=new Error(s);if(n&&(this.clearAssetPlayer(a,null),n.error=m),e.assetList.some((t=>!t.error)))for(let t=r;t<e.assetList.length;t++)this.resetAssetPlayer(e.assetList[t].identifier);else e.error=m;this.updateSchedule(!0),e.error?this.primaryFallback(e):f&&f.identifier===a?this.advanceAfterAssetEnded(e,i,r):g&&g.identifier===a&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,g)}primaryFallback(t){const e=t.timelineStart,i=this.effectivePlayingItem;let r=this.timelinePos;if(i){this.log(`Fallback to primary from event "${t.identifier}" start: ${e} pos: ${r} playing: ${Ua(i)} error: ${t.error}`),-1===r&&(r=this.hls.startPosition);const s=this.updateItem(i,r);this.itemsMatch(i,s)&&this.clearInterstitial(t,null),t.appendInPlace&&(this.attachPrimary(e,null),this.flushFrontBuffer(e))}else if(-1===r)return void this.checkStart();if(!this.schedule)return;const s=this.schedule.findItemIndexAtTime(r);this.setSchedulePosition(s)}onAssetListLoaded(t,e){var i,r;const s=e.event,n=s.identifier,a=e.assetListResponse.ASSETS;if(null==(i=this.schedule)||!i.hasEvent(n))return;const o=s.timelineStart,l=s.duration;let u=0;a.forEach(((t,e)=>{const i=parseFloat(t.DURATION);this.createAsset(s,e,u,o+u,i,t.URI),u+=i})),s.duration=u,this.log(`Loaded asset-list with duration: ${u} (was: ${l}) ${s}`);const c=this.waitingItem,d=(null==c?void 0:c.event.identifier)===n;this.updateSchedule();const h=null==(r=this.bufferingItem)?void 0:r.event;if(d){var f;const t=this.schedule.findEventIndex(n),e=null==(f=this.schedule.items)?void 0:f[t];if(e){if(!this.playingItem&&this.timelinePos>e.end){if(this.schedule.findItemIndexAtTime(this.timelinePos)!==t)return s.error=new Error(`Interstitial ${a.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${s}`),this.log(s.error.message),this.updateSchedule(!0),void this.primaryFallback(s)}this.setBufferingItem(e)}this.setSchedulePosition(t)}else if((null==h?void 0:h.identifier)===n){const t=s.assetList[0];if(t){const e=this.getAssetPlayer(t.identifier);if(h.appendInPlace){const t=this.primaryMedia;e&&t&&this.bufferAssetPlayer(e,t)}else e&&e.loadSource()}}}onError(t,e){if(this.schedule)switch(e.details){case o.ASSET_LIST_PARSING_ERROR:case o.ASSET_LIST_LOAD_ERROR:case o.ASSET_LIST_LOAD_TIMEOUT:{const t=e.interstitial;t&&(this.updateSchedule(!0),this.primaryFallback(t));break}case o.BUFFER_STALLED_ERROR:{const t=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(t)&&t.event.appendInPlace)return void this.handleInPlaceStall(t.event);this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}});function Yo(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(Yo):Object.keys(t).reduce(((e,i)=>(e[i]=Yo(t[i]),e)),{}):t}function qo(t,e){const i=t.loader;if(i!==Go&&i!==Ko)e.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1;else{(function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1})()&&(t.loader=Go,t.progressive=!0,t.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class zo extends Je{constructor(t,e){super("gap-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var t;null!=(t=this.media)&&t.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var t;this.hls&&(this.ended=(null==(t=this.media)?void 0:t.currentTime)||1,this.hls.trigger(l.MEDIA_ENDED,{stalled:!1}))},this.hls=t,this.fragmentTracker=e,this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(l.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(l.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(t,e){this.setInterval(100),this.mediaSource=e.mediaSource;const i=this.media=e.media;yr(i,"playing",this.onMediaPlaying),yr(i,"waiting",this.onMediaWaiting),yr(i,"ended",this.onMediaEnded)}onMediaDetaching(t,e){this.clearInterval();const{media:i}=this;i&&(Er(i,"playing",this.onMediaPlaying),Er(i,"waiting",this.onMediaWaiting),Er(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(t,e){this.buffered=e.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var t;if(null==(t=this.media)||!t.readyState||!this.hasBuffered)return;const e=this.media.currentTime;this.poll(e,this.lastCurrentTime),this.lastCurrentTime=e}poll(t,e){var i,r;const s=null==(i=this.hls)?void 0:i.config;if(!s)return;const n=this.media;if(!n)return;const{seeking:a}=n,o=this.seeking&&!a,u=!this.seeking&&a,c=n.paused&&!a||n.ended||0===n.playbackRate;if(this.seeking=a,t!==e)return e&&(this.ended=0),this.moved=!0,a||(this.nudgeRetry=0,s.nudgeOnVideoHole&&!c&&t>e&&this.nudgeOnVideoHole(t,e)),void(0===this.waiting&&this.stallResolved(t));if(u||o)return void(o&&this.stallResolved(t));if(c)return this.nudgeRetry=0,this.stallResolved(t),void(!this.ended&&n.ended&&this.hls&&(this.ended=t||1,this.hls.trigger(l.MEDIA_ENDED,{stalled:!1})));if(!ii.getBuffered(n).length)return void(this.nudgeRetry=0);const d=ii.bufferInfo(n,t,0),h=d.nextStart||0,f=this.fragmentTracker;if(a&&f&&this.hls){const e=Xo(this.hls.inFlightFragments,t),i=d.len>2,r=!h||e||h-t>2&&!f.getPartialFragment(t);if(i||r)return;this.moved=!1}const g=null==(r=this.hls)?void 0:r.latestLevelDetails;if(!this.moved&&null!==this.stalled&&f){if(!(d.len>0)&&!h)return;const e=Math.max(h,d.start||0)-t,i=!(null==g||!g.live)?2*g.targetduration:2,r=Zo(t,f);if(e>0&&(e<=i||r))return void(n.paused||this._trySkipBufferHole(r))}const m=s.detectStallWithCurrentTimeMs,p=self.performance.now(),v=this.waiting;let y=this.stalled;if(null===y){if(!(v>0&&p-v<m))return void(this.stalled=p);y=this.stalled=v}const E=p-y;if(!a&&(E>=m||v)&&this.hls){var T;if("ended"===(null==(T=this.mediaSource)?void 0:T.readyState)&&(null==g||!g.live)&&Math.abs(t-((null==g?void 0:g.edge)||0))<1){if(this.ended)return;return this.ended=t||1,void this.hls.trigger(l.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(d),!this.media||!this.hls)return}const b=ii.bufferInfo(n,t,s.maxBufferHole);this._tryFixBufferStall(b,E,t)}stallResolved(t){const e=this.stalled;if(e&&this.hls&&(this.stalled=null,this.stallReported)){const i=self.performance.now()-e;this.log(`playback not stuck anymore @${t}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(l.STALL_RESOLVED,{})}}nudgeOnVideoHole(t,e){var i;const r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(i=this.buffered.audio)&&i.length&&r&&r.length>1&&t>r.end(0)){const i=ii.bufferedInfo(ii.timeRangesToArray(this.buffered.audio),t,0);if(i.len>1&&e>=i.start){const i=ii.timeRangesToArray(r),s=ii.bufferedInfo(i,e,0).bufferedIndex;if(s>-1&&s<i.length-1){const e=ii.bufferedInfo(i,t,0).bufferedIndex,r=i[s].end,n=i[s+1].start;if((-1===e||e>s)&&n-r<1&&t-r<2){const i=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${r} -> ${n} buffered index: ${e}`);this.warn(i.message),this.media.currentTime+=1e-6;let s=Zo(t,this.fragmentTracker);s&&"fragment"in s?s=s.fragment:s||(s=void 0);const u=ii.bufferInfo(this.media,t,0);this.hls.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,frag:s,buffer:u.len,bufferInfo:u})}}}}}_tryFixBufferStall(t,e,i){var r,s;const{fragmentTracker:n,media:a}=this,o=null==(r=this.hls)?void 0:r.config;if(!a||!n||!o)return;const l=null==(s=this.hls)?void 0:s.latestLevelDetails,u=Zo(i,n);if(u||null!=l&&l.live&&i<l.fragmentStart){if(this._trySkipBufferHole(u)||!this.media)return}const c=t.buffered,d=this.adjacentTraversal(t,i);(c&&c.length>1&&t.len>o.maxBufferHole||t.nextStart&&(t.nextStart-i<o.maxBufferHole||d))&&(e>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}adjacentTraversal(t,e){const i=this.fragmentTracker,r=t.nextStart;if(i&&r){const t=i.getFragAtPos(e,f),s=i.getFragAtPos(r,f);if(t&&s)return s.sn-t.sn<2}return!1}_reportStall(t){const{hls:e,media:i,stallReported:r,stalled:s}=this;if(!r&&null!==s&&i&&e){this.stallReported=!0;const r=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${re(t)})`);this.warn(r.message),e.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:t.len,bufferInfo:t,stalled:{start:s}})}}_trySkipBufferHole(t){var e;const{fragmentTracker:i,media:r}=this,s=null==(e=this.hls)?void 0:e.config;if(!r||!i||!s)return 0;const n=r.currentTime,u=ii.bufferInfo(r,n,0),c=n<u.start?u.start:u.nextStart;if(c&&this.hls){const e=u.len<=s.maxBufferHole,h=u.len>0&&u.len<1&&r.readyState<3,g=c-n;if(g>0&&(e||h)){if(g>s.maxBufferHole){let e=!1;if(0===n){const t=i.getAppendedFrag(0,f);t&&c<t.end&&(e=!0)}if(!e&&t){var d;if(null==(d=this.hls.loadLevelObj)||!d.details)return 0;if(Xo(this.hls.inFlightFragments,c))return 0;let e=!1,r=t.end;for(;r<c;){const t=Zo(r,i);if(!t){e=!0;break}r+=t.duration}if(e)return 0}}const e=Math.max(c+.05,n+.1);if(this.warn(`skipping hole, adjusting currentTime from ${n} to ${e}`),this.moved=!0,r.currentTime=e,null==t||!t.gap){const i=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${e}`),r={type:a.MEDIA_ERROR,details:o.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,buffer:u.len,bufferInfo:u};t&&("fragment"in t?r.part=t:r.frag=t),this.hls.trigger(l.ERROR,r)}return e}}return 0}_tryNudgeBuffer(t){const{hls:e,media:i,nudgeRetry:r}=this,s=null==e?void 0:e.config;if(!i||!s)return 0;const n=i.currentTime;if(this.nudgeRetry++,r<s.nudgeMaxRetry){const u=n+(r+1)*s.nudgeOffset,c=new Error(`Nudging 'currentTime' from ${n} to ${u}`);this.warn(c.message),i.currentTime=u,e.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.BUFFER_NUDGE_ON_STALL,error:c,fatal:!1,buffer:t.len,bufferInfo:t})}else{const i=new Error(`Playhead still not moving while enough data buffered @${n} after ${s.nudgeMaxRetry} nudges`);this.error(i.message),e.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.BUFFER_STALLED_ERROR,error:i,fatal:!0,buffer:t.len,bufferInfo:t})}}}function Xo(t,e){const i=Qo(t.main);if(i&&i.start<=e)return i;const r=Qo(t.audio);return r&&r.start<=e?r:null}function Qo(t){if(!t)return null;switch(t.state){case Sr:case br:case wr:case Pr:return null}return t.frag}function Zo(t,e){return e.getAppendedFrag(t,f)||e.getPartialFragment(t)}function Jo(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function tl(t,e,i,r,s){let n=new t(e,i,"");try{n.value=r,s&&(n.type=s)}catch(a){n=new t(e,i,re(s?b({type:s},r):r))}return n}const el=(()=>{const t=Jo();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class il{constructor(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(l.EVENT_CUE_ENTER,{})},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:t}=this;t&&(t.on(l.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(l.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(l.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(l.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(l.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(l.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(l.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(l.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(t,e){var i;this.media=e.media,!1===(null==(i=e.overrides)?void 0:i.cueRemoval)&&(this.removeCues=!1)}onMediaAttached(){var t;const e=null==(t=this.hls)?void 0:t.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(t,e){this.media=null;!!e.transferMedia||(this.id3Track&&(this.removeCues&&ka(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){const e=this.getID3Track(t.textTracks);return e.mode="hidden",e}getID3Track(t){if(this.media){for(let e=0;e<t.length;e++){const i=t[e];if("metadata"===i.kind&&"id3"===i.label)return Aa(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(t,e){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:i,enableID3MetadataCues:r}=this.hls.config;if(!i&&!r)return;const{samples:s}=e;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=Jo();if(n)for(let t=0;t<s.length;t++){const e=s[t].type;if(e===us.emsg&&!i||!r)continue;const a=ns(s[t].data),o=s[t].pts;let l=o+s[t].duration;l>el&&(l=el);l-o<=0&&(l=o+.25);for(let t=0;t<a.length;t++){const i=a[t];if(!as(i)){this.updateId3CueEnds(o,e);const t=tl(n,o,l,i,e);t&&this.id3Track.addCue(t)}}}}updateId3CueEnds(t,e){var i;const r=null==(i=this.id3Track)?void 0:i.cues;if(r)for(let i=r.length;i--;){const s=r[i];s.type===e&&s.startTime<t&&s.endTime===el&&(s.endTime=t)}}onBufferFlushing(t,{startOffset:e,endOffset:i,type:r}){const{id3Track:s,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(s&&(a||o)){let t;t="audio"===r?t=>t.type===us.audioId3&&o:"video"===r?t=>t.type===us.emsg&&a:t=>t.type===us.audioId3&&o||t.type===us.emsg&&a,Ra(s,e,i,t)}}onLevelUpdated(t,{details:e}){this.updateDateRangeCues(e,!0)}onLevelPtsUpdated(t,e){Math.abs(e.drift)>.01&&this.updateDateRangeCues(e.details)}updateDateRangeCues(t,e){if(!this.hls||!this.media)return;const{assetPlayerId:i,timelineOffset:s,enableDateRangeMetadataCues:n,interstitialsController:a}=this.hls.config;if(!n)return;const o=Jo();if(i&&s&&!a){const{fragmentStart:e,fragmentEnd:r}=t;let s=this.assetCue;s?(s.startTime=e,s.endTime=r):o&&(s=this.assetCue=tl(o,e,r,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),s&&(s.id=i,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(s),s.addEventListener("enter",this.onEventCueEnter)))}if(!t.hasProgramDateTime)return;const{id3Track:l}=this,{dateRanges:u}=t,c=Object.keys(u);let d=this.dateRangeCuesAppended;var h;if(l&&e)if(null!=(h=l.cues)&&h.length){const t=Object.keys(d).filter((t=>!c.includes(t)));for(let e=t.length;e--;){var f;const i=t[e],r=null==(f=d[i])?void 0:f.cues;delete d[i],r&&Object.keys(r).forEach((t=>{const e=r[t];if(e){e.removeEventListener("enter",this.onEventCueEnter);try{l.removeCue(e)}catch(t){}}}))}}else d=this.dateRangeCuesAppended={};const g=t.fragments[t.fragments.length-1];if(0!==c.length&&r(null==g?void 0:g.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let t=0;t<c.length;t++){const e=c[t],i=u[e],r=i.startTime,s=d[e],n=(null==s?void 0:s.cues)||{};let l=(null==s?void 0:s.durationKnown)||!1,h=el;const{duration:f,endDate:g}=i;if(g&&null!==f)h=r+f,l=!0;else if(i.endOnNext&&!l){const t=c.reduce(((t,e)=>{if(e!==i.id){const r=u[e];if(r.class===i.class&&r.startDate>i.startDate&&(!t||i.startDate<t.startDate))return r}return t}),null);t&&(h=t.startTime,l=!0)}const p=Object.keys(i.attr);for(let t=0;t<p.length;t++){const u=p[t];if("ID"===(m=u)||"CLASS"===m||"CUE"===m||"START-DATE"===m||"DURATION"===m||"END-DATE"===m||"END-ON-NEXT"===m)continue;const c=n[u];if(c)!l||null!=s&&s.durationKnown?Math.abs(c.startTime-r)>.01&&(c.startTime=r,c.endTime=h):c.endTime=h;else if(o){let t=i.attr[u];di(u)&&(t=O(t));const s=tl(o,r,h,{key:u,data:t},us.dateRange);s&&(s.id=e,this.id3Track.addCue(s),n[u]=s,a&&("X-ASSET-LIST"!==u&&"X-ASSET-URL"!==u||s.addEventListener("enter",this.onEventCueEnter)))}}d[e]={cues:n,dateRange:i,durationKnown:l}}var m}}}class rl{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,e=this.levelDetails;if(!t||!e)return;this.currentTime=t.currentTime;const i=this.computeLatency();if(null===i)return;this._latency=i;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:s}=this.config;if(!r||1===s||!e.live)return;const n=this.targetLatency;if(null===n)return;const a=i-n;if(a<Math.min(this.maxLatency,n+e.targetduration)&&a>.05&&this.forwardBufferLength>1){const e=Math.min(2,Math.max(1,s)),i=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20,r=Math.min(e,Math.max(1,i));this.changeMediaPlaybackRate(t,r)}else 1!==t.playbackRate&&0!==t.playbackRate&&this.changeMediaPlaybackRate(t,1)},this.hls=t,this.config=t.config,this.registerListeners()}get levelDetails(){var t;return(null==(t=this.hls)?void 0:t.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:t}=this;if(void 0!==t.liveMaxLatencyDuration)return t.liveMaxLatencyDuration;const e=this.levelDetails;return e?t.liveMaxLatencyDurationCount*e.targetduration:0}get targetLatency(){const t=this.levelDetails;if(null===t||null===this.hls)return null;const{holdBack:e,partHoldBack:i,targetduration:r}=t,{liveSyncDuration:s,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&i||e;(this._targetLatencyUpdated||o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==s?s:n*r);const u=r;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,u)}set targetLatency(t){this.stallCount=0,this.config.liveSyncDuration=t,this._targetLatencyUpdated=!0}get liveSyncPosition(){const t=this.estimateLiveEdge(),e=this.targetLatency;if(null===t||null===e)return null;const i=this.levelDetails;if(null===i)return null;const r=i.edge,s=t-e-this.edgeStalled,n=r-i.totalduration,a=r-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(n,s),a)}get drift(){const t=this.levelDetails;return null===t?1:t.drift}get edgeStalled(){const t=this.levelDetails;if(null===t)return 0;const e=3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}get forwardBufferLength(){const{media:t}=this,e=this.levelDetails;if(!t||!e)return 0;const i=t.buffered.length;return(i?t.buffered.end(i-1):e.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:t}=this;t&&(t.on(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(l.ERROR,this.onError,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(l.ERROR,this.onError,this))}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(t,{details:e}){e.advanced&&this.onTimeupdate(),!e.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(t,e){var i;e.details===o.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(i=this.levelDetails)&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(t,e){var i,r;t.playbackRate!==e&&(null==(i=this.hls)||i.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 ${t.playbackRate} to ${e}`),t.playbackRate=e)}estimateLiveEdge(){const t=this.levelDetails;return null===t?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return null===t?null:t-this.currentTime}}class sl extends hn{constructor(t,e){super(t,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=e,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(l.LEVEL_LOADED,this.onLevelLoaded,this),t.on(l.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(l.FRAG_BUFFERED,this.onFragBuffered,this),t.on(l.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(l.LEVEL_LOADED,this.onLevelLoaded,this),t.off(l.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(l.FRAG_BUFFERED,this.onFragBuffered,this),t.off(l.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach((t=>{t.loadError=0,t.fragmentError=0})),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(t,e){this.resetLevels()}onManifestLoaded(t,e){const i=this.hls.config.preferManagedMediaSource,r=[],s={},n={};let a=!1,o=!1,l=!1;e.levels.forEach((t=>{const e=t.attrs;let{audioCodec:u,videoCodec:c}=t;u&&(t.audioCodec=u=xt(u,i)||void 0),c&&(c=t.videoCodec=function(t){const e=t.split(",");for(let t=0;t<e.length;t++){const i=e[t].split(".");i.length>2&&"avc1"===i[0]&&(e[t]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`)}return e.join(",")}(c));const{width:d,height:h,unknownCodecs:f}=t,g=(null==f?void 0:f.length)||0;if(a||(a=!(!d||!h)),o||(o=!!c),l||(l=!!u),g||u&&!this.isAudioSupported(u)||c&&!this.isVideoSupported(c))return void this.log(`Some or all CODECS not supported "${e.CODECS}"`);const{CODECS:m,"FRAME-RATE":p,"HDCP-LEVEL":v,"PATHWAY-ID":y,RESOLUTION:E,"VIDEO-RANGE":T}=e,b=`${`${y||"."}-`}${t.bitrate}-${E}-${p}-${m}-${T}-${v}`;if(s[b])if(s[b].uri===t.url||t.attrs["PATHWAY-ID"])s[b].addGroupId("audio",e.AUDIO),s[b].addGroupId("text",e.SUBTITLES);else{const e=n[b]+=1;t.attrs["PATHWAY-ID"]=new Array(e+1).join(".");const i=this.createLevel(t);s[b]=i,r.push(i)}else{const e=this.createLevel(t);s[b]=e,n[b]=1,r.push(e)}})),this.filterAndSortMediaOptions(r,e,a,o,l)}createLevel(t){const e=new te(t),i=t.supplemental;if(null!=i&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){const t=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(t.message),e.supportedResult=Ht(t,[])}return e}isAudioSupported(t){return It(t,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(t){return It(t,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(t,e,i,r,s){var n;let u=[],c=[],d=t;const h=(null==(n=e.stats)?void 0:n.parsing)||{};if((i||r)&&s&&(d=d.filter((({videoCodec:t,videoRange:e,width:i,height:r})=>{return(!!t||!(!i||!r))&&(!!(s=e)&&qt.indexOf(s)>-1);var s}))),0===d.length)return Promise.resolve().then((()=>{if(this.hls){let t="no level with compatible codecs found in manifest",i=t;e.levels.length&&(i=`one or more CODECS in variant not supported: ${re(e.levels.map((t=>t.attrs.CODECS)).filter(((t,e,i)=>i.indexOf(t)===e)))}`,this.warn(i),t+=` (${i})`);const r=new Error(t);this.hls.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:r,reason:i})}})),void(h.end=performance.now());e.audioTracks&&(u=e.audioTracks.filter((t=>!t.audioCodec||this.isAudioSupported(t.audioCodec))),nl(u)),e.subtitles&&(c=e.subtitles,nl(c));const f=d.slice(0);d.sort(((t,e)=>{if(t.attrs["HDCP-LEVEL"]!==e.attrs["HDCP-LEVEL"])return(t.attrs["HDCP-LEVEL"]||"")>(e.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&t.height!==e.height)return t.height-e.height;if(t.frameRate!==e.frameRate)return t.frameRate-e.frameRate;if(t.videoRange!==e.videoRange)return qt.indexOf(t.videoRange)-qt.indexOf(e.videoRange);if(t.videoCodec!==e.videoCodec){const i=Pt(t.videoCodec),r=Pt(e.videoCodec);if(i!==r)return r-i}if(t.uri===e.uri&&t.codecSet!==e.codecSet){const i=Dt(t.codecSet),r=Dt(e.codecSet);if(i!==r)return r-i}return t.averageBitrate!==e.averageBitrate?t.averageBitrate-e.averageBitrate:0}));let g=f[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==f.length))for(let t=0;t<f.length;t++)if(f[t].pathwayId===d[0].pathwayId){g=f[t];break}this._levels=d;for(let t=0;t<d.length;t++)if(d[t]===g){var m;this._firstLevel=t;const e=g.bitrate,i=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${d.length} level(s) found, first bitrate: ${e}`),void 0===(null==(m=this.hls.userConfig)?void 0:m.abrEwmaDefaultEstimate)){const t=Math.min(e,this.hls.config.abrEwmaDefaultEstimateMax);t>i&&i===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=t)}break}const p=s&&!r,v=this.hls.config,y=!(!v.audioStreamController||!v.audioTrackController),E={levels:d,audioTracks:u,subtitleTracks:c,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:s,video:r,altAudio:y&&!p&&u.some((t=>!!t.url))};h.end=performance.now(),this.hls.trigger(l.MANIFEST_PARSED,E)}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(t){const e=this._levels;if(0===e.length)return;if(t<0||t>=e.length){const i=new Error("invalid level idx"),r=t<0;if(this.hls.trigger(l.ERROR,{type:a.OTHER_ERROR,details:o.LEVEL_SWITCH_ERROR,level:t,fatal:r,error:i,reason:i.message}),r)return;t=Math.min(t,e.length-1)}const i=this.currentLevelIndex,r=this.currentLevel,s=r?r.attrs["PATHWAY-ID"]:void 0,n=e[t],u=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=n,i===t&&r&&s===u)return;this.log(`Switching to level ${t} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${u?" with Pathway "+u:""} from level ${i}${s?" with Pathway "+s:""}`);const c={level:t,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(l.LEVEL_SWITCHING,c);const d=n.details;if(!d||d.live){const t=this.switchParams(n.uri,null==r?void 0:r.details,d);this.loadPlaylist(t)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(void 0===this._startLevel){const t=this.hls.config.startLevel;return void 0!==t?t:this.hls.firstAutoLevel}return this._startLevel}set startLevel(t){this._startLevel=t}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(t){if(this.steering){const e=this.steering.pathways(),i=t.filter((t=>-1!==e.indexOf(t)));if(t.length<1)return void this.warn(`pathwayPriority ${t} should contain at least one pathway from list: ${e}`);this.steering.pathwayPriority=i}}onError(t,e){!e.fatal&&e.context&&e.context.type===c&&e.context.level===this.level&&this.checkRetry(e)}onFragBuffered(t,{frag:e}){if(void 0!==e&&e.type===f){const t=e.elementaryStreams;if(!Object.keys(t).some((e=>!!t[e])))return;const i=this._levels[e.level];null!=i&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(t,e){var i;const{level:r,details:s}=e,n=e.levelInfo;var a;if(!n)return this.warn(`Invalid level index ${r}`),void(null!=(a=e.deliveryDirectives)&&a.skip&&(s.deltaUpdateFailed=!0));if(n===this.currentLevel||e.withoutMultiVariant){0===n.fragmentError&&(n.loadError=0);let t=n.details;t===e.details&&t.advanced&&(t=void 0),this.playlistLoaded(r,e,t)}else null!=(i=e.deliveryDirectives)&&i.skip&&(s.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const i=this.getUrlWithDirectives(t.uri,e),r=this.currentLevelIndex,s=t.attrs["PATHWAY-ID"],n=t.details,a=null==n?void 0:n.age;this.log(`Loading level index ${r}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${s?" Pathway "+s:""}${a&&n.live?" age "+a.toFixed(1)+(n.type?" "+n.type||0:""):""} ${i}`),this.hls.trigger(l.LEVEL_LOADING,{url:i,level:r,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}removeLevel(t){var e;if(1===this._levels.length)return;const i=this._levels.filter(((e,i)=>i!==t||(this.steering&&this.steering.removeLevel(e),e===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,e.details&&e.details.fragments.forEach((t=>t.level=-1))),!1)));cr(i),this._levels=i,this.currentLevelIndex>-1&&null!=(e=this.currentLevel)&&e.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const r=i.length-1;this._firstLevel=Math.min(this._firstLevel,r),this._startLevel&&(this._startLevel=Math.min(this._startLevel,r)),this.hls.trigger(l.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(t,{levels:e}){this._levels=e}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:e,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==e&&(this._maxAutoLevel=e,this.hls.trigger(l.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function nl(t){const e={};t.forEach((t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++}))}function al(){return self.SourceBuffer||self.WebKitSourceBuffer}function ol(){if(!w())return!1;const t=al();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}class ll extends Or{constructor(t,e,i){super(t,e,i,"stream-controller",f),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const t=this.media,e=t?t.currentTime:null;if(null===e||!r(e))return;if(this.log(`Media seeked to ${e.toFixed(3)}`),!this.getBufferedFrag(e))return;const i=this.getFwdBufferInfoAtPos(t,e,f,0);null!==i&&0!==i.len?this.tick():this.warn(`Main forward buffer length at ${e} on "seeked" event ${i?i.len:"empty"})`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(l.MANIFEST_PARSED,this.onManifestParsed,this),t.on(l.LEVEL_LOADING,this.onLevelLoading,this),t.on(l.LEVEL_LOADED,this.onLevelLoaded,this),t.on(l.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(l.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(l.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(l.BUFFER_CREATED,this.onBufferCreated,this),t.on(l.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(l.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(l.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(l.MANIFEST_PARSED,this.onManifestParsed,this),t.off(l.LEVEL_LOADED,this.onLevelLoaded,this),t.off(l.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(l.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(l.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(l.BUFFER_CREATED,this.onBufferCreated,this),t.off(l.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(l.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(l.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(t,e){if(this.levels){const{lastCurrentTime:i,hls:r}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let t=r.startLevel;-1===t&&(r.config.testBandwidth&&this.levels.length>1?(t=0,this.bitrateTest=!0):t=r.firstAutoLevel),r.nextLoadLevel=t,this.level=r.loadLevel,this._hasEnoughToStart=!!e}i>0&&-1===t&&!e&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),t=i),this.state=Sr,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}else this._forceStartLoad=!0,this.state=br}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Cr:{const{levels:t,level:e}=this,i=null==t?void 0:t[e],r=null==i?void 0:i.details;if(r&&(!r.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(r))break;this.state=Sr;break}if(this.hls.nextLoadLevel!==this.level){this.state=Sr;break}break}case kr:this.checkRetryDate()}this.state===Sr&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var t;super.onTickEnd(),null!=(t=this.media)&&t.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:i,media:r}=this;if(null===e||!r&&!this.primaryPrefetch&&(this.startFragRequested||!t.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const s=this.buffering?t.nextLoadLevel:t.loadLevel;if(null==i||!i[s])return;const n=i[s],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const t={};return 2===this.altAudio&&(t.type="video"),this.hls.trigger(l.BUFFER_EOS,t),void(this.state=wr)}if(!this.buffering)return;t.loadLevel!==s&&-1===t.manualLevel&&this.log(`Adapting to level ${s} from level ${this.level}`),this.level=t.nextLoadLevel=s;const u=n.details;if(!u||this.state===Cr||this.waitForLive(n))return this.level=s,this.state=Cr,void(this.startFragRequested=!1);const c=a.len,d=this.getMaxBufferLength(n.maxBitrate);if(c>=d)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const h=this.backtrackFragment?this.backtrackFragment.start:a.end;let g=this.getNextFragment(h,u);if(this.couldBacktrack&&!this.fragPrevious&&g&&q(g)&&this.fragmentTracker.getState(g)!==Ne){var m;const t=(null!=(m=this.backtrackFragment)?m:g).sn-u.startSN,e=u.fragments[t-1];e&&g.cc===e.cc&&(g=e,this.fragmentTracker.removeFragment(e))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(g&&this.isLoopLoading(g,h)){if(!g.gap){const t=this.audioOnly&&!this.altAudio?j:K,e=(t===K?this.videoBuffer:this.mediaBuffer)||this.media;e&&this.afterBufferFlushed(e,t,f)}g=this.getNextFragmentLoopLoading(g,u,a,f,d)}g&&(!g.initSegment||g.initSegment.data||this.bitrateTest||(g=g.initSegment),this.loadFragment(g,n,h))}loadFragment(t,e,i){const r=this.fragmentTracker.getState(t);r===xe||r===Fe?q(t)?this.bitrateTest?(this.log(`Fragment ${t.sn} of level ${t.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(t,e)):super.loadFragment(t,e,i):this._loadInitSegment(t,e):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,f)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:t,media:e}=this;if(null!=e&&e.readyState){let i;const r=this.getAppendedFrag(e.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);const s=this.getLevelDetails();if(null!=s&&s.live){const t=this.getMainFwdBufferInfo();if(!t||t.len<2*s.targetduration)return}if(!e.paused&&t){const e=t[this.hls.nextLoadLevel],r=this.fragLastKbps;i=r&&this.fragCurrent?this.fragCurrent.duration*e.maxBitrate/(1e3*r)+1:0}else i=0;const n=this.getBufferedFrag(e.currentTime+i);if(n){const t=this.followingBufferedFrag(n);if(t){this.abortCurrentFrag();const e=t.maxStartPTS?t.maxStartPTS:t.start,i=t.duration,r=Math.max(n.end,e+Math.min(Math.max(i-this.config.maxFragLookUpTolerance,i*(this.couldBacktrack?.5:.125)),i*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(r,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const t=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.state){case Ar:case Lr:case kr:case Ir:case _r:this.state=Sr}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,2===this.altAudio?"video":null)}onMediaAttached(t,e){super.onMediaAttached(t,e);const i=e.media;yr(i,"playing",this.onMediaPlaying),yr(i,"seeked",this.onMediaSeeked)}onMediaDetaching(t,e){const{media:i}=this;i&&(Er(i,"playing",this.onMediaPlaying),Er(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(t,e);!!e.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(l.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(t,e){let i=!1,r=!1;for(let t=0;t<e.levels.length;t++){const s=e.levels[t].audioCodec;s&&(i=i||-1!==s.indexOf("mp4a.40.2"),r=r||-1!==s.indexOf("mp4a.40.5"))}this.audioCodecSwitch=i&&r&&!function(){var t;const e=al();return"function"==typeof(null==e||null==(t=e.prototype)?void 0:t.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1}onLevelLoading(t,e){const{levels:i}=this;if(!i||this.state!==Sr)return;const r=e.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=Cr)}onLevelLoaded(t,e){var i;const{levels:r,startFragRequested:s}=this,n=e.level,a=e.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 u=e.levelInfo,c=this.fragCurrent;!c||this.state!==Lr&&this.state!==kr||c.level!==e.level&&c.loader&&this.abortCurrentFrag();let d=0;if(a.live||null!=(i=u.details)&&i.live){var h;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;d=this.alignPlaylists(a,u.details,null==(h=this.levelLastLoaded)?void 0:h.details)}if(u.details=a,this.levelLastLoaded=u,s||this.setStartPosition(a,d),this.hls.trigger(l.LEVEL_UPDATED,{details:a,level:n}),this.state===Cr){if(this.waitForCdnTuneIn(a))return;this.state=Sr}s&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}synchronizeToLiveEdge(t){const{config:e,media:i}=this;if(!i)return;const r=this.hls.liveSyncPosition,s=this.getLoadPosition(),n=t.fragmentStart,a=t.edge,o=s>=n-e.maxFragLookUpTolerance&&s<=a;if(null!==r&&i.duration>r&&(s<r||!o)){const n=void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;if((!o&&i.readyState<4||s<a-n)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),i.readyState))if(this.warn(`Playback: ${s.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 t=ii.bufferInfo(i,r,0);if(null==(l=t.buffered)||!l.length)return void(i.currentTime=r);if(t.start<=s)return void(i.currentTime=r);const{nextStart:e}=ii.bufferedInfo(t.buffered,s,0);e&&(i.currentTime=e)}else i.currentTime=r}}_handleFragmentLoadProgress(t){var e;const i=t.frag,{part:r,payload:s}=t,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);const a=n[i.level];if(!a)return void this.warn(`Level ${i.level} not found on progress`);const o=a.details;if(!o)return this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),void this.fragmentTracker.removeFragment(i);const l=a.videoCodec,u=o.PTSKnown||!o.live,c=null==(e=i.initSegment)?void 0:e.data,d=this._getAudioCodec(a),h=this.transmuxer=this.transmuxer||new dn(this.hls,f,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=r?r.index:-1,m=-1!==g,p=new ti(i.level,i.sn,i.stats.chunkCount,s.byteLength,g,m),v=this.initPTS[i.cc];h.push(s,c,d,l,i,r,o.totalduration,u,p,v)}onAudioTrackSwitching(t,e){const i=this.hls,r=0!==this.altAudio;if(de(e.url,i))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const t=this.fragCurrent;t&&(this.log("Switching to main audio track, cancel main fragment load"),t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(r)return this.altAudio=0,this.fragmentTracker.removeAllFragments(),i.once(l.BUFFER_FLUSHED,(()=>{this.hls&&this.hls.trigger(l.AUDIO_TRACK_SWITCHED,e)})),void i.trigger(l.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});i.trigger(l.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const i=de(e.url,this.hls);if(i){const t=this.videoBuffer;t&&this.mediaBuffer!==t&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=t)}this.altAudio=i?2:0,this.tick()}onBufferCreated(t,e){const i=e.tracks;let r,s,n=!1;for(const t in i){const e=i[t];if("main"===e.id){if(s=t,r=e,"video"===t){const e=i[t];e&&(this.videoBuffer=e.buffer)}}else n=!0}n&&r?(this.log(`Alternate track found, use ${s}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:i,part:r}=e,s=i.type===f;if(s){if(this.fragContextChanged(i))return this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===_r&&(this.state=Sr));const t=r?r.stats:i.stats;this.fragLastKbps=Math.round(8*t.total/(t.buffering.end-t.loading.first)),q(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,r)}const n=this.media;n&&(!this._hasEnoughToStart&&ii.getBuffered(n).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),s&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,e){var i;if(e.fatal)this.state=Pr;else switch(e.details){case o.FRAG_GAP:case o.FRAG_PARSING_ERROR:case o.FRAG_DECRYPT_ERROR:case o.FRAG_LOAD_ERROR:case o.FRAG_LOAD_TIMEOUT:case o.KEY_LOAD_ERROR:case o.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(f,e);break;case o.LEVEL_LOAD_ERROR:case o.LEVEL_LOAD_TIMEOUT:case o.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==Cr||(null==(i=e.context)?void 0:i.type)!==c||(this.state=Sr);break;case o.BUFFER_ADD_CODEC_ERROR:case o.BUFFER_APPEND_ERROR:if("main"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&this.resetLoadingState();break;case o.BUFFER_FULL_ERROR:if("main"!==e.parent)return;if(this.reduceLengthAndFlushBuffer(e)){!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}break;case o.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onFragLoadEmergencyAborted(){this.state=Sr,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==j||!this.altAudio){const t=(e===K?this.videoBuffer:this.mediaBuffer)||this.media;t&&(this.afterBufferFlushed(t,e,f),this.tick())}}onLevelsUpdated(t,e){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=e.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:t}=this;if(!t)return;const e=t.currentTime;let i=this.startPosition;if(i>=0&&e<i){if(t.seeking)return void this.log(`could not seek to ${i}, already seeking at ${e}`);const r=this.timelineOffset;r&&i&&(i+=r);const s=this.getLevelDetails(),n=ii.getBuffered(t),a=n.length?n.start(0):0,o=a-i,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==s?void 0:s.partTarget)||0)))&&(this.log(`adjusting start position by ${o} to match buffer start`),i+=o,this.startPosition=i),e<i&&(this.log(`seek to target start position ${i} from current time ${e} buffer start ${a}`),t.currentTime=i)}}_getAudioCodec(t){let e=this.config.defaultAudioCodec||t.audioCodec;return this.audioCodecSwap&&e&&(this.log("Swapping audio codec"),e=-1!==e.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),e}_loadBitrateTestFrag(t,e){t.bitrateTest=!0,this._doFragLoad(t,e).then((t=>{const{hls:i}=this,r=null==t?void 0:t.frag;if(!r||this.fragContextChanged(r))return;e.fragmentError=0,this.state=Sr,this.startFragRequested=!1,this.bitrateTest=!1;const s=r.stats;s.parsing.start=s.parsing.end=s.buffering.start=s.buffering.end=self.performance.now(),i.trigger(l.FRAG_LOADED,t),r.bitrateTest=!1})).catch((e=>{this.state!==br&&this.state!==Pr&&(this.warn(e),this.resetFragmentLoading(t))}))}_handleTransmuxComplete(t){const e=this.playlistType,{hls:i}=this,{remuxResult:s,chunkMeta:n}=t,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:u,level:c}=a,{video:d,text:h,id3:f,initSegment:g}=s,{details:m}=c,p=this.altAudio?void 0:s.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=Ir,g){const t=g.tracks;if(t){const r=o.initSegment||o;if(this.unhandledEncryptionError(g,o))return;this._bufferInitSegment(c,t,r,n),i.trigger(l.FRAG_PARSING_INIT_SEGMENT,{frag:r,id:e,tracks:t})}const s=g.initPTS,a=g.timescale,u=this.initPTS[o.cc];if(r(s)&&(!u||u.baseTime!==s||u.timescale!==a)){const t=g.trackId;this.initPTS[o.cc]={baseTime:s,timescale:a,trackId:t},i.trigger(l.INIT_PTS_FOUND,{frag:o,id:e,initPTS:s,timescale:a,trackId:t})}}if(d&&m){p&&"audiovideo"===d.type&&this.logMuxedErr(o);const t=m.fragments[o.sn-1-m.startSN],e=o.sn===m.startSN,i=!t||o.cc>t.cc;if(!1!==s.independent){const{startPTS:t,endPTS:r,startDTS:s,endDTS:a}=d;if(u)u.elementaryStreams[d.type]={startPTS:t,endPTS:r,startDTS:s,endDTS:a};else if(d.firstKeyFrame&&d.independent&&1===n.id&&!i&&(this.couldBacktrack=!0),d.dropped&&d.independent){const s=this.getMainFwdBufferInfo(),n=(s?s.end:this.getLoadPosition())+this.config.maxBufferHole,l=d.firstKeyFramePTS?d.firstKeyFramePTS:t;if(!e&&n<l-this.config.maxBufferHole&&!i)return void this.backtrack(o);i&&(o.gap=!0),o.setElementaryStreamInfo(d.type,o.start,r,o.start,a,!0)}else e&&t-(m.appliedTimelineOffset||0)>2&&(o.gap=!0);o.setElementaryStreamInfo(d.type,t,r,s,a),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(d,o,u,n,e||i)}else{if(!e&&!i)return void this.backtrack(o);o.gap=!0}}if(p){const{startPTS:t,endPTS:e,startDTS:i,endDTS:r}=p;u&&(u.elementaryStreams[j]={startPTS:t,endPTS:e,startDTS:i,endDTS:r}),o.setElementaryStreamInfo(j,t,e,i,r),this.bufferFragmentData(p,o,u,n)}if(m&&null!=f&&f.samples.length){const t={id:e,frag:o,details:m,samples:f.samples};i.trigger(l.FRAG_PARSING_METADATA,t)}if(m&&h){const t={id:e,frag:o,details:m,samples:h.samples};i.trigger(l.FRAG_PARSING_USERDATA,t)}}}logMuxedErr(t){this.warn(`${q(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,e,i,r){if(this.state!==Ir)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&(delete e.audio,e.audiovideo&&this.logMuxedErr(i));const{audio:s,video:n,audiovideo:a}=e;if(s){const i=t.audioCodec;let r=Mt(s.codec,i);"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 t=s.metadata;t&&"channelCount"in t&&1!==(t.channelCount||1)&&-1===n.indexOf("firefox")&&(r="mp4a.40.5")}r&&-1!==r.indexOf("mp4a.40.5")&&-1!==n.indexOf("android")&&"audio/mpeg"!==s.container&&(r="mp4a.40.2",this.log(`Android: force audio codec to ${r}`)),i&&i!==r&&this.log(`Swapping manifest audio codec "${i}" for "${r}"`),s.levelCodec=r,s.id=f,this.log(`Init audio buffer, container:${s.container}, codecs[selected/level/parsed]=[${r||""}/${i||""}/${s.codec}]`),delete e.audiovideo}if(n){n.levelCodec=t.videoCodec,n.id=f;const i=n.codec;if(4===(null==i?void 0:i.length))switch(i){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]=[${t.videoCodec||""}/${i}]${n.codec!==i?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete e.audiovideo}a&&(this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${t.codecs}/${a.codec}]`),delete e.video,delete e.audio);const o=Object.keys(e);if(o.length){if(this.hls.trigger(l.BUFFER_CODECS,e),!this.hls)return;o.forEach((t=>{const s=e[t].initSegment;null!=s&&s.byteLength&&this.hls.trigger(l.BUFFER_APPENDING,{type:t,data:s,frag:i,part:null,chunkMeta:r,parent:i.type})}))}this.tickImmediate()}getMainFwdBufferInfo(){const t=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(t,f)}get maxBufferLength(){const{levels:t,level:e}=this,i=null==t?void 0:t[e];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=Sr}checkFragmentChanged(){const t=this.media;let e=null;if(t&&t.readyState>1&&!1===t.seeking){const i=t.currentTime;if(ii.isBuffered(t,i)?e=this.getAppendedFrag(i):ii.isBuffered(t,i+.1)&&(e=this.getAppendedFrag(i+.1)),e){this.backtrackFragment=null;const t=this.fragPlaying,i=e.level;t&&e.sn===t.sn&&t.level===i||(this.fragPlaying=e,this.hls.trigger(l.FRAG_CHANGED,{frag:e}),t&&t.level===i||this.hls.trigger(l.LEVEL_SWITCHED,{level:i}))}}}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){var t;if(this.fragPlaying)return this.fragPlaying;const e=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;return r(e)?this.getAppendedFrag(e):null}get currentProgramDateTime(){var t;const e=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;if(r(e)){const t=this.getLevelDetails(),i=this.currentFrag||(t?fe(null,t.fragments,e):null);if(i){const t=i.programDateTime;if(null!==t){const r=t+1e3*(e-i.start);return new Date(r)}}}return null}get currentLevel(){const t=this.currentFrag;return t?t.level:-1}get nextBufferedFrag(){const t=this.currentFrag;return t?this.followingBufferedFrag(t):null}get forceStartLoad(){return this._forceStartLoad}}class ul extends S{constructor(t,e){super("key-loader",e),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=t}abort(t){for(const i in this.keyIdToKeyInfo){const r=this.keyIdToKeyInfo[i].loader;if(r){var e;if(t&&t!==(null==(e=r.context)?void 0:e.frag.type))return;r.abort()}}}detach(){for(const t in this.keyIdToKeyInfo){const e=this.keyIdToKeyInfo[t];(e.mediaKeySessionContext||e.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[t]}}destroy(){this.detach();for(const t in this.keyIdToKeyInfo){const e=this.keyIdToKeyInfo[t].loader;e&&e.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(t,e=o.KEY_LOAD_ERROR,i,r,s){return new Ze({type:a.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:s,error:i,networkDetails:r})}loadClear(t,e,i){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(e.length)for(let r=0,s=e.length;r<s;r++){const n=e[r];if(t.cc<=n.cc&&(!q(t)||!q(n)||t.sn<n.sn)||!i&&r==s-1)return this.emeController.selectKeySystemFormat(n).then((t=>{if(!this.emeController)return;n.setKeyFormat(t);const e=_i(t);return e?this.emeController.getKeySystemAccess([e]):void 0}))}if(this.config.requireKeySystemAccessOnStart){const t=Pi(this.config);if(t.length)return this.emeController.getKeySystemAccess(t)}}return null}load(t){return!t.decryptdata&&t.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(t).then((e=>this.loadInternal(t,e))):this.loadInternal(t)}loadInternal(t,e){var i,r;e&&t.setKeyFormat(e);const s=t.decryptdata;if(!s){const i=new Error(e?`Expected frag.decryptdata to be defined after setting format ${e}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(t,o.KEY_LOAD_ERROR,i))}const n=s.uri;if(!n)return Promise.reject(this.createKeyLoadError(t,o.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));const a=cl(s);let l=this.keyIdToKeyInfo[a];if(null!=(i=l)&&i.decryptdata.key)return s.key=l.decryptdata.key,Promise.resolve({frag:t,keyInfo:l});if(this.emeController&&null!=(r=l)&&r.keyLoadPromise){switch(this.emeController.getKeyStatus(l.decryptdata)){case"usable":case"usable-in-future":return l.keyLoadPromise.then((e=>{const{keyInfo:i}=e;return s.key=i.decryptdata.key,{frag:t,keyInfo:i}}))}}switch(this.log(`${this.keyIdToKeyInfo[a]?"Rel":"L"}oading${s.keyId?" keyId: "+C(s.keyId):""} URI: ${s.uri} from ${t.type} ${t.level}`),l=this.keyIdToKeyInfo[a]={decryptdata:s,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},s.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===s.keyFormat?this.loadKeyHTTP(l,t):this.loadKeyEME(l,t);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(l,t);default:return Promise.reject(this.createKeyLoadError(t,o.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(t,e){const i={frag:e,keyInfo:t};if(this.emeController&&this.config.emeEnabled){var r;if(!t.decryptdata.keyId&&null!=(r=e.initSegment)&&r.data){const i=function(t){const e=[];return gt(t,(t=>e.push(t.subarray(8,24)))),e}(e.initSegment.data);if(i.length){let e=i[0];e.some((t=>0!==t))?(this.log(`Using keyId found in init segment ${C(e)}`),Mi.setKeyIdForUri(t.decryptdata.uri,e)):(e=Mi.addKeyIdForUri(t.decryptdata.uri),this.log(`Generating keyId to patch media ${C(e)}`)),t.decryptdata.keyId=e}}if(!t.decryptdata.keyId&&!q(e))return Promise.resolve(i);const s=this.emeController.loadKey(i);return(t.keyLoadPromise=s.then((e=>(t.mediaKeySessionContext=e,i)))).catch((i=>{throw t.keyLoadPromise=null,"data"in i&&(i.data.frag=e),i}))}return Promise.resolve(i)}loadKeyHTTP(t,e){const i=this.config,r=new(0,i.loader)(i);return e.keyLoader=t.loader=r,t.keyLoadPromise=new Promise(((s,n)=>{const a={keyInfo:t,frag:e,responseType:"arraybuffer",url:t.decryptdata.uri},l=i.keyLoadPolicy.default,u={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(t,e,i,r)=>{const{frag:a,keyInfo:l}=i,u=cl(l.decryptdata);if(!a.decryptdata||l!==this.keyIdToKeyInfo[u])return n(this.createKeyLoadError(a,o.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),r));l.decryptdata.key=a.decryptdata.key=new Uint8Array(t.data),a.keyLoader=null,l.loader=null,s({frag:a,keyInfo:l})},onError:(t,i,r,s)=>{this.resetLoader(i),n(this.createKeyLoadError(e,o.KEY_LOAD_ERROR,new Error(`HTTP Error ${t.code} loading key ${t.text}`),r,b({url:a.url,data:void 0},t)))},onTimeout:(t,i,r)=>{this.resetLoader(i),n(this.createKeyLoadError(e,o.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),r))},onAbort:(t,i,r)=>{this.resetLoader(i),n(this.createKeyLoadError(e,o.INTERNAL_ABORTED,new Error("key loading aborted"),r))}};r.load(a,u,c)}))}resetLoader(t){const{frag:e,keyInfo:i,url:r}=t,s=i.loader;e.keyLoader===s&&(e.keyLoader=null,i.loader=null);const n=cl(i.decryptdata)||r;delete this.keyIdToKeyInfo[n],s&&s.destroy()}}function cl(t){if(t.keyFormat!==ki){const e=t.keyId;if(e)return C(e)}return t.uri}function dl(t){const{type:e}=t;switch(e){case d:return g;case h:return m;default:return f}}function hl(t,e){let i=t.url;return void 0!==i&&0!==i.indexOf("data:")||(i=e.url),i}class fl{constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=t,this.registerListeners()}startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:t}=this;t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.LEVEL_LOADING,this.onLevelLoading,this),t.on(l.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(l.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(l.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.LEVEL_LOADING,this.onLevelLoading,this),t.off(l.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(l.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(l.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(t){const e=this.hls.config,i=e.pLoader,r=e.loader,s=new(i||r)(e);return this.loaders[t.type]=s,s}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}destroyInternalLoaders(){for(const t in this.loaders){const e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,e){const{url:i}=e;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:u,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(t,e){const{id:i,level:r,pathwayId:s,url:n,deliveryDirectives:a,levelInfo:o}=e;this.load({id:i,level:r,pathwayId:s,responseType:"text",type:c,url:n,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(t,e){const{id:i,groupId:r,url:s,deliveryDirectives:n,track:a}=e;this.load({id:i,groupId:r,level:null,responseType:"text",type:d,url:s,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(t,e){const{id:i,groupId:r,url:s,deliveryDirectives:n,track:a}=e;this.load({id:i,groupId:r,level:null,responseType:"text",type:h,url:s,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(t,e){const i=this.loaders[c];if(i){const t=i.context;t&&!e.levels.some((e=>e===t.levelOrTrack))&&(i.abort(),delete this.loaders[c])}}load(t){var e;const i=this.hls.config;let s,n=this.getInternalLoader(t);if(n){const e=this.hls.logger,i=n.context;if(i&&i.levelOrTrack===t.levelOrTrack&&(i.url===t.url||i.deliveryDirectives&&!t.deliveryDirectives))return void(i.url===t.url?e.log(`[playlist-loader]: ignore ${t.url} ongoing request`):e.log(`[playlist-loader]: ignore ${t.url} in favor of ${i.url}`));e.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),n.abort()}if(s=t.type===u?i.manifestLoadPolicy.default:E({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(t),r(null==(e=t.deliveryDirectives)?void 0:e.part)){let e;if(t.type===c&&null!==t.level?e=this.hls.levels[t.level].details:t.type===d&&null!==t.id?e=this.hls.audioTracks[t.id].details:t.type===h&&null!==t.id&&(e=this.hls.subtitleTracks[t.id].details),e){const t=e.partTarget,i=e.targetduration;if(t&&i){const e=1e3*Math.max(3*t,.8*i);s=E({},s,{maxTimeToFirstByteMs:Math.min(e,s.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(e,s.maxTimeToFirstByteMs)})}}}const a=s.errorRetry||s.timeoutRetry||{},o={loadPolicy:s,timeout:s.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(t,e,i,r)=>{const s=this.getInternalLoader(i);this.resetInternalLoader(i.type);const n=t.data;e.parsing.start=performance.now(),Hi.isMediaPlaylist(n)||i.type!==u?this.handleTrackOrLevelPlaylist(t,e,i,r||null,s):this.handleMasterPlaylist(t,e,i,r)},onError:(t,e,i,r)=>{this.handleNetworkError(e,i,!1,t,r)},onTimeout:(t,e,i)=>{this.handleNetworkError(e,i,!0,void 0,t)}};n.load(t,o,l)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:t,startPosition:e},forceStartLoad:i}=this.hls;(t||i)&&(this.hls.logger.log(`${t?"auto":"force"} startLoad with configured startPosition ${e}`),this.hls.startLoad(e))}handleMasterPlaylist(t,e,i,r){const s=this.hls,n=t.data,a=hl(t,i),o=Hi.parseMasterPlaylist(n,a);if(o.playlistParsingError)return e.parsing.end=performance.now(),void this.handleManifestParsingError(t,i,o.playlistParsingError,r,e);const{contentSteering:u,levels:c,sessionData:d,sessionKeys:h,startTimeOffset:f,variableList:g}=o;this.variableList=g,c.forEach((t=>{const{unknownCodecs:e}=t;if(e){const{preferManagedMediaSource:i}=this.hls.config;let{audioCodec:r,videoCodec:s}=t;for(let n=e.length;n--;){const a=e[n];It(a,"audio",i)?(t.audioCodec=r=r?`${r},${a}`:a,kt.audio[r.substring(0,4)]=2,e.splice(n,1)):It(a,"video",i)&&(t.videoCodec=s=s?`${s},${a}`:a,kt.video[s.substring(0,4)]=2,e.splice(n,1))}}}));const{AUDIO:m=[],SUBTITLES:p,"CLOSED-CAPTIONS":v}=Hi.parseMasterPlaylistMedia(n,a,o);if(m.length){m.some((t=>!t.url))||!c[0].audioCodec||c[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ci({}),bitrate:0,url:""}))}s.trigger(l.MANIFEST_LOADED,{levels:c,audioTracks:m,subtitles:p,captions:v,contentSteering:u,url:a,stats:e,networkDetails:r,sessionData:d,sessionKeys:h,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(t,e,i,s,n){const a=this.hls,{id:o,level:c,type:d}=i,h=hl(t,i),f=r(c)?c:r(o)?o:0,g=dl(i),m=Hi.parseLevelPlaylist(t.data,h,f,g,0,this.variableList);if(d===u){const t={attrs:new ci({}),bitrate:0,details:m,name:"",url:h};m.requestScheduled=e.loading.start+ar(m,0),a.trigger(l.MANIFEST_LOADED,{levels:[t],audioTracks:[],url:h,stats:e,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),i.levelDetails=m,this.handlePlaylistLoaded(m,t,e,i,s,n)}handleManifestParsingError(t,e,i,r,s){this.hls.trigger(l.ERROR,{type:a.NETWORK_ERROR,details:o.MANIFEST_PARSING_ERROR,fatal:e.type===u,url:t.url,err:i,error:i,reason:i.message,response:t,context:e,networkDetails:r,stats:s})}handleNetworkError(t,e,i=!1,r,s){let n=`A network ${i?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${t.type}`;t.type===c?n+=`: ${t.level} id: ${t.id}`:t.type!==d&&t.type!==h||(n+=` id: ${t.id} group-id: "${t.groupId}"`);const f=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let g=o.UNKNOWN,m=!1;const p=this.getInternalLoader(t);switch(t.type){case u:g=i?o.MANIFEST_LOAD_TIMEOUT:o.MANIFEST_LOAD_ERROR,m=!0;break;case c:g=i?o.LEVEL_LOAD_TIMEOUT:o.LEVEL_LOAD_ERROR,m=!1;break;case d:g=i?o.AUDIO_TRACK_LOAD_TIMEOUT:o.AUDIO_TRACK_LOAD_ERROR,m=!1;break;case h:g=i?o.SUBTITLE_TRACK_LOAD_TIMEOUT:o.SUBTITLE_LOAD_ERROR,m=!1}p&&this.resetInternalLoader(t.type);const v={type:a.NETWORK_ERROR,details:g,fatal:m,url:t.url,loader:p,context:t,error:f,networkDetails:e,stats:s};if(r){const i=(null==e?void 0:e.url)||t.url;v.response=b({url:i,data:void 0},r)}this.hls.trigger(l.ERROR,v)}handlePlaylistLoaded(t,e,i,r,s,n){const g=this.hls,{type:m,level:p,levelOrTrack:v,id:y,groupId:E,deliveryDirectives:T}=r,b=hl(e,r),S=dl(r);let A="number"==typeof r.level&&S===f?p:void 0;const L=t.playlistParsingError;if(L){if(this.hls.logger.warn(`${L} ${t.url}`),!g.config.ignorePlaylistParsingErrors)return void g.trigger(l.ERROR,{type:a.NETWORK_ERROR,details:o.LEVEL_PARSING_ERROR,fatal:!1,url:b,error:L,reason:L.message,response:e,context:r,level:A,parent:S,networkDetails:s,stats:i});t.playlistParsingError=null}if(t.fragments.length)switch(t.live&&n&&(n.getCacheAge&&(t.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),m){case u:case c:if(A)if(v){if(v!==g.levels[A]){const t=g.levels.indexOf(v);t>-1&&(A=t)}}else A=0;g.trigger(l.LEVEL_LOADED,{details:t,levelInfo:v||g.levels[0],level:A||0,id:y||0,stats:i,networkDetails:s,deliveryDirectives:T,withoutMultiVariant:m===u});break;case d:g.trigger(l.AUDIO_TRACK_LOADED,{details:t,track:v,id:y||0,groupId:E||"",stats:i,networkDetails:s,deliveryDirectives:T});break;case h:g.trigger(l.SUBTITLE_TRACK_LOADED,{details:t,track:v,id:y||0,groupId:E||"",stats:i,networkDetails:s,deliveryDirectives:T})}else{const n=t.playlistParsingError=new Error("No Segments found in Playlist");g.trigger(l.ERROR,{type:a.NETWORK_ERROR,details:o.LEVEL_EMPTY_ERROR,fatal:!1,url:b,error:n,reason:n.message,response:e,context:r,level:A,parent:S,networkDetails:s,stats:i})}}}class gl{static get version(){return $r}static isMSESupported(){return ol()}static isSupported(){return function(){if(!ol())return!1;const t=w();return"function"==typeof(null==t?void 0:t.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((e=>t.isTypeSupported(wt(e,"video"))))||["mp4a.40.2","fLaC"].some((e=>t.isTypeSupported(wt(e,"audio")))))}()}static getMediaSource(){return w()}static get Events(){return l}static get MetadataSchema(){return us}static get ErrorTypes(){return a}static get ErrorDetails(){return o}static get DefaultConfig(){return gl.defaultConfig?gl.defaultConfig:Wo}static set DefaultConfig(t){gl.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Ur,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const e=this.logger=function(t,e,i){const r=k();if("object"==typeof console&&!0===t||"object"==typeof t){const s=["debug","log","info","warn","error"];s.forEach((e=>{r[e]=R(e,t,i)}));try{r.log(`Debug logs enabled for "${e}" in hls.js version 1.6.15`)}catch(t){return k()}s.forEach((e=>{I[e]=R(e,t)}))}else E(I,r);return r}(t.debug||!1,"Hls instance",t.assetPlayerId),i=this.config=function(t,e,i){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==e.liveMaxLatencyDurationCount&&(void 0===e.liveSyncDurationCount||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==e.liveMaxLatencyDuration&&(void 0===e.liveSyncDuration||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const r=Yo(t),s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((t=>{const n=`${"level"===t?"playlist":t}LoadPolicy`,a=void 0===e[n],o=[];s.forEach((i=>{const s=`${t}Loading${i}`,l=e[s];if(void 0!==l&&a){o.push(s);const t=r[n].default;switch(e[n]={default:t},i){case"TimeOut":t.maxLoadTimeMs=l,t.maxTimeToFirstByteMs=l;break;case"MaxRetry":t.errorRetry.maxNumRetry=l,t.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":t.errorRetry.retryDelayMs=l,t.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":t.errorRetry.maxRetryDelayMs=l,t.timeoutRetry.maxRetryDelayMs=l}}})),o.length&&i.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${n}": ${re(e[n])}`)})),b(b({},r),e)}(gl.DefaultConfig,t,e);this.userConfig=t,i.progressive&&qo(i,e);const{abrController:r,bufferController:s,capLevelController:n,errorController:a,fpsController:o}=i,u=new a(this),c=this.abrController=new r(this),d=new Be(this),h=i.interstitialsController,f=h?this.interstitialsController=new h(this,gl):null,g=this.bufferController=new s(this,d),m=this.capLevelController=new n(this),p=new o(this),v=new fl(this),y=i.contentSteeringController,T=y?new y(this):null,S=this.levelController=new sl(this,T),A=new il(this),L=new ul(this.config,this.logger),_=this.streamController=new ll(this,d,L),w=this.gapController=new zo(this,d);m.setStreamController(_),p.setStreamController(_);const P=[v,S,_];f&&P.splice(1,0,f),T&&P.splice(1,0,T),this.networkControllers=P;const D=[c,g,w,m,p,A,d];this.audioTrackController=this.createController(i.audioTrackController,P);const C=i.audioStreamController;C&&P.push(this.audioStreamController=new C(this,d,L)),this.subtitleTrackController=this.createController(i.subtitleTrackController,P);const O=i.subtitleStreamController;O&&P.push(this.subtititleStreamController=new O(this,d,L)),this.createController(i.timelineController,D),L.emeController=this.emeController=this.createController(i.emeController,D),this.cmcdController=this.createController(i.cmcdController,D),this.latencyController=this.createController(rl,D),this.coreComponents=D,P.push(u);const x=u.onErrorOut;"function"==typeof x&&this.on(l.ERROR,x,u),this.on(l.MANIFEST_LOADED,v.onManifestLoaded,v)}createController(t,e){if(t){const i=new t(this);return e&&e.push(i),i}return null}on(t,e,i=this){this._emitter.on(t,e,i)}once(t,e,i=this){this._emitter.once(t,e,i)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,e,i=this,r){this._emitter.off(t,e,i,r)}listeners(t){return this._emitter.listeners(t)}emit(t,e,i){return this._emitter.emit(t,e,i)}trigger(t,e){if(this.config.debug)return this.emit(t,t,e);try{return this.emit(t,t,e)}catch(e){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+e.message+'". Here is a stacktrace:',e),!this.triggeringException){this.triggeringException=!0;const i=t===l.ERROR;this.trigger(l.ERROR,{type:a.OTHER_ERROR,details:o.INTERNAL_EXCEPTION,fatal:i,event:t,error:e}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger(l.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach((t=>t.destroy())),this.networkControllers.length=0,this.coreComponents.forEach((t=>t.destroy())),this.coreComponents.length=0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){if(!t||"media"in t&&!t.media){const e=new Error(`attachMedia failed: invalid argument (${t})`);return void this.trigger(l.ERROR,{type:a.OTHER_ERROR,details:o.ATTACH_MEDIA_ERROR,fatal:!0,error:e})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const e="media"in t,i=e?t.media:t,r=e?t:{media:i};this._media=i,this.trigger(l.MEDIA_ATTACHING,r)}detachMedia(){this.logger.log("detachMedia"),this.trigger(l.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger(l.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const e=this.media,i=this._url,r=this._url=H.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),e&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(e)),this.trigger(l.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(t=-1,e){this.logger.log(`startLoad(${t+(e?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(t,e),this.started&&this.networkControllers);i++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let t=0;t<this.networkControllers.length&&(this.networkControllers[t].stopLoad(),!this.started&&this.networkControllers);t++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach((t=>{t.resumeBuffering&&t.resumeBuffering()})))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach((t=>{t.pauseBuffering&&t.pauseBuffering()})))}get inFlightFragments(){const t={[f]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[g]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[m]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const t=this._media,e=null==t?void 0:t.currentTime;this.detachMedia(),t&&(this.attachMedia(t),e&&this.startLoad(e))}removeLevel(t){this.levelController.removeLevel(t)}get sessionId(){let t=this._sessionId;return t||(t=this._sessionId=function(){try{return crypto.randomUUID()}catch(t){try{const t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}catch(t){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(t=>{const i=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?i:3&i|8).toString(16)}))}}}()),t}get levels(){const t=this.levelController.levels;return t||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){this.logger.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){this.logger.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){this.logger.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){this.logger.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return-1===t&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){this.logger.log(`set startLevel:${t}`),-1!==t&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const e=!!t;e!==this.config.capLevelToPlayerSize&&(e?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=e)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get abrEwmaDefaultEstimate(){const{bwEstimator:t}=this.abrController;return t?t.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(this.logger.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){(function(t){return Yt.indexOf(t)>-1})(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:e}}=this;if(!t)return 0;const i=t.length;for(let r=0;r<i;r++)if(t[r].maxBitrate>=e)return r;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:i}=this;let r;if(r=-1===e&&null!=t&&t.length?t.length-1:e,i)for(let e=r;e--;){const r=t[e].attrs["HDCP-LEVEL"];if(r&&r<=i)return e}return r}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(t){var e;return(null==(e=this.audioTrackController)?void 0:e.setAudioOption(t))||null}setSubtitleOption(t){var e;return(null==(e=this.subtitleTrackController)?void 0:e.setSubtitleOption(t))||null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const e=this.audioTrackController;e&&(e.audioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return!!t&&t.subtitleDisplay}set subtitleDisplay(t){const e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(t){this.latencyController.targetLatency=t}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(t){this.levelController.pathwayPriority=t}get bufferedToEnd(){var t;return!(null==(t=this.bufferController)||!t.bufferedToEnd)}get interstitialsManager(){var t;return(null==(t=this.interstitialsController)?void 0:t.interstitialsManager)||null}getMediaDecodingInfo(t,e=this.allAudioTracks){return jt(t,ne(e),navigator.mediaCapabilities)}}gl.defaultConfig=void 0},(t,e,i)=>{i.d(e,{setup:()=>l,teardown:()=>u});var r=i(270),s=i(272),n=i(227),a=(0,s.makeCacheable)("bandwidth_tracking"),o=(0,s.makeNamespace)("bandwidth_tracking"),l=function(t){var e=t.hls,i=a(t,"persistBandwidthEstimate",(function(){return function(){var t=e.abrController.bwEstimator.getEstimate();(0,n.setOrGet)("hls.bandwidth_estimate",t)}}));e.off(r.default.Events.FRAG_LOADED,i),e.on(r.default.Events.FRAG_LOADED,i)},u=function(t){o(t).persistBandwidthEstimate&&t.hls&&t.hls.off(r.default.Events.FRAG_LOADED,o(t).persistBandwidthEstimate),(0,s.uncacheNamespace)("bandwidth_tracking",t)}},(t,e,i)=>{i.d(e,{makeCacheable:()=>r,makeNamespace:()=>s,uncacheNamespace:()=>u});var r=function(t){return function(e,i,r){if(o(t,e),n(t,e,i))return a(t,e,i);var s=r();return l(t,e,i,s),s}},s=function(t){return function(e){return null==e[t]&&(e[t]={}),e[t]}},n=function(t,e,i){return null!=a(t,e,i)},a=function(t,e,i){return o(t,e),e[t][i]},o=function(t,e){null==e[t]&&(e[t]={})},l=function(t,e,i,r){o(t,e),e[t][i]=r},u=function(t,e){e[t]={}}},(t,e,i)=>{i.d(e,{setup:()=>u,teardown:()=>d});var r=i(270),s=i(12),n=i(272),a=s.wlog.getPrefixedFunctions("hls_video"),o=(0,n.makeCacheable)("dynamic_max_max_buffer"),l=(0,n.makeNamespace)("dynamic_max_max_buffer"),u=function(t){var e=t.hls,i=o(t,"onFragLoaded",(function(){return function(){c(t)}}));e.off(r.default.Events.FRAG_LOADED,i),e.on(r.default.Events.FRAG_LOADED,i)},c=function(t){var e=t.hls;t.attributes.maxMaxBufferLength&&(e.config.maxMaxBufferLength=t.attributes.maxMaxBufferLength);var i=e.levels[e.currentLevel];i&&e.abrController.bwEstimator.getEstimate()*e.config.abrBandWidthFactor<i.attrs.BANDWIDTH&&(e.manualLevel>=0||0===e.currentLevel?(a.info("set maxMaxBufferLength",t.getDuration()),e.config.maxMaxBufferLength=t.getDuration()):(a.info("set maxMaxBufferLength",60),e.config.maxMaxBufferLength=60))},d=function(t){l(t).onFragLoaded&&t.hls&&t.hls.off(r.default.Events.FRAG_LOADED,l(t).onFragLoaded),(0,n.uncacheNamespace)("dynamic_max_max_buffer",t)}},(t,e,i)=>{i.d(e,{setup:()=>f,teardown:()=>S});var r=i(270),s=i(75),n=i(4),a=i(12),o=i(226),l=i(272),u=(0,l.makeCacheable)("error_handling"),c=(0,l.makeNamespace)("error_handling"),d=a.wlog.getPrefixedFunctions("hls error_handling"),h=0,f=function(t){var e=u(t,"onError",(function(){return function(e,i){g(t,e,i)}}));t.hls.on(r.default.Events.ERROR,e);var i=u(t,"onEmergencyAbortLoad",(function(){return function(){v(t)}}));t.hls.on(r.default.Events.FRAG_LOAD_EMERGENCY_ABORTED,i)},g=function(t,e,i){i.fatal&&m(t,e,i);var r="player/hlsjs/error/".concat(i.details);y(t,r,i)},m=function(t,e,i){var n,o,l=t.hls,u=t.attributes;if(h+=1,i.type===r.default.ErrorTypes.MEDIA_ERROR)a.wlog.info("hlsjsplugin - Fatal media error encountered, try to recover"),c(t).countedRecoverMediaError||(c(t).countedRecoverMediaError=!0,y(t,"player/hls/recover_media_error")),t.isChangingVideo()||i.details===r.default.ErrorDetails.BUFFER_STALLED_ERROR&&l.startLoad(),d.error("trying to recover from media error..."),n=t.getCurrentTime(),3===h?((0,s.clearTimeouts)("".concat(t.uuid,".nudge_if_not_playing")),l.destroy(),t.trigger("fatalerrorrebuild")):(l.recoverMediaError(),o=null!=u.bufferStallRecoveryTimeout?u.bufferStallRecoveryTimeout:1e3,(0,s.doTimeout)("".concat(t.uuid,".nudge_if_not_playing"),(function(){"playing"!==t.getPlaybackMode()?(d.error("trying to nudge 0.5 seconds..."),t.seek(t.getCurrentTime()+.5).then((function(){t.play()}))):t.getCurrentTime()!==n&&d.error("video is playing; recoverMediaError() succeeded")}),o));else y(t,"player/playback-error"),y(t,"player/hls/fatal",{errorType:i.type,errorDetails:i.details,errorInfo:i}),a.wlog.info("hlsjsplugin - Fatal error - cannot recover",e,i),l.destroy()},p=[100,500,1500,3e3,6e3],v=function(t){for(var e=function(){var e=t.hls;e&&e.startLoad()},i=0;i<p.length;i++){var r=p[i];(0,s.doTimeout)("".concat(t.uuid,".hls.start_load_on_stall_").concat(r),e,r)}},y=function(t,e,i){i=b(t,(0,n.merge)({at:t.getCurrentTime()},i)),t.attributes.liveMedia&&o.count("live_stream/".concat(e),1,i),o.count(e,1,i),E(t,e)},E=function(t,e){T(t),c(t).metricsCounted[e]=!0},T=function(t){null==c(t).metricsCounted&&(c(t).metricsCounted={})},b=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i={hlsVideo:t.diagnosticData()};return i.locationHref=location.href,top!==self&&(i.referrer=document.referrer,i.inIframe=!0),(0,n.merge)(i,e)},S=function(t){c(t).onError&&t.hls&&t.hls.off(r.default.Events.ERROR,c(t).onError),c(t).onEmergencyAbortLoad&&t.hls&&t.hls.off(r.default.Events.ERROR,c(t).onEmergencyAbortLoad),(0,l.uncacheNamespace)("error_handling",t)}},(t,e,i)=>{i.d(e,{allHlsAudioAssets:()=>l,allMp4VideoAssets:()=>u,audioTracksForVideo:()=>c,buildMasterM3u8Asset:()=>d,multivariantM3u8Url:()=>o,rejectAudioAsset:()=>h});var r=i(61),s=i(4),n=i(25),a=(0,i(9).cachedDetect)(),o=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(t.attributes.liveMedia)return t.mediaData.liveStreamEventDetails.manifestUrl;var i=t.attributes,r=i.allowHdr,s=i.authorization,o=i.bitDepth,l=i.channelId,u=i.channelPassword,c=i.clipForPoster,d=i.clipFrom,h=i.clipTo,f=i.codec,g=i.deliveryCdn,m=i.disallowOriginalFilePlayback,p=i.forceInstantHls,v=i.forceOriginalFilePlayback,y=(i.includeExtendedAudioDescription,i.password),E=i.qualityMax,T=i.qualityMin,b=i.startPosition,S=e.qualityMin||T,A=e.qualityMax||E,L=function(t){var e,i=t.mediaData,r=t.attributes,s="".concat((0,n.eV1Protocol)(),"//").concat((0,n.cdnFastWistiaComHost)(r.embedHost)),a="".concat((0,n.eV1Protocol)(),"//").concat((0,n.cdnFastProtectedWistiaComHost)(r.assetHost));return i.protected&&null!==(e=r.authorization)&&void 0!==e&&e.jwt?new URL("".concat(a,"/embed/accounts/").concat(i.accountId,"/medias/").concat(i.hashedId,".m3u8")):new URL("".concat(s,"/embed/medias/").concat(i.hashedId,".m3u8"))}(t);return"HlsVideo"!==(null==t?void 0:t.name)&&(S&&L.searchParams.set("quality_min",S),A&&L.searchParams.set("quality_max",A)),m&&L.searchParams.set("disallow_original_file_playback",m),g&&L.searchParams.set("delivery_cdn",g),b&&-1!==b&&L.searchParams.set("start_position",b),c&&null!=d&&h&&(L.searchParams.set("clip_to",h),L.searchParams.set("clip_from",d)),p&&L.searchParams.set("force_instant_hls",!0),v&&L.searchParams.set("force_original_file_playback",!0),r&&a.hdr&&L.searchParams.set("allow_hdr",!0),o&&(Array.isArray(o)?o.forEach((function(t){L.searchParams.append("bit_depth[]",t)})):L.searchParams.set("bit_depth",o)),f&&(Array.isArray(f)?f.forEach((function(t){L.searchParams.append("codec[]",t)})):L.searchParams.set("codec",f)),null!=s&&s.jwt&&L.searchParams.set("pma",s.jwt),y&&L.searchParams.set("password",y),l&&u&&(L.searchParams.set("channel_id",l),L.searchParams.set("channel_password",u)),L.toString()},l=function(t){return(0,r.filter)(t,{type:"mp4_alternate_audio",status:r.READY})},u=function(t){return(0,r.filter)(t,{container:"mp4",status:r.READY,public:!0,metadata:function(t){return Object(t).max_bitrate},type:/\b(?!captioned_video)\S+/}).sort((function(t,e){return(t.metadata.max_bitrate||0)-(e.metadata.max_bitrate||0)}))},c=function(t){var e=[{audioCodec:void 0,autoselect:!0,default:!0,forced:!1,groupId:"audio",id:0,lang:void 0,name:"Off",label:"Original",type:"AUDIO",isSelected:!0}];return t.forEach((function(t,i){var r,s,n,a={audioCodec:void 0,autoselect:!1,default:!1,forced:!1,groupId:"audio",id:i+1,lang:void 0,name:(null===(r=t.details)||void 0===r?void 0:r.languageMetadata.name)||"Alt Audio",label:(null===(s=t.details)||void 0===s?void 0:s.languageMetadata.name)||"Alt Audio",type:"AUDIO",isSelected:!1};!0===(null===(n=t.details)||void 0===n?void 0:n.audioDescription)&&(a.characteristics="public.accessibility.describes-video"),e.push(a)})),e},d=function(t){return{bitrate:"variable",ext:"m3u8",height:"variable",public:!0,size:"variable",type:"hls_video",url:t,width:"variable",slug:"hls_master_m3u8_seg3s"}},h=function(t,e){return(0,s.filter)(e,(function(t){return"Audio"!=t.display_name}))}},(t,e,i)=>{i.d(e,{setup:()=>u,teardown:()=>c});var r=i(270),s=i(12),n=i(272),a=s.wlog.getPrefixedFunctions("hls_video"),o=(0,n.makeCacheable)("track_stream_changes"),l=(0,n.makeNamespace)("track_stream_changes"),u=function(t){var e=t.hls;l(t).lastLevel=null,l(t).lastAutoLevel=null,l(t).substreamIndex=0;var i=o(t,"onFragChanged",(function(){return function(e,i){if(i.frag.level!==t._lastLevel||i.frag.autoLevel!=t._lastAutoLevel){var r=t.hls.levels[i.frag.level];l(t).lastLevel=i.frag.level,l(t).lastAutoLevel=i.frag.autoLevel,l(t).substreamIndex+=1,i.frag.level>=0?a.notice("frag switch to",r,"at",t.getCurrentTime()):a.notice("frag switch to Auto at",t.getCurrentTime())}}}));e.off(r.default.Events.FRAG_CHANGED,i),e.on(r.default.Events.FRAG_CHANGED,i);var s=o(t,"onAudioSwitching",(function(){return function(e,i){t.trigger("audiostreamchange"),i.id>0?a.notice("audio asset switch to track: ",i.id,"at",t.lastBufferedTime()):a.notice("level switch to original encoded audio at",t.lastBufferedTime())}}));e.off(r.default.Events.AUDIO_TRACK_SWITCHING,s),e.on(r.default.Events.AUDIO_TRACK_SWITCHING,s);var n=o(t,"onLevelSwitching",(function(){return function(e,i){if(i.level>=0){var r=t.hls.levels[i.level];a.notice("level switch to",r,"at",t.lastBufferedTime())}else a.notice("level switch to Auto at",t.lastBufferedTime())}}));e.off(r.default.Events.LEVEL_SWITCHING,n),e.on(r.default.Events.LEVEL_SWITCHING,n)},c=function(t){l(t).onFragChanged&&t.hls&&t.hls.off(r.default.Events.FRAG_CHANGED,l(t).onFragChanged),l(t).onLevelSwitch&&t.hls&&t.hls.off(r.default.Events.LEVEL_SWITCHING,l(t).onLevelSwitching),(0,n.uncacheNamespace)("track_stream_changes",t)}},(t,e,i)=>{i.d(e,{default:()=>x});var r=i(15),s=i(4),n=i(61),a=i(28),o=i(278),l=i(279),u=i(280),c=i(285),d=i(286),h=i(282),f=i(291),g=i(281),m=i(292),p=i(293),v=i(287),y=i(295),E=i(284),T=i(296),b=i(283),S=i(297);function A(){var t,e,i="function"==typeof Symbol?Symbol:{},r=i.iterator||"@@iterator",s=i.toStringTag||"@@toStringTag";function n(i,r,s,n){var l=r&&r.prototype instanceof o?r:o,u=Object.create(l.prototype);return L(u,"_invoke",function(i,r,s){var n,o,l,u=0,c=s||[],d=!1,h={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,i){return n=e,o=0,l=t,h.n=i,a}};function f(i,r){for(o=i,l=r,e=0;!d&&u&&!s&&e<c.length;e++){var s,n=c[e],f=h.p,g=n[2];i>3?(s=g===r)&&(l=n[(o=n[4])?5:(o=3,3)],n[4]=n[5]=t):n[0]<=f&&((s=i<2&&f<n[1])?(o=0,h.v=r,h.n=n[1]):f<g&&(s=i<3||n[0]>r||r>g)&&(n[4]=i,n[5]=r,h.n=g,o=0))}if(s||i>1)return a;throw d=!0,r}return function(s,c,g){if(u>1)throw TypeError("Generator is already running");for(d&&1===c&&f(c,g),o=c,l=g;(e=o<2?t:l)||!d;){n||(o?o<3?(o>1&&(h.n=-1),f(o,l)):h.n=l:h.v=l);try{if(u=2,n){if(o||(s="next"),e=n[s]){if(!(e=e.call(n,l)))throw TypeError("iterator result is not an object");if(!e.done)return e;l=e.value,o<2&&(o=0)}else 1===o&&(e=n.return)&&e.call(n),o<2&&(l=TypeError("The iterator does not provide a '"+s+"' method"),o=1);n=t}else if((e=(d=h.n<0)?l:i.call(r,h))!==a)break}catch(e){n=t,o=1,l=e}finally{u=1}}return{value:e,done:d}}}(i,s,n),!0),u}var a={};function o(){}function l(){}function u(){}e=Object.getPrototypeOf;var c=[][r]?e(e([][r]())):(L(e={},r,(function(){return this})),e),d=u.prototype=o.prototype=Object.create(c);function h(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,u):(t.__proto__=u,L(t,s,"GeneratorFunction")),t.prototype=Object.create(d),t}return l.prototype=u,L(d,"constructor",u),L(u,"constructor",l),l.displayName="GeneratorFunction",L(u,s,"GeneratorFunction"),L(d),L(d,s,"Generator"),L(d,r,(function(){return this})),L(d,"toString",(function(){return"[object Generator]"})),(A=function(){return{w:n,m:h}})()}function L(t,e,i,r){var s=Object.defineProperty;try{s({},"",{})}catch(t){s=0}L=function(t,e,i,r){function n(e,i){L(t,e,(function(t){return this._invoke(e,i,t)}))}e?s?s(t,e,{value:i,enumerable:!r,configurable:!r,writable:!r}):t[e]=i:(n("next",0),n("throw",1),n("return",2))},L(t,e,i,r)}function k(t,e,i,r,s,n,a){try{var o=t[n](a),l=o.value}catch(t){return void i(t)}o.done?e(l):Promise.resolve(l).then(r,s)}function R(t,e){for(var i=0;i<e.length;i++){var r=e[i];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,I(r.key),r)}}function I(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var r=i.call(t,e||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}function _(t,e,i){return e=D(e),function(t,e){if(e&&("object"==typeof e||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}(t,w()?Reflect.construct(e,i||[],D(t).constructor):e.apply(t,i))}function w(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(t){}return(w=function(){return!!t})()}function P(){return P="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(t,e,i){var r=function(t,e){for(;!{}.hasOwnProperty.call(t,e)&&null!==(t=D(t)););return t}(t,e);if(r){var s=Object.getOwnPropertyDescriptor(r,e);return s.get?s.get.call(arguments.length<3?t:i):s.value}},P.apply(null,arguments)}function D(t){return D=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},D(t)}function C(t,e){return C=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},C(t,e)}var O=function(t){function e(t,i,r,s){var n;return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),(n=_(this,e,[t,i,r,s])).uuid=(0,a.seqId)("wistia_simple_video_"),n.root=t,n.state={},n.name="SimpleVideo",v.setupProperties(n,i,r||{}),s?v.fromOtherEngine(n,s):v.injectVideo(n),f.fixWebkitControlsBug(n),v.setupBindingsAndLoops(n),m.fit(n),n}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&C(t,e)}(e,t),i=e,r=[{key:"addTextTracks",value:function(t){(0,S.addTextTracks)(t,this.video)}},{key:"activeBufferRange",value:function(){return l.activeBufferRange(this)}},{key:"anyBuffered",value:function(){return l.anyBuffered(this)}},{key:"cancelFullscreen",value:function(){return h.cancelFullscreen(this)}},{key:"captureCurrentFrame",value:function(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];return h.captureCurrentFrame.apply(h,[this].concat(e))}},{key:"changeQuality",value:function(t){return d.changeQuality(this,t)}},{key:"changeStream",value:function(t){return d.changeStream(this,t)}},{key:"changeStreamWithoutLoad",value:function(t){return d.changeStreamWithoutLoad(this,t)}},{key:"changeVideo",value:function(t,e){return d.changeVideo(this,t,e)}},{key:"currentAsset",value:function(){return this._currentAsset}},{key:"defaultAsset",value:function(){return this.selectableAssets()[0]}},{key:"destroy",value:function(){var t,i,r,s,n,a=this.state||{};this.state={eventContext:a.eventContext,destroyed:!0,issuedPlay:a.issuedPlay},v.killBindingsAndStopLoops(this),(t=e,i="destroy",r=this,n=P(D(1&(s=3)?t.prototype:t),i,r),2&s&&"function"==typeof n?function(t){return n.apply(r,t)}:n)([])}},{key:"diagnosticData",value:function(){return p.getDiagnosticData(this)}},{key:"eventContext",value:function(){return this.state.eventContext}},{key:"fit",value:function(){return m.fit(this)}},{key:"hasIssuedPlay",value:function(){return!!this.state.issuedPlay}},{key:"getAudioTracks",value:(T=A().m((function t(){return A().w((function(t){for(;;)if(0===t.n)return t.a(2,Promise.resolve([]))}),t)})),L=function(){var t=this,e=arguments;return new Promise((function(i,r){var s=T.apply(t,e);function n(t){k(s,i,r,n,a,"next",t)}function a(t){k(s,i,r,n,a,"throw",t)}n(void 0)}))},function(){return L.apply(this,arguments)})},{key:"getCurrentQuality",value:function(){var t=this.currentAsset();if(t)return"hdr_video"===t.type?"".concat((0,n.numericSizeSnapped)(t.width,t.height)," (HDR)"):(0,n.numericSizeSnapped)(t.width,t.height);var e=this.selectedAsset();return e?(0,n.numericSizeSnapped)(e.width,e.height):"?"}},{key:"getCurrentTime",value:function(){return h.getCurrentTime(this)}},{key:"getCuts",value:function(){return(0,b.getCuts)(this)}},{key:"getDuration",value:function(){return h.getDuration(this)}},{key:"getMediaElement",value:function(){return this.video}},{key:"getMediaType",value:function(){return this.mediaData.mediaType}},{key:"getPlaybackMode",value:function(){return g.getPlaybackMode(this)}},{key:"getPlaybackRate",value:function(){return h.getPlaybackRate(this)}},{key:"getPreload",value:function(){return h.getPreload(this)}},{key:"getState",value:function(){return h.getState(this)}},{key:"getDurationBeforeCuts",value:function(){return(0,b.getDurationBeforeCuts)(this)}},{key:"getTimeAfterCuts",value:function(t){return(0,b.getTimeAfterCuts)(this,t)}},{key:"getTimeBeforeCuts",value:function(t){return(0,b.getTimeBeforeCuts)(this,t)}},{key:"getTrim",value:function(){return(0,E.getTrim)(this)}},{key:"getVolume",value:function(){return h.getVolume(this)}},{key:"isChangingVideo",value:function(){return d.isChangingVideo(this)}},{key:"isInFullscreen",value:function(){return h.isInFullscreen(this)}},{key:"isInitializingFromUnmuted",value:function(){return h.isInitializingFromUnmuted(this)}},{key:"isMuted",value:function(){return h.isMuted(this)}},{key:"isSeeking",value:function(){return u.isSeeking(this)}},{key:"isSourceOfBrowserEvent",value:function(t){return h.isSourceOfBrowserEvent(this,t)}},{key:"lastBufferedTime",value:function(t){return l.lastBufferedTime(this,t)}},{key:"loadSource",value:function(){var t=this.currentAsset();t&&this.changeStream(t)}},{key:"mute",value:function(){return h.mute(this)}},{key:"onEnterFullscreen",value:function(){return h.onEnterFullscreen(this)}},{key:"onHeightChange",value:function(t){return m.onHeightChange(this,t)}},{key:"onLeaveFullscreen",value:function(){return h.onLeaveFullscreen(this)}},{key:"onReady",value:function(){return c.onReady(this)}},{key:"onWidthChange",value:function(t){return m.onWidthChange(this,t)}},{key:"pause",value:function(){return h.pause(this)}},{key:"play",value:function(t){return h.play(this,t)}},{key:"playType",value:function(){return h.playType(this)}},{key:"removeTextTracks",value:function(t){(0,S.removeTextTracks)(t,this.video)}},{key:"requestFullscreen",value:function(){return h.requestFullscreen(this)}},{key:"reset",value:function(){this.state={}}},{key:"seek",value:function(t,e){return u.seek(this,t,e)}},{key:"seekOnPlay",value:function(t){return u.seekOnPlay(this,t)}},{key:"selectedAsset",value:function(){return this._currentAsset}},{key:"selectableAssets",value:function(){return this.allAssets}},{key:"selectableQualities",value:function(){return this.selectableAssets().map((function(t){return"variable"===t.width?t.slug:"hdr_video"===t.type?"".concat((0,n.numericSizeSnapped)(t.width,t.height)," (HDR)"):(0,n.numericSizeSnapped)(t.width,t.height)})).sort((function(t,e){return("auto"===t?-1:t)-("auto"===e?-1:e)}))}},{key:"selectedQuality",value:function(){var t=this.selectedAsset();return t?"hdr_video"===t.type?"".concat((0,n.numericSizeSnapped)(t.width,t.height)," (HDR)"):(0,n.numericSizeSnapped)(t.width,t.height):"?"}},{key:"sequentialBufferedRange",value:function(){return l.sequentialBufferedRange(this)}},{key:"setAttributes",value:function(t){(0,s.assign)(this.attributes,t)}},{key:"onMediaDataChanged",value:function(){}},{key:"onPlayed",value:function(){var t=this,e=this.state;return e&&e.hasPlayed?Promise.resolve():new Promise((function(e){var i=function(){t.unbind("playing",i),e()};t.bind("playing",i)}))}},{key:"setCurrentTime",value:function(t){return h.setCurrentTime(this,t)}},{key:"setCuts",value:function(t){return(0,E.setCuts)(this,t)}},{key:"setPlaybackRate",value:function(t){return h.setPlaybackRate(this,t)}},{key:"setTrim",value:function(t){return(0,E.setTrim)(this,t)}},{key:"setVolume",value:function(t){return h.setVolume(this,t)}},{key:"showFirstFrame",value:function(){return u.seek(this,.01)}},{key:"canDownloadMedia",value:function(){return!0}},{key:"stopStreaming",value:function(){return d.stopStreaming(this)}},{key:"timeBeforeEndOfBuffer",value:function(t){return l.timeBeforeEndOfBuffer(this,t)}},{key:"totalBuffered",value:function(){return l.totalBuffered(this)}},{key:"totalPlayed",value:function(){return o.sumTimeRanges(this.video.played)}},{key:"unmute",value:function(){return h.unmute(this)}},{key:"updateStartPosition",value:function(){}}],r&&R(i.prototype,r),y&&R(i,y),Object.defineProperty(i,"prototype",{writable:!1}),i;var i,r,y,T,L}(i(298).PlaybackEngine);(0,r.bindify)(O.prototype),O.delegatePublicMethods=y.delegatePublicMethods,O.PUBLIC_METHODS=y.PUBLIC_METHODS,O.mediaDataWithAssets=function(t,e){var i=(0,s.clone)(t);return i.assets=(0,s.clone)(e),i},(0,T.default)("SimpleVideo",O);const x=O},(t,e,i)=>{i.d(e,{bufferedInfo:()=>m,createElement:()=>l,properAssetUrl:()=>p,setupVideoElemAttributes:()=>d,setupVideoElemStyles:()=>c,srcProtocolAndHost:()=>f,sumTimeRanges:()=>g});var r=i(3),s=i(26),n=i(61),a=i(25),o="".concat((0,a.eV1Protocol)(),"//").concat((0,a.eV1HostWithPort)(),"/assets/images/blank.gif"),l=function(t,e,i){var s={tagName:"video",id:t,crossorigin:"anonymous",style:{background:"transparent",display:"block",height:"100%",maxHeight:"none",maxWidth:"none",position:"static",visibility:"visible",width:"100%"}};return i.isWebComponentPlayer&&(s.style.aspectRatio=i.aspectRatio||"auto",!0===i.liveMedia&&(s.style.transform="scale(1.003)")),d((0,r.elemFromObject)(s),e,i)},u=function(t,e,i){null!=i&&!1!==i?!0===i?(t[e]=!0,t.setAttribute(e,"")):(t[e]=i,t.setAttribute(e,i)):(t[e]=!1,t.removeAttribute(e))},c=function(t,e){e.isWebComponentPlayer&&(t.style.aspectRatio=e.aspectRatio||"auto")},d=function(t,e,i){return i.poster?(t.poster=i.poster,t.setAttribute("poster",i.poster)):i.isWebComponentPlayer||(t.poster=o,t.setAttribute("poster",o)),u(t,"aria-label",i.name||"Video"),u(t,"src",p(e.url)),u(t,"controlslist",i.controlslist||"nodownload"),u(t,"playsinline",i.playsinline),u(t,"muted",i.muted),u(t,"loop",i.loop),u(t,"controls",null!=i.controls&&i.controls),u(t,"preload",i.preload||"none"),u(t,"type",h(e,i)),u(t,"x-webkit-airplay",null!=i.webkitAirplay?i.webkitAirplay:"allow"),null!=i.volume&&(t.volume=i.volume),i.disablePictureInPicture&&u(t,"disablePictureInPicture",i.disablePictureInPicture),null!=i.playbackRate&&(t.playbackRate=i.playbackRate),t},h=function(t,e){if(null!=e.contentType)return e.contentType;var i="video/".concat(t.ext);return e.spherical&&(i+=";dimension=360;"),i},f=function(t){if((0,n.isBakeryUrl)(t)){var e=new s.Url(t);if(e.protocol)return"".concat(e.protocol,"//").concat(e.host)}return"".concat((0,a.eV1Protocol)(),"//").concat((0,a.deliveryHost)((0,a.eV1Protocol)()))},g=function(t){if(null==t)return null;for(var e=0,i=0;i<t.length;i++)e+=t.end(i)-t.start(i);return e},m=function(t,e,i){var r,s,n,a,o,l=[];for(t.sort((function(t,e){var i=t.start-e.start;return i||e.end-t.end})),o=0;o<t.length;o++){var u=l.length;if(u){var c=l[u-1].end;t[o].start-c<i?t[o].end>c&&(l[u-1].end=t[o].end):l.push(t[o])}else l.push(t[o])}for(o=0,r=0,s=n=e;o<l.length;o++){var d=l[o].start,h=l[o].end;if(e+i>=d&&e<h)s=d,r=(n=h)-e;else if(e+i<d){a=d;break}}return{len:r,start:s,end:n,nextStart:a}},p=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"mp4";return(0,n.isBakeryUrl)(t)&&/\.bin$/.test(t)?"".concat(t.replace(/\.bin$/,""),"/file.").concat(e):t}},(t,e,i)=>{i.d(e,{activeBufferRange:()=>o,anyBuffered:()=>a,lastBufferedTime:()=>c,sequentialBufferedRange:()=>u,timeBeforeEndOfBuffer:()=>d,totalBuffered:()=>l});var r=i(12),s=i(278),n=r.wlog.getPrefixedFunctions("buffering"),a=function(t){var e=t.video;return e.buffered.length>0&&e.buffered.end(0)>0},o=function(t){for(var e=t.video,i=e.currentTime,r=0;r<e.buffered.length;r++){var s=e.buffered.start(r),n=e.buffered.end(r);if(s<=i&&i<n)return[s,n]}return null},l=function(t){return s.sumTimeRanges(t.video.buffered)},u=function(t){var e=t.video,i=e.buffered,r=null;try{for(var s=0;s<i.length;s++){var a=i.start(s)-.5,o=i.end(s)+.5;if(a<=e.currentTime&&e.currentTime<o){r=s;break}}if(null!=r){for(var l=r,u=r;u<i.length;u++){if(!(i.start(u)-.5<=i.end(l)+.5))break;l=u}return[i.start(r),i.end(l)]}return null}catch(t){return n.error(t),null}},c=function(t,e){return function(t,e,i){var r=t.video;if(r){var n,a=r.buffered,o=[];for(n=0;n<a.length;n++)o.push({start:a.start(n),end:a.end(n)});return s.bufferedInfo(o,e,i)}return{len:0,start:0,end:0,nextStart:void 0}}(t,t.getCurrentTime(),e).end},d=function(t,e){return c(t,e)-t.getCurrentTime()}},(t,e,i)=>{i.d(e,{isSeeking:()=>p,seek:()=>c,seekOnPlay:()=>g,seekWithoutCuts:()=>d});var r=i(4),s=i(3),n=i(12),a=i(281),o=i(282),l=i(283),u=n.wlog.getPrefixedFunctions("SimpleVideo"),c=function(t,e,i){var r=(0,l.getTimeBeforeCuts)(t,e);return d(t,r,i)},d=function(t,e,i){return u.info("seek",e),t.getPlaybackMode()===a.BEFORE_PLAY?h(t,e,i):f(t,e,i)},h=function(t,e){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},s=t.video;return u.info("seekBeforePlay",e),new Promise((function(n,a){u.info("time ".concat(e,": seek beforeplay"));var l="playing"===t.getPlaybackMode();s.style.visibility="hidden",(0,r.assign)(t.state,{seeking:!0}),u.info("time ".concat(e,": start stream by calling play")),(0,o.playWithoutCuts)(t).then((function(a){u.info("time ".concat(e,": jump to time after playing")),s.currentTime=e;var c=new Promise((function(r){l||!1===i.pause?(u.info("time: ".concat(e,": play after seek")),r()):(u.info("time: ".concat(e,": pause after seek")),(0,o.pause)(t).then(r))}));m(t).then((function(){return c})).then((function(){s.style.visibility="inherit",(0,r.assign)(t.state,{seeking:!1}),n(a)}))})).catch((function(e){s.style.visibility="inherit",(0,r.assign)(t.state,{seeking:!1}),a(e)}))}))},f=function(t,e){return u.info("seekNow",e),new Promise((function(i){u.info("seekNow: start",e),t.video.currentTime=e,(0,r.assign)(t.state,{seeking:!0}),m(t).then((function(){(0,r.assign)(t.state,{seeking:!1}),u.info("seekNow: resolve",e),i()}))}))},g=function(t,e){return new Promise((function(i){"playing"===t.getPlaybackMode()?f(t,e).then(i):t.bind("playing",(function(){return f(t,e).then(i),t.unbind}))}))},m=function(t){var e=t.video;return new Promise((function(t){e.seeking?(u.info("waiting for seek"),(0,s.elemBind)(e,"seeked",(function(){return u.info("seeked"),t(),s.elemUnbind}))):(u.info("no wait for seek"),t())}))},p=function(t){var e=t.state,i=t.video;return Boolean(e.seeking||i.seeking)}},(t,e,i)=>{i.d(e,{BEFORE_PLAY:()=>s,getPlaybackMode:()=>n});var r=i(12).wlog.getPrefixedFunctions("SimpleVideo"),s="beforeplay",n=function(t){var e=t.video;try{return t.state.hasPlayed?t.state.fakeEnded||e.ended?"ended":e.paused?"paused":"playing":s}catch(t){return r.warn(t),"unknown"}}},(t,e,i)=>{i.r(e),i.d(e,{cancelFullscreen:()=>V,captureCurrentFrame:()=>j,getCurrentTime:()=>A,getDuration:()=>P,getPlaybackRate:()=>w,getPreload:()=>O,getState:()=>L,getVolume:()=>R,isInFullscreen:()=>U,isInitializingFromUnmuted:()=>B,isMuted:()=>C,isSourceOfBrowserEvent:()=>D,mute:()=>x,onEnterFullscreen:()=>F,onHeightChange:()=>G,onLeaveFullscreen:()=>N,onWidthChange:()=>$,pause:()=>T,play:()=>v,playType:()=>E,playWithoutCuts:()=>y,requestFullscreen:()=>H,setCurrentTime:()=>b,setCurrentTimeWithoutCuts:()=>S,setPlaybackRate:()=>_,setVolume:()=>k,supportsPlaybackRate:()=>I,unmute:()=>M});var r=i(3),s=i(12),n=i(9),a=i(4),o=i(283),l=i(284);function u(){var t,e,i="function"==typeof Symbol?Symbol:{},r=i.iterator||"@@iterator",s=i.toStringTag||"@@toStringTag";function n(i,r,s,n){var l=r&&r.prototype instanceof o?r:o,u=Object.create(l.prototype);return c(u,"_invoke",function(i,r,s){var n,o,l,u=0,c=s||[],d=!1,h={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,i){return n=e,o=0,l=t,h.n=i,a}};function f(i,r){for(o=i,l=r,e=0;!d&&u&&!s&&e<c.length;e++){var s,n=c[e],f=h.p,g=n[2];i>3?(s=g===r)&&(l=n[(o=n[4])?5:(o=3,3)],n[4]=n[5]=t):n[0]<=f&&((s=i<2&&f<n[1])?(o=0,h.v=r,h.n=n[1]):f<g&&(s=i<3||n[0]>r||r>g)&&(n[4]=i,n[5]=r,h.n=g,o=0))}if(s||i>1)return a;throw d=!0,r}return function(s,c,g){if(u>1)throw TypeError("Generator is already running");for(d&&1===c&&f(c,g),o=c,l=g;(e=o<2?t:l)||!d;){n||(o?o<3?(o>1&&(h.n=-1),f(o,l)):h.n=l:h.v=l);try{if(u=2,n){if(o||(s="next"),e=n[s]){if(!(e=e.call(n,l)))throw TypeError("iterator result is not an object");if(!e.done)return e;l=e.value,o<2&&(o=0)}else 1===o&&(e=n.return)&&e.call(n),o<2&&(l=TypeError("The iterator does not provide a '"+s+"' method"),o=1);n=t}else if((e=(d=h.n<0)?l:i.call(r,h))!==a)break}catch(e){n=t,o=1,l=e}finally{u=1}}return{value:e,done:d}}}(i,s,n),!0),u}var a={};function o(){}function l(){}function d(){}e=Object.getPrototypeOf;var h=[][r]?e(e([][r]())):(c(e={},r,(function(){return this})),e),f=d.prototype=o.prototype=Object.create(h);function g(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,d):(t.__proto__=d,c(t,s,"GeneratorFunction")),t.prototype=Object.create(f),t}return l.prototype=d,c(f,"constructor",d),c(d,"constructor",l),l.displayName="GeneratorFunction",c(d,s,"GeneratorFunction"),c(f),c(f,s,"Generator"),c(f,r,(function(){return this})),c(f,"toString",(function(){return"[object Generator]"})),(u=function(){return{w:n,m:g}})()}function c(t,e,i,r){var s=Object.defineProperty;try{s({},"",{})}catch(t){s=0}c=function(t,e,i,r){function n(e,i){c(t,e,(function(t){return this._invoke(e,i,t)}))}e?s?s(t,e,{value:i,enumerable:!r,configurable:!r,writable:!r}):t[e]=i:(n("next",0),n("throw",1),n("return",2))},c(t,e,i,r)}function d(t,e,i,r,s,n,a){try{var o=t[n](a),l=o.value}catch(t){return void i(t)}o.done?e(l):Promise.resolve(l).then(r,s)}var h=s.wlog.getPrefixedFunctions("SimpleVideo"),f=(0,n.cachedDetect)(),g="play",m="play-silently",p="cannot-play",v=function(t,e){var i=(0,l.trimStartFromCuts)(t);return t.state.fakeEnded||t.video.currentTime<i?t.seek(0,{pause:!1}).then((function(i){return y(t,(0,a.merge)({},e,{playType:g}))})):y(t,e)},y=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=t.video,s=e.playType||E(t,e);return null==t.state.issuedPlay&&s!==p&&(t.state.issuedPlay=!0),new Promise((function(n,a){t.state.lastPlayRejected=!1;var o=t.getPlaybackMode();if(h.info("play: start",s),"playing"===o)h.info("play: already playing, resolve"),n(g);else if(s===p)a(new Error("Cannot issue play."));else{s===m&&t.mute(),t.trigger("beforeplay");var l=i.play();if(l&&l.then&&l.catch)l.then((function(){h.info("play: got",s,"resolve"),n(s)})).catch(function(){var r,o=(r=u().m((function r(o){var l,c;return u().w((function(r){for(;;)switch(r.p=r.n){case 0:if(h.notice(o),t.state.lastPlayRejected=!0,l=null!=e.silentAutoplay?e.silentAutoplay:t.attributes.silentAutoplay,s!==g||t.isMuted()||"allow"!==l&&null!=l){r.n=5;break}return t.mute(),r.p=1,r.n=2,i.play();case 2:h.info("play: got silent fallback, resolve"),n(m),r.n=4;break;case 3:r.p=3,c=r.v,t.unmute(),a(c);case 4:r.n=6;break;case 5:h.notice("play: rejected"),a(o);case 6:return r.a(2)}}),r,null,[[1,3]])})),function(){var t=this,e=arguments;return new Promise((function(i,s){var n=r.apply(t,e);function a(t){d(n,i,s,a,o,"next",t)}function o(t){d(n,i,s,a,o,"throw",t)}a(void 0)}))});return function(t){return o.apply(this,arguments)}}());else{setTimeout((function(){f.ios.version&&f.ios.version<10.1&&i.paused&&a(new Error("Video still paused after play issued."))}),10);t.bind("playing",(function(){return h.info("play: got playing, resolve"),n(s),r.elemUnbind}))}}}))},E=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("playing"===t.getPlaybackMode())return g;if(t.isInitializingFromUnmuted())return g;if((0,r.inUserEventContext)())return g;var i=t.attributes,s=null!=e.silentAutoplay?e.silentAutoplay:i.silentAutoplay;return!0===s?t.isMuted()?g:m:!1===s?g:"allow"===s||null==s?f.chrome||f.firefox||f.edge||(f.safari||f.ios.version&&f.ios.version>=12)||t.isMuted()?g:m:g},T=function(t){var e=t.video;return h.info("pause"),new Promise((function(t){h.info("pause: start"),e.pause(),(0,r.safeRequestAnimationFrame)((function(){h.info("pause: resolve"),t()}))}))},b=function(t,e){var i=(0,o.getTimeBeforeCuts)(t,e);return S(t,i)},S=function(t,e){h.info("setCurrentTime",e),t.video.currentTime=e},A=function(t){return(0,l.getCurrentTimeAfterCuts)(t)},L=function(t){return{playbackMode:t.getPlaybackMode(),currentTime:t.getCurrentTime(),volume:t.getVolume(),playbackRate:t.getPlaybackRate()}},k=function(t,e){h.info("setVolume",e),t.video.volume=e},R=function(t){return t.video.volume},I=function(t){return null!=t.video.playbackRate},_=function(t,e){h.info("setPlaybackRate",e),I(t)?t.video.playbackRate=e:h.info("playbackRate is not supported on",t.video)},w=function(t){return I(t)?t.video.playbackRate:1},P=function(t){return(0,l.getDurationAfterCuts)(t)},D=function(t,e){return e.target==t.video},C=function(t){var e=t.video;return!!(e.muted||t.state.loadedMetadata&&0===e.volume||t.state.hasPlayed&&e.audioTracks&&0===e.audioTracks.length)},O=function(t){return t.video.getAttribute("preload")},x=function(t){t.video.muted=!0,t.video.setAttribute("muted","muted")},M=function(t){t.video.muted=!1,t.video.removeAttribute("muted")},F=function(t){t.state.isInFullscreen=!0;var e=t.attributes.backgroundColor||"#000";t.video.style.backgroundColor=e},N=function(t){t.state.isInFullscreen=!1,t.video.style.backgroundColor="transparent",t.setAttributes({fitStrategy:t.state.fitStrategyBeforeFullscreen||"auto"}),delete t.state.fitStrategyBeforeFullscreen,t.fit()},B=function(t){var e=t.state;return e.isInitializingFromOtherEngine&&e.otherEnginePlayed&&!e.otherEngineWasMuted},U=function(t){return!!t.state.isInFullscreen},$=function(t){},G=function(t){},H=function(t){return t.state||(t.state={}),t.state.fitStrategyBeforeFullscreen=t.attributes.fitStrategy,t.setAttributes({fitStrategy:"contain"}),t.fit(),(0,r.elemRequestFullscreen)(t.video)},V=function(t){return t.setAttributes({fitStrategy:t.state.fitStrategyBeforeFullscreen||"auto"}),t.fit(),(0,r.elemCancelFullscreen)(t.video)},j=function(t){var e=t.video,i=document.createElement("canvas");i.width=e.videoWidth,i.height=e.videoHeight,i.getContext("2d").drawImage(e,0,0,i.width,i.height);for(var r=arguments.length,s=new Array(r>1?r-1:0),n=1;n<r;n++)s[n-1]=arguments[n];return i.toDataURL.apply(i,s)}},(t,e,i)=>{function r(t){return function(t){if(Array.isArray(t))return s(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||function(t,e){if(t){if("string"==typeof t)return s(t,e);var i={}.toString.call(t).slice(8,-1);return"Object"===i&&t.constructor&&(i=t.constructor.name),"Map"===i||"Set"===i?Array.from(t):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?s(t,e):void 0}}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function s(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,r=Array(e);i<e;i++)r[i]=t[i];return r}i.d(e,{getCurrentTimeAfterCuts:()=>u,getCuts:()=>d,getDurationAfterCuts:()=>a,getDurationBeforeCuts:()=>n,getTimeAfterCuts:()=>l,getTimeBeforeCuts:()=>o});var n=function(t){var e=t.attributes;return null!=e.duration?e.duration:t.video.readyState>=2?t.video.duration:null},a=function(t){var e=d(t),i=n(t);if(e.length<1)return i;var r=i;return e.forEach((function(t){r-=t.end-t.start})),r},o=function(t,e){var i=n(t),r=d(t),s=0,a=0,o=0;return r.forEach((function(t){var i=t.start-a;if((o+=i)<=e+s){var r=t.end-t.start;s+=r,o+=r}a=t.end})),Math.min(i,e+s)},l=function(t,e){var i=d(t);if(i.length<1)return e;var r=e;return i.forEach((function(t){t.start<=e&&(r-=Math.min(e,t.end)-t.start)})),Math.max(0,r)},u=function(t){return l(t,t.video.currentTime)},c=Object.freeze([]),d=function(t){var e=t.attributes,i=e.cuts,r=e.trimStart,s=e.trimEnd;if(t._cuts&&i===t._rawCuts)return t._cuts;if(!i&&null==r&&null==s)return c;t._rawCuts=i,t._cuts=h(t);var n={start:t.attributes.trimStart,end:t.attributes.trimEnd};return t._cuts=f(t,n,t._cuts),Object.freeze(t._cuts),t._cuts},h=function(t){var e=n(t),i=t.attributes,r=i.cuts,s=i.trimStart,a=i.trimEnd;if(!r)return[];var o=r.map((function(i){var r=null!=i.start?g(t,i.start):0,s=null!=i.end&&-1!==i.end?g(t,i.end):e;return s>r?{start:r,end:s}:null})).filter(Boolean);null!=s&&o.push({start:0,end:s}),null!=a&&o.push({start:a,end:e}),o=o.sort((function(t,e){return t.start-e.start}));var l={start:0,end:0};return o=o.map((function(t){return t.end<l.end?null:(t.start<l.end&&(t.start=l.end),l=t,t)})).filter(Boolean)},f=function(t,e,i){var s=r(i),a=n(t),o=e.start,l=e.end,u=s[0],c=s[s.length-1],d=u&&(0===u.start||u.start<0)?u:void 0,h=c&&(c.end>=a||c.end<0)?c:void 0;if(null!=o)if(o>=0){var f={start:0,end:o};d?s.splice(0,1,f):s.unshift(f)}else d&&s.shift();if(null!=l)if(l>=0){var g={start:l,end:a};h?s.splice(s.length-1,1,g):s.push(g)}else h&&s.pop();return s},g=function(t,e){var i=n(t);return Math.min(i,Math.max(0,e))}},(t,e,i)=>{i.d(e,{enforceCuts:()=>h,getCurrentTimeAfterCuts:()=>s.getCurrentTimeAfterCuts,getDurationAfterCuts:()=>s.getDurationAfterCuts,getTrim:()=>u,setCuts:()=>c,setTrim:()=>m,teardownCuts:()=>f,trimStartFromCuts:()=>o});var r=i(9),s=i(283),n=i(280),a=(0,r.cachedDetect)(),o=function(t){var e=(0,s.getCuts)(t);return e.length<1||e[0].start>0?0:e[0].end},l=function(t){var e=(0,s.getCuts)(t),i=(0,s.getDurationBeforeCuts)(t);return e.length<1||e[e.length-1].end<i?-1:e[e.length-1].start},u=function(t){return{start:o(t),end:l(t)}},c=function(t,e){t.attributes.cuts=e,e!==t._rawCuts&&(t._cuts=void 0,t._rawCuts=void 0),h(t)},d=function(t,e){return e||(e={current:null}),e.current=requestAnimationFrame((function(){!1!==t()&&d(t,e)})),function(){cancelAnimationFrame(e.current)}},h=function(t){if(!t._stopEnforcingCuts&&0!==(0,s.getCuts)(t).length){var e=function(){t._stopEnforcingCutsViaRafLoop&&(t._stopEnforcingCutsViaRafLoop(),t._stopEnforcingCutsViaRafLoop=void 0)},i=[t.on("playing",(function(){e(),t._stopEnforcingCutsViaRafLoop=d((function(){if(!t.state.seeking&&!t.video.seeking)return g(t),!!t._stopEnforcingCutsViaRafLoop&&void 0}))})),t.on("pause",e),t.on("ended",e),t.on("beforeplay",e),t.on("timeupdate",(function(){g(t)}))];t._stopEnforcingCuts=function(){e(),i.forEach((function(t){return t()})),t._stopEnforcingCuts=void 0}}},f=function(t){t._stopEnforcingCuts&&(t._stopEnforcingCuts(),t._stopEnforcingCuts=void 0)},g=function(t){if("beforeplay"!==t.getPlaybackMode()){var e=t.video.currentTime,i=(0,s.getCuts)(t),r=-1,o=i.filter((function(t,i){return t.start<=e&&e<t.end&&r<0&&(r=i),t.start<=e&&e<t.end}))[0],l=(0,s.getDurationBeforeCuts)(t);if(t.state.fakeEnded&&(0,s.getTimeAfterCuts)(t,e)<(0,s.getDurationAfterCuts)(t)-.1&&(t.state.fakeEnded=!1),o){var u=p(i,r);if(u<l-.1){var c=a.ios.version>0?.09:1e-6;(0,n.seekWithoutCuts)(t,u+c)}else t.state.fakeEnded||(t.state.fakeEnded=!0,t.attributes.loop?(t.trigger("ended"),t.seek(0).then((function(){return t.play()}))):(t.pause(),t.trigger("ended")))}}},m=function(t,e){var i=e.start,r=e.end;null!=i&&(i>=0?t.attributes.trimStart=e.start:delete t.attributes.trimStart),null!=r&&(r>=0?t.attributes.trimEnd=e.end:delete t.attributes.trimEnd),t._cuts=void 0,g(t),h(t)},p=function(t,e){if(e>=t.length)return-1;for(var i=t[e].end,r=e;r<t.length;r+=1){var s=t[r];if(s.start>i)break;s.start===i&&(i=s.end)}return i}},(t,e,i)=>{i.d(e,{onReady:()=>s});var r=i(12).wlog.getPrefixedFunctions("SimpleVideo"),s=function(t){var e=t.video;null==t.state&&(t.state={});var i=t.state;return i.onReadyPromise||(i.onReadyPromise=new Promise((function(s){if(i.hasBeenReady)s();else{if(e.readyState>=2)r.info("ready readyState",e.src,e.readyState),i.hasBeenReady=!0,s();else{t.bind("loadstart",(function(){r.info("ready loadstart"),i.hasBeenReady=!0,s()}))}setTimeout((function(){i.hasBeenReady||(i.hasBeenReady=!0,s())}),200)}}))),i.onReadyPromise}},(t,e,i)=>{i.d(e,{changeQuality:()=>g,changeStream:()=>p,changeStreamWithoutLoad:()=>m,changeVideo:()=>y,initAfterChangeVideo:()=>T,isChangingVideo:()=>v,stopStreaming:()=>f,teardownBeforeChangeVideo:()=>E});var r=i(12),s=i(3),n=i(61),a=i(287),o=i(278);function l(){var t,e,i="function"==typeof Symbol?Symbol:{},r=i.iterator||"@@iterator",s=i.toStringTag||"@@toStringTag";function n(i,r,s,n){var l=r&&r.prototype instanceof o?r:o,c=Object.create(l.prototype);return u(c,"_invoke",function(i,r,s){var n,o,l,u=0,c=s||[],d=!1,h={p:0,n:0,v:t,a:f,f:f.bind(t,4),d:function(e,i){return n=e,o=0,l=t,h.n=i,a}};function f(i,r){for(o=i,l=r,e=0;!d&&u&&!s&&e<c.length;e++){var s,n=c[e],f=h.p,g=n[2];i>3?(s=g===r)&&(l=n[(o=n[4])?5:(o=3,3)],n[4]=n[5]=t):n[0]<=f&&((s=i<2&&f<n[1])?(o=0,h.v=r,h.n=n[1]):f<g&&(s=i<3||n[0]>r||r>g)&&(n[4]=i,n[5]=r,h.n=g,o=0))}if(s||i>1)return a;throw d=!0,r}return function(s,c,g){if(u>1)throw TypeError("Generator is already running");for(d&&1===c&&f(c,g),o=c,l=g;(e=o<2?t:l)||!d;){n||(o?o<3?(o>1&&(h.n=-1),f(o,l)):h.n=l:h.v=l);try{if(u=2,n){if(o||(s="next"),e=n[s]){if(!(e=e.call(n,l)))throw TypeError("iterator result is not an object");if(!e.done)return e;l=e.value,o<2&&(o=0)}else 1===o&&(e=n.return)&&e.call(n),o<2&&(l=TypeError("The iterator does not provide a '"+s+"' method"),o=1);n=t}else if((e=(d=h.n<0)?l:i.call(r,h))!==a)break}catch(e){n=t,o=1,l=e}finally{u=1}}return{value:e,done:d}}}(i,s,n),!0),c}var a={};function o(){}function c(){}function d(){}e=Object.getPrototypeOf;var h=[][r]?e(e([][r]())):(u(e={},r,(function(){return this})),e),f=d.prototype=o.prototype=Object.create(h);function g(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,d):(t.__proto__=d,u(t,s,"GeneratorFunction")),t.prototype=Object.create(f),t}return c.prototype=d,u(f,"constructor",d),u(d,"constructor",c),c.displayName="GeneratorFunction",u(d,s,"GeneratorFunction"),u(f),u(f,s,"Generator"),u(f,r,(function(){return this})),u(f,"toString",(function(){return"[object Generator]"})),(l=function(){return{w:n,m:g}})()}function u(t,e,i,r){var s=Object.defineProperty;try{s({},"",{})}catch(t){s=0}u=function(t,e,i,r){function n(e,i){u(t,e,(function(t){return this._invoke(e,i,t)}))}e?s?s(t,e,{value:i,enumerable:!r,configurable:!r,writable:!r}):t[e]=i:(n("next",0),n("throw",1),n("return",2))},u(t,e,i,r)}function c(t,e,i,r,s,n,a){try{var o=t[n](a),l=o.value}catch(t){return void i(t)}o.done?e(l):Promise.resolve(l).then(r,s)}function d(t){return function(){var e=this,i=arguments;return new Promise((function(r,s){var n=t.apply(e,i);function a(t){c(n,r,s,a,o,"next",t)}function o(t){c(n,r,s,a,o,"throw",t)}a(void 0)}))}}var h=r.wlog.getPrefixedFunctions("SimpleVideo"),f=function(t){try{if(t.state.destroyed)return;h.info("stopStreaming");var e=t.video;e.src="".concat(o.srcProtocolAndHost(e.getAttribute("src")),"/tiny.mp4"),e.load()}catch(t){h.notice(t)}},g=function(t,e,i,r){var s=t.selectableAssets(),a=(0,n.findClosestAssetByQuality)(s,e);return"beforeplay"===t.getPlaybackMode()?(m(t,a),Promise.resolve()):p(t,a,i,r)},m=function(t,e){h.info("changeStreamWithoutLoad",e&&e.slug,e);var i=t.video;if((0,s.elemInDom)(i)){var r=o.properAssetUrl(e.url,e.container);t.state={eventContext:t.state.eventContext},t._currentAsset=e,i.src=r;var n=function(t){for(var e=t.video,i=[],r=0;r<e.childNodes.length;r++){var s=e.childNodes[r];1===s.nodeType&&"source"===s.tagName.toLowerCase()&&i.push(s)}return i}(t);n.length>0&&(n[0].src=r)}},p=function(t,e){var i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],r=arguments.length>3&&void 0!==arguments[3]&&arguments[3];h.info("changeStream",i,r,e&&e.slug,e);var n=t.video;return t.asset=e,new Promise((function(a){var u=o.properAssetUrl(e.url,e.container);if(r||u!==n.getAttribute("src")){var c=t.getState();t.state.seeking=!0,(0,s.elemBind)(n,"loadstart",d(l().m((function e(){return l().w((function(e){for(;;)switch(e.n){case 0:if(!r){e.n=1;break}n.style.visibility="visible",t.state.seeking=!1,a(),e.n=8;break;case 1:if(!(c.currentTime>2)){e.n=7;break}return e.n=2,t.seek(c.currentTime);case 2:if("playing"!==c.playbackMode){e.n=4;break}return e.n=3,t.play();case 3:t.state.seeking=!1,n.style.visibility="visible",a(),e.n=6;break;case 4:return e.n=5,t.pause();case 5:n.style.visibility="visible",t.state.seeking=!1,a();case 6:e.n=8;break;case 7:"playing"===c.playbackMode&&t.play(),n.style.visibility="visible",t.state.seeking=!1,a();case 8:return t.setPlaybackRate(c.playbackRate),e.a(2,s.elemUnbind)}}),e)})))),n.style.visibility="hidden",m(t,e,r),"beforeplay"===c.playbackMode||i||t.play()}else a()}))},v=function(t){return!!t.state.isChangingVideo},y=function(t,e,i){return E(t),t.state.isChangingVideo=!0,T(t,e,i),new Promise((function(e){p(t,t.defaultAsset()).then((function(){t.state.isChangingVideo=!1,e()}))}))},E=function(t){var e=t.state.eventContext;t.destroy(),t.state.eventContext=e},T=function(t,e,i){a.setupProperties(t,e,i),a.setupBindingsAndLoops(t,t.allAssets,i)}},(t,e,i)=>{i.d(e,{fromOtherEngine:()=>d,injectVideo:()=>c,killBindingsAndStopLoops:()=>f,setupBindingsAndLoops:()=>h,setupProperties:()=>u});var r=i(3),s=i(278),n=i(288),a=i(289),o=i(290),l=i(284),u=function(t,e,i){var r=e.assets;0===r.length&&(r=[{}]),t.mediaData=e,t.allAssets=r,t.attributes=i},c=function(t){t._currentAsset=t.defaultAsset(),t.video=s.createElement(t.uuid,t._currentAsset,t.attributes),t.onReady(),(0,r.elemAppend)(t.root,t.video)},d=function(t,e){var i=e.isMuted(),r=e.hasIssuedPlay();"Audio"===e.mediaData.mediaType?c(t):t.video=e.getMediaElement(),t.onReady(),t.bind("loadstart",(function(){return setTimeout((function(){t.state.isInitializingFromOtherEngine=!1}),0),t.unbind})),s.setupVideoElemAttributes(t.video,t.defaultAsset(),t.attributes),s.setupVideoElemStyles(t.video,t.attributes),t.state.eventContext=e.eventContext(),t.root.appendChild(t.video),t._currentAsset=t.defaultAsset(),t.changeStreamWithoutLoad(t.defaultAsset()),t.state.isInitializingFromOtherEngine=!0,t.state.otherEngineWasMuted=i,t.state.otherEnginePlayed=r,t.video.load()},h=function(t){a.setup(t),(0,l.enforceCuts)(t),o.setup(t),n.setup(t)},f=function(t){o.teardown(t),(0,l.teardownCuts)(t),n.teardown(t),a.teardown(t)}},(t,e,i)=>{i.d(e,{setup:()=>a,teardown:()=>o});var r=i(4),s=i(63),n=function(t){var e=t.attributes;return(null!=e.eventLoopDuration?e.eventLoopDuration:300)/t.getPlaybackRate()},a=function(t){null==t.state&&(t.state={}),"playing"===t.getPlaybackMode()&&(t.state.hasPlayed=!0),t.bind("playing",(function(){t.state.hasPlayed=!0})),t.bind("waiting",(function(){t.state.gotWaiting=!0})),t.bind("loadedmetadata",(function(){t.state.loadedMetadata=!0})),(0,r.assign)(t.state,{lastPlaybackMode:t.getPlaybackMode(),lastTimePosition:t.getCurrentTime(),lastEventLoopDuration:n(t)});var e="".concat(t.uuid,".custom_state_and_events");s.globalEventLoop.add(e,n(t),(function(){(0,r.assign)(t.state,{lastTimePosition:t.getCurrentTime(),lastPlaybackMode:t.getPlaybackMode(),lastEventLoopDuration:n(t)}),s.globalEventLoop.interval(e,n(t))}))},o=function(t){var e="".concat(t.uuid,".custom_state_and_events");s.globalEventLoop.remove(e)}},(t,e,i)=>{i.d(e,{setup:()=>o,teardown:()=>l});var r=i(4),s=i(3),n=i(63),a=function(t){var e=t.attributes;return(null!=e.eventLoopDuration?e.eventLoopDuration:300)/t.getPlaybackRate()},o=function(t){null==t.state&&(t.state={}),t.state.waiting=-1;var e="".concat(t.uuid,".waiting_events");n.globalEventLoop.add(e,a(t),(function(){u(t),n.globalEventLoop.interval(e,a(t))}))},l=function(t){var e="".concat(t.uuid,".waiting_events");n.globalEventLoop.remove(e)},u=function(t){var e=t.video,i=t.state,n=i.lastPlaybackMode,o=i.gotWaiting&&"beforeplay"===t.getPlaybackMode()||"playing"===t.getPlaybackMode(),l="playing"===n||"beforeplay"===n&&!i.lastPlayRejected,u=i.lastEventLoopDuration||a(t);if(o&&l)if(t.getCurrentTime()===i.lastTimePosition){var d=i.startedWaitingAt;d?(i.waiting=((new Date).getTime()-d)/1e3,t.trigger("custom-waiting",i.waiting)):((0,r.assign)(i,{startedWaitingAt:(new Date).getTime()-u,waiting:u/1e3}),t.trigger("custom-waiting",u/1e3),(0,s.elemBind)(e,"timeupdate",(function(){return c(t),s.elemUnbind})))}else c(t);else c(t)},c=function(t){var e=t.state.waiting;(0,r.assign)(t.state,{waiting:-1,startedWaitingAt:null}),null!=e&&e>=0&&t.trigger("custom-done-waiting",e)}},(t,e,i)=>{i.d(e,{setup:()=>n,teardown:()=>a});var r=i(3),s=["beforeplay","canplay","canplaythrough","ended","error","loadeddata","loadedmetadata","loadstart","pause","playing","progress","ratechange","seeked","seeking","volumechange","timeupdate","waiting","webkitbeginfullscreen","webkitendfullscreen","webkitplaybacktargetavailabilitychanged"],n=function(t){for(var e=0;e<s.length;e++){var i=s[e];!function(e,i){var s="_marshalEvent_".concat(i);t[s]=t[s]||function(r){null==t.state&&(t.state={}),("playing"!==i||"playing"===i&&!e.paused)&&(t.state.eventContext=r,t.trigger(i,r),t.state.eventContext=null)},(0,r.elemBind)(e,i,t[s])}(t.video,i)}},a=function(t){for(var e=0;e<s.length;e++){var i=s[e],n="_marshalEvent_".concat(i);(0,r.elemUnbind)(t.video,i,t[n])}}},(t,e,i)=>{i.d(e,{fixWebkitControlsBug:()=>o});var r=i(9),s=i(12),n=(0,r.cachedDetect)(),a=s.wlog.getPrefixedFunctions("SimpleVideo"),o=function(t){var e=t.video;if(n.browser.webkit){a.info("fixWebkitControlsBug");var i=e.getAttribute("controls");e.setAttribute("controls","controls"),e.removeAttribute("controls"),null!=i&&e.setAttribute("controls",i)}}},(t,e,i)=>{i.d(e,{fit:()=>c,onHeightChange:()=>o,onWidthChange:()=>a});var r=i(3),s=i(61),n=(0,i(9).cachedDetect)(),a=function(t,e){return t.setAttributes({width:e}),c(t)},o=function(t,e){return t.setAttributes({height:e}),c(t)},l="contain",u="fill",c=function(t){var e=t.attributes.fitStrategy||d(t);return e===l?f(t):"cover"===e?h(t):e===u?g(t):f(t)},d=function(t){var e=t.attributes.height,i=t.attributes.width,r=(0,s.originalAspect)(t.allAssets),a=e*r,o=2*Math.floor(i/r/2),c=Math.abs(o-e),d=Math.abs(a-i),h=n.firefox&&n.browser.mozilla&&n.browser.version>=36;return(n.browser.webkit||h)&&c>0&&c<=10&&d>0&&d<=10?u:l},h=function(t){var e=t.video,i=(0,s.videoAspect)(t.allAssets),a=(0,r.elemWidth)(t.root)/(0,r.elemHeight)(t.root);n.edge?a<=i?(0,r.elemStyle)(e,{height:"100%",left:"50%",objectFit:"contain",position:"relative",top:"50%",transform:"translate(-50%,-50%)",width:"1920px"}):(0,r.elemStyle)(e,{height:"1088px",left:"50%",objectFit:"contain",position:"relative",top:"50%",transform:"translate(-50%,-50%)",width:"100%"}):(0,r.elemStyle)(e,{objectFit:"cover"})},f=function(t){var e=t.video,i={height:"100%",width:"100%",objectFit:"contain"};(0,r.elemStyle)(e,i)},g=function(t){var e=t.video,i={height:"100%",width:"100%",objectFit:"fill"};(0,r.elemStyle)(e,i)}},(t,e,i)=>{i.d(e,{getDiagnosticData:()=>a});var r=i(294),s=i(25),n=function(t){try{return t()}catch(t){return"ERROR: ".concat(t.message)}},a=function(t){var e=""!==s.TAGGED_VERSION&&s.TAGGED_VERSION.length>0?s.TAGGED_VERSION:r.PLAYER_VERSION,i={};return i.player_version=e,i.state=t.state,i.attributes=t.attributes,i.currentAsset=t.currentAsset(),i.currentAsset&&i.currentAsset.url&&i.currentAsset.url.length>100&&(i.currentAsset.url="".concat(i.currentAsset.url.substring(0,97),"...")),i.selectedAsset=t.selectedAsset(),i.selectedAsset&&i.selectedAsset.url&&i.selectedAsset.url.length>100&&(i.selectedAsset.url="".concat(i.selectedAsset.url.substring(0,97),"...")),i.getState=n((function(){return t.getState()})),i.getDuration=n((function(){return t.getDuration()})),i.getPlaybackRate=n((function(){return t.getPlaybackRate()})),i.getPlaybackMode=n((function(){return t.getPlaybackMode()})),i.isSeeking=n((function(){return t.isSeeking()})),i.getCurrentTime=n((function(){return t.getCurrentTime()})),i.activeBufferRange=n((function(){return t.activeBufferRange()})),i.sequentialBufferedRange=n((function(){return t.sequentialBufferedRange()})),i.getVolume=n((function(){return t.getVolume()})),i.timeBeforeEndOfBuffer=n((function(){return t.timeBeforeEndOfBuffer()})),i.lastBufferedTime=n((function(){return t.lastBufferedTime()})),i.totalBuffered=n((function(){return t.totalBuffered()})),i.anyBuffered=n((function(){return t.anyBuffered()})),i.getPreload=n((function(){return t.getPreload()})),i.rawVideoProps=n((function(){return l(t)})),i},o=["autoplay","controls","crossOrigin","currentSrc","currentTime","defaultMuted","defaultPlaybackRate","duration","ended","error","loop","muted","networkState","paused","playbackRate","preload","readyState","seeking","src","startDate","volume"],l=function(t){for(var e=t.video,i={},r=0;r<o.length;r++){var s=o[r],n=e[s];i[s]=n}return i}},(t,e,i)=>{i.d(e,{PLAYER_VERSION:()=>r});var r="main"},(t,e,i)=>{i.d(e,{PUBLIC_METHODS:()=>r,delegatePublicMethods:()=>s});var r=["activeBufferRange","addTextTracks","anyBuffered","bind","bindNamed","bufferInfo","canDownloadMedia","cancelFullscreen","captureCurrentFrame","changeQuality","changeStream","changeStreamWithoutLoad","changeVideo","currentAsset","defaultAsset","destroy","diagnosticData","eventContext","fit","getAudioTracks","getCurrentQuality","getCurrentTime","getCuts","getDuration","getDurationBeforeCuts","getMediaElement","getMediaType","getPlaybackMode","getPlaybackRate","getPreload","getState","getTimeAfterCuts","getTimeBeforeCuts","getTrim","getVolume","hasIssuedPlay","isChangingVideo","isInitializingFromUnmuted","isInFullscreen","isMuted","isSeeking","isSourceOfBrowserEvent","lastBufferedTime","mute","onEnterFullscreen","onHeightChange","onLeaveFullscreen","onMediaDataChanged","onPlayed","onReady","onWidthChange","pause","play","playType","removeTextTracks","requestFullscreen","reset","seek","seekOnPlay","selectedAsset","selectableAssets","selectableQualities","selectedQuality","sequentialBufferedRange","setAttributes","setCurrentTime","setPlaybackRate","setCuts","setTrim","setVolume","showFirstFrame","stopStreaming","timeBeforeEndOfBuffer","totalBuffered","totalPlayed","trigger","unbind","unbindNamed","unbindAllInNamespace","unmute","updateStartPosition"],s=function(t,e){!function(t,e,i){for(var r=0;r<t.length;r++){var s=t[r];e[s]||function(t){e[t]=function(){var e=i.call(this);return e?e[t].apply(e,arguments):null}}(s)}}(r,t,e)}},(t,e,i)=>{i.d(e,{default:()=>s});var r=i(16);null==r.Wistia.engines&&(r.Wistia.engines={});const s=function(t,e){r.Wistia.engines[t]=e}},(t,e,i)=>{i.d(e,{addTextTracks:()=>n,removeTextTracks:()=>a});var r=i(28),s=i(3),n=function(t,e){var i=(0,r.seqId)("wistia_captions_");t.forEach((function(t){var r=document.createElement("track");r.kind=t.kind||"captions",r.label=t.native_name,r.srclang=t.language,r.src=t.src,r._wistiaCaptionsId=t._wistiaCaptionsId||i,e.appendChild(r,{wistiaGridCaller:!0})}))},a=function(t,e){for(var i=Array.prototype.slice.call(e.childNodes),r=0;r<i.length;r++){var n=i[r];/^track$/i.test(n.tagName)&&n._wistiaCaptionsId===t&&(0,s.elemRemove)(n)}}},(t,e,i)=>{function r(t,e){for(var i=0;i<e.length;i++){var r=e[i];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,s(r.key),r)}}function s(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var r=i.call(t,e||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}i.d(e,{PlaybackEngine:()=>n});var n=function(){return t=function t(e,i,r){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.root=e,this.mediaData=i,this.attributes=r,this.unbinds=[]},(e=[{key:"destroy",value:function(){this.unbinds.forEach((function(t){"function"==typeof t&&t()})),this._bindings={}}}])&&r(t.prototype,e),i&&r(t,i),Object.defineProperty(t,"prototype",{writable:!1}),t;var t,e,i}()},(t,e,i)=>{i.d(e,{assetToLevel:()=>c,bestStartingLevel:()=>f,deliveryUrlToLevel:()=>d,filteredHlsAssets:()=>g,levelToAsset:()=>m,startLoadOnce:()=>p,stopLoad:()=>y,teardown:()=>E});var r=i(61),s=i(4),n=i(272),a=i(275),o=(0,n.makeNamespace)("asset_to_level"),l=(0,n.makeNamespace)("level_to_asset"),u=function(t){if(t){var e=t.match(/deliveries\/(.*?)(?=\.)/);return e&&e[1]?e[1]:void 0}},c=function(t,e){return d(t,e.url)},d=function(t,e){var i,r=u(e);if(null!=(i=o(t)[r]))return i;if(!t.hls||!t.hls.levels)return-1;var n=(0,s.filter)(t.hls.levels,(function(t){return u(t.url[0])===r}))[0],a=t.hls.levels.indexOf(n);return n&&(o(t)[r]=a),a},h=function(t){if(t.attrs.BANDWIDTH)return Number(t.attrs.BANDWIDTH)},f=function(t){return v(t)?v(t):-1!==t.hls.autoLevelCapping?t.hls.autoLevelCapping:t.hls.levels.length-1},g=function(t,e){var i=e,s=t.attributes,n=s.qualityMin,o=s.qualityMax;n>0&&(i=a.rejectAudioAsset(t,i));var l=(0,r.withinQualityRange)(i,n,o);return i=l.length>0?l:(0,r.nearestOutsideRange)(i,n,o)},m=function(t,e){var i;if(null!=(i=l(t)[e]))return i;var r=(0,s.getDeep)(t.hls.levels,[e,"url",0]),n=u(r),a=(0,s.filter)(t.allAssets,(function(t){if(t.url){var e=u(t.url);return n===e}}))[0];return l(t)[e]=a,a},p=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:-1;t.attributes.calledStartLoad||(t.onReady().then((function(){t.hls.startLoad(e)})),t.setAttributes({calledStartLoad:!0}))},v=function(t){var e=t.attributes,i=e.qualityMin,s=void 0===i?100:i,n=e.qualityMax,a=void 0===n?1e4:n,o=e.bwEstimateOnInit;if(o&&t.hls.levels){for(var l,u,c=t.hls.autoLevelCapping||t.hls.levels.length-1,d=0;d<=c;d++){var f=t.hls.levels[d],g=(u=f).attrs.AVERAGE_BANDWIDTH?Number(u.attrs.AVERAGE_BANDWIDTH):h(u),m=(0,r.numericSizeSnapped)(f.width,f.height);s<=m&&m<=a&&g<99999999999&&g<o*t.abrBandWidthUpFactor()&&(l=d)}return l}},y=function(t){t.hls.stopLoad(),t.setAttributes({calledStartLoad:!1})},E=function(t){(0,n.uncacheNamespace)("level_to_asset",t),(0,n.uncacheNamespace)("asset_to_level",t)}},(t,e,i)=>{i.d(e,{default:()=>b});var r=i(270),s=i(61);function n(t,e){for(var i=0;i<e.length;i++){var r=e[i];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,c(r.key),r)}}function a(t,e,i){return e=g(e),function(t,e){if(e&&("object"==typeof e||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}(t,o()?Reflect.construct(e,i||[],g(t).constructor):e.apply(t,i))}function o(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(t){}return(o=function(){return!!t})()}function l(t,e,i,r,s,n){return function(t,e,i,r,s){if(!u(t,e,i,r||t)&&s)throw new TypeError("failed to set property");return i}(g(n?t.prototype:t),e,i,r,s)}function u(t,e,i,r){return u="undefined"!=typeof Reflect&&Reflect.set?Reflect.set:function(t,e,i,r){var s,n=f(t,e);if(n){if((s=Object.getOwnPropertyDescriptor(n,e)).set)return s.set.call(r,i),!0;if(!s.writable)return!1}if(s=Object.getOwnPropertyDescriptor(r,e)){if(!s.writable)return!1;s.value=i,Object.defineProperty(r,e,s)}else!function(t,e,i){(e=c(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i}(r,e,i);return!0},u(t,e,i,r)}function c(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var r=i.call(t,e||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}function d(t,e,i,r){var s=h(g(1&r?t.prototype:t),e,i);return 2&r&&"function"==typeof s?function(t){return s.apply(i,t)}:s}function h(){return h="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(t,e,i){var r=f(t,e);if(r){var s=Object.getOwnPropertyDescriptor(r,e);return s.get?s.get.call(arguments.length<3?t:i):s.value}},h.apply(null,arguments)}function f(t,e){for(;!{}.hasOwnProperty.call(t,e)&&null!==(t=g(t)););return t}function g(t){return g=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},g(t)}function m(t,e){return m=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},m(t,e)}function p(t,e){if(e.has(t))throw new TypeError("Cannot initialize the same private elements twice on an object")}function v(t,e,i){if("function"==typeof t?t===e:t.has(e))return arguments.length<3?e:i;throw new TypeError("Private element is not present on this object")}var y=r.default.DefaultConfig.abrController,E=new WeakMap,T=new WeakSet,b=function(t){function e(t){var i,r,s;return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),i=a(this,e,[t]),p(r=i,s=T),s.add(r),function(t,e,i){p(t,e),e.set(t,i)}(i,E,void 0),i.hls=t,i}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&m(t,e)}(e,t),i=e,(r=[{key:"autoLevelCapping",get:function(){return v(T,this,S).call(this,(e=this,(t=E).get(v(t,e))));var t,e},set:function(t){var e,i,r;i=this,r=t,(e=E).set(v(e,i),r)}},{key:"nextAutoLevel",get:function(){return v(T,this,S).call(this,d(e,"nextAutoLevel",this,1))},set:function(t){l(e,"nextAutoLevel",t,this,1,1)}},{key:"destroy",value:function(){d(e,"destroy",this,3)([])}}])&&n(i.prototype,r),s&&n(i,s),Object.defineProperty(i,"prototype",{writable:!1}),i;var i,r,s}(y);function S(t){if(!this.hls.levels||0===this.hls.levels.length)return t;var e=this.hls.config.qualityMin||0,i=this.hls.config.qualityMax||5e3,r=(0,s.findClosestAssetByQuality)(this.hls.levels,e),n=this.hls.levels.indexOf(r),a=(0,s.findClosestAssetByQuality)(this.hls.levels,i),o=this.hls.levels.indexOf(a);return t>o?o:t<n?n:t}},(t,e,i)=>{i.d(e,{default:()=>T});var r=i(270),s=i(61);function n(t,e){for(var i=0;i<e.length;i++){var r=e[i];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,c(r.key),r)}}function a(t,e,i){return e=g(e),function(t,e){if(e&&("object"==typeof e||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}(t,o()?Reflect.construct(e,i||[],g(t).constructor):e.apply(t,i))}function o(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(t){}return(o=function(){return!!t})()}function l(t,e,i,r,s,n){return function(t,e,i,r,s){if(!u(t,e,i,r||t)&&s)throw new TypeError("failed to set property");return i}(g(n?t.prototype:t),e,i,r,s)}function u(t,e,i,r){return u="undefined"!=typeof Reflect&&Reflect.set?Reflect.set:function(t,e,i,r){var s,n=f(t,e);if(n){if((s=Object.getOwnPropertyDescriptor(n,e)).set)return s.set.call(r,i),!0;if(!s.writable)return!1}if(s=Object.getOwnPropertyDescriptor(r,e)){if(!s.writable)return!1;s.value=i,Object.defineProperty(r,e,s)}else!function(t,e,i){(e=c(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i}(r,e,i);return!0},u(t,e,i,r)}function c(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var r=i.call(t,e||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}function d(t,e,i,r){var s=h(g(1&r?t.prototype:t),e,i);return 2&r&&"function"==typeof s?function(t){return s.apply(i,t)}:s}function h(){return h="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(t,e,i){var r=f(t,e);if(r){var s=Object.getOwnPropertyDescriptor(r,e);return s.get?s.get.call(arguments.length<3?t:i):s.value}},h.apply(null,arguments)}function f(t,e){for(;!{}.hasOwnProperty.call(t,e)&&null!==(t=g(t)););return t}function g(t){return g=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},g(t)}function m(t,e){return m=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},m(t,e)}function p(t,e){(function(t,e){if(e.has(t))throw new TypeError("Cannot initialize the same private elements twice on an object")})(t,e),e.add(t)}function v(t,e,i){if("function"==typeof t?t===e:t.has(e))return arguments.length<3?e:i;throw new TypeError("Private element is not present on this object")}var y=r.default.DefaultConfig.capLevelController,E=new WeakSet,T=function(t){function e(t){var i;return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),p(i=a(this,e,[t]),E),i.hls=t,i}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&m(t,e)}(e,t),i=e,(r=[{key:"autoLevelCapping",get:function(){return d(e,"autoLevelCapping",this,1)},set:function(t){l(e,"autoLevelCapping",Infinity!==t&&void 0!==t?v(E,this,b).call(this,t):t,this,1,1)}},{key:"detectPlayerSize",value:function(){if(this.clientRect=null,d(e,"detectPlayerSize",this,3)([]),this.hls&&this.media&&this.mediaHeight>0&&this.mediaWidth>0){var t=v(E,this,b).call(this,this.hls.autoLevelCapping);t!==this.hls.autoLevelCapping&&(this.hls.autoLevelCapping=t)}}}])&&n(i.prototype,r),s&&n(i,s),Object.defineProperty(i,"prototype",{writable:!1}),i;var i,r,s}(y);function b(t){if(!this.hls.levels||0===this.hls.levels.length)return t;var e=this.hls.config.qualityMin||0,i=this.hls.config.qualityMax||5e3,r=(0,s.findClosestAssetByQuality)(this.hls.levels,e),n=this.hls.levels.indexOf(r),a=(0,s.findClosestAssetByQuality)(this.hls.levels,i),o=this.hls.levels.indexOf(a);return t>o?o:t>=0&&t<n?n:t}}],__webpack_module_cache__={};function __webpack_require__(t){var e=__webpack_module_cache__[t];if(void 0!==e)return e.exports;var i=__webpack_module_cache__[t]={exports:{}};return __webpack_modules__[t](i,i.exports,__webpack_require__),i.exports}__webpack_require__.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return __webpack_require__.d(e,{a:e}),e},__webpack_require__.d=(t,e)=>{for(var i in e)__webpack_require__.o(e,i)&&!__webpack_require__.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},__webpack_require__.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),__webpack_require__.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var __webpack_exports__={};(()=>{__webpack_require__.d(__webpack_exports__,{default:()=>t});const t=__webpack_require__(269).default})();const __webpack_exports__default=__webpack_exports__.default;export{__webpack_exports__default as default};
//# debugId=4f6d2127-9730-413f-88e4-b05576387d4e
//# sourceMappingURL=hls_video.js.map