(function(ue,It){typeof exports=="object"&&typeof module<"u"?It(exports):typeof define=="function"&&define.amd?define(["exports"],It):(ue=typeof globalThis<"u"?globalThis:ue||self,It(ue.VOCPlayer={}))})(this,function(ue){"use strict";function It(s,e){var t=Object.keys(s);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);e&&(i=i.filter(function(n){return Object.getOwnPropertyDescriptor(s,n).enumerable})),t.push.apply(t,i)}return t}function ei(s){for(var e=1;e"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function ti(s){if(s===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return s}function Na(s,e){if(e&&(typeof e=="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return ti(s)}function Ae(s){var e=Oa();return function(){var i=nt(s),n;if(e){var r=nt(this).constructor;n=Reflect.construct(i,arguments,r)}else n=i.apply(this,arguments);return Na(this,n)}}function Fa(s,e){for(;!Object.prototype.hasOwnProperty.call(s,e)&&(s=nt(s),s!==null););return s}function Et(){return typeof Reflect<"u"&&Reflect.get?Et=Reflect.get.bind():Et=function(e,t,i){var n=Fa(e,t);if(n){var r=Object.getOwnPropertyDescriptor(n,t);return r.get?r.get.call(arguments.length<3?e:i):r.value}},Et.apply(this,arguments)}function Ii(s,e){return Ba(s)||$a(s,e)||Ri(s,e)||Ga()}function Dt(s){return Ma(s)||Ua(s)||Ri(s)||Va()}function Ma(s){if(Array.isArray(s))return Di(s)}function Ba(s){if(Array.isArray(s))return s}function Ua(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function $a(s,e){var t=s==null?null:typeof Symbol<"u"&&s[Symbol.iterator]||s["@@iterator"];if(t!=null){var i=[],n=!0,r=!1,a,o;try{for(t=t.call(s);!(n=(a=t.next()).done)&&(i.push(a.value),!(e&&i.length===e));n=!0);}catch(l){r=!0,o=l}finally{try{!n&&t.return!=null&&t.return()}finally{if(r)throw o}}return i}}function Ri(s,e){if(s){if(typeof s=="string")return Di(s,e);var t=Object.prototype.toString.call(s).slice(8,-1);if(t==="Object"&&s.constructor&&(t=s.constructor.name),t==="Map"||t==="Set")return Array.from(s);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return Di(s,e)}}function Di(s,e){(e==null||e>s.length)&&(e=s.length);for(var t=0,i=new Array(e);t=s.length?{done:!0}:{done:!1,value:s[i++]}},e:function(l){throw l},f:n}}throw new TypeError(`Invalid attempt to iterate non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var r=!0,a=!1,o;return{s:function(){t=t.call(s)},n:function(){var l=t.next();return r=l.done,l},e:function(l){a=!0,o=l},f:function(){try{!r&&t.return!=null&&t.return()}finally{if(a)throw o}}}}Array.prototype.find||Object.defineProperty(Array.prototype,"find",{value:function(e){if(this==null)throw new TypeError('"this" is null or not defined');var t=Object(this),i=t.length>>>0;if(typeof e!="function")throw new TypeError("predicate must be a function");for(var n=arguments[1],r=0;r>>0;if(typeof e!="function")throw new TypeError("predicate must be a function");for(var n=arguments[1],r=0;r]*>/,f=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,g=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,v=/^(?:body|html)$/i,A=/([A-Z])/g,T=["val","css","html","text","data","width","height","offset"],x=["after","prepend","before","append"],_=l.createElement("table"),P=l.createElement("tr"),L={tr:l.createElement("tbody"),tbody:_,thead:_,tfoot:_,td:P,th:P,"*":l.createElement("div")},G=/complete|loaded|interactive/,O=/^[\w-]*$/,B={},k=B.toString,E={},N,S,I=l.createElement("div"),M={tabindex:"tabIndex",readonly:"readOnly",for:"htmlFor",class:"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},K=Array.isArray||function(m){return m instanceof Array};E.matches=function(m,b){if(!b||!m||m.nodeType!==1)return!1;var D=m.matches||m.webkitMatchesSelector||m.mozMatchesSelector||m.oMatchesSelector||m.matchesSelector;if(D)return D.call(m,b);var V,re=m.parentNode,te=!re;return te&&(re=I).appendChild(m),V=~E.qsa(re,b).indexOf(m),te&&I.removeChild(m),V};function H(m){return m==null?String(m):B[k.call(m)]||"object"}function W(m){return H(m)=="function"}function U(m){return m!=null&&m==m.window}function $(m){return m!=null&&m.nodeType==m.DOCUMENT_NODE}function j(m){return H(m)=="object"}function X(m){return j(m)&&!U(m)&&Object.getPrototypeOf(m)==Object.prototype}function ne(m){var b=!!m&&"length"in m&&m.length,D=t.type(m);return D!="function"&&!U(m)&&(D=="array"||b===0||typeof b=="number"&&b>0&&b-1 in m)}function q(m){return a.call(m,function(b){return b!=null})}function Le(m){return m.length>0?t.fn.concat.apply([],m):m}N=function(m){return m.replace(/-+(.)?/g,function(b,D){return D?D.toUpperCase():""})};function Ee(m){return m.replace(/::/g,"/").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/_/g,"-").toLowerCase()}S=function(m){return a.call(m,function(b,D){return m.indexOf(b)==D})};function ke(m){return m in u?u[m]:u[m]=new RegExp("(^|\\s)"+m+"(\\s|$)")}function pe(m,b){return typeof b=="number"&&!h[Ee(m)]?b+"px":b}function Xe(m){var b,D;return c[m]||(b=l.createElement(m),l.body.appendChild(b),D=getComputedStyle(b,"").getPropertyValue("display"),b.parentNode.removeChild(b),D=="none"&&(D="block"),c[m]=D),c[m]}function xi(m){return"children"in m?o.call(m.children):t.map(m.childNodes,function(b){if(b.nodeType==1)return b})}function La(m,b){var D,V=m?m.length:0;for(D=0;D")),b===s&&(b=d.test(m)&&RegExp.$1),b in L||(b="*"),te=L[b],te.innerHTML=""+m,V=t.each(o.call(te.childNodes),function(){te.removeChild(this)})),X(D)&&(re=t(V),t.each(D,function(We,$e){T.indexOf(We)>-1?re[We]($e):re.attr(We,$e)})),V},E.Z=function(m,b){return new La(m,b)},E.isZ=function(m){return m instanceof E.Z},E.init=function(m,b){var D;if(m)if(typeof m=="string")if(m=m.trim(),m[0]=="<"&&d.test(m))D=E.fragment(m,RegExp.$1,b),m=null;else{if(b!==s)return t(b).find(m);D=E.qsa(l,m)}else{if(W(m))return t(l).ready(m);if(E.isZ(m))return m;if(K(m))D=q(m);else if(j(m))D=[m],m=null;else if(d.test(m))D=E.fragment(m.trim(),RegExp.$1,b),m=null;else{if(b!==s)return t(b).find(m);D=E.qsa(l,m)}}else return E.Z();return E.Z(D,m)},t=function(m,b){return E.init(m,b)};function Ia(m,b,D){for(e in b)D&&(X(b[e])||K(b[e]))?(X(b[e])&&!X(m[e])&&(m[e]={}),K(b[e])&&!K(m[e])&&(m[e]=[]),Ia(m[e],b[e],D)):b[e]!==s&&(m[e]=b[e])}t.extend=function(m){var b,D=o.call(arguments,1);return typeof m=="boolean"&&(b=m,m=D.shift()),D.forEach(function(V){Ia(m,V,b)}),m},E.qsa=function(m,b){var D,V=b[0]=="#",re=!V&&b[0]==".",te=V||re?b.slice(1):b,We=O.test(te);return m.getElementById&&We&&V?(D=m.getElementById(te))?[D]:[]:m.nodeType!==1&&m.nodeType!==9&&m.nodeType!==11?[]:o.call(We&&!V&&m.getElementsByClassName?re?m.getElementsByClassName(te):m.getElementsByTagName(b):m.querySelectorAll(b))};function Ci(m,b){return b==null?t(m):t(m).filter(b)}t.contains=l.documentElement.contains?function(m,b){return m!==b&&m.contains(b)}:function(m,b){for(;b&&(b=b.parentNode);)if(b===m)return!0;return!1};function it(m,b,D,V){return W(b)?b.call(m,D,V):b}function Wn(m,b,D){D==null?m.removeAttribute(b):m.setAttribute(b,D)}function Ct(m,b){var D=m.className||"",V=D&&D.baseVal!==s;if(b===s)return V?D.baseVal:D;V?D.baseVal=b:m.className=b}function Ra(m){try{return m&&(m=="true"||(m=="false"?!1:m=="null"?null:+m+""==m?+m:/^[\[\{]/.test(m)?t.parseJSON(m):m))}catch{return m}}t.type=H,t.isFunction=W,t.isWindow=U,t.isArray=K,t.isPlainObject=X,t.isEmptyObject=function(m){var b;for(b in m)return!1;return!0},t.isNumeric=function(m){var b=Number(m),D=typeof m;return m!=null&&D!="boolean"&&(D!="string"||m.length)&&!isNaN(b)&&isFinite(b)||!1},t.inArray=function(m,b,D){return n.indexOf.call(b,m,D)},t.camelCase=N,t.trim=function(m){return m==null?"":String.prototype.trim.call(m)},t.uuid=0,t.support={},t.expr={},t.noop=function(){},t.map=function(m,b){var D,V=[],re,te;if(ne(m))for(re=0;re=0?m:m+this.length]},toArray:function(){return this.get()},size:function(){return this.length},remove:function(){return this.each(function(){this.parentNode!=null&&this.parentNode.removeChild(this)})},each:function(m){return n.every.call(this,function(b,D){return m.call(b,D,b)!==!1}),this},filter:function(m){return W(m)?this.not(this.not(m)):t(a.call(this,function(b){return E.matches(b,m)}))},add:function(m,b){return t(S(this.concat(t(m,b))))},is:function(m){return this.length>0&&E.matches(this[0],m)},not:function(m){var b=[];if(W(m)&&m.call!==s)this.each(function(V){m.call(this,V)||b.push(this)});else{var D=typeof m=="string"?this.filter(m):ne(m)&&W(m.item)?o.call(m):t(m);this.forEach(function(V){D.indexOf(V)<0&&b.push(V)})}return t(b)},has:function(m){return this.filter(function(){return j(m)?t.contains(this,m):t(this).find(m).size()})},eq:function(m){return m===-1?this.slice(m):this.slice(m,+m+1)},first:function(){var m=this[0];return m&&!j(m)?m:t(m)},last:function(){var m=this[this.length-1];return m&&!j(m)?m:t(m)},find:function(m){var b,D=this;return m?typeof m=="object"?b=t(m).filter(function(){var V=this;return n.some.call(D,function(re){return t.contains(re,V)})}):this.length==1?b=t(E.qsa(this[0],m)):b=this.map(function(){return E.qsa(this,m)}):b=t(),b},closest:function(m,b){var D=[],V=typeof m=="object"&&t(m);return this.each(function(re,te){for(;te&&!(V?V.indexOf(te)>=0:E.matches(te,m));)te=te!==b&&!$(te)&&te.parentNode;te&&D.indexOf(te)<0&&D.push(te)}),t(D)},parents:function(m){for(var b=[],D=this;D.length>0;)D=t.map(D,function(V){if((V=V.parentNode)&&!$(V)&&b.indexOf(V)<0)return b.push(V),V});return Ci(b,m)},parent:function(m){return Ci(S(this.pluck("parentNode")),m)},children:function(m){return Ci(this.map(function(){return xi(this)}),m)},contents:function(){return this.map(function(){return this.contentDocument||o.call(this.childNodes)})},siblings:function(m){return Ci(this.map(function(b,D){return a.call(xi(D.parentNode),function(V){return V!==D})}),m)},empty:function(){return this.each(function(){this.innerHTML=""})},pluck:function(m){return t.map(this,function(b){return b[m]})},show:function(){return this.each(function(){this.style.display=="none"&&(this.style.display=""),getComputedStyle(this,"").getPropertyValue("display")=="none"&&(this.style.display=Xe(this.nodeName))})},replaceWith:function(m){return this.before(m).remove()},wrap:function(m){var b=W(m);if(this[0]&&!b)var D=t(m).get(0),V=D.parentNode||this.length>1;return this.each(function(re){t(this).wrapAll(b?m.call(this,re):V?D.cloneNode(!0):D)})},wrapAll:function(m){if(this[0]){t(this[0]).before(m=t(m));for(var b;(b=m.children()).length;)m=b.first();t(m).append(this)}return this},wrapInner:function(m){var b=W(m);return this.each(function(D){var V=t(this),re=V.contents(),te=b?m.call(this,D):m;re.length?re.wrapAll(te):V.append(te)})},unwrap:function(){return this.parent().each(function(){t(this).replaceWith(t(this).children())}),this},clone:function(){return this.map(function(){return this.cloneNode(!0)})},hide:function(){return this.css("display","none")},toggle:function(m){return this.each(function(){var b=t(this);(m===s?b.css("display")=="none":m)?b.show():b.hide()})},prev:function(m){return t(this.pluck("previousElementSibling")).filter(m||"*")},next:function(m){return t(this.pluck("nextElementSibling")).filter(m||"*")},html:function(m){return 0 in arguments?this.each(function(b){var D=this.innerHTML;t(this).empty().append(it(this,m,b,D))}):0 in this?this[0].innerHTML:null},text:function(m){return 0 in arguments?this.each(function(b){var D=it(this,m,b,this.textContent);this.textContent=D==null?"":""+D}):0 in this?this.pluck("textContent").join(""):null},attr:function(m,b){var D;return typeof m=="string"&&!(1 in arguments)?0 in this&&this[0].nodeType==1&&(D=this[0].getAttribute(m))!=null?D:s:this.each(function(V){if(this.nodeType===1)if(j(m))for(e in m)Wn(this,e,m[e]);else Wn(this,m,it(this,b,V,this.getAttribute(m)))})},removeAttr:function(m){return this.each(function(){this.nodeType===1&&m.split(" ").forEach(function(b){Wn(this,b)},this)})},prop:function(m,b){return m=M[m]||m,1 in arguments?this.each(function(D){this[m]=it(this,b,D,this[m])}):this[0]&&this[0][m]},removeProp:function(m){return m=M[m]||m,this.each(function(){delete this[m]})},data:function(m,b){var D="data-"+m.replace(A,"-$1").toLowerCase(),V=1 in arguments?this.attr(D,b):this.attr(D);return V!==null?Ra(V):s},val:function(m){return 0 in arguments?(m==null&&(m=""),this.each(function(b){this.value=it(this,m,b,this.value)})):this[0]&&(this[0].multiple?t(this[0]).find("option").filter(function(){return this.selected}).pluck("value"):this[0].value)},offset:function(m){if(m)return this.each(function(D){var V=t(this),re=it(this,m,D,V.offset()),te=V.offsetParent().offset(),We={top:re.top-te.top,left:re.left-te.left};V.css("position")=="static"&&(We.position="relative"),V.css(We)});if(!this.length)return null;if(l.documentElement!==this[0]&&!t.contains(l.documentElement,this[0]))return{top:0,left:0};var b=this[0].getBoundingClientRect();return{left:b.left+window.pageXOffset,top:b.top+window.pageYOffset,width:Math.round(b.width),height:Math.round(b.height)}},css:function(m,b){if(arguments.length<2){var D=this[0];if(typeof m=="string")return D?D.style[N(m)]||getComputedStyle(D,"").getPropertyValue(m):void 0;if(K(m)){if(!D)return;var V={},re=getComputedStyle(D,"");return t.each(m,function(We,$e){V[$e]=D.style[N($e)]||re.getPropertyValue($e)}),V}}var te="";if(H(m)=="string")!b&&b!==0?this.each(function(){this.style.removeProperty(Ee(m))}):te=Ee(m)+":"+pe(m,b);else for(e in m)!m[e]&&m[e]!==0?this.each(function(){this.style.removeProperty(Ee(e))}):te+=Ee(e)+":"+pe(e,m[e])+";";return this.each(function(){this.style.cssText+=";"+te})},index:function(m){return m?this.indexOf(t(m)[0]):this.parent().children().indexOf(this[0])},hasClass:function(m){return m?n.some.call(this,function(b){return this.test(Ct(b))},ke(m)):!1},addClass:function(m){return m?this.each(function(b){if("className"in this){i=[];var D=Ct(this),V=it(this,m,b,D);V.split(/\s+/g).forEach(function(re){t(this).hasClass(re)||i.push(re)},this),i.length&&Ct(this,D+(D?" ":"")+i.join(" "))}}):this},removeClass:function(m){return this.each(function(b){if("className"in this){if(m===s)return Ct(this,"");i=Ct(this),it(this,m,b,i).split(/\s+/g).forEach(function(D){i=i.replace(ke(D)," ")}),Ct(this,i.trim())}})},toggleClass:function(m,b){return m?this.each(function(D){var V=t(this),re=it(this,m,D,Ct(this));re.split(/\s+/g).forEach(function(te){(b===s?!V.hasClass(te):b)?V.addClass(te):V.removeClass(te)})}):this},scrollTop:function(m){if(this.length){var b="scrollTop"in this[0];return m===s?b?this[0].scrollTop:this[0].pageYOffset:this.each(b?function(){this.scrollTop=m}:function(){this.scrollTo(this.scrollX,m)})}},scrollLeft:function(m){if(this.length){var b="scrollLeft"in this[0];return m===s?b?this[0].scrollLeft:this[0].pageXOffset:this.each(b?function(){this.scrollLeft=m}:function(){this.scrollTo(m,this.scrollY)})}},position:function(){if(this.length){var m=this[0],b=this.offsetParent(),D=this.offset(),V=v.test(b[0].nodeName)?{top:0,left:0}:b.offset();return D.top-=parseFloat(t(m).css("margin-top"))||0,D.left-=parseFloat(t(m).css("margin-left"))||0,V.top+=parseFloat(t(b[0]).css("border-top-width"))||0,V.left+=parseFloat(t(b[0]).css("border-left-width"))||0,{top:D.top-V.top,left:D.left-V.left}}},offsetParent:function(){return this.map(function(){for(var m=this.offsetParent||l.body;m&&!v.test(m.nodeName)&&t(m).css("position")=="static";)m=m.offsetParent;return m})}},t.fn.detach=t.fn.remove,["width","height"].forEach(function(m){var b=m.replace(/./,function(D){return D[0].toUpperCase()});t.fn[m]=function(D){var V,re=this[0];return D===s?U(re)?re["inner"+b]:$(re)?re.documentElement["scroll"+b]:(V=this.offset())&&V[m]:this.each(function(te){re=t(this),re.css(m,it(this,D,te,re[m]()))})}});function Da(m,b){b(m);for(var D=0,V=m.childNodes.length;D1;return re.length<1?this:this.each(function($e,Oe){te=D?Oe:Oe.parentNode,Oe=b==0?Oe.nextSibling:b==1?Oe.firstChild:b==2?Oe:null;var Lt=t.contains(l.documentElement,te);re.forEach(function(Jt){if(We)Jt=Jt.cloneNode(!0);else if(!te)return t(Jt).remove();te.insertBefore(Jt,Oe),Lt&&Da(Jt,function(At){if(At.nodeName!=null&&At.nodeName.toUpperCase()==="SCRIPT"&&(!At.type||At.type==="text/javascript")&&!At.src){var wa=At.ownerDocument?At.ownerDocument.defaultView:window;wa.eval.call(wa,At.innerHTML)}})})})},t.fn[D?m+"To":"insert"+(b?"Before":"After")]=function(V){return t(V)[m](this),this}}),E.Z.prototype=La.prototype=t.fn,E.uniq=S,E.deserializeValue=Ra,t.zepto=E,t}();window.Zepto=ht,window.$===void 0&&(window.$=ht),function(s){var e=+new Date,t=window.document,i,n,r=/)<[^<]*)*<\/script>/gi,a=/^(?:text|application)\/javascript/i,o=/^(?:text|application)\/xml/i,l="application/json",c="text/html",u=/^\s*$/,h=t.createElement("a");h.href=window.location.href;function d(S,I,M){var K=s.Event(I);return s(S).trigger(K,M),!K.isDefaultPrevented()}function f(S,I,M,K){if(S.global)return d(I||t,M,K)}s.active=0;function g(S){S.global&&s.active++===0&&f(S,null,"ajaxStart")}function v(S){S.global&&!--s.active&&f(S,null,"ajaxStop")}function A(S,I){var M=I.context;if(I.beforeSend.call(M,S,I)===!1||f(I,M,"ajaxBeforeSend",[S,I])===!1)return!1;f(I,M,"ajaxSend",[S,I])}function T(S,I,M,K){var H=M.context,W="success";M.success.call(H,S,W,I),K&&K.resolveWith(H,[S,W,I]),f(M,H,"ajaxSuccess",[I,M,S]),_(W,I,M)}function x(S,I,M,K,H){var W=K.context;K.error.call(W,M,I,S),H&&H.rejectWith(W,[M,I,S]),f(K,W,"ajaxError",[M,K,S||I]),_(I,M,K)}function _(S,I,M){var K=M.context;M.complete.call(K,I,S),f(M,K,"ajaxComplete",[I,M]),v(M)}function P(S,I,M){if(M.dataFilter==L)return S;var K=M.context;return M.dataFilter.call(K,S,I)}function L(){}s.ajaxJSONP=function(S,I){if(!("type"in S))return s.ajax(S);var M=S.jsonpCallback,K=(s.isFunction(M)?M():M)||"Zepto"+e++,H=t.createElement("script"),W=window[K],U,$=function(ne){s(H).triggerHandler("error",ne||"abort")},j={abort:$},X;return I&&I.promise(j),s(H).on("load error",function(ne,q){clearTimeout(X),s(H).off().remove(),ne.type=="error"||!U?x(null,q||"error",j,S,I):T(U[0],j,S,I),window[K]=W,U&&s.isFunction(W)&&W(U[0]),W=U=void 0}),A(j,S)===!1?($("abort"),j):(window[K]=function(){U=arguments},H.src=S.url.replace(/\?(.+)=\?/,"?$1="+K),t.head.appendChild(H),S.timeout>0&&(X=setTimeout(function(){$("timeout")},S.timeout)),j)},s.ajaxSettings={type:"GET",beforeSend:L,success:L,error:L,complete:L,context:null,global:!0,xhr:function(){return new window.XMLHttpRequest},accepts:{script:"text/javascript, application/javascript, application/x-javascript",json:l,xml:"application/xml, text/xml",html:c,text:"text/plain"},crossDomain:!1,timeout:0,processData:!0,cache:!0,dataFilter:L};function G(S){return S&&(S=S.split(";",2)[0]),S&&(S==c?"html":S==l?"json":a.test(S)?"script":o.test(S)&&"xml")||"text"}function O(S,I){return I==""?S:(S+"&"+I).replace(/[&?]{1,2}/,"?")}function B(S){S.processData&&S.data&&s.type(S.data)!="string"&&(S.data=s.param(S.data,S.traditional)),S.data&&(!S.type||S.type.toUpperCase()=="GET"||S.dataType=="jsonp")&&(S.url=O(S.url,S.data),S.data=void 0)}s.ajax=function(S){var I=s.extend({},S||{}),M=s.Deferred&&s.Deferred(),K,H;for(i in s.ajaxSettings)I[i]===void 0&&(I[i]=s.ajaxSettings[i]);g(I),I.crossDomain||(K=t.createElement("a"),K.href=I.url,K.href=K.href,I.crossDomain=h.protocol+"//"+h.host!=K.protocol+"//"+K.host),I.url||(I.url=window.location.toString()),(H=I.url.indexOf("#"))>-1&&(I.url=I.url.slice(0,H)),B(I);var W=I.dataType,U=/\?.+=\?/.test(I.url);if(U&&(W="jsonp"),(I.cache===!1||(!S||S.cache!==!0)&&(W=="script"||W=="jsonp"))&&(I.url=O(I.url,"_="+Date.now())),W=="jsonp")return U||(I.url=O(I.url,I.jsonp?I.jsonp+"=?":I.jsonp===!1?"":"callback=?")),s.ajaxJSONP(I,M);var $=I.accepts[W],j={},X=function(pe,Xe){j[pe.toLowerCase()]=[pe,Xe]},ne=/^([\w-]+:)\/\//.test(I.url)?RegExp.$1:window.location.protocol,q=I.xhr(),Le=q.setRequestHeader,Ee;if(M&&M.promise(q),I.crossDomain||X("X-Requested-With","XMLHttpRequest"),X("Accept",$||"*/*"),($=I.mimeType||$)&&($.indexOf(",")>-1&&($=$.split(",",2)[0]),q.overrideMimeType&&q.overrideMimeType($)),(I.contentType||I.contentType!==!1&&I.data&&I.type.toUpperCase()!="GET")&&X("Content-Type",I.contentType||"application/x-www-form-urlencoded"),I.headers)for(n in I.headers)X(n,I.headers[n]);if(q.setRequestHeader=X,q.onreadystatechange=function(){if(q.readyState==4){q.onreadystatechange=L,clearTimeout(Ee);var pe,Xe=!1;if(q.status>=200&&q.status<300||q.status==304||q.status==0&&ne=="file:"){if(W=W||G(I.mimeType||q.getResponseHeader("content-type")),q.responseType=="arraybuffer"||q.responseType=="blob")pe=q.response;else{pe=q.responseText;try{pe=P(pe,W,I),W=="script"?(0,eval)(pe):W=="xml"?pe=q.responseXML:W=="json"&&(pe=u.test(pe)?null:s.parseJSON(pe))}catch(xi){Xe=xi}if(Xe)return x(Xe,"parsererror",q,I,M)}T(pe,q,I,M)}else x(q.statusText||null,q.status?"error":"abort",q,I,M)}},A(q,I)===!1)return q.abort(),x(null,"abort",q,I,M),q;var ke="async"in I?I.async:!0;if(q.open(I.type,I.url,ke,I.username,I.password),I.xhrFields)for(n in I.xhrFields)q[n]=I.xhrFields[n];for(n in j)Le.apply(q,j[n]);return I.timeout>0&&(Ee=setTimeout(function(){q.onreadystatechange=L,q.abort(),x(null,"timeout",q,I,M)},I.timeout)),q.send(I.data?I.data:null),q};function k(S,I,M,K){return s.isFunction(I)&&(K=M,M=I,I=void 0),s.isFunction(M)||(K=M,M=void 0),{url:S,data:I,success:M,dataType:K}}s.get=function(){return s.ajax(k.apply(null,arguments))},s.post=function(){var S=k.apply(null,arguments);return S.type="POST",s.ajax(S)},s.getJSON=function(){var S=k.apply(null,arguments);return S.dataType="json",s.ajax(S)},s.fn.load=function(S,I,M){if(!this.length)return this;var K=this,H=S.split(/\s/),W,U=k(S,I,M),$=U.success;return H.length>1&&(U.url=H[0],W=H[1]),U.success=function(j){K.html(W?s("
").html(j.replace(r,"")).find(W):j),$&&$.apply(K,arguments)},s.ajax(U),this};var E=encodeURIComponent;function N(S,I,M,K){var H,W=s.isArray(I),U=s.isPlainObject(I);s.each(I,function($,j){H=s.type(j),K&&($=M?K:K+"["+(U||H=="object"||H=="array"?$:"")+"]"),!K&&W?S.add(j.name,j.value):H=="array"||!M&&H=="object"?N(S,j,M,$):S.add($,j)})}s.param=function(S,I){var M=[];return M.add=function(K,H){s.isFunction(H)&&(H=H()),H==null&&(H=""),this.push(E(K)+"="+E(H))},N(M,S,I),M.join("&").replace(/%20/g,"+")}}(ht),function(s){s.Callbacks=function(e){e=s.extend({},e);var t,i,n,r,a,o,l=[],c=!e.once&&[],u=function(d){for(t=e.memory&&d,i=!0,o=r||0,r=0,a=l.length,n=!0;l&&o-1;)l.splice(g,1),n&&(g<=a&&--a,g<=o&&--o)}),this},has:function(d){return!!(l&&(d?s.inArray(d,l)>-1:l.length))},empty:function(){return a=l.length=0,this},disable:function(){return l=c=t=void 0,this},disabled:function(){return!l},lock:function(){return c=void 0,t||h.disable(),this},locked:function(){return!c},fireWith:function(d,f){return l&&(!i||c)&&(f=f||[],f=[d,f.slice?f.slice():f],n?c.push(f):u(f)),this},fire:function(){return h.fireWith(this,arguments)},fired:function(){return!!i}};return h}}(ht),function(s){var e=Array.prototype.slice;function t(i){var n=[["resolve","done",s.Callbacks({once:1,memory:1}),"resolved"],["reject","fail",s.Callbacks({once:1,memory:1}),"rejected"],["notify","progress",s.Callbacks({memory:1})]],r="pending",a={state:function(){return r},always:function(){return o.done(arguments).fail(arguments),this},then:function(){var l=arguments;return t(function(c){s.each(n,function(u,h){var d=s.isFunction(l[u])&&l[u];o[h[1]](function(){var f=d&&d.apply(this,arguments);if(f&&s.isFunction(f.promise))f.promise().done(c.resolve).fail(c.reject).progress(c.notify);else{var g=this===a?c.promise():this,v=d?[f]:arguments;c[h[0]+"With"](g,v)}})}),l=null}).promise()},promise:function(l){return l!=null?s.extend(l,a):a}},o={};return s.each(n,function(l,c){var u=c[2],h=c[3];a[c[1]]=u.add,h&&u.add(function(){r=h},n[l^1][2].disable,n[2][2].lock),o[c[0]]=function(){return o[c[0]+"With"](this===o?a:this,arguments),this},o[c[0]+"With"]=u.fireWith}),a.promise(o),i&&i.call(o,o),o}s.when=function(i){var n=e.call(arguments),r=n.length,a=0,o=r!==1||i&&s.isFunction(i.promise)?r:0,l=o===1?i:t(),c,u,h,d=function(f,g,v){return function(A){g[f]=this,v[f]=arguments.length>1?e.call(arguments):A,v===c?l.notifyWith(g,v):--o||l.resolveWith(g,v)}};if(r>1)for(c=new Array(r),u=new Array(r),h=new Array(r);a-1)return this},has:function(u,h,d){if(e.qsa(this,d).length)return this}},a=new RegExp("(.*):(\\w+)(?:\\(([^)]+)\\))?$\\s*"),o=/^\s*>/,l="Zepto"+ +new Date;function c(u,h){u=u.replace(/=#\]/g,'="#"]');var d,f,g=a.exec(u);if(g&&g[2]in r&&(d=r[g[2]],f=g[3],u=g[1],f)){var v=Number(f);isNaN(v)?f=f.replace(/^["']|["']$/g,""):f=v}return h(u,d,f)}e.qsa=function(u,h){return c(h,function(d,f,g){try{var v;!d&&f?d="*":o.test(d)&&(v=s(u).addClass(l),d="."+l+" "+d);var A=t(u,d)}catch(T){throw console.error("error performing selector: %o",h),T}finally{v&&v.removeClass(l)}return f?e.uniq(s.map(A,function(T,x){return f.call(T,x,A,g)})):A})},e.matches=function(u,h){return c(h,function(d,f,g){return(!d||i(u,d))&&(!f||f.call(u,null,g)===u)})}}(ht);var Q=ht,Ha=[{name:"Chromium",group:"Chrome",identifier:"Chromium/([0-9.]*)"},{name:"Chrome Mobile",group:"Chrome",identifier:"Chrome/([0-9.]*) Mobile",versionIdentifier:"Chrome/([0-9.]*)"},{name:"Chrome",group:"Chrome",identifier:"Chrome/([0-9.]*)"},{name:"Chrome for iOS",group:"Chrome",identifier:"CriOS/([0-9.]*)"},{name:"Android Browser",group:"Chrome",identifier:"CrMo/([0-9.]*)"},{name:"Firefox",group:"Firefox",identifier:"Firefox/([0-9.]*)"},{name:"Opera Mini",group:"Opera",identifier:"Opera Mini/([0-9.]*)"},{name:"Opera",group:"Opera",identifier:"Opera ([0-9.]*)"},{name:"Opera",group:"Opera",identifier:"Opera/([0-9.]*)",versionIdentifier:"Version/([0-9.]*)"},{name:"IEMobile",group:"Explorer",identifier:"IEMobile/([0-9.]*)"},{name:"Internet Explorer",group:"Explorer",identifier:"MSIE ([a-zA-Z0-9.]*)"},{name:"Internet Explorer",group:"Explorer",identifier:"Trident/([0-9.]*)",versionIdentifier:"rv:([0-9.]*)"},{name:"Spartan",group:"Spartan",identifier:"Edge/([0-9.]*)",versionIdentifier:"Edge/([0-9.]*)"},{name:"Safari",group:"Safari",identifier:"Safari/([0-9.]*)",versionIdentifier:"Version/([0-9.]*)"}],Ya=[{name:"Windows 2000",group:"Windows",identifier:"Windows NT 5.0",version:"5.0"},{name:"Windows XP",group:"Windows",identifier:"Windows NT 5.1",version:"5.1"},{name:"Windows Vista",group:"Windows",identifier:"Windows NT 6.0",version:"6.0"},{name:"Windows 7",group:"Windows",identifier:"Windows NT 6.1",version:"7.0"},{name:"Windows 8",group:"Windows",identifier:"Windows NT 6.2",version:"8.0"},{name:"Windows 8.1",group:"Windows",identifier:"Windows NT 6.3",version:"8.1"},{name:"Windows 10",group:"Windows",identifier:"Windows NT 10.0",version:"10.0"},{name:"Windows Phone",group:"Windows Phone",identifier:"Windows Phone ([0-9.]*)"},{name:"Windows Phone",group:"Windows Phone",identifier:"Windows Phone OS ([0-9.]*)"},{name:"Windows",group:"Windows",identifier:"Windows"},{name:"Chrome OS",group:"Chrome OS",identifier:"CrOS"},{name:"Android",group:"Android",identifier:"Android",versionIdentifier:"Android ([a-zA-Z0-9.-]*)"},{name:"iPad",group:"iOS",identifier:"iPad",versionIdentifier:"OS ([0-9_]*)",versionSeparator:"[_|.]"},{name:"iPod",group:"iOS",identifier:"iPod",versionIdentifier:"OS ([0-9_]*)",versionSeparator:"[_|.]"},{name:"iPhone",group:"iOS",identifier:"iPhone OS",versionIdentifier:"OS ([0-9_]*)",versionSeparator:"[_|.]"},{name:"Mac OS X High Sierra",group:"Mac OS",identifier:"Mac OS X (10([_|.])13([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Sierra",group:"Mac OS",identifier:"Mac OS X (10([_|.])12([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X El Capitan",group:"Mac OS",identifier:"Mac OS X (10([_|.])11([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Yosemite",group:"Mac OS",identifier:"Mac OS X (10([_|.])10([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Mavericks",group:"Mac OS",identifier:"Mac OS X (10([_|.])9([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Mountain Lion",group:"Mac OS",identifier:"Mac OS X (10([_|.])8([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Lion",group:"Mac OS",identifier:"Mac OS X (10([_|.])7([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Snow Leopard",group:"Mac OS",identifier:"Mac OS X (10([_|.])6([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Leopard",group:"Mac OS",identifier:"Mac OS X (10([_|.])5([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Tiger",group:"Mac OS",identifier:"Mac OS X (10([_|.])4([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Panther",group:"Mac OS",identifier:"Mac OS X (10([_|.])3([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Jaguar",group:"Mac OS",identifier:"Mac OS X (10([_|.])2([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Puma",group:"Mac OS",identifier:"Mac OS X (10([_|.])1([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS X Cheetah",group:"Mac OS",identifier:"Mac OS X (10([_|.])0([0-9_.]*))",versionSeparator:"[_|.]"},{name:"Mac OS",group:"Mac OS",identifier:"Mac OS"},{name:"Ubuntu",group:"Linux",identifier:"Ubuntu",versionIdentifier:"Ubuntu/([0-9.]*)"},{name:"Debian",group:"Linux",identifier:"Debian"},{name:"Gentoo",group:"Linux",identifier:"Gentoo"},{name:"Linux",group:"Linux",identifier:"Linux"},{name:"BlackBerry",group:"BlackBerry",identifier:"BlackBerry"}],z={},Wa=function(){try{return localStorage.setItem("clappr","clappr"),localStorage.removeItem("clappr"),!0}catch{return!1}},za=function(){try{var e=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");return!!e}catch{return!!(navigator.mimeTypes&&navigator.mimeTypes["application/x-shockwave-flash"]!==void 0&&navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin)}},ja=function(e){var t=e.match(/\b(playstation 4|nx|opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[],i;if(/trident/i.test(t[1]))return i=/\brv[ :]+(\d+)/g.exec(e)||[],{name:"IE",version:parseInt(i[1]||"")};if(t[1]==="Chrome"){if(i=e.match(/\bOPR\/(\d+)/),i!=null)return{name:"Opera",version:parseInt(i[1])};if(i=e.match(/\bEdge\/(\d+)/),i!=null)return{name:"Edge",version:parseInt(i[1])}}else/android/i.test(e)&&(i=e.match(/version\/(\d+)/i))&&(t.splice(1,1,"Android WebView"),t.splice(2,1,i[1]));return t=t[2]?[t[1],t[2]]:[navigator.appName,navigator.appVersion,"-?"],{name:t[0],version:parseInt(t[1])}},qa=function(){var e={},t=z.userAgent.toLowerCase(),i=jn(Ha),n;try{for(i.s();!(n=i.n()).done;){var r=n.value,a=new RegExp(r.identifier.toLowerCase()),o=a.exec(t);if(o!=null&&o[1]){if(e.name=r.name,e.group=r.group,r.versionIdentifier){var l=new RegExp(r.versionIdentifier.toLowerCase()),c=l.exec(t);c!=null&&c[1]&&Xn(c[1],e)}else Xn(o[1],e);break}}}catch(u){i.e(u)}finally{i.f()}return e},Xn=function(e,t){var i=e.split(".",2);t.fullVersion=e,i[0]&&(t.majorVersion=parseInt(i[0])),i[1]&&(t.minorVersion=parseInt(i[1]))},Xa=function(){var e={},t=z.userAgent.toLowerCase(),i=jn(Ya),n;try{for(i.s();!(n=i.n()).done;){var r=n.value,a=new RegExp(r.identifier.toLowerCase()),o=a.exec(t);if(o!=null){if(e.name=r.name,e.group=r.group,r.version)wi(r.version,r.versionSeparator?r.versionSeparator:".",e);else if(o[1])wi(o[1],r.versionSeparator?r.versionSeparator:".",e);else if(r.versionIdentifier){var l=new RegExp(r.versionIdentifier.toLowerCase()),c=l.exec(t);c!=null&&c[1]&&wi(c[1],r.versionSeparator?r.versionSeparator:".",e)}break}}}catch(u){i.e(u)}finally{i.f()}return e},wi=function(e,t,i){var n=t.substr(0,1)=="["?new RegExp(t,"g"):t,r=e.split(n,2);t!="."&&(e=e.replace(new RegExp(t,"g"),".")),i.fullVersion=e,r&&r[0]&&(i.majorVersion=parseInt(r[0])),r&&r[1]&&(i.minorVersion=parseInt(r[1]))},Qa=function(){var e={};return e.width=Q(window).width(),e.height=Q(window).height(),e},Za=function(){switch(window.orientation){case-90:case 90:z.viewport.orientation="landscape";break;default:z.viewport.orientation="portrait";break}},Ja=function(e){var t=/\((iP(?:hone|ad|od))?(?:[^;]*; ){0,2}([^)]+(?=\)))/,i=t.exec(e),n=i&&(i[1]||i[2])||"";return n},Qn=ja(navigator.userAgent);z.isEdge=/Edg|EdgiOS|EdgA/i.test(navigator.userAgent),z.isChrome=/Chrome|CriOS/i.test(navigator.userAgent)&&!z.isEdge,z.isSafari=/Safari/i.test(navigator.userAgent)&&!z.isChrome&&!z.isEdge,z.isFirefox=/Firefox/i.test(navigator.userAgent),z.isLegacyIE=!!window.ActiveXObject,z.isIE=z.isLegacyIE||/trident.*rv:1\d/i.test(navigator.userAgent),z.isIE11=/trident.*rv:11/i.test(navigator.userAgent),z.isChromecast=z.isChrome&&/CrKey/i.test(navigator.userAgent),z.isMobile=/Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone|IEMobile|Mobile Safari|Opera Mini/i.test(navigator.userAgent),z.isiOS=/iPad|iPhone|iPod/i.test(navigator.userAgent),z.isAndroid=/Android/i.test(navigator.userAgent),z.isWindowsPhone=/Windows Phone/i.test(navigator.userAgent),z.isWin8App=/MSAppHost/i.test(navigator.userAgent),z.isWiiU=/WiiU/i.test(navigator.userAgent),z.isPS4=/PlayStation 4/i.test(navigator.userAgent),z.hasLocalstorage=Wa(),z.hasFlash=za(),z.name=Qn.name,z.version=Qn.version,z.userAgent=navigator.userAgent,z.data=qa(),z.os=Xa(),z.isWindows=/^Windows$/i.test(z.os.group),z.isMacOS=/^Mac OS$/i.test(z.os.group),z.isLinux=/^Linux$/i.test(z.os.group),z.viewport=Qa(),z.device=Ja(z.userAgent),typeof window.orientation<"u"&&Za();var Pi={},Oi=[],Zn=(window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||function(s){window.setTimeout(s,1e3/60)}).bind(window),Jn=(window.cancelAnimationFrame||window.mozCancelAnimationFrame||window.webkitCancelAnimationFrame||window.clearTimeout).bind(window);function er(s,e){if(e)for(var t in e){var i=Object.getOwnPropertyDescriptor(e,t);i?Object.defineProperty(s,t,i):s[t]=e[t]}return s}function wt(s,e){var t=function(i){ve(r,i);var n=Ae(r);function r(){var a;he(this,r);for(var o=arguments.length,l=new Array(o),c=0;c0&&(a+=r+":",n<1&&(a+="00:")),(n&&n>0||e)&&(a+=("0"+n).slice(-2)+":"),a+=("0"+i).slice(-2)+":",a+=("0"+t).slice(-2),a.trim()}var Kt={fullscreenElement:function(){return document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement},requestFullscreen:function(e){if(e.requestFullscreen)return e.requestFullscreen();if(e.webkitRequestFullscreen){if(typeof e.then=="function")return e.webkitRequestFullscreen();e.webkitRequestFullscreen()}else{if(e.mozRequestFullScreen)return e.mozRequestFullScreen();if(e.msRequestFullscreen)return e.msRequestFullscreen();e.querySelector&&e.querySelector("video")&&e.querySelector("video").webkitEnterFullScreen?e.querySelector("video").webkitEnterFullScreen():e.webkitEnterFullScreen&&e.webkitEnterFullScreen()}},cancelFullscreen:function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:document;e.exitFullscreen?e.exitFullscreen():e.webkitCancelFullScreen?e.webkitCancelFullScreen():e.webkitExitFullscreen?e.webkitExitFullscreen():e.mozCancelFullScreen?e.mozCancelFullScreen():e.msExitFullscreen&&e.msExitFullscreen()},fullscreenEnabled:function(){return!!(document.fullscreenEnabled||document.webkitFullscreenEnabled||document.mozFullScreenEnabled||document.msFullscreenEnabled)}},to=function(){function s(){he(this,s)}return de(s,null,[{key:"_defaultConfig",value:function(){return{volume:{value:100,parse:parseInt}}}},{key:"_defaultValueFor",value:function(t){try{return this._defaultConfig()[t].parse(this._defaultConfig()[t].value)}catch{return}}},{key:"_createKeyspace",value:function(t){return"clappr.".concat(document.domain,".").concat(t)}},{key:"restore",value:function(t){return z.hasLocalstorage&&localStorage[this._createKeyspace(t)]?this._defaultConfig()[t].parse(localStorage[this._createKeyspace(t)]):this._defaultValueFor(t)}},{key:"persist",value:function(t,i){if(z.hasLocalstorage)try{return localStorage[this._createKeyspace(t)]=i,!0}catch{return!1}}}]),s}(),Ni=function(){function s(){he(this,s)}return de(s,null,[{key:"params",get:function(){var t=window.location.search.substring(1);return t!==this.query&&(this._urlParams=this.parse(t),this.query=t),this._urlParams}},{key:"hashParams",get:function(){var t=window.location.hash.substring(1);return t!==this.hash&&(this._hashParams=this.parse(t),this.hash=t),this._hashParams}},{key:"parse",value:function(t){for(var i,n=/\+/g,r=/([^&=]+)=?([^&]*)/g,a=function(c){return decodeURIComponent(c.replace(n," "))},o={};i=r.exec(t);)o[a(i[1]).toLowerCase()]=a(i[2]);return o}}]),s}();function tr(){var s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"t",e=0,t=Ni.params[s]||Ni.hashParams[s]||"",i=t.match(/[0-9]+[hms]+/g)||[];if(i.length>0){var n={h:3600,m:60,s:1};i.forEach(function(r){if(r){var a=r[r.length-1],o=parseInt(r.slice(0,r.length-1),10);e+=o*n[a]}})}else t&&(e=parseInt(t,10));return e}function Ht(s){Pi[s]||(Pi[s]=0);var e=++Pi[s];return s+e}function ii(s){return s-parseFloat(s)+1>=0}function ir(){var s=document.getElementsByTagName("script");return s.length?s[s.length-1].src:""}function nr(){return window.navigator&&window.navigator.language}function io(){return window.performance&&window.performance.now?performance.now():Date.now()}function no(s,e){var t=s.indexOf(e);t>=0&&s.splice(t,1)}function ro(s,e){return s===void 0||e===void 0?!1:e.find(function(t){return s.toLowerCase()===t.toLowerCase()})!==void 0}function rr(s,e){e=Object.assign({inline:!1,muted:!1,timeout:250,type:"video",source:qn.mp4,element:null},e);var t=e.element?e.element:document.createElement(e.type);t.muted=e.muted,e.muted===!0&&t.setAttribute("muted","muted"),e.inline===!0&&t.setAttribute("playsinline","playsinline"),t.src=e.source;var i=t.play(),n=setTimeout(function(){r(!1,new Error("Timeout ".concat(e.timeout," ms has been reached")))},e.timeout),r=function(o){var l=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null;clearTimeout(n),s(o,l)};i!==void 0?i.then(function(){return r(!0)}).catch(function(a){return r(!1,a)}):r(!0)}var Pt=function(){function s(){he(this,s)}return de(s,null,[{key:"configure",value:function(t){this.options=Q.extend(!0,this.options,t)}},{key:"create",value:function(t){return this.options.recycleVideo&&t==="video"&&Oi.length>0?Oi.shift():document.createElement(t)}},{key:"garbage",value:function(t){!this.options.recycleVideo||t.tagName.toUpperCase()!=="VIDEO"||(Q(t).children().remove(),Object.values(t.attributes).forEach(function(i){return t.removeAttribute(i.name)}),Oi.push(t))}}]),s}();Pt.options={recycleVideo:!1};var sr=function(){function s(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:500;he(this,s),this.delay=e,this.lastTime=0}return de(s,[{key:"handle",value:function(t,i){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=new Date().getTime(),a=r-this.lastTime;a0&&(i(),n&&t.preventDefault()),this.lastTime=r}}]),s}(),rt={Config:to,Fullscreen:Kt,QueryString:Ni,DomRecycler:Pt,assign:er,extend:wt,formatTime:eo,seekStringToSeconds:tr,uniqueId:Ht,currentScriptUrl:ir,isNumber:ii,requestAnimationFrame:Zn,cancelAnimationFrame:Jn,getBrowserLanguage:nr,now:io,removeArrayItem:no,listContainsIgnoreCase:ro,canAutoPlayMedia:rr,Media:qn,DoubleEventHandler:sr},ni="font-weight: bold; font-size: 13px;",so="color: #006600;"+ni,ao="color: #0000ff;"+ni,ar="color: #ff8000;"+ni,or="color: #ff0000;"+ni,lr=0,Fi=1,cr=2,Mi=3,oo=Mi,lo=[ao,so,ar,or,or],ur=["debug","info","warn","error","disabled"],ae=function(){function s(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Fi,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:oo;he(this,s),this.EXCLUDE_LIST=["timeupdate","playback:timeupdate","playback:progress","container:hover","container:timeupdate","container:progress"],this.level=e,this.previousLevel=this.level,this.offLevel=t}return de(s,[{key:"level",get:function(){return this._level},set:function(t){this._level=t}},{key:"debug",value:function(t){this.log(t,lr,Array.prototype.slice.call(arguments,1))}},{key:"info",value:function(t){this.log(t,Fi,Array.prototype.slice.call(arguments,1))}},{key:"warn",value:function(t){this.log(t,cr,Array.prototype.slice.call(arguments,1))}},{key:"error",value:function(t){this.log(t,Mi,Array.prototype.slice.call(arguments,1))}},{key:"onOff",value:function(){this.level===this.offLevel?this.level=this.previousLevel:(this.previousLevel=this.level,this.level=this.offLevel),window.console&&window.console.log&&window.console.log("%c[Clappr.Log] set log level to "+ur[this.level],ar)}},{key:"log",value:function(t,i,n){if(!(this.EXCLUDE_LIST.indexOf(n[0])>=0)&&!(i0&&arguments[0]!==void 0?arguments[0]:{};return he(this,t),i=e.call(this,n),i._options=n,i.uniqueId=Ht("o"),i}return de(t,[{key:"options",get:function(){return this._options}}]),t}(p),Tt={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g},Bi=/(.)^/,uo={"'":"'","\\":"\\","\r":"r","\n":"n"," ":"t","\u2028":"u2028","\u2029":"u2029"},ho=/\\|'|\r|\n|\t|\u2028|\u2029/g,fo={"&":"&","<":"<",">":">",'"':""","'":"'"},go=new RegExp(`[&<>"']`,"g"),gr=function(e){return e===null?"":(""+e).replace(go,function(t){return fo[t]})},po=0,Ie=function(e,t){var i,n=new RegExp([(Tt.escape||Bi).source,(Tt.interpolate||Bi).source,(Tt.evaluate||Bi).source].join("|")+"|$","g"),r=0,a="__p+='";e.replace(n,function(l,c,u,h,d){return a+=e.slice(r,d).replace(ho,function(f){return"\\"+uo[f]}),c&&(a+=`'+ ((__t=(`+c+`))==null?'':escapeExpr(__t))+ '`),u&&(a+=`'+ ((__t=(`+u+`))==null?'':__t)+ '`),h&&(a+=`'; `+h+` __p+='`),r=d+l.length,l}),a+=`'; `,Tt.variable||(a=`with(obj||{}){ `+a+`} `),a=`var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');}; `+a+`return __p; //# sourceURL=/microtemplates/source[`+po+++"]";try{i=new Function(Tt.variable||"obj","escapeExpr",a)}catch(l){throw l.source=a,l}if(t)return i(t,gr);var o=function(c){return i.call(this,c,gr)};return o.source="function("+(Tt.variable||"obj")+`){ `+a+"}",o};Ie.settings=Tt;var Se={getStyleFor:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{baseUrl:""};return Q('').html(Ie(e.toString())(t))}},mo=/^(\S+)\s*(.*)$/,Ot=function(s){ve(t,s);var e=Ae(t);function t(i){var n;return he(this,t),n=e.call(this,i),n.cid=Ht("c"),n._ensureElement(),n.delegateEvents(),n}return de(t,[{key:"tagName",get:function(){return"div"}},{key:"events",get:function(){return{}}},{key:"attributes",get:function(){return{}}},{key:"$",value:function(n){return this.$el.find(n)}},{key:"render",value:function(){return this}},{key:"destroy",value:function(){return this.$el.remove(),this.stopListening(),this.undelegateEvents(),this}},{key:"setElement",value:function(n,r){return this.$el&&this.undelegateEvents(),this.$el=Q.zepto.isZ(n)?n:Q(n),this.el=this.$el[0],r!==!1&&this.delegateEvents(),this}},{key:"delegateEvents",value:function(n){n||(n=this.events),this.undelegateEvents();for(var r in n){var a=n[r];if(a&&a.constructor!==Function&&(a=this[n[r]]),!!a){var o=r.match(mo),l=o[1],c=o[2];l+=".delegateEvents"+this.cid,c===""?this.$el.on(l,a.bind(this)):this.$el.on(l,c,a.bind(this))}}return this}},{key:"undelegateEvents",value:function(){return this.$el.off(".delegateEvents"+this.cid),this}},{key:"_ensureElement",value:function(){if(this.el)this.setElement(this.el,!1);else{var n=Q.extend(!0,{},this.attributes);this.id&&(n.id=this.id),this.className&&(n.class=this.className);var r=Q(Pt.create(this.tagName)).attr(n);this.setElement(r,!1)}}}]),t}(st),Ve=function(s){ve(t,s);var e=Ae(t);function t(){var i,n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},r=arguments.length>1?arguments[1]:void 0;return he(this,t),i=e.call(this,n),i.core=r,i}return de(t,[{key:"name",get:function(){return"error"}},{key:"createError",value:function(n){if(!this.core){ae.warn(this.name,"Core is not set. Error: ",n);return}this.core.trigger(p.ERROR,n)}}],[{key:"Levels",get:function(){return{FATAL:"FATAL",WARN:"WARN",INFO:"INFO"}}}]),t}(st),dt={createError:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{useCodePrefix:!0},i=this.constructor&&this.constructor.type||"",n=this.name||i,r=this.i18n||this.core&&this.core.i18n||this.container&&this.container.i18n,a="".concat(n,":").concat(e&&e.code||"unknown"),o={description:"",level:Ve.Levels.FATAL,origin:n,scope:i,raw:{}},l=Object.assign({},o,e,{code:t.useCodePrefix?a:e.code});if(r&&l.level==Ve.Levels.FATAL&&!l.UI){var c={title:r.t("default_error_title"),message:r.t("default_error_message")};l.UI=c}return this.playerError?this.playerError.createError(l):ae.warn(n,"PlayerError is not defined. Error: ",l),l}},Ne=function(s){ve(t,s);var e=Ae(t);function t(i){var n;return he(this,t),n=e.call(this,i.options),n.core=i,n.enabled=!0,n.bindEvents(),n.render(),n}return de(t,[{key:"playerError",get:function(){return this.core.playerError}},{key:"bindEvents",value:function(){}},{key:"getExternalInterface",value:function(){return{}}},{key:"enable",value:function(){this.enabled||(this.bindEvents(),this.$el.show(),this.enabled=!0)}},{key:"disable",value:function(){this.stopListening(),this.$el.hide(),this.enabled=!1}},{key:"render",value:function(){return this}}]),t}(Ot);Object.assign(Ne.prototype,dt),Ne.extend=function(s){return wt(Ne,s)},Ne.type="core";var yo=`.container[data-container] { position: absolute; background-color: black; height: 100%; width: 100%; max-width: 100%; } .container[data-container] .chromeless { cursor: default; } [data-player]:not(.nocursor) .container[data-container]:not(.chromeless).pointer-enabled { cursor: pointer; } `,Ui=function(s){ve(t,s);var e=Ae(t);function t(i,n,r){var a;return he(this,t),a=e.call(this,i),a._i18n=n,a.currentTime=0,a.volume=100,a.playback=i.playback,a.playerError=r,a.settings=Q.extend(!0,{},a.playback.settings),a.isReady=!1,a.mediaControlDisabled=!1,a.plugins=[a.playback],a.dblTapHandler=new sr(500),a.clickTimer=null,a.clickDelay=200,a.actionsMetadata={},a.bindEvents(),a}return de(t,[{key:"name",get:function(){return"Container"}},{key:"attributes",get:function(){return{class:"container","data-container":""}}},{key:"events",get:function(){return{click:"clicked",dblclick:"dblClicked",touchend:"dblTap",contextmenu:"onContextMenu",mouseenter:"mouseEnter",mouseleave:"mouseLeave",mouseup:"onMouseUp",mousedown:"onMouseDown"}}},{key:"ended",get:function(){return this.playback.ended}},{key:"buffering",get:function(){return this.playback.buffering}},{key:"i18n",get:function(){return this._i18n}},{key:"hasClosedCaptionsTracks",get:function(){return this.playback.hasClosedCaptionsTracks}},{key:"closedCaptionsTracks",get:function(){return this.playback.closedCaptionsTracks}},{key:"closedCaptionsTrackId",get:function(){return this.playback.closedCaptionsTrackId},set:function(n){this.playback.closedCaptionsTrackId=n}},{key:"audioTracks",get:function(){return this.playback.audioTracks}},{key:"currentAudioTrack",get:function(){return this.playback.currentAudioTrack}},{key:"bindEvents",value:function(){this.listenTo(this.playback,p.PLAYBACK_PROGRESS,this.onProgress),this.listenTo(this.playback,p.PLAYBACK_TIMEUPDATE,this.timeUpdated),this.listenTo(this.playback,p.PLAYBACK_READY,this.ready),this.listenTo(this.playback,p.PLAYBACK_BUFFERING,this.onBuffering),this.listenTo(this.playback,p.PLAYBACK_BUFFERFULL,this.bufferfull),this.listenTo(this.playback,p.PLAYBACK_SETTINGSUPDATE,this.settingsUpdate),this.listenTo(this.playback,p.PLAYBACK_LOADEDMETADATA,this.loadedMetadata),this.listenTo(this.playback,p.PLAYBACK_HIGHDEFINITIONUPDATE,this.highDefinitionUpdate),this.listenTo(this.playback,p.PLAYBACK_BITRATE,this.updateBitrate),this.listenTo(this.playback,p.PLAYBACK_PLAYBACKSTATE,this.playbackStateChanged),this.listenTo(this.playback,p.PLAYBACK_DVR,this.playbackDvrStateChanged),this.listenTo(this.playback,p.PLAYBACK_MEDIACONTROL_DISABLE,this.disableMediaControl),this.listenTo(this.playback,p.PLAYBACK_MEDIACONTROL_ENABLE,this.enableMediaControl),this.listenTo(this.playback,p.PLAYBACK_SEEK,this.onSeek),this.listenTo(this.playback,p.PLAYBACK_SEEKED,this.onSeeked),this.listenTo(this.playback,p.PLAYBACK_ENDED,this.onEnded),this.listenTo(this.playback,p.PLAYBACK_PLAY,this.playing),this.listenTo(this.playback,p.PLAYBACK_PAUSE,this.paused),this.listenTo(this.playback,p.PLAYBACK_STOP,this.stopped),this.listenTo(this.playback,p.PLAYBACK_ERROR,this.error),this.listenTo(this.playback,p.PLAYBACK_SUBTITLE_AVAILABLE,this.subtitleAvailable),this.listenTo(this.playback,p.PLAYBACK_SUBTITLE_CHANGED,this.subtitleChanged),this.listenTo(this.playback,p.PLAYBACK_AUDIO_AVAILABLE,this.audioAvailable),this.listenTo(this.playback,p.PLAYBACK_AUDIO_CHANGED,this.audioChanged)}},{key:"subtitleAvailable",value:function(){this.trigger(p.CONTAINER_SUBTITLE_AVAILABLE)}},{key:"subtitleChanged",value:function(n){this.trigger(p.CONTAINER_SUBTITLE_CHANGED,n)}},{key:"audioAvailable",value:function(n){this.trigger(p.CONTAINER_AUDIO_AVAILABLE,n)}},{key:"audioChanged",value:function(n){this.trigger(p.CONTAINER_AUDIO_CHANGED,n)}},{key:"playbackStateChanged",value:function(n){this.trigger(p.CONTAINER_PLAYBACKSTATE,n)}},{key:"playbackDvrStateChanged",value:function(n){this.settings=this.playback.settings,this.dvrInUse=n,this.trigger(p.CONTAINER_PLAYBACKDVRSTATECHANGED,n)}},{key:"updateBitrate",value:function(n){this.trigger(p.CONTAINER_BITRATE,n)}},{key:"statsReport",value:function(n){this.trigger(p.CONTAINER_STATS_REPORT,n)}},{key:"getPlaybackType",value:function(){return this.playback.getPlaybackType()}},{key:"isDvrEnabled",value:function(){return!!this.playback.dvrEnabled}},{key:"isDvrInUse",value:function(){return!!this.dvrInUse}},{key:"destroy",value:function(){this.disableResizeObserver(),this.trigger(p.CONTAINER_DESTROYED,this,this.name),this.stopListening(),this.plugins.forEach(function(n){return n.destroy()}),this.$el.remove()}},{key:"setStyle",value:function(n){this.$el.css(n)}},{key:"animate",value:function(n,r){return this.$el.animate(n,r).promise()}},{key:"ready",value:function(){this.isReady=!0,this.trigger(p.CONTAINER_READY,this.name)}},{key:"isPlaying",value:function(){return this.playback.isPlaying()}},{key:"getStartTimeOffset",value:function(){return this.playback.getStartTimeOffset()}},{key:"getCurrentTime",value:function(){return this.currentTime}},{key:"getDuration",value:function(){return this.playback.getDuration()}},{key:"error",value:function(n){this.isReady||this.ready(),this.trigger(p.CONTAINER_ERROR,n,this.name)}},{key:"loadedMetadata",value:function(n){this.trigger(p.CONTAINER_LOADEDMETADATA,n)}},{key:"timeUpdated",value:function(n){this.currentTime=n.current,this.trigger(p.CONTAINER_TIMEUPDATE,n,this.name)}},{key:"onProgress",value:function(){for(var n=arguments.length,r=new Array(n),a=0;a0&&arguments[0]!==void 0?arguments[0]:{};this.actionsMetadata.playEvent=n,this.playback.play(n)}},{key:"stop",value:function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.actionsMetadata.stopEvent=n,this.playback.stop(n),this.currentTime=0}},{key:"switchAudioTrack",value:function(n){this.playback.switchAudioTrack(n)}},{key:"pause",value:function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.actionsMetadata.pauseEvent=n,this.playback.pause(n)}},{key:"onEnded",value:function(){this.trigger(p.CONTAINER_ENDED,this,this.name),this.currentTime=0}},{key:"clicked",value:function(){var n=this;(!this.options.chromeless||this.options.allowUserInteraction)&&(this.clickTimer=setTimeout(function(){n.clickTimer&&n.trigger(p.CONTAINER_CLICK,n,n.name)},this.clickDelay))}},{key:"cancelClicked",value:function(){clearTimeout(this.clickTimer),this.clickTimer=null}},{key:"dblClicked",value:function(){(!this.options.chromeless||this.options.allowUserInteraction)&&(this.cancelClicked(),this.trigger(p.CONTAINER_DBLCLICK,this,this.name))}},{key:"dblTap",value:function(n){var r=this;(!this.options.chromeless||this.options.allowUserInteraction)&&this.dblTapHandler.handle(n,function(){r.cancelClicked(),r.trigger(p.CONTAINER_DBLCLICK,r,r.name)})}},{key:"onContextMenu",value:function(n){(!this.options.chromeless||this.options.allowUserInteraction)&&this.trigger(p.CONTAINER_CONTEXTMENU,n,this.name)}},{key:"seek",value:function(n){this.playback.seek(n)}},{key:"onSeek",value:function(n){this.trigger(p.CONTAINER_SEEK,n,this.name)}},{key:"onSeeked",value:function(){this.trigger(p.CONTAINER_SEEKED,this.name)}},{key:"seekPercentage",value:function(n){var r=this.getDuration();if(n>=0&&n<=100){var a=r*(n/100);this.seek(a)}}},{key:"setVolume",value:function(n){this.volume=parseFloat(n),this.trigger(p.CONTAINER_VOLUME,this.volume,this.name),this.playback.volume(this.volume)}},{key:"fullscreen",value:function(){this.trigger(p.CONTAINER_FULLSCREEN,this.name)}},{key:"onBuffering",value:function(){this.trigger(p.CONTAINER_STATE_BUFFERING,this.name)}},{key:"bufferfull",value:function(){this.trigger(p.CONTAINER_STATE_BUFFERFULL,this.name)}},{key:"addPlugin",value:function(n){this.plugins.push(n)}},{key:"hasPlugin",value:function(n){return!!this.getPlugin(n)}},{key:"getPlugin",value:function(n){return this.plugins.filter(function(r){return r.name===n})[0]}},{key:"mouseEnter",value:function(){(!this.options.chromeless||this.options.allowUserInteraction)&&this.trigger(p.CONTAINER_MOUSE_ENTER)}},{key:"mouseLeave",value:function(){(!this.options.chromeless||this.options.allowUserInteraction)&&this.trigger(p.CONTAINER_MOUSE_LEAVE)}},{key:"mouseUp",value:function(){(!this.options.chromeless||this.options.allowUserInteraction)&&this.trigger(p.CONTAINER_MOUSE_UP)}},{key:"mouseDown",value:function(){(!this.options.chromeless||this.options.allowUserInteraction)&&this.trigger(p.CONTAINER_MOUSE_DOWN)}},{key:"settingsUpdate",value:function(){this.settings=this.playback.settings,this.trigger(p.CONTAINER_SETTINGSUPDATE)}},{key:"highDefinitionUpdate",value:function(n){this.trigger(p.CONTAINER_HIGHDEFINITIONUPDATE,n)}},{key:"isHighDefinitionInUse",value:function(){return this.playback.isHighDefinitionInUse()}},{key:"disableMediaControl",value:function(){this.mediaControlDisabled||(this.mediaControlDisabled=!0,this.trigger(p.CONTAINER_MEDIACONTROL_DISABLE))}},{key:"enableMediaControl",value:function(){this.mediaControlDisabled&&(this.mediaControlDisabled=!1,this.trigger(p.CONTAINER_MEDIACONTROL_ENABLE))}},{key:"updateStyle",value:function(){!this.options.chromeless||this.options.allowUserInteraction?this.$el.removeClass("chromeless"):this.$el.addClass("chromeless")}},{key:"enableResizeObserver",value:function(){var n=this;this.disableResizeObserver(),this.resizeObserverInterval=setInterval(function(){return n.checkResize()},500)}},{key:"disableResizeObserver",value:function(){this.resizeObserverInterval&&clearInterval(this.resizeObserverInterval)}},{key:"checkResize",value:function(){var n={width:this.el.clientWidth,height:this.el.clientHeight},r=this.currentSize||{},a=r.width,o=r.height,l=o!==n.height||a!==n.width;l&&(this.currentSize=n,this.trigger(p.CONTAINER_RESIZE,n))}},{key:"configure",value:function(n){this._options=Q.extend(!0,this._options,n),this.updateStyle(),this.playback.configure(this.options),this.trigger(p.CONTAINER_OPTIONS_CHANGE)}},{key:"render",value:function(){var n=Se.getStyleFor(yo.toString(),{baseUrl:this.options.baseUrl});return this.$el.append(n[0]),this.$el.append(this.playback.render().el),this.updateStyle(),this.checkResize(),this.enableResizeObserver(),this}}]),t}(Ot);Object.assign(Ui.prototype,dt);var se=function(s){ve(t,s);var e=Ae(t);function t(i,n,r){var a;return he(this,t),a=e.call(this,i),a.settings={},a._i18n=n,a.playerError=r,a._consented=!1,a}return de(t,[{key:"isAudioOnly",get:function(){return!1}},{key:"isAdaptive",get:function(){return!1}},{key:"ended",get:function(){return!1}},{key:"i18n",get:function(){return this._i18n}},{key:"buffering",get:function(){return!1}},{key:"consent",value:function(n){typeof n=="function"&&n()}},{key:"play",value:function(){}},{key:"pause",value:function(){}},{key:"stop",value:function(){}},{key:"seek",value:function(n){}},{key:"seekPercentage",value:function(n){}},{key:"getStartTimeOffset",value:function(){return 0}},{key:"getDuration",value:function(){return 0}},{key:"isPlaying",value:function(){return!1}},{key:"isReady",get:function(){return!1}},{key:"hasClosedCaptionsTracks",get:function(){return this.closedCaptionsTracks.length>0}},{key:"closedCaptionsTracks",get:function(){return[]}},{key:"closedCaptionsTrackId",get:function(){return-1},set:function(n){}},{key:"audioTracks",get:function(){return[]}},{key:"currentAudioTrack",get:function(){return null}},{key:"switchAudioTrack",value:function(n){}},{key:"getPlaybackType",value:function(){return t.NO_OP}},{key:"isHighDefinitionInUse",value:function(){return!1}},{key:"mute",value:function(){}},{key:"unmute",value:function(){}},{key:"volume",value:function(n){}},{key:"configure",value:function(n){this._options=Q.extend(!0,this._options,n)}},{key:"attemptAutoPlay",value:function(){var n=this;this.canAutoPlay(function(r,a){r&&n.play()})}},{key:"canAutoPlay",value:function(n){n(!0,null)}}]),t}(Ot);Object.assign(se.prototype,dt),se.extend=function(s){return wt(se,s)},se.canPlay=function(s,e){return!1},se.VOD="vod",se.AOD="aod",se.LIVE="live",se.NO_OP="no_op",se.type="playback";var vo=function(s){ve(t,s);var e=Ae(t);function t(i,n,r,a){var o;return he(this,t),o=e.call(this,i),o._i18n=r,o.loader=n,o.playerError=a,o}return de(t,[{key:"options",get:function(){return this._options},set:function(n){this._options=n}},{key:"createContainers",value:function(){var n=this;return Q.Deferred(function(r){r.resolve(n.options.sources.map(function(a){return n.createContainer(a)}))})}},{key:"findPlaybackPlugin",value:function(n,r){return this.loader.playbackPlugins.filter(function(a){return a.canPlay(n,r)})[0]}},{key:"createContainer",value:function(n){var r=null,a=this.options.mimeType;Rt(n)==="object"?(r=n.source.toString(),n.mimeType&&(a=n.mimeType)):r=n.toString(),r.match(/^\/\//)&&(r=window.location.protocol+r);var o=ei(ei({},this.options),{},{src:r,mimeType:a}),l=this.findPlaybackPlugin(r,a),c=l?new l(o,this._i18n,this.playerError):new se;o=ei(ei({},o),{},{playback:c});var u=new Ui(o,this._i18n,this.playerError),h=Q.Deferred();return h.promise(u),this.addContainerPlugins(u),this.listenToOnce(u,p.CONTAINER_READY,function(){return h.resolve(u)}),u}},{key:"addContainerPlugins",value:function(n){this.loader.containerPlugins.forEach(function(r){n.addPlugin(new r(n))})}}]),t}(st),Ao=`[data-player] { -webkit-touch-callout: none; -webkit-user-select: none; -moz-user-select: none; -o-user-select: none; user-select: none; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; transform: translate3d(0, 0, 0); position: relative; margin: 0; padding: 0; border: 0; font-style: normal; font-weight: normal; text-align: center; overflow: hidden; font-size: 100%; font-family: "Roboto", "Open Sans", Arial, sans-serif; text-shadow: 0 0 0; box-sizing: border-box; } [data-player]:focus { outline: 0; } [data-player] * { box-sizing: inherit; } [data-player] > * { float: none; max-width: none; } [data-player] > div { display: block; } [data-player].fullscreen { width: 100% !important; height: 100% !important; top: 0; left: 0; } [data-player].nocursor { cursor: none; } .clappr-style { display: none !important; } `,Eo=`[data-player] div, [data-player] span, [data-player] applet, [data-player] object, [data-player] iframe, [data-player] h1, [data-player] h2, [data-player] h3, [data-player] h4, [data-player] h5, [data-player] h6, [data-player] p, [data-player] blockquote, [data-player] pre, [data-player] a, [data-player] abbr, [data-player] acronym, [data-player] address, [data-player] big, [data-player] cite, [data-player] code, [data-player] del, [data-player] dfn, [data-player] em, [data-player] img, [data-player] ins, [data-player] kbd, [data-player] q, [data-player] s, [data-player] samp, [data-player] small, [data-player] strike, [data-player] strong, [data-player] sub, [data-player] sup, [data-player] tt, [data-player] var, [data-player] b, [data-player] u, [data-player] i, [data-player] center, [data-player] dl, [data-player] dt, [data-player] dd, [data-player] ol, [data-player] ul, [data-player] li, [data-player] fieldset, [data-player] form, [data-player] label, [data-player] legend, [data-player] table, [data-player] caption, [data-player] tbody, [data-player] tfoot, [data-player] thead, [data-player] tr, [data-player] th, [data-player] td, [data-player] article, [data-player] aside, [data-player] canvas, [data-player] details, [data-player] embed, [data-player] figure, [data-player] figcaption, [data-player] footer, [data-player] header, [data-player] hgroup, [data-player] menu, [data-player] nav, [data-player] output, [data-player] ruby, [data-player] section, [data-player] summary, [data-player] time, [data-player] mark, [data-player] audio, [data-player] video { margin: 0; padding: 0; border: 0; font: inherit; font-size: 100%; vertical-align: baseline; } [data-player] table { border-collapse: collapse; border-spacing: 0; } [data-player] caption, [data-player] th, [data-player] td { text-align: left; font-weight: normal; vertical-align: middle; } [data-player] q, [data-player] blockquote { quotes: none; } [data-player] q:before, [data-player] q:after, [data-player] blockquote:before, [data-player] blockquote:after { content: ""; content: none; } [data-player] a img { border: none; } `,$i=function(s){ve(t,s);var e=Ae(t);function t(i){var n;return he(this,t),n=e.call(this,i),n.playerError=new Ve(i,ti(n)),n.configureDomRecycler(),n.firstResize=!0,n.plugins=[],n.containers=[],n._boundFullscreenHandler=function(){return n.handleFullscreenChange()},Q(document).bind("fullscreenchange",n._boundFullscreenHandler),Q(document).bind("MSFullscreenChange",n._boundFullscreenHandler),Q(document).bind("mozfullscreenchange",n._boundFullscreenHandler),z.isMobile&&Q(window).bind("resize",function(r){n.handleWindowResize(r)}),n}return de(t,[{key:"events",get:function(){return{webkitfullscreenchange:"handleFullscreenChange",mousemove:"onMouseMove",mouseleave:"onMouseLeave"}}},{key:"attributes",get:function(){return{"data-player":"",tabindex:9999}}},{key:"isReady",get:function(){return!!this.ready}},{key:"i18n",get:function(){return this.getPlugin("strings")||{t:function(r){return r}}}},{key:"mediaControl",get:function(){return this._mediaControl||(this._mediaControl=this.getPlugin("media_control"))||this.dummyMediaControl}},{key:"dummyMediaControl",get:function(){return this._dummyMediaControl?this._dummyMediaControl:(this._dummyMediaControl=new Ne(this),this._dummyMediaControl)}},{key:"activeContainer",get:function(){return this._activeContainer},set:function(n){this._activeContainer=n,this.trigger(p.CORE_ACTIVE_CONTAINER_CHANGED,this._activeContainer)}},{key:"activePlayback",get:function(){return this.activeContainer&&this.activeContainer.playback}},{key:"activePlaybackEl",get:function(){if(this.activePlayback)return this.activePlayback.$el?this.activePlayback.$el.find("video")[0]:this.activePlayback.el}},{key:"configureDomRecycler",value:function(){var n=this.options&&this.options.playback&&this.options.playback.recycleVideo;Pt.configure({recycleVideo:n})}},{key:"createContainers",value:function(n){this.defer=Q.Deferred(),this.defer.promise(this),this.containerFactory=new vo(n,n.loader,this.i18n,this.playerError),this.prepareContainers()}},{key:"prepareContainers",value:function(){var n=this;this.containerFactory.createContainers().then(function(r){return n.setupContainers(r)}).then(function(r){return n.resolveOnContainersReady(r)})}},{key:"updateSize",value:function(){this.isFullscreen()?this.setFullscreen():this.setPlayerSize()}},{key:"setFullscreen",value:function(){z.isiOS||(this.$el.addClass("fullscreen"),this.$el.removeAttr("style"),this.previousSize={width:this.options.width,height:this.options.height},this.currentSize={width:Q(window).width(),height:Q(window).height()})}},{key:"setPlayerSize",value:function(){this.$el.removeClass("fullscreen"),this.currentSize=this.previousSize,this.previousSize={width:Q(window).width(),height:Q(window).height()},this.resize(this.currentSize)}},{key:"resize",value:function(n){!ii(n.height)&&!ii(n.width)?(this.el.style.height="".concat(n.height),this.el.style.width="".concat(n.width)):(this.el.style.height="".concat(n.height,"px"),this.el.style.width="".concat(n.width,"px")),this.previousSize={width:this.options.width,height:this.options.height},this.options.width=n.width,this.options.height=n.height,this.currentSize=n,this.triggerResize(this.currentSize)}},{key:"enableResizeObserver",value:function(){var n=this;this.disableResizeObserver();var r=function(){n.triggerResize({width:n.el.clientWidth,height:n.el.clientHeight})};this.resizeObserverInterval=setInterval(r,500)}},{key:"triggerResize",value:function(n){var r=this.firstResize||this.oldHeight!==n.height||this.oldWidth!==n.width;r&&(this.oldHeight=n.height,this.oldWidth=n.width,this.computedSize=n,this.firstResize=!1,this.trigger(p.CORE_RESIZE,n))}},{key:"disableResizeObserver",value:function(){this.resizeObserverInterval&&clearInterval(this.resizeObserverInterval),this.resizeObserverInterval=null}},{key:"resolveOnContainersReady",value:function(n){var r=this;Q.when.apply(Q,n).done(function(){r.defer.resolve(r),r.ready=!0,r.trigger(p.CORE_READY)})}},{key:"addPlugin",value:function(n){this.plugins.push(n)}},{key:"hasPlugin",value:function(n){return!!this.getPlugin(n)}},{key:"getPlugin",value:function(n){return this.plugins.filter(function(r){return r.name===n})[0]}},{key:"load",value:function(n,r){this.options.mimeType=r,n=n&&n.constructor===Array?n:[n],this.options.sources=n,this.containers.forEach(function(a){return a.destroy()}),this.containerFactory.options=Q.extend(!0,this.options,{sources:n}),this.prepareContainers()}},{key:"destroy",value:function(){this.disableResizeObserver(),this.containers.forEach(function(n){return n.destroy()}),this.plugins.forEach(function(n){return n.destroy()}),this.$el.remove(),Q(document).unbind("fullscreenchange",this._boundFullscreenHandler),Q(document).unbind("MSFullscreenChange",this._boundFullscreenHandler),Q(document).unbind("mozfullscreenchange",this._boundFullscreenHandler),this.stopListening()}},{key:"handleFullscreenChange",value:function(){this.trigger(p.CORE_FULLSCREEN,this.isFullscreen()),this.updateSize()}},{key:"handleWindowResize",value:function(n){var r=window.innerWidth>window.innerHeight?"landscape":"portrait";this._screenOrientation!==r&&(this._screenOrientation=r,this.triggerResize({width:this.el.clientWidth,height:this.el.clientHeight}),this.trigger(p.CORE_SCREEN_ORIENTATION_CHANGED,{event:n,orientation:this._screenOrientation}))}},{key:"removeContainer",value:function(n){this.stopListening(n),this.containers=this.containers.filter(function(r){return r!==n})}},{key:"setupContainer",value:function(n){this.listenTo(n,p.CONTAINER_DESTROYED,this.removeContainer),this.containers.push(n)}},{key:"setupContainers",value:function(n){return n.forEach(this.setupContainer.bind(this)),this.trigger(p.CORE_CONTAINERS_CREATED),this.renderContainers(),this.activeContainer=n[0],this.render(),this.appendToParent(),this.containers}},{key:"renderContainers",value:function(){var n=this;this.containers.forEach(function(r){return n.el.appendChild(r.render().el)})}},{key:"createContainer",value:function(n,r){var a=this.containerFactory.createContainer(n,r);return this.setupContainer(a),this.el.appendChild(a.render().el),a}},{key:"getCurrentContainer",value:function(){return this.activeContainer}},{key:"getCurrentPlayback",value:function(){return this.activePlayback}},{key:"getPlaybackType",value:function(){return this.activeContainer&&this.activeContainer.getPlaybackType()}},{key:"isFullscreen",value:function(){var n=Kt.fullscreenElement();return n&&n===this.el||n&&n===this.activePlaybackEl||this.activePlaybackEl&&this.activePlaybackEl.webkitDisplayingFullscreen||!1}},{key:"toggleFullscreen",value:function(){var n=this;if(this.isFullscreen()){var r=z.isiOS?this.activePlaybackEl:document;Kt.cancelFullscreen(r),!z.isiOS&&this.$el.removeClass("fullscreen nocursor")}else{var a=z.isiOS?this.activePlaybackEl:this.el;if(!a)return;z.isSafari||z.isiOS?Kt.requestFullscreen(a):Kt.requestFullscreen(a).then(function(o){return o},function(o){return setTimeout(function(){if(!n.isFullscreen())throw new ReferenceError(o)},600)}),!z.isiOS&&this.$el.addClass("fullscreen")}}},{key:"onMouseMove",value:function(n){this.trigger(p.CORE_MOUSE_MOVE,n)}},{key:"onMouseLeave",value:function(n){this.trigger(p.CORE_MOUSE_LEAVE,n)}},{key:"configure",value:function(n){var r=this;this._options=Q.extend(!0,this._options,n),this.configureDomRecycler();var a=n.source||n.sources;a&&this.load(a,n.mimeType||this.options.mimeType),this.trigger(p.CORE_OPTIONS_CHANGE,n),this.containers.forEach(function(o){return o.configure(r.options)})}},{key:"appendToParent",value:function(){var n=Se.getStyleFor(Ao.toString(),{baseUrl:this.options.baseUrl}),r=Se.getStyleFor(Eo.toString(),{baseUrl:this.options.baseUrl});this.$el.append(n[0]),this.options.includeResetStyle&&this.$el.append(r[0]);var a=this.$el.parent()&&this.$el.parent().length;!a&&this.$el.appendTo(this.options.parentElement)}},{key:"render",value:function(){this.options.width=this.options.width||this.$el.width(),this.options.height=this.options.height||this.$el.height();var n={width:this.options.width,height:this.options.height};return this.previousSize=this.currentSize=this.computedSize=n,this.updateSize(),this.enableResizeObserver(),this}}]),t}(Ot);Object.assign($i.prototype,dt);var To=function(s){ve(t,s);var e=Ae(t);function t(i){var n;return he(this,t),n=e.call(this,i.options),n.player=i,n}return de(t,[{key:"loader",get:function(){return this.player.loader}},{key:"create",value:function(){return this.options.loader=this.loader,this.core=new $i(this.options),this.addCorePlugins(),this.core.createContainers(this.options),this.core}},{key:"addCorePlugins",value:function(){var n=this;return this.loader.corePlugins.forEach(function(r){var a=new r(n.core);n.core.addPlugin(a),n.setupExternalInterface(a)}),this.core}},{key:"setupExternalInterface",value:function(n){var r=n.getExternalInterface();for(var a in r)this.player[a]=r[a].bind(n)}}]),t}(st),bo=/(\d+)(?:\.(\d+))?(?:\.(\d+))?/,si=function(){function s(e,t,i){he(this,s),this.major=parseInt(e||0,10),this.minor=parseInt(t||0,10),this.patch=parseInt(i||0,10)}return de(s,[{key:"compare",value:function(t){var i=this.major-t.major;return i=i||this.minor-t.minor,i=i||this.patch-t.patch,i}},{key:"inc",value:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"patch";return typeof this[t]<"u"&&(this[t]+=1),this}},{key:"satisfies",value:function(t,i){return this.compare(t)>=0&&(!i||this.compare(i)<0)}},{key:"toString",value:function(){return"".concat(this.major,".").concat(this.minor,".").concat(this.patch)}}],[{key:"parse",value:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"",i=t.match(bo)||[],n=Ii(i,4),r=n[1],a=n[2],o=n[3];return typeof r>"u"?null:new s(r,a,o)}}]),s}(),pr=function(e,t){return!e||!t?{}:Object.entries(e).filter(function(i){var n=Ii(i,2),r=n[1];return r.type===t}).reduce(function(i,n){var r=Ii(n,2),a=r[0],o=r[1];return i[a]=o,i},{})},Qe=function(){var s={plugins:{},playbacks:[]},e="0.4.27";return function(){function t(){var i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;he(this,t),this.playerId=n,this.playbackPlugins=Dt(s.playbacks);var r=t.registeredPlugins,a=r.core,o=r.container;this.containerPlugins=Object.values(o),this.corePlugins=Object.values(a),Array.isArray(i)||this.validateExternalPluginsType(i),this.addExternalPlugins(i)}return de(t,[{key:"groupPluginsByType",value:function(n){return Array.isArray(n)&&(n=n.reduce(function(r,a){return r[a.type]||(r[a.type]=[]),r[a.type].push(a),r},{})),n}},{key:"removeDups",value:function(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,a=function(h,d){return h[d.prototype.name]&&r||(h[d.prototype.name]&&delete h[d.prototype.name],h[d.prototype.name]=d),h},o=n.reduceRight(a,Object.create(null)),l=[];for(var c in o)l.unshift(o[c]);return l}},{key:"addExternalPlugins",value:function(n){var r=typeof n.loadExternalPluginsFirst=="boolean"?n.loadExternalPluginsFirst:!0,a=typeof n.loadExternalPlaybacksFirst=="boolean"?n.loadExternalPlaybacksFirst:!0;if(n=this.groupPluginsByType(n),n.playback){var o=n.playback.filter(function(u){return t.checkVersionSupport(u),!0});this.playbackPlugins=a?this.removeDups(o.concat(this.playbackPlugins)):this.removeDups(this.playbackPlugins.concat(o),!0)}if(n.container){var l=n.container.filter(function(u){return t.checkVersionSupport(u),!0});this.containerPlugins=r?this.removeDups(l.concat(this.containerPlugins)):this.removeDups(this.containerPlugins.concat(l),!0)}if(n.core){var c=n.core.filter(function(u){return t.checkVersionSupport(u),!0});this.corePlugins=r?this.removeDups(c.concat(this.corePlugins)):this.removeDups(this.corePlugins.concat(c),!0)}}},{key:"validateExternalPluginsType",value:function(n){var r=["playback","container","core"];r.forEach(function(a){(n[a]||[]).forEach(function(o){var l="external "+o.type+" plugin on "+a+" array";if(o.type!==a)throw new ReferenceError(l)})})}}],[{key:"registeredPlaybacks",get:function(){return Dt(s.playbacks)}},{key:"registeredPlugins",get:function(){var n=s.plugins,r=pr(n,"core"),a=pr(n,"container");return{core:r,container:a}}},{key:"checkVersionSupport",value:function(n){var r=n.prototype,a=r.supportedVersion,o=r.name;if(!a||!a.min)return ae.warn("Loader","missing version information for ".concat(o)),!1;var l=a.max?si.parse(a.max):si.parse(a.min).inc("minor"),c=si.parse(a.min);return si.parse(e).satisfies(c,l)?!0:(ae.warn("Loader","unsupported plugin ".concat(o,": Clappr version ").concat(e," does not match required range [").concat(c,",").concat(l,")")),!1)}},{key:"registerPlugin",value:function(n){if(!n||!n.prototype.name)return ae.warn("Loader","missing information to register plugin: ".concat(n)),!1;t.checkVersionSupport(n);var r=s.plugins;if(!r)return!1;var a=r[n.prototype.name];return a&&ae.warn("Loader","overriding plugin entry: ".concat(n.prototype.name," - ").concat(a)),r[n.prototype.name]=n,!0}},{key:"registerPlayback",value:function(n){if(!n||!n.prototype.name)return!1;t.checkVersionSupport(n);var r=s.playbacks,a=r.findIndex(function(l){return l.prototype.name===n.prototype.name});if(a>=0){var o=r[a];r.splice(a,1),ae.warn("Loader","overriding playback entry: ".concat(o.name," - ").concat(o))}return s.playbacks=[n].concat(Dt(r)),!0}},{key:"unregisterPlugin",value:function(n){if(!n)return!1;var r=s.plugins,a=r[n];return a?(delete r[n],!0):!1}},{key:"unregisterPlayback",value:function(n){if(!n)return!1;var r=s.playbacks,a=r.findIndex(function(o){return o.prototype.name===n});return a<0?!1:(r.splice(a,1),s.playbacks=r,!0)}},{key:"clearPlugins",value:function(){s.plugins={}}},{key:"clearPlaybacks",value:function(){s.playbacks=[]}}]),t}()}(),So=ir().replace(/\/[^/]+$/,""),mr=function(s){ve(t,s);var e=Ae(t);function t(i){var n;he(this,t),n=e.call(this,i);var r={recycleVideo:!0},a={playerId:Ht(""),persistConfig:!0,width:640,height:360,baseUrl:So,allowUserInteraction:z.isMobile,includeResetStyle:!0,playback:r};n._options=Q.extend(!0,a,i),n.options.sources=n._normalizeSources(i),n.options.chromeless||(n.options.allowUserInteraction=!0),n.options.allowUserInteraction||(n.options.disableKeyboardShortcuts=!0),n._registerOptionEventListeners(n.options.events),n._coreFactory=new To(ti(n));var o=n._getParentElement(n.options);return o&&n.attachTo(o),n}return de(t,[{key:"loader",get:function(){return this._loader||(this._loader=new Qe(this.options.plugins||{},this.options.playerId)),this._loader},set:function(n){this._loader=n}},{key:"ended",get:function(){return this.core.activeContainer.ended}},{key:"buffering",get:function(){return this.core.activeContainer.buffering}},{key:"isReady",get:function(){return!!this._ready}},{key:"eventsMapping",get:function(){return{onReady:p.PLAYER_READY,onResize:p.PLAYER_RESIZE,onPlay:p.PLAYER_PLAY,onPause:p.PLAYER_PAUSE,onStop:p.PLAYER_STOP,onEnded:p.PLAYER_ENDED,onSeek:p.PLAYER_SEEK,onError:p.PLAYER_ERROR,onTimeUpdate:p.PLAYER_TIMEUPDATE,onVolumeUpdate:p.PLAYER_VOLUMEUPDATE,onSubtitleAvailable:p.PLAYER_SUBTITLE_AVAILABLE}}},{key:"_getParentElement",value:function(n){var r=n.parentId,a=n.parent;return r?document.querySelector(r):a}},{key:"attachTo",value:function(n){return this.options.parentElement=n,this.core=this._coreFactory.create(),this._addEventListeners(),this}},{key:"_addEventListeners",value:function(){return this.core.isReady?this._onReady():this.listenToOnce(this.core,p.CORE_READY,this._onReady),this.listenTo(this.core,p.CORE_ACTIVE_CONTAINER_CHANGED,this._containerChanged),this.listenTo(this.core,p.CORE_FULLSCREEN,this._onFullscreenChange),this.listenTo(this.core,p.CORE_RESIZE,this._onResize),this}},{key:"_addContainerEventListeners",value:function(){var n=this.core.activeContainer;return n&&(this.listenTo(n,p.CONTAINER_PLAY,this._onPlay),this.listenTo(n,p.CONTAINER_PAUSE,this._onPause),this.listenTo(n,p.CONTAINER_STOP,this._onStop),this.listenTo(n,p.CONTAINER_ENDED,this._onEnded),this.listenTo(n,p.CONTAINER_SEEK,this._onSeek),this.listenTo(n,p.CONTAINER_ERROR,this._onError),this.listenTo(n,p.CONTAINER_TIMEUPDATE,this._onTimeUpdate),this.listenTo(n,p.CONTAINER_VOLUME,this._onVolumeUpdate),this.listenTo(n,p.CONTAINER_SUBTITLE_AVAILABLE,this._onSubtitleAvailable)),this}},{key:"_registerOptionEventListeners",value:function(){var n=this,r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},o=Object.keys(r).length>0;return o&&Object.keys(a).forEach(function(l){var c=n.eventsMapping[l];c&&n.off(c,a[l])}),Object.keys(r).forEach(function(l){var c=n.eventsMapping[l];if(c){var u=r[l];u=typeof u=="function"&&u,u&&n.on(c,u)}}),this}},{key:"_containerChanged",value:function(){this.stopListening(),this._addEventListeners()}},{key:"_onReady",value:function(){this._ready=!0,this._addContainerEventListeners(),this.trigger(p.PLAYER_READY)}},{key:"_onFullscreenChange",value:function(n){this.trigger(p.PLAYER_FULLSCREEN,n)}},{key:"_onVolumeUpdate",value:function(n){this.trigger(p.PLAYER_VOLUMEUPDATE,n)}},{key:"_onSubtitleAvailable",value:function(){this.trigger(p.PLAYER_SUBTITLE_AVAILABLE)}},{key:"_onResize",value:function(n){this.trigger(p.PLAYER_RESIZE,n)}},{key:"_onPlay",value:function(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.trigger(p.PLAYER_PLAY,r)}},{key:"_onPause",value:function(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.trigger(p.PLAYER_PAUSE,r)}},{key:"_onStop",value:function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.trigger(p.PLAYER_STOP,this.getCurrentTime(),n)}},{key:"_onEnded",value:function(){this.trigger(p.PLAYER_ENDED)}},{key:"_onSeek",value:function(n){this.trigger(p.PLAYER_SEEK,n)}},{key:"_onTimeUpdate",value:function(n){this.trigger(p.PLAYER_TIMEUPDATE,n)}},{key:"_onError",value:function(n){this.trigger(p.PLAYER_ERROR,n)}},{key:"_normalizeSources",value:function(n){var r=n.sources||(n.source!==void 0?[n.source]:[]);return r.length===0?[{source:"",mimeType:""}]:r}},{key:"resize",value:function(n){return this.core.resize(n),this}},{key:"load",value:function(n,r,a){return a!==void 0&&this.configure({autoPlay:!!a}),this.core.load(n,r),this}},{key:"destroy",value:function(){return this.stopListening(),this.core.destroy(),this}},{key:"consent",value:function(n){this.core.getCurrentPlayback().consent(n)}},{key:"play",value:function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return this.core.activeContainer.play(n),this}},{key:"pause",value:function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return this.core.activeContainer.pause(n),this}},{key:"stop",value:function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return this.core.activeContainer.stop(n),this}},{key:"seek",value:function(n){return this.core.activeContainer.seek(n),this}},{key:"seekPercentage",value:function(n){return this.core.activeContainer.seekPercentage(n),this}},{key:"mute",value:function(){return this.core.activePlayback.mute(),this}},{key:"unmute",value:function(){return this.core.activePlayback.unmute(),this}},{key:"isPlaying",value:function(){return this.core.activeContainer.isPlaying()}},{key:"isDvrEnabled",value:function(){return this.core.activeContainer.isDvrEnabled()}},{key:"isDvrInUse",value:function(){return this.core.activeContainer.isDvrInUse()}},{key:"configure",value:function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return this._registerOptionEventListeners(n.events,this.options.events),this.core.configure(n),this}},{key:"getPlugin",value:function(n){var r=this.core.plugins.concat(this.core.activeContainer.plugins);return r.filter(function(a){return a.name===n})[0]}},{key:"getCurrentTime",value:function(){return this.core.activeContainer.getCurrentTime()}},{key:"getStartTimeOffset",value:function(){return this.core.activeContainer.getStartTimeOffset()}},{key:"getDuration",value:function(){return this.core.activeContainer.getDuration()}}]),t}(st);Object.assign(mr.prototype,dt);var at=function(s){ve(t,s);var e=Ae(t);function t(i){var n;return he(this,t),n=e.call(this,i.options),n.container=i,n.enabled=!0,n.bindEvents(),n}return de(t,[{key:"playerError",get:function(){return this.container.playerError}},{key:"enable",value:function(){this.enabled||(this.bindEvents(),this.enabled=!0)}},{key:"disable",value:function(){this.enabled&&(this.stopListening(),this.enabled=!1)}},{key:"bindEvents",value:function(){}},{key:"destroy",value:function(){this.stopListening()}}]),t}(st);Object.assign(at.prototype,dt),at.extend=function(s){return wt(at,s)},at.type="container";var ot=function(s){ve(t,s);var e=Ae(t);function t(i){var n;return he(this,t),n=e.call(this,i.options),n.core=i,n.enabled=!0,n.bindEvents(),n}return de(t,[{key:"playerError",get:function(){return this.core.playerError}},{key:"bindEvents",value:function(){}},{key:"enable",value:function(){this.enabled||(this.bindEvents(),this.enabled=!0)}},{key:"disable",value:function(){this.enabled&&(this.stopListening(),this.enabled=!1)}},{key:"getExternalInterface",value:function(){return{}}},{key:"destroy",value:function(){this.stopListening()}}]),t}(st);Object.assign(ot.prototype,dt),ot.extend=function(s){return wt(ot,s)},ot.type="core";var ft=function(s){ve(t,s);var e=Ae(t);function t(i){var n;return he(this,t),n=e.call(this,i.options),n.container=i,n.enabled=!0,n.bindEvents(),n}return de(t,[{key:"playerError",get:function(){return this.container.playerError}},{key:"enable",value:function(){this.enabled||(this.bindEvents(),this.$el.show(),this.enabled=!0)}},{key:"disable",value:function(){this.stopListening(),this.$el.hide(),this.enabled=!1}},{key:"bindEvents",value:function(){}}]),t}(Ot);Object.assign(ft.prototype,dt),ft.extend=function(s){return wt(ft,s)},ft.type="container";var _o=`<% for (var i = 0; i < tracks.length; i++) { %> <% }; %> `,ko=`[data-html5-video] { position: absolute; height: 100%; width: 100%; display: block; } `,Nt={mp4:["avc1.42E01E","avc1.58A01E","avc1.4D401E","avc1.64001E","mp4v.20.8","mp4v.20.240","mp4a.40.2"].map(function(s){return'video/mp4; codecs="'+s+', mp4a.40.2"'}),ogg:['video/ogg; codecs="theora, vorbis"','video/ogg; codecs="dirac"','video/ogg; codecs="theora, speex"'],"3gpp":['video/3gpp; codecs="mp4v.20.8, samr"'],webm:['video/webm; codecs="vp8, vorbis"'],mkv:['video/x-matroska; codecs="theora, vorbis"'],m3u8:["application/x-mpegurl"]};Nt.ogv=Nt.ogg,Nt["3gp"]=Nt["3gpp"];var Yt={wav:["audio/wav"],mp3:["audio/mp3",'audio/mpeg;codecs="mp3"'],aac:['audio/mp4;codecs="mp4a.40.5"'],oga:["audio/ogg"]},xo=Object.keys(Yt).reduce(function(s,e){return[].concat(Dt(s),Dt(Yt[e]))},[]),yr={code:"unknown",message:"unknown"},Ge=function(s){ve(t,s);var e=Ae(t);function t(){var i;he(this,t);for(var n=arguments.length,r=new Array(n),a=0;a=0}},{key:"attributes",get:function(){return{"data-html5-video":""}}},{key:"events",get:function(){return{canplay:"_onCanPlay",canplaythrough:"_handleBufferingEvents",durationchange:"_onDurationChange",ended:"_onEnded",error:"_onError",loadeddata:"_onLoadedData",loadedmetadata:"_onLoadedMetadata",pause:"_onPause",playing:"_onPlaying",progress:"_onProgress",seeking:"_onSeeking",seeked:"_onSeeked",stalled:"_handleBufferingEvents",timeupdate:"_onTimeUpdate",waiting:"_onWaiting"}}},{key:"ended",get:function(){return this.el.ended}},{key:"buffering",get:function(){return this._isBuffering}},{key:"isLive",get:function(){return this.getPlaybackType()===se.LIVE}},{key:"dvrEnabled",get:function(){return this.getDuration()>=this._minDvrSize&&this.isLive}},{key:"minimumDVRSizeConfig",get:function(){return this.options.playback&&this.options.playback.minimumDvrSize}},{key:"isValidMinimumDVRSizeConfig",get:function(){return typeof this.minimumDVRSizeConfig<"u"&&typeof this.minimumDVRSizeConfig=="number"}},{key:"configure",value:function(n){Et(nt(t.prototype),"configure",this).call(this,n),this.el.loop=!!n.loop}},{key:"attemptAutoPlay",value:function(){var n=this;this.canAutoPlay(function(r,a){a&&ae.warn(n.name,"autoplay error.",{result:r,error:a}),r&&setTimeout(function(){return!n._destroyed&&n.play()},0)})}},{key:"canAutoPlay",value:function(n){if(this.options.disableCanAutoPlay){n(!0,null);return}var r={timeout:this.options.autoPlayTimeout||500,inline:this.options.playback.playInline||!1,muted:this.options.mute||!1};z.isMobile&&Pt.options.recycleVideo&&(r.element=this.el),rr(n,r)}},{key:"_setupExternalTracks",value:function(n){this._externalTracks=n.map(function(r){return{kind:r.kind||"subtitles",label:r.label,lang:r.lang,src:r.src}})}},{key:"_setupSrc",value:function(n){this.el.src!==n&&(this._ccIsSetup=!1,this.el.src=n,this._src=this.el.src)}},{key:"_onLoadedMetadata",value:function(n){this._handleBufferingEvents(),this.trigger(p.PLAYBACK_LOADEDMETADATA,{duration:n.target.duration,data:n}),this._updateSettings();var r=typeof this._options.autoSeekFromUrl>"u"||this._options.autoSeekFromUrl;this.getPlaybackType()!==se.LIVE&&r&&this._checkInitialSeek()}},{key:"_onDurationChange",value:function(){this._updateSettings(),this._onTimeUpdate(),this._onProgress()}},{key:"_updateSettings",value:function(){this.getPlaybackType()===se.VOD||this.getPlaybackType()===se.AOD?this.settings.left=["playpause","position","duration"]:this.settings.left=["playstop"],this.settings.seekEnabled=this.isSeekEnabled(),this.trigger(p.PLAYBACK_SETTINGSUPDATE)}},{key:"isSeekEnabled",value:function(){return isFinite(this.getDuration())}},{key:"getPlaybackType",value:function(){var n=this.tagName==="audio"?se.AOD:se.VOD;return[0,void 0,1/0].indexOf(this.el.duration)>=0?se.LIVE:n}},{key:"isHighDefinitionInUse",value:function(){return!1}},{key:"consent",value:function(n){var r=this;if(this.isPlaying()||this.el._consented)Et(nt(t.prototype),"consent",this).call(this,n);else{var a=function o(){r.el.removeEventListener("loadedmetadata",o,!1),r.el.removeEventListener("error",o,!1),r.el._consented=!0,Et(nt(t.prototype),"consent",r).call(r,n)};this.el.addEventListener("loadedmetadata",a,!1),this.el.addEventListener("error",a,!1),this.el.load()}}},{key:"play",value:function(){this.trigger(p.PLAYBACK_PLAY_INTENT),this._stopped=!1,this._setupSrc(this._src),this._handleBufferingEvents();var n=this.el.play();n&&n.catch&&n.catch(function(){})}},{key:"pause",value:function(){this.el.pause(),this.dvrEnabled&&this._updateDvr(!0)}},{key:"stop",value:function(){this.pause(),this._stopped=!0,this.el.removeAttribute("src"),this.el.load(),this._stopPlayheadMovingChecks(),this._handleBufferingEvents(),this.trigger(p.PLAYBACK_STOP)}},{key:"volume",value:function(n){n===0?(this.$el.attr({muted:"true"}),this.el.muted=!0):(this.$el.attr({muted:null}),this.el.muted=!1,this.el.volume=n/100)}},{key:"mute",value:function(){this.el.muted=!0}},{key:"unmute",value:function(){this.el.muted=!1}},{key:"isMuted",value:function(){return this.el.muted===!0||this.el.volume===0}},{key:"isPlaying",value:function(){return!this.el.paused&&!this.el.ended}},{key:"isReady",get:function(){return this._isReadyState}},{key:"_startPlayheadMovingChecks",value:function(){this._playheadMovingTimer===null&&(this._playheadMovingTimeOnCheck=null,this._determineIfPlayheadMoving(),this._playheadMovingTimer=setInterval(this._determineIfPlayheadMoving.bind(this),500))}},{key:"_stopPlayheadMovingChecks",value:function(){this._playheadMovingTimer!==null&&(clearInterval(this._playheadMovingTimer),this._playheadMovingTimer=null,this._playheadMoving=!1)}},{key:"_determineIfPlayheadMoving",value:function(){var n=this._playheadMovingTimeOnCheck,r=this.el.currentTime;this._playheadMoving=n!==r,this._playheadMovingTimeOnCheck=r,this._handleBufferingEvents()}},{key:"_onWaiting",value:function(){this._loadStarted=!0,this._handleBufferingEvents()}},{key:"_onLoadedData",value:function(){this._loadStarted=!0,this._handleBufferingEvents()}},{key:"_onCanPlay",value:function(){this._handleBufferingEvents()}},{key:"_onPlaying",value:function(){this._checkForClosedCaptions(),this._startPlayheadMovingChecks(),this._handleBufferingEvents(),this.trigger(p.PLAYBACK_PLAY)}},{key:"_onPause",value:function(){this._stopPlayheadMovingChecks(),this._handleBufferingEvents(),this.trigger(p.PLAYBACK_PAUSE)}},{key:"_onSeeking",value:function(){this.trigger(p.PLAYBACK_SEEK,this.getCurrentTime()),this._handleBufferingEvents()}},{key:"_onSeeked",value:function(){this._handleBufferingEvents(),this.trigger(p.PLAYBACK_SEEKED)}},{key:"_onEnded",value:function(){this._handleBufferingEvents(),this.trigger(p.PLAYBACK_ENDED,this.name)}},{key:"_handleBufferingEvents",value:function(){var n=!this.el.ended&&!this.el.paused,r=this._loadStarted&&!this.el.ended&&!this._stopped&&(n&&!this._playheadMoving||this.el.readyState0)return this.el.seekable.end(0)-this.el.seekable.start(0);this._scheduleUpdateSettingsCheck()}return this.el.duration}},{key:"_scheduleUpdateSettingsCheck",value:function(){var n=this;this._updateSettingsCheckInFlight||(this._updateSettingsCheckInFlight=setTimeout(function(){n._updateSettings(),n._updateSettingsCheckInFlight=null},1e3))}},{key:"_onTimeUpdate",value:function(){var n=this.isLive?this.getDuration():this.el.duration;this.trigger(p.PLAYBACK_TIMEUPDATE,{current:this.el.currentTime,total:n},this.name)}},{key:"_onProgress",value:function(){if(this.el.buffered.length){for(var n=[],r=0,a=0;a=n[a].start&&this.el.currentTime<=n[a].end&&(r=a);var o={start:n[r].start,current:n[r].end,total:this.el.duration};this.trigger(p.PLAYBACK_PROGRESS,o,n)}}},{key:"_typeFor",value:function(n){var r=t._mimeTypesForUrl(n,Nt,this.options.mimeType);r.length===0&&(r=t._mimeTypesForUrl(n,Yt,this.options.mimeType));var a=r[0]||"";return a.split(";")[0]}},{key:"_ready",value:function(){this._isReadyState||(this._isReadyState=!0,this.trigger(p.PLAYBACK_READY,this.name))}},{key:"_checkForClosedCaptions",value:function(){if(this.isHTML5Video&&!this._ccIsSetup){if(this.hasClosedCaptionsTracks){this.trigger(p.PLAYBACK_SUBTITLE_AVAILABLE);var n=this.closedCaptionsTrackId;this.closedCaptionsTrackId=n,this.handleTextTrackChange=this._handleTextTrackChange.bind(this),this.el.textTracks.addEventListener("change",this.handleTextTrackChange)}this._ccIsSetup=!0}}},{key:"_handleTextTrackChange",value:function(){var n=this.closedCaptionsTracks,r=n.find(function(a){return a.track.mode==="showing"})||{id:-1};this._ccTrackId!==r.id&&(this._ccTrackId=r.id,this.trigger(p.PLAYBACK_SUBTITLE_CHANGED,{id:r.id}))}},{key:"isHTML5Video",get:function(){return this.name===t.prototype.name}},{key:"closedCaptionsTracks",get:function(){var n=0,r=function(){return n++},a=this.el.textTracks?Array.from(this.el.textTracks):[];return a.filter(function(o){return o.kind==="subtitles"||o.kind==="captions"}).map(function(o){return{id:r(),name:o.label,track:o}})}},{key:"closedCaptionsTrackId",get:function(){return this._ccTrackId},set:function(n){if(ii(n)){var r=this.closedCaptionsTracks,a;n!==-1&&(a=r.find(function(o){return o.id===n}),!a||a.track.mode==="showing")||(r.filter(function(o){return o.track.mode!=="hidden"}).forEach(function(o){return o.track.mode="hidden"}),a&&(a.track.mode="showing"),this._ccTrackId=n,this.trigger(p.PLAYBACK_SUBTITLE_CHANGED,{id:n}))}}},{key:"template",get:function(){return Ie(_o)}},{key:"render",value:function(){this.options.playback.disableContextMenu&&this.$el.on("contextmenu",function(){return!1}),this._externalTracks&&this._externalTracks.length>0&&this.$el.html(this.template({tracks:this._externalTracks})),this._ready();var n=Se.getStyleFor(ko.toString(),{baseUrl:this.options.baseUrl});return this.$el.append(n[0]),this}}]),t}(se);Ge._mimeTypesForUrl=function(s,e,t){var i=(s.split("?")[0].match(/.*\.(.*)$/)||[])[1],n=t||i&&e[i.toLowerCase()]||[];return n.constructor===Array?n:[n]},Ge._canPlay=function(s,e,t,i){var n=Ge._mimeTypesForUrl(t,e,i),r=document.createElement(s);return!!n.filter(function(a){return!!r.canPlayType(a).replace(/no/,"")})[0]},Ge.canPlay=function(s,e){return Ge._canPlay("audio",Yt,s,e)||Ge._canPlay("video",Nt,s,e)};var Vi=function(s){ve(t,s);var e=Ae(t);function t(){return he(this,t),e.apply(this,arguments)}return de(t,[{key:"name",get:function(){return"html5_audio"}},{key:"supportedVersion",get:function(){return{min:"0.4.27"}}},{key:"tagName",get:function(){return"audio"}},{key:"isAudioOnly",get:function(){return!0}},{key:"updateSettings",value:function(){this.settings.left=["playpause","position","duration"],this.settings.seekEnabled=this.isSeekEnabled(),this.trigger(p.PLAYBACK_SETTINGSUPDATE)}},{key:"getPlaybackType",value:function(){return se.AOD}}]),t}(Ge);Vi.canPlay=function(s,e){var t={wav:["audio/wav"],mp3:["audio/mp3",'audio/mpeg;codecs="mp3"'],aac:['audio/mp4;codecs="mp4a.40.5"'],oga:["audio/ogg"]};return Ge._canPlay("audio",t,s,e)};var Co=`[data-html-img] { max-width: 100%; max-height: 100%; } `,Gi=function(s){ve(t,s);var e=Ae(t);function t(i){var n;return he(this,t),n=e.call(this,i),n.el.src=i.src,n}return de(t,[{key:"name",get:function(){return"html_img"}},{key:"supportedVersion",get:function(){return{min:"0.4.27"}}},{key:"tagName",get:function(){return"img"}},{key:"attributes",get:function(){return{"data-html-img":""}}},{key:"events",get:function(){return{load:"_onLoad",abort:"_onError",error:"_onError"}}},{key:"getPlaybackType",value:function(){return se.NO_OP}},{key:"render",value:function(){var n=Se.getStyleFor(Co.toString(),{baseUrl:this.options.baseUrl});return this.$el.append(n[0]),this.trigger(p.PLAYBACK_READY,this.name),this}},{key:"_onLoad",value:function(){this.trigger(p.PLAYBACK_ENDED,this.name)}},{key:"_onError",value:function(n){var r=n.type==="error"?"load error":"loading aborted";this.trigger(p.PLAYBACK_ERROR,{message:r},this.name)}}]),t}(se);Gi.canPlay=function(s){return/\.(png|jpg|jpeg|gif|bmp|tiff|pgm|pnm|webp)(|\?.*)$/i.test(s)};var Lo=`

<%=message%>

`,Io=`[data-no-op] { position: absolute; height: 100%; width: 100%; text-align: center; } [data-no-op] p[data-no-op-msg] { position: absolute; text-align: center; font-size: 25px; left: 0; right: 0; color: white; padding: 10px; /* center vertically */ top: 50%; transform: translateY(-50%); max-height: 100%; overflow: auto; } [data-no-op] canvas[data-no-op-canvas] { background-color: #777; height: 100%; width: 100%; } `,vr=function(s){ve(t,s);var e=Ae(t);function t(){var i;he(this,t);for(var n=arguments.length,r=new Array(n),a=0;a"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function Bo(s){if(s===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return s}function Uo(s,e){if(e&&(typeof e=="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Bo(s)}function $o(s){var e=Mo();return function(){var i=Ze(s),n;if(e){var r=Ze(this).constructor;n=Reflect.construct(i,arguments,r)}else n=i.apply(this,arguments);return Uo(this,n)}}function Vo(s,e){for(;!Object.prototype.hasOwnProperty.call(s,e)&&(s=Ze(s),s!==null););return s}function gt(){return typeof Reflect<"u"&&Reflect.get?gt=Reflect.get.bind():gt=function(e,t,i){var n=Vo(e,t);if(n){var r=Object.getOwnPropertyDescriptor(n,t);return r.get?r.get.call(arguments.length<3?e:i):r.value}},gt.apply(this,arguments)}function Go(s){return Ko(s)||Ho(s)||Yo(s)||Wo()}function Ko(s){if(Array.isArray(s))return Yi(s)}function Ho(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function Yo(s,e){if(s){if(typeof s=="string")return Yi(s,e);var t=Object.prototype.toString.call(s).slice(8,-1);if(t==="Object"&&s.constructor&&(t=s.constructor.name),t==="Map"||t==="Set")return Array.from(s);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return Yi(s,e)}}function Yi(s,e){(e==null||e>s.length)&&(e=s.length);for(var t=0,i=new Array(e);t`):bt}function Jo(s,...e){e.forEach(function(t){Wt[t]=s[t]?s[t].bind(s):Zo(t)})}function el(s,e){if(self.console&&s===!0||typeof s=="object"){Jo(s,"debug","log","info","warn","error");try{Wt.log(`Debug logs enabled for "${e}" in hls.js version 1.4.10`)}catch{Wt=zi}}else Wt=zi}const C=Wt,tl=/^(\d+)x(\d+)$/,_r=/(.+?)=(".*?"|.*?)(?:,|$)/g;class me{constructor(e){typeof e=="string"&&(e=me.parseAttrList(e));for(const t in e)e.hasOwnProperty(t)&&(t.substring(0,2)==="X-"&&(this.clientAttrs=this.clientAttrs||[],this.clientAttrs.push(t)),this[t]=e[t])}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;const i=new Uint8Array(t.length/2);for(let n=0;nNumber.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}bool(e){return this[e]==="YES"}decimalResolution(e){const t=tl.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t;const i={},n='"';for(_r.lastIndex=0;(t=_r.exec(e))!==null;){let r=t[2];r.indexOf(n)===0&&r.lastIndexOf(n)===r.length-1&&(r=r.slice(1,-1));const a=t[1].trim();i[a]=r}return i}}function il(s){return s!=="ID"&&s!=="CLASS"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function nl(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"}class kr{constructor(e,t){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,t){const i=t.attr;for(const n in i)if(Object.prototype.hasOwnProperty.call(e,n)&&e[n]!==i[n]){C.warn(`DATERANGE tag attribute: "${n}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=n;break}e=Te(new me({}),i,e)}if(this.attr=e,this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const i=new Date(this.attr["END-DATE"]);Z(i.getTime())&&(this._endDate=i)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get startDate(){return this._startDate}get endDate(){if(this._endDate)return this._endDate;const e=this.duration;return e!==null?new Date(this._startDate.getTime()+e*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(Z(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isValid(){return!!this.id&&!this._badValueForSameId&&Z(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class ai{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 fe={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class xr{constructor(e){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[fe.AUDIO]:null,[fe.VIDEO]:null,[fe.AUDIOVIDEO]:null},this.baseurl=e}setByteRange(e,t){const i=e.split("@",2),n=[];i.length===1?n[0]=t?t.byteRangeEndOffset:0:n[0]=parseInt(i[1]),n[1]=parseInt(i[0])+n[0],this._byteRange=n}get byteRange(){return this._byteRange?this._byteRange:[]}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Wi.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}}class ji extends xr{constructor(e,t){super(t),this._decryptdata=null,this.rawProgramDateTime=null,this.programDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.stats=new ai,this.urlId=0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.type=e}get decryptdata(){const{levelkeys:e}=this;if(!e&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const t=this.levelkeys.identity;if(t)this._decryptdata=t.getDecryptData(this.sn);else{const i=Object.keys(this.levelkeys);if(i.length===1)return this._decryptdata=this.levelkeys[i[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null||!Z(this.programDateTime))return null;const e=Z(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){const t=Object.keys(this.levelkeys),i=t.length;if(i>1||i===1&&this.levelkeys[t[0]].encrypted)return!0}return!1}setKeyFormat(e){if(this.levelkeys){const t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,i,n,r,a=!1){const{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:t,endPTS:i,startDTS:n,endDTS:r,partial:a};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,i),l.startDTS=Math.min(l.startDTS,n),l.endDTS=Math.max(l.endDTS,r)}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[fe.AUDIO]=null,e[fe.VIDEO]=null,e[fe.AUDIOVIDEO]=null}}class rl extends xr{constructor(e,t,i,n,r){super(i),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.stats=new ai,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=n;const a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}const sl=10;class al{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t,this.advanced=this.endSN>e.endSN||t>0||t===0&&i>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1,this.availabilityDelay=e.availabilityDelay}get hasProgramDateTime(){return this.fragments.length?Z(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||sl}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var e;return(e=this.fragments)!=null&&e.length?this.fragments[this.fragments.length-1].end:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}function qi(s){return Uint8Array.from(atob(s),e=>e.charCodeAt(0))}function ol(s){const e=Cr(s).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function ll(s){const e=function(i,n,r){const a=i[n];i[n]=i[r],i[r]=a};e(s,0,3),e(s,1,2),e(s,4,5),e(s,6,7)}function cl(s){const e=s.split(":");let t=null;if(e[0]==="data"&&e.length===2){const i=e[1].split(";"),n=i[i.length-1].split(",");if(n.length===2){const r=n[0]==="base64",a=n[1];r?(i.splice(-1,1),t=qi(a)):t=ol(a)}}return t}function Cr(s){return Uint8Array.from(unescape(encodeURIComponent(s)),e=>e.charCodeAt(0))}var ye={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},De={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Lr(s){switch(s){case De.FAIRPLAY:return ye.FAIRPLAY;case De.PLAYREADY:return ye.PLAYREADY;case De.WIDEVINE:return ye.WIDEVINE;case De.CLEARKEY:return ye.CLEARKEY}}var Ir={WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function ul(s){if(s===Ir.WIDEVINE)return ye.WIDEVINE}function Rr(s){switch(s){case ye.FAIRPLAY:return De.FAIRPLAY;case ye.PLAYREADY:return De.PLAYREADY;case ye.WIDEVINE:return De.WIDEVINE;case ye.CLEARKEY:return De.CLEARKEY}}function Xi(s){const{drmSystems:e,widevineLicenseUrl:t}=s,i=e?[ye.FAIRPLAY,ye.WIDEVINE,ye.PLAYREADY,ye.CLEARKEY].filter(n=>!!e[n]):[];return!i[ye.WIDEVINE]&&t&&i.push(ye.WIDEVINE),i}const Dr=function(){return typeof self<"u"&&self.navigator&&self.navigator.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function hl(s,e,t,i){let n;switch(s){case ye.FAIRPLAY:n=["cenc","sinf"];break;case ye.WIDEVINE:case ye.PLAYREADY:n=["cenc"];break;case ye.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${s}`)}return dl(n,e,t,i)}function dl(s,e,t,i){return[{initDataTypes:s,persistentState:i.persistentState||"not-allowed",distinctiveIdentifier:i.distinctiveIdentifier||"not-allowed",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map(r=>({contentType:`audio/mp4; codecs="${r}"`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:t.map(r=>({contentType:`video/mp4; codecs="${r}"`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}function St(s,e,t){return Uint8Array.prototype.slice?s.slice(e,t):new Uint8Array(Array.prototype.slice.call(s,e,t))}const Qi=(s,e)=>e+10<=s.length&&s[e]===73&&s[e+1]===68&&s[e+2]===51&&s[e+3]<255&&s[e+4]<255&&s[e+6]<128&&s[e+7]<128&&s[e+8]<128&&s[e+9]<128,wr=(s,e)=>e+10<=s.length&&s[e]===51&&s[e+1]===68&&s[e+2]===73&&s[e+3]<255&&s[e+4]<255&&s[e+6]<128&&s[e+7]<128&&s[e+8]<128&&s[e+9]<128,oi=(s,e)=>{const t=e;let i=0;for(;Qi(s,e);){i+=10;const n=li(s,e+6);i+=n,wr(s,e+10)&&(i+=10),e+=i}if(i>0)return s.subarray(t,t+i)},li=(s,e)=>{let t=0;return t=(s[e]&127)<<21,t|=(s[e+1]&127)<<14,t|=(s[e+2]&127)<<7,t|=s[e+3]&127,t},fl=(s,e)=>Qi(s,e)&&li(s,e+6)+10<=s.length-e,gl=s=>{const e=Or(s);for(let t=0;ts&&s.key==="PRIV"&&s.info==="com.apple.streaming.transportStreamTimestamp",pl=s=>{const e=String.fromCharCode(s[0],s[1],s[2],s[3]),t=li(s,4),i=10;return{type:e,size:t,data:s.subarray(i,i+t)}},Or=s=>{let e=0;const t=[];for(;Qi(s,e);){const i=li(s,e+6);e+=10;const n=e+i;for(;e+8s.type==="PRIV"?yl(s):s.type[0]==="W"?Al(s):vl(s),yl=s=>{if(s.size<2)return;const e=Je(s.data,!0),t=new Uint8Array(s.data.subarray(e.length+1));return{key:s.type,info:e,data:t.buffer}},vl=s=>{if(s.size<2)return;if(s.type==="TXXX"){let t=1;const i=Je(s.data.subarray(t),!0);t+=i.length+1;const n=Je(s.data.subarray(t));return{key:s.type,info:i,data:n}}const e=Je(s.data.subarray(1));return{key:s.type,data:e}},Al=s=>{if(s.type==="WXXX"){if(s.size<2)return;let t=1;const i=Je(s.data.subarray(t),!0);t+=i.length+1;const n=Je(s.data.subarray(t));return{key:s.type,info:i,data:n}}const e=Je(s.data);return{key:s.type,data:e}},El=s=>{if(s.data.byteLength===8){const e=new Uint8Array(s.data),t=e[3]&1;let i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,t&&(i+=4772185884e-2),Math.round(i)}},Je=(s,e=!1)=>{const t=Tl();if(t){const c=t.decode(s);if(e){const u=c.indexOf("\0");return u!==-1?c.substring(0,u):c}return c.replace(/\0/g,"")}const i=s.length;let n,r,a,o="",l=0;for(;l>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(n);break;case 12:case 13:r=s[l++],o+=String.fromCharCode((n&31)<<6|r&63);break;case 14:r=s[l++],a=s[l++],o+=String.fromCharCode((n&15)<<12|(r&63)<<6|(a&63)<<0);break}}return o};let Zi;function Tl(){return!Zi&&typeof self.TextDecoder<"u"&&(Zi=new self.TextDecoder("utf-8")),Zi}const et={hexDump:function(s){let e="";for(let t=0;t>24,s[e+1]=t>>16&255,s[e+2]=t>>8&255,s[e+3]=t&255}function oe(s,e){const t=[];if(!e.length)return t;const i=s.byteLength;for(let n=0;n1?n+r:i;if(a===e[0])if(e.length===1)t.push(s.subarray(n+8,o));else{const l=oe(s.subarray(n+8,o),e.slice(1));l.length&&bl.apply(t,l)}n=o}return t}function Sl(s){const e=[],t=s[0];let i=8;const n=ie(s,i);i+=4;const r=0,a=0;t===0?i+=8:i+=16,i+=2;let o=s.length+a;const l=Fr(s,i);i+=2;for(let c=0;c>>31===1)return C.warn("SIDX has hierarchical references (not supported)"),null;const g=ie(s,u);u+=4,e.push({referenceSize:d,subsegmentDuration:g,info:{duration:g/n,start:o,end:o+d-1}}),o+=d,u+=4,i=u}return{earliestPresentationTime:r,timescale:n,version:t,referencesCount:l,references:e}}function Br(s){const e=[],t=oe(s,["moov","trak"]);for(let n=0;n{const r=ie(n,4),a=e[r];a&&(a.default={duration:ie(n,12),flags:ie(n,20)})}),e}function _l(s,e){if(!s||!e)return s;const t=e.keyId;return t&&e.isCommonEncryption&&oe(s,["moov","trak"]).forEach(n=>{const a=oe(n,["mdia","minf","stbl","stsd"])[0].subarray(8);let o=oe(a,["enca"]);const l=o.length>0;l||(o=oe(a,["encv"])),o.forEach(c=>{const u=l?c.subarray(28):c.subarray(78);oe(u,["sinf"]).forEach(d=>{const f=Ur(d);if(f){const g=f.subarray(8,24);g.some(v=>v!==0)||(C.log(`[eme] Patching keyId in 'enc${l?"a":"v"}>sinf>>tenc' box: ${et.hexDump(g)} -> ${et.hexDump(t)}`),f.set(t,8))}})})}),s}function Ur(s){const e=oe(s,["schm"])[0];if(e){const t=_e(e.subarray(4,8));if(t==="cbcs"||t==="cenc")return oe(s,["schi","tenc"])[0]}return C.error("[eme] missing 'schm' box"),null}function kl(s,e){return oe(e,["moof","traf"]).reduce((t,i)=>{const n=oe(i,["tfdt"])[0],r=n[0],a=oe(i,["tfhd"]).reduce((o,l)=>{const c=ie(l,4),u=s[c];if(u){let h=ie(n,4);if(r===1){if(h===ci)return C.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),o;h*=ci+1,h+=ie(n,8)}const d=u.timescale||9e4,f=h/d;if(isFinite(f)&&(o===null||fu+h.info.duration||0,0))}return a}return i||n}function Cl(s){const e=ie(s,0);let t=8;e&1&&(t+=4),e&4&&(t+=4);let i=0;const n=ie(s,4);for(let r=0;r{oe(i,["tfhd"]).forEach(n=>{const r=ie(n,4),a=s[r];if(!a)return;const o=a.timescale||9e4;oe(i,["tfdt"]).forEach(l=>{const c=l[0];let u=ie(l,4);if(c===0)u-=t*o,u=Math.max(u,0),Ji(l,4,u);else{u*=Math.pow(2,32),u+=ie(l,8),u-=t*o,u=Math.max(u,0);const h=Math.floor(u/(ci+1)),d=Math.floor(u%(ci+1));Ji(l,4,h),Ji(l,8,d)}})})})}function Il(s){const e={valid:null,remainder:null},t=oe(s,["moof"]);if(t){if(t.length<2)return e.remainder=s,e}else return e;const i=t[t.length-1];return e.valid=St(s,0,i.byteOffset-8),e.remainder=St(s,i.byteOffset-8),e}function _t(s,e){const t=new Uint8Array(s.length+e.length);return t.set(s),t.set(e,s.length),t}function $r(s,e){const t=[],i=e.samples,n=e.timescale,r=e.id;let a=!1;return oe(i,["moof"]).map(l=>{const c=l.byteOffset-8;oe(l,["traf"]).map(h=>{const d=oe(h,["tfdt"]).map(f=>{const g=f[0];let v=ie(f,4);return g===1&&(v*=Math.pow(2,32),v+=ie(f,8)),v/n})[0];return d!==void 0&&(s=d),oe(h,["tfhd"]).map(f=>{const g=ie(f,4),v=ie(f,0)&16777215,A=(v&1)!==0,T=(v&2)!==0,x=(v&8)!==0;let _=0;const P=(v&16)!==0;let L=0;const G=(v&32)!==0;let O=8;g===r&&(A&&(O+=8),T&&(O+=4),x&&(_=ie(f,O),O+=4),P&&(L=ie(f,O),O+=4),G&&(O+=4),e.type==="video"&&(a=Rl(e.codec)),oe(h,["trun"]).map(B=>{const k=B[0],E=ie(B,0)&16777215,N=(E&1)!==0;let S=0;const I=(E&4)!==0,M=(E&256)!==0;let K=0;const H=(E&512)!==0;let W=0;const U=(E&1024)!==0,$=(E&2048)!==0;let j=0;const X=ie(B,4);let ne=8;N&&(S=ie(B,ne),ne+=4),I&&(ne+=4);let q=S+c;for(let Le=0;Le>1&63;return t===39||t===40}else return(e&31)===6}function Vr(s,e,t,i){const n=Gr(s);let r=0;r+=e;let a=0,o=0,l=!1,c=0;for(;r=n.length)break;c=n[r++],a+=c}while(c===255);o=0;do{if(r>=n.length)break;c=n[r++],o+=c}while(c===255);const u=n.length-r;if(!l&&a===4&&r16){const h=[];for(let g=0;g<16;g++){const v=n[r++].toString(16);h.push(v.length==1?"0"+v:v),(g===3||g===5||g===7||g===9)&&h.push("-")}const d=o-16,f=new Uint8Array(d);for(let g=0;gu)break}}function Gr(s){const e=s.byteLength,t=[];let i=1;for(;i>24&255,r[1]=i>>16&255,r[2]=i>>8&255,r[3]=i&255,r.set(s,4),n=0,i=8;n0?(r=new Uint8Array(4),e.length>0&&new DataView(r.buffer).setUint32(0,e.length,!1)):r=new Uint8Array;const a=new Uint8Array(4);return t&&t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),Pl([112,115,115,104],new Uint8Array([i,0,0,0]),s,r,n,a,t||new Uint8Array)}function Nl(s){if(!(s instanceof ArrayBuffer)||s.byteLength<32)return null;const e={version:0,systemId:"",kids:null,data:null},t=new DataView(s),i=t.getUint32(0);if(s.byteLength!==i&&i>44||t.getUint32(4)!==1886614376||(e.version=t.getUint32(8)>>>24,e.version>1))return null;e.systemId=et.hexDump(new Uint8Array(s,12,16));const r=t.getUint32(28);if(e.version===0){if(i-32=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case De.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Ol(i,null,t);const n=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),r=String.fromCharCode.apply(null,Array.from(n)),a=r.substring(r.indexOf("<"),r.length),c=new DOMParser().parseFromString(a,"text/xml").getElementsByTagName("KID")[0];if(c){const u=c.childNodes[0]?c.childNodes[0].nodeValue:c.getAttribute("VALUE");if(u){const h=qi(u).subarray(0,16);ll(h),this.keyId=h}}break}default:{let i=t.subarray(0,16);if(i.length!==16){const n=new Uint8Array(16);n.set(i,16-i.length),i=n}this.keyId=i;break}}if(!this.keyId||this.keyId.byteLength!==16){let i=ui[this.uri];if(!i){const n=Object.keys(ui).length%Number.MAX_SAFE_INTEGER;i=new Uint8Array(16),new DataView(i.buffer,12,4).setUint32(0,n),ui[this.uri]=i}this.keyId=i}return this}}function Fl(s){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=s>>8*(15-t)&255;return e}const Kr=/\{\$([a-zA-Z0-9-_]+)\}/g;function Hr(s){return Kr.test(s)}function we(s,e,t){if(s.variableList!==null||s.hasVariableRefs)for(let i=t.length;i--;){const n=t[i],r=e[n];r&&(e[n]=en(s,r))}}function en(s,e){if(s.variableList!==null||s.hasVariableRefs){const t=s.variableList;return e.replace(Kr,i=>{const n=i.substring(2,i.length-1),r=t==null?void 0:t[n];return r===void 0?(s.playlistParsingError||(s.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${n}"`)),i):r})}return e}function Yr(s,e,t){let i=s.variableList;i||(s.variableList=i={});let n,r;if("QUERYPARAM"in e){n=e.QUERYPARAM;try{const a=new self.URL(t).searchParams;if(a.has(n))r=a.get(n);else throw new Error(`"${n}" does not match any query parameter in URI: "${t}"`)}catch(a){s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else n=e.NAME,r=e.VALUE;n in i?s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${n}"`)):i[n]=r||""}function Ml(s,e,t){const i=e.IMPORT;if(t&&i in t){let n=s.variableList;n||(s.variableList=n={}),n[i]=t[i]}else s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}function hi(){if(!(typeof self>"u"))return self.MediaSource||self.WebKitMediaSource}const Bl={audio:{a3ds:!0,"ac-3":!0,"ac-4":!0,alac:!0,alaw:!0,dra1:!0,"dts+":!0,"dts-":!0,dtsc:!0,dtse:!0,dtsh:!0,"ec-3":!0,enca:!0,g719:!0,g726:!0,m4ae:!0,mha1:!0,mha2:!0,mhm1:!0,mhm2:!0,mlpa:!0,mp4a:!0,"raw ":!0,Opus:!0,opus:!0,samr:!0,sawb:!0,sawp:!0,sevc:!0,sqcp:!0,ssmv:!0,twos:!0,ulaw:!0},video:{avc1:!0,avc2:!0,avc3:!0,avc4:!0,avcp:!0,av01:!0,drac:!0,dva1:!0,dvav:!0,dvh1:!0,dvhe:!0,encv:!0,hev1:!0,hvc1:!0,mjp2:!0,mp4v:!0,mvc1:!0,mvc2:!0,mvc3:!0,mvc4:!0,resv:!0,rv60:!0,s263:!0,svc1:!0,svc2:!0,"vc-1":!0,vp08:!0,vp09:!0},text:{stpp:!0,wvtt:!0}},Wr=hi();function Ul(s,e){const t=Bl[e];return!!t&&t[s.slice(0,4)]===!0}function tn(s,e){var t;return(t=Wr==null?void 0:Wr.isTypeSupported(`${e||"video"}/mp4;codecs="${s}"`))!=null?t:!1}const zr=/#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,jr=/#EXT-X-MEDIA:(.*)/g,$l=/^#EXT(?:INF|-X-TARGETDURATION):/m,qr=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),Vl=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class ze{static findGroup(e,t){for(let i=0;i2){let i=t.shift()+".";return i+=parseInt(t.shift()).toString(16),i+=("000"+parseInt(t.shift()).toString(16)).slice(-4),i}return e}static resolve(e,t){return Wi.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return $l.test(e)}static parseMasterPlaylist(e,t){const i=Hr(e),n={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:i},r=[];zr.lastIndex=0;let a;for(;(a=zr.exec(e))!=null;)if(a[1]){var o;const c=new me(a[1]);we(n,c,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const u=en(n,a[2]),h={attrs:c,bitrate:c.decimalInteger("AVERAGE-BANDWIDTH")||c.decimalInteger("BANDWIDTH"),name:c.NAME,url:ze.resolve(u,t)},d=c.decimalResolution("RESOLUTION");d&&(h.width=d.width,h.height=d.height),Gl((c.CODECS||"").split(/[ ,]+/).filter(f=>f),h),h.videoCodec&&h.videoCodec.indexOf("avc1")!==-1&&(h.videoCodec=ze.convertAVC1ToAVCOTI(h.videoCodec)),(o=h.unknownCodecs)!=null&&o.length||r.push(h),n.levels.push(h)}else if(a[3]){const c=a[3],u=a[4];switch(c){case"SESSION-DATA":{const h=new me(u);we(n,h,["DATA-ID","LANGUAGE","VALUE","URI"]);const d=h["DATA-ID"];d&&(n.sessionData===null&&(n.sessionData={}),n.sessionData[d]=h);break}case"SESSION-KEY":{const h=Xr(u,t,n);h.encrypted&&h.isSupported()?(n.sessionKeys===null&&(n.sessionKeys=[]),n.sessionKeys.push(h)):C.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${u}"`);break}case"DEFINE":{{const h=new me(u);we(n,h,["NAME","VALUE","QUERYPARAM"]),Yr(n,h,t)}break}case"CONTENT-STEERING":{const h=new me(u);we(n,h,["SERVER-URI","PATHWAY-ID"]),n.contentSteering={uri:ze.resolve(h["SERVER-URI"],t),pathwayId:h["PATHWAY-ID"]||"."};break}case"START":{n.startTimeOffset=Qr(u);break}}}const l=r.length>0&&r.length({id:c.attrs.AUDIO,audioCodec:c.audioCodec})),SUBTITLES:a.map(c=>({id:c.attrs.SUBTITLES,textCodec:c.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(jr.lastIndex=0;(n=jr.exec(e))!==null;){const c=new me(n[1]),u=c.TYPE;if(u){const h=o[u],d=r[u]||[];r[u]=d,we(i,c,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const f={attrs:c,bitrate:0,id:l++,groupId:c["GROUP-ID"]||"",instreamId:c["INSTREAM-ID"],name:c.NAME||c.LANGUAGE||"",type:u,default:c.bool("DEFAULT"),autoselect:c.bool("AUTOSELECT"),forced:c.bool("FORCED"),lang:c.LANGUAGE,url:c.URI?ze.resolve(c.URI,t):""};if(h!=null&&h.length){const g=ze.findGroup(h,f.groupId)||h[0];Zr(f,g,"audioCodec"),Zr(f,g,"textCodec")}d.push(f)}}return r}static parseLevelPlaylist(e,t,i,n,r,a){const o=new al(t),l=o.fragments;let c=null,u=0,h=0,d=0,f=0,g=null,v=new ji(n,t),A,T,x,_=-1,P=!1;for(qr.lastIndex=0,o.m3u8=e,o.hasVariableRefs=Hr(e);(A=qr.exec(e))!==null;){P&&(P=!1,v=new ji(n,t),v.start=d,v.sn=u,v.cc=f,v.level=i,c&&(v.initSegment=c,v.rawProgramDateTime=c.rawProgramDateTime,c.rawProgramDateTime=null));const B=A[1];if(B){v.duration=parseFloat(B);const k=(" "+A[2]).slice(1);v.title=k||null,v.tagList.push(k?["INF",B,k]:["INF",B])}else if(A[3]){if(Z(v.duration)){v.start=d,x&&ts(v,x,o),v.sn=u,v.level=i,v.cc=f,v.urlId=r,l.push(v);const k=(" "+A[3]).slice(1);v.relurl=en(o,k),Jr(v,g),g=v,d+=v.duration,u++,h=0,P=!0}}else if(A[4]){const k=(" "+A[4]).slice(1);g?v.setByteRange(k,g):v.setByteRange(k)}else if(A[5])v.rawProgramDateTime=(" "+A[5]).slice(1),v.tagList.push(["PROGRAM-DATE-TIME",v.rawProgramDateTime]),_===-1&&(_=l.length);else{if(A=A[0].match(Vl),!A){C.warn("No matches on slow regex match for level playlist!");continue}for(T=1;T0&&S.bool("CAN-SKIP-DATERANGES"),o.partHoldBack=S.optionalFloat("PART-HOLD-BACK",0),o.holdBack=S.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const S=new me(E);o.partTarget=S.decimalFloatingPoint("PART-TARGET");break}case"PART":{let S=o.partList;S||(S=o.partList=[]);const I=h>0?S[S.length-1]:void 0,M=h++,K=new me(E);we(o,K,["BYTERANGE","URI"]);const H=new rl(K,v,t,M,I);S.push(H),v.duration+=H.duration;break}case"PRELOAD-HINT":{const S=new me(E);we(o,S,["URI"]),o.preloadHint=S;break}case"RENDITION-REPORT":{const S=new me(E);we(o,S,["URI"]),o.renditionReports=o.renditionReports||[],o.renditionReports.push(S);break}default:C.warn(`line parsed but not handled: ${A}`);break}}}g&&!g.relurl?(l.pop(),d-=g.duration,o.partList&&(o.fragmentHint=g)):o.partList&&(Jr(v,g),v.cc=f,o.fragmentHint=v,x&&ts(v,x,o));const L=l.length,G=l[0],O=l[L-1];if(d+=o.skippedSegments*o.targetduration,d>0&&L&&O){o.averagetargetduration=d/L;const B=O.sn;o.endSN=B!=="initSegment"?B:0,o.live||(O.endList=!0),G&&(o.startCC=G.cc)}else o.endSN=0,o.startCC=0;return o.fragmentHint&&(d+=o.fragmentHint.duration),o.totalduration=d,o.endCC=f,_>0&&Kl(l,_),o}}function Xr(s,e,t){var i,n;const r=new me(s);we(t,r,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const a=(i=r.METHOD)!=null?i:"",o=r.URI,l=r.hexadecimalInteger("IV"),c=r.KEYFORMATVERSIONS,u=(n=r.KEYFORMAT)!=null?n:"identity";o&&r.IV&&!l&&C.error(`Invalid IV: ${r.IV}`);const h=o?ze.resolve(o,e):"",d=(c||"1").split("/").map(Number).filter(Number.isFinite);return new zt(a,h,u,d,l)}function Qr(s){const t=new me(s).decimalFloatingPoint("TIME-OFFSET");return Z(t)?t:null}function Gl(s,e){["video","audio","text"].forEach(t=>{const i=s.filter(n=>Ul(n,t));if(i.length){const n=i.filter(r=>r.lastIndexOf("avc1",0)===0||r.lastIndexOf("mp4a",0)===0);e[`${t}Codec`]=n.length>0?n[0]:i[0],s=s.filter(r=>i.indexOf(r)===-1)}}),e.unknownCodecs=s}function Zr(s,e,t){const i=e[t];i&&(s[t]=i)}function Kl(s,e){let t=s[e];for(let i=e;i--;){const n=s[i];if(!n)return;n.programDateTime=t.programDateTime-n.duration*1e3,t=n}}function Jr(s,e){s.rawProgramDateTime?s.programDateTime=Date.parse(s.rawProgramDateTime):e!=null&&e.programDateTime&&(s.programDateTime=e.endProgramDateTime),Z(s.programDateTime)||(s.programDateTime=null,s.rawProgramDateTime=null)}function es(s,e,t,i){s.relurl=e.URI,e.BYTERANGE&&s.setByteRange(e.BYTERANGE),s.level=t,s.sn="initSegment",i&&(s.levelkeys=i),s.initSegment=null}function ts(s,e,t){s.levelkeys=e;const{encryptedFragments:i}=t;(!i.length||i[i.length-1].levelkeys!==e)&&Object.keys(e).some(n=>e[n].isCommonEncryption)&&i.push(s)}var le={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},ee={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};function is(s){const{type:e}=s;switch(e){case le.AUDIO_TRACK:return ee.AUDIO;case le.SUBTITLE_TRACK:return ee.SUBTITLE;default:return ee.MAIN}}function nn(s,e){let t=s.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class Hl{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.LEVEL_LOADING,this.onLevelLoading,this),e.on(y.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(y.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:e}=this;e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.LEVEL_LOADING,this.onLevelLoading,this),e.off(y.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(y.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(e){const t=this.hls.config,i=t.pLoader,n=t.loader,r=i||n,a=new r(t);return this.loaders[e.type]=a,a}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:le.MANIFEST,url:i,deliveryDirectives:null})}onLevelLoading(e,t){const{id:i,level:n,url:r,deliveryDirectives:a}=t;this.load({id:i,level:n,responseType:"text",type:le.LEVEL,url:r,deliveryDirectives:a})}onAudioTrackLoading(e,t){const{id:i,groupId:n,url:r,deliveryDirectives:a}=t;this.load({id:i,groupId:n,level:null,responseType:"text",type:le.AUDIO_TRACK,url:r,deliveryDirectives:a})}onSubtitleTrackLoading(e,t){const{id:i,groupId:n,url:r,deliveryDirectives:a}=t;this.load({id:i,groupId:n,level:null,responseType:"text",type:le.SUBTITLE_TRACK,url:r,deliveryDirectives:a})}load(e){var t;const i=this.hls.config;let n=this.getInternalLoader(e);if(n){const c=n.context;if(c&&c.url===e.url){C.trace("[playlist-loader]: playlist request ongoing");return}C.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),n.abort()}let r;if(e.type===le.MANIFEST?r=i.manifestLoadPolicy.default:r=Te({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(e),(t=e.deliveryDirectives)!=null&&t.part){let c;if(e.type===le.LEVEL&&e.level!==null?c=this.hls.levels[e.level].details:e.type===le.AUDIO_TRACK&&e.id!==null?c=this.hls.audioTracks[e.id].details:e.type===le.SUBTITLE_TRACK&&e.id!==null&&(c=this.hls.subtitleTracks[e.id].details),c){const u=c.partTarget,h=c.targetduration;if(u&&h){const d=Math.max(u*3,h*.8)*1e3;r=Te({},r,{maxTimeToFirstByteMs:Math.min(d,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(d,r.maxTimeToFirstByteMs)})}}}const a=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(c,u,h,d)=>{const f=this.getInternalLoader(h);this.resetInternalLoader(h.type);const g=c.data;if(g.indexOf("#EXTM3U")!==0){this.handleManifestParsingError(c,h,new Error("no EXTM3U delimiter"),d||null,u);return}u.parsing.start=performance.now(),ze.isMediaPlaylist(g)?this.handleTrackOrLevelPlaylist(c,u,h,d||null,f):this.handleMasterPlaylist(c,u,h,d)},onError:(c,u,h,d)=>{this.handleNetworkError(u,h,!1,c,d)},onTimeout:(c,u,h)=>{this.handleNetworkError(u,h,!0,void 0,c)}};n.load(e,o,l)}handleMasterPlaylist(e,t,i,n){const r=this.hls,a=e.data,o=nn(e,i),l=ze.parseMasterPlaylist(a,o);if(l.playlistParsingError){this.handleManifestParsingError(e,i,l.playlistParsingError,n,t);return}const{contentSteering:c,levels:u,sessionData:h,sessionKeys:d,startTimeOffset:f,variableList:g}=l;this.variableList=g;const{AUDIO:v=[],SUBTITLES:A,"CLOSED-CAPTIONS":T}=ze.parseMasterPlaylistMedia(a,o,l);v.length&&!v.some(_=>!_.url)&&u[0].audioCodec&&!u[0].attrs.AUDIO&&(C.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),v.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new me({}),bitrate:0,url:""})),r.trigger(y.MANIFEST_LOADED,{levels:u,audioTracks:v,subtitles:A,captions:T,contentSteering:c,url:o,stats:t,networkDetails:n,sessionData:h,sessionKeys:d,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(e,t,i,n,r){const a=this.hls,{id:o,level:l,type:c}=i,u=nn(e,i),h=Z(o)?o:0,d=Z(l)?l:h,f=is(i),g=ze.parseLevelPlaylist(e.data,u,d,f,h,this.variableList);if(c===le.MANIFEST){const v={attrs:new me({}),bitrate:0,details:g,name:"",url:u};a.trigger(y.MANIFEST_LOADED,{levels:[v],audioTracks:[],url:u,stats:t,networkDetails:n,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=g,this.handlePlaylistLoaded(g,e,t,i,n,r)}handleManifestParsingError(e,t,i,n,r){this.hls.trigger(y.ERROR,{type:J.NETWORK_ERROR,details:w.MANIFEST_PARSING_ERROR,fatal:t.type===le.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:n,stats:r})}handleNetworkError(e,t,i=!1,n,r){let a=`A network ${i?"timeout":"error"+(n?" (status "+n.code+")":"")} occurred while loading ${e.type}`;e.type===le.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===le.AUDIO_TRACK||e.type===le.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(a);C.warn(`[playlist-loader]: ${a}`);let l=w.UNKNOWN,c=!1;const u=this.getInternalLoader(e);switch(e.type){case le.MANIFEST:l=i?w.MANIFEST_LOAD_TIMEOUT:w.MANIFEST_LOAD_ERROR,c=!0;break;case le.LEVEL:l=i?w.LEVEL_LOAD_TIMEOUT:w.LEVEL_LOAD_ERROR,c=!1;break;case le.AUDIO_TRACK:l=i?w.AUDIO_TRACK_LOAD_TIMEOUT:w.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case le.SUBTITLE_TRACK:l=i?w.SUBTITLE_TRACK_LOAD_TIMEOUT:w.SUBTITLE_LOAD_ERROR,c=!1;break}u&&this.resetInternalLoader(e.type);const h={type:J.NETWORK_ERROR,details:l,fatal:c,url:e.url,loader:u,context:e,error:o,networkDetails:t,stats:r};if(n){const d=(t==null?void 0:t.url)||e.url;h.response=Re({url:d,data:void 0},n)}this.hls.trigger(y.ERROR,h)}handlePlaylistLoaded(e,t,i,n,r,a){const o=this.hls,{type:l,level:c,id:u,groupId:h,deliveryDirectives:d}=n,f=nn(t,n),g=is(n),v=typeof n.level=="number"&&g===ee.MAIN?c:void 0;if(!e.fragments.length){const T=new Error("No Segments found in Playlist");o.trigger(y.ERROR,{type:J.NETWORK_ERROR,details:w.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:T,reason:T.message,response:t,context:n,level:v,parent:g,networkDetails:r,stats:i});return}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const A=e.playlistParsingError;if(A){o.trigger(y.ERROR,{type:J.NETWORK_ERROR,details:w.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:A,reason:A.message,response:t,context:n,level:v,parent:g,networkDetails:r,stats:i});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case le.MANIFEST:case le.LEVEL:o.trigger(y.LEVEL_LOADED,{details:e,level:v||0,id:u||0,stats:i,networkDetails:r,deliveryDirectives:d});break;case le.AUDIO_TRACK:o.trigger(y.AUDIO_TRACK_LOADED,{details:e,id:u||0,groupId:h||"",stats:i,networkDetails:r,deliveryDirectives:d});break;case le.SUBTITLE_TRACK:o.trigger(y.SUBTITLE_TRACK_LOADED,{details:e,id:u||0,groupId:h||"",stats:i,networkDetails:r,deliveryDirectives:d});break}}}function ns(s,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=s,e.dispatchEvent(t)}function rs(s,e){const t=s.mode;if(t==="disabled"&&(s.mode="hidden"),s.cues&&!s.cues.getCueById(e.id))try{if(s.addCue(e),!s.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){C.debug(`[texttrack-utils]: ${i}`);try{const n=new self.TextTrackCue(e.startTime,e.endTime,e.text);n.id=e.id,s.addCue(n)}catch(n){C.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${n}`)}}t==="disabled"&&(s.mode=t)}function Ft(s){const e=s.mode;if(e==="disabled"&&(s.mode="hidden"),s.cues)for(let t=s.cues.length;t--;)s.removeCue(s.cues[t]);e==="disabled"&&(s.mode=e)}function rn(s,e,t,i){const n=s.mode;if(n==="disabled"&&(s.mode="hidden"),s.cues&&s.cues.length>0){const r=Wl(s.cues,e,t);for(let a=0;as[t].endTime)return-1;let i=0,n=t;for(;i<=n;){const r=Math.floor((n+i)/2);if(es[r].startTime&&i-1)for(let r=n,a=s.length;r=e&&o.endTime<=t)i.push(o);else if(o.startTime>t)return i}return i}var je={audioId3:"org.id3",dateRange:"com.apple.quicktime.HLS",emsg:"https://aomedia.org/emsg/ID3"};const zl=.25;function sn(){if(!(typeof self>"u"))return self.WebKitDataCue||self.VTTCue||self.TextTrackCue}const di=(()=>{const s=sn();try{new s(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function an(s,e){return s.getTime()/1e3-e}function jl(s){return Uint8Array.from(s.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}class ql{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){const{hls:e}=this;e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:e}=this;e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(e,t){this.media=t.media}onMediaDetaching(){this.id3Track&&(Ft(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;tdi&&(h=di),h-u<=0&&(h=u+zl);for(let f=0;fu.type===je.audioId3&&l:n==="video"?c=u=>u.type===je.emsg&&o:c=u=>u.type===je.audioId3&&l||u.type===je.emsg&&o,rn(r,t,i,c)}}onLevelUpdated(e,{details:t}){if(!this.media||!t.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:i,id3Track:n}=this,{dateRanges:r}=t,a=Object.keys(r);if(n){const u=Object.keys(i).filter(h=>!a.includes(h));for(let h=u.length;h--;){const d=u[h];Object.keys(i[d].cues).forEach(f=>{n.removeCue(i[d].cues[f])}),delete i[d]}}const o=t.fragments[t.fragments.length-1];if(a.length===0||!Z(o==null?void 0:o.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const l=o.programDateTime/1e3-o.start,c=sn();for(let u=0;u{const O=r[G];return O.class===d.class&&O.id!==G&&O.startDate>d.startDate&&L.push(O),L},[]).sort((L,G)=>L.startDate.getTime()-G.startDate.getTime())[0];P&&(T=an(P.startDate,l),v=!0)}const _=Object.keys(d.attr);for(let P=0;P<_.length;P++){const L=_[P];if(!il(L))continue;let G=g[L];if(G)v&&!f.durationKnown&&(G.endTime=T);else{let O=d.attr[L];G=new c(A,T,""),nl(L)&&(O=jl(O)),G.value={key:L,data:O},G.type=je.dateRange,G.id=h,this.id3Track.addCue(G),g[L]=G}}i[h]={cues:g,dateRange:d,durationKnown:v}}}}class Xl{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.levelDetails=null,this.currentTime=0,this.stallCount=0,this._latency=null,this.timeupdateHandler=()=>this.timeupdate(),this.hls=e,this.config=e.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:e,levelDetails:t}=this;return e.liveMaxLatencyDuration!==void 0?e.liveMaxLatencyDuration:t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const{levelDetails:e}=this;if(e===null)return null;const{holdBack:t,partHoldBack:i,targetduration:n}=e,{liveSyncDuration:r,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,l=this.hls.userConfig;let c=o&&i||t;(l.liveSyncDuration||l.liveSyncDurationCount||c===0)&&(c=r!==void 0?r:a*n);const u=n,h=1;return c+Math.min(this.stallCount*h,u)}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency,i=this.levelDetails;if(e===null||t===null||i===null)return null;const n=i.edge,r=e-t-this.edgeStalled,a=n-i.totalduration,o=n-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(a,r),o)}get drift(){const{levelDetails:e}=this;return e===null?1:e.drift}get edgeStalled(){const{levelDetails:e}=this;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e,levelDetails:t}=this;if(!e||!t)return 0;const i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(y.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(y.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(y.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(y.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){this.levelDetails=t,t.advanced&&this.timeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(e,t){var i;t.details===w.BUFFER_STALLED_ERROR&&(this.stallCount++,(i=this.levelDetails)!=null&&i.live&&C.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:e,levelDetails:t}=this;if(!e||!t)return;this.currentTime=e.currentTime;const i=this.computeLatency();if(i===null)return;this._latency=i;const{lowLatencyMode:n,maxLiveSyncPlaybackRate:r}=this.config;if(!n||r===1)return;const a=this.targetLatency;if(a===null)return;const o=i-a,l=Math.min(this.maxLatency,a+t.targetduration),c=o.05&&this.forwardBufferLength>1){const u=Math.min(2,Math.max(1,r)),h=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20;e.playbackRate=Math.min(u,Math.max(1,h))}else e.playbackRate!==1&&e.playbackRate!==0&&(e.playbackRate=1)}estimateLiveEdge(){const{levelDetails:e}=this;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}const on=["NONE","TYPE-0","TYPE-1",null];var jt={No:"",Yes:"YES",v2:"v2"};function Ql(s,e){const{canSkipUntil:t,canSkipDateRanges:i,endSN:n}=s,r=e!==void 0?e-n:0;return t&&rt).join(",").replace(/\.[^.,]+/g,"")}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get attrs(){return this._attrs[this._urlId]}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get uri(){return this.url[this._urlId]||""}get urlId(){return this._urlId}set urlId(e){const t=e%this.url.length;this._urlId!==t&&(this.fragmentError=0,this.loadError=0,this.details=void 0,this._urlId=t)}get audioGroupId(){var e;return(e=this.audioGroupIds)==null?void 0:e[this.urlId]}get textGroupId(){var e;return(e=this.textGroupIds)==null?void 0:e[this.urlId]}addFallback(e){this.url.push(e.url),this._attrs.push(e.attrs)}}function ln(s,e){const t=e.startPTS;if(Z(t)){let i=0,n;e.sn>s.sn?(i=t-s.start,n=s):(i=s.start-t,n=e),n.duration!==i&&(n.duration=i)}else e.sn>s.sn?s.cc===e.cc&&s.minEndPTS?e.start=s.start+(s.minEndPTS-s.start):e.start=s.start+s.duration:e.start=Math.max(s.start-e.duration,0)}function as(s,e,t,i,n,r){i-t<=0&&(C.warn("Fragment should have a positive duration",e),i=t+e.duration,r=n+e.duration);let o=t,l=i;const c=e.startPTS,u=e.endPTS;if(Z(c)){const A=Math.abs(c-t);Z(e.deltaPTS)?e.deltaPTS=Math.max(A,e.deltaPTS):e.deltaPTS=A,o=Math.max(t,c),t=Math.min(t,c),n=Math.min(n,e.startDTS),l=Math.min(i,u),i=Math.max(i,u),r=Math.max(r,e.endDTS)}const h=t-e.start;e.start!==0&&(e.start=t),e.duration=i-e.start,e.startPTS=t,e.maxStartPTS=o,e.startDTS=n,e.endPTS=i,e.minEndPTS=l,e.endDTS=r;const d=e.sn;if(!s||ds.endSN)return 0;let f;const g=d-s.startSN,v=s.fragments;for(v[g]=e,f=g;f>0;f--)ln(v[f],v[f-1]);for(f=g;f=0;l--){const c=i[l].initSegment;if(c){t=c;break}}s.fragmentHint&&delete s.fragmentHint.endPTS;let n=0,r;if(tc(s,e,(l,c)=>{l.relurl&&(n=l.cc-c.cc),Z(l.startPTS)&&Z(l.endPTS)&&(c.start=c.startPTS=l.startPTS,c.startDTS=l.startDTS,c.maxStartPTS=l.maxStartPTS,c.endPTS=l.endPTS,c.endDTS=l.endDTS,c.minEndPTS=l.minEndPTS,c.duration=l.endPTS-l.startPTS,c.duration&&(r=c),e.PTSKnown=e.alignedSliding=!0),c.elementaryStreams=l.elementaryStreams,c.loader=l.loader,c.stats=l.stats,c.urlId=l.urlId,l.initSegment&&(c.initSegment=l.initSegment,t=l.initSegment)}),t&&(e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments).forEach(c=>{var u;(!c.initSegment||c.initSegment.relurl===((u=t)==null?void 0:u.relurl))&&(c.initSegment=t)}),e.skippedSegments)if(e.deltaUpdateFailed=e.fragments.some(l=>!l),e.deltaUpdateFailed){C.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let l=e.skippedSegments;l--;)e.fragments.shift();e.startSN=e.fragments[0].sn,e.startCC=e.fragments[0].cc}else e.canSkipDateRanges&&(e.dateRanges=Jl(s.dateRanges,e.dateRanges,e.recentlyRemovedDateranges));const a=e.fragments;if(n){C.warn("discontinuity sliding from playlist, take drift into account");for(let l=0;l{c.elementaryStreams=l.elementaryStreams,c.stats=l.stats}),r?as(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS):os(s,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=s.driftStartTime,e.driftStart=s.driftStart;const o=e.advancedDateTime;if(e.advanced&&o){const l=e.edge;e.driftStart||(e.driftStartTime=o,e.driftStart=l),e.driftEndTime=o,e.driftEnd=l}else e.driftEndTime=s.driftEndTime,e.driftEnd=s.driftEnd,e.advancedDateTime=s.advancedDateTime}function Jl(s,e,t){const i=Te({},s);return t&&t.forEach(n=>{delete i[n]}),Object.keys(e).forEach(n=>{const r=new kr(e[n].attr,i[n]);r.isValid?i[n]=r:C.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(e[n].attr)}"`)}),i}function ec(s,e,t){if(s&&e){let i=0;for(let n=0,r=s.length;n<=r;n++){const a=s[n],o=e[n+i];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):i--}}}function tc(s,e,t){const i=e.skippedSegments,n=Math.max(s.startSN,e.startSN)-e.startSN,r=(s.fragmentHint?1:0)+(i?e.endSN:Math.min(s.endSN,e.endSN))-e.startSN,a=e.startSN-s.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=s.fragmentHint?s.fragments.concat(s.fragmentHint):s.fragments;for(let c=n;c<=r;c++){const u=l[a+c];let h=o[c];i&&!h&&c=i.length||cn(e,i[t].start)}function cn(s,e){if(e){const t=s.fragments;for(let i=s.skippedSegments;ie){const r=i[i.length-1].duration*1e3;r499)}const ds={search:function(s,e){let t=0,i=s.length-1,n=null,r=null;for(;t<=i;){n=(t+i)/2|0,r=s[n];const a=e(r);if(a>0)t=n+1;else if(a<0)i=n-1;else return r}return null}};function sc(s,e,t){if(e===null||!Array.isArray(s)||!s.length||!Z(e))return null;const i=s[0].programDateTime;if(e<(i||0))return null;const n=s[s.length-1].endProgramDateTime;if(e>=(n||0))return null;t=t||0;for(let r=0;rs)return 0;const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-i<=s?1:t.start-i>s&&t.start?-1:0}function ac(s,e,t){const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-i>s}function oc(s,e){return ds.search(s,t=>t.cce?-1:0)}const lc=3e5;var xe={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},Ke={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,SwitchToSDR:4};class cc{constructor(e){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=e,this.log=C.log.bind(C,"[info]:"),this.warn=C.warn.bind(C,"[warning]:"),this.error=C.error.bind(C,"[error]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(y.ERROR,this.onError,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(y.ERROR,this.onError,this),e.off(y.ERROR,this.onErrorOut,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){this.playlistError=0}stopLoad(){}getVariantLevelIndex(e){return(e==null?void 0:e.type)===ee.MAIN?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var i,n;if(t.fatal)return;const r=this.hls,a=t.context;switch(t.details){case w.FRAG_LOAD_ERROR:case w.FRAG_LOAD_TIMEOUT:case w.KEY_LOAD_ERROR:case w.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case w.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction={action:xe.DoNothing,flags:Ke.None};return}case w.FRAG_GAP:case w.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=xe.SendAlternateToPenaltyBox;return}case w.LEVEL_EMPTY_ERROR:case w.LEVEL_PARSING_ERROR:{var o,l;const c=t.parent===ee.MAIN?t.level:r.loadLevel;t.details===w.LEVEL_EMPTY_ERROR&&((o=t.context)!=null&&(l=o.levelDetails)!=null&&l.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,c):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,c))}return;case w.LEVEL_LOAD_ERROR:case w.LEVEL_LOAD_TIMEOUT:typeof(a==null?void 0:a.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,a.level));return;case w.AUDIO_TRACK_LOAD_ERROR:case w.AUDIO_TRACK_LOAD_TIMEOUT:case w.SUBTITLE_LOAD_ERROR:case w.SUBTITLE_TRACK_LOAD_TIMEOUT:if(a){const c=r.levels[r.loadLevel];if(c&&(a.type===le.AUDIO_TRACK&&a.groupId===c.audioGroupId||a.type===le.SUBTITLE_TRACK&&a.groupId===c.textGroupId)){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=xe.SendAlternateToPenaltyBox,t.errorAction.flags=Ke.MoveAllAlternatesMatchingHost;return}}return;case w.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const c=r.levels[r.loadLevel],u=c==null?void 0:c.attrs["HDCP-LEVEL"];u&&(t.errorAction={action:xe.SendAlternateToPenaltyBox,flags:Ke.MoveAllAlternatesMatchingHDCP,hdcpLevel:u})}return;case w.BUFFER_ADD_CODEC_ERROR:case w.REMUX_ALLOC_ERROR:t.errorAction=this.getLevelSwitchAction(t,(n=t.level)!=null?n:r.loadLevel);return;case w.INTERNAL_EXCEPTION:case w.BUFFER_APPENDING_ERROR:case w.BUFFER_APPEND_ERROR:case w.BUFFER_FULL_ERROR:case w.LEVEL_SWITCH_ERROR:case w.BUFFER_STALLED_ERROR:case w.BUFFER_SEEK_OVER_HOLE:case w.BUFFER_NUDGE_ON_STALL:t.errorAction={action:xe.DoNothing,flags:Ke.None};return}if(t.type===J.KEY_SYSTEM_ERROR){const c=this.getVariantLevelIndex(t.frag);t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,c);return}}getPlaylistRetryOrSwitchAction(e,t){var i;const n=this.hls,r=us(n.config.playlistLoadPolicy,e),a=this.playlistError++,o=(i=e.response)==null?void 0:i.code;if(gi(r,a,fi(e),o))return{action:xe.RetryRequest,flags:Ke.None,retryConfig:r,retryCount:a};const c=this.getLevelSwitchAction(e,t);return r&&(c.retryConfig=r,c.retryCount=a),c}getFragRetryOrSwitchAction(e){const t=this.hls,i=this.getVariantLevelIndex(e.frag),n=t.levels[i],{fragLoadPolicy:r,keyLoadPolicy:a}=t.config,o=us(e.details.startsWith("key")?a:r,e),l=t.levels.reduce((h,d)=>h+d.fragmentError,0);if(n){var c;e.details!==w.FRAG_GAP&&n.fragmentError++;const h=(c=e.response)==null?void 0:c.code;if(gi(o,l,fi(e),h))return{action:xe.RetryRequest,flags:Ke.None,retryConfig:o,retryCount:l}}const u=this.getLevelSwitchAction(e,i);return o&&(u.retryConfig=o,u.retryCount=l),u}getLevelSwitchAction(e,t){const i=this.hls;t==null&&(t=i.loadLevel);const n=this.hls.levels[t];if(n&&(n.loadError++,i.autoLevelEnabled)){var r,a;let o=-1;const{levels:l,loadLevel:c,minAutoLevel:u,maxAutoLevel:h}=i,d=(r=e.frag)==null?void 0:r.type,{type:f,groupId:g}=(a=e.context)!=null?a:{};for(let v=l.length;v--;){const A=(v+c)%l.length;if(A!==c&&A>=u&&A<=h&&l[A].loadError===0){const T=l[A];if(e.details===w.FRAG_GAP&&e.frag){const x=l[A].details;if(x){const _=Xt(e.frag,x.fragments,e.frag.start);if(_!=null&&_.gap)continue}}else{if(f===le.AUDIO_TRACK&&g===T.audioGroupId||f===le.SUBTITLE_TRACK&&g===T.textGroupId)continue;if(d===ee.AUDIO&&n.audioGroupId===T.audioGroupId||d===ee.SUBTITLE&&n.textGroupId===T.textGroupId)continue}o=A;break}}if(o>-1&&i.loadLevel!==o)return e.levelRetry=!0,this.playlistError=0,{action:xe.SendAlternateToPenaltyBox,flags:Ke.None,nextAutoLevel:o}}return{action:xe.SendAlternateToPenaltyBox,flags:Ke.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch((i=t.errorAction)==null?void 0:i.action){case xe.DoNothing:break;case xe.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==w.FRAG_GAP&&(t.fatal=!0);break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,i=e.errorAction;if(!i)return;const{flags:n,hdcpLevel:r,nextAutoLevel:a}=i;switch(n){case Ke.None:this.switchLevel(e,a);break;case Ke.MoveAllAlternatesMatchingHost:i.resolved||(i.resolved=this.redundantFailover(e));break;case Ke.MoveAllAlternatesMatchingHDCP:r&&(t.maxHdcpLevel=on[on.indexOf(r)-1],i.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}i.resolved||this.switchLevel(e,a)}switchLevel(e,t){t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}redundantFailover(e){const{hls:t,penalizedRenditions:i}=this,n=e.parent===ee.MAIN?e.level:t.loadLevel,r=t.levels[n],a=r.url.length,o=e.frag?e.frag.urlId:r.urlId;r.urlId===o&&(!e.frag||r.details)&&this.penalizeRendition(r,e);for(let l=1;l{h.urlId=c}),t.nextLoadLevel=n,!0}return!1}penalizeRendition(e,t){const{penalizedRenditions:i}=this,n=i[e.urlId]||{lastErrorPerfMs:0,errors:[],details:void 0};n.lastErrorPerfMs=performance.now(),n.errors.push(t),n.details=e.details,i[e.urlId]=n}}function uc(s,e,t){if(performance.now()-s.lastErrorPerfMs>lc)return!0;const i=s.details;if(e.details===w.FRAG_GAP&&i&&e.frag){const n=e.frag.start,r=Xt(null,i.fragments,n);if(r&&!r.gap)return!0}if(t&&s.errors.lengthi.targetduration*3)return!0}return!1}class dn{constructor(e,t){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=C.log.bind(C,`${t}:`),this.warn=C.warn.bind(C,`${t}:`),this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){clearTimeout(this.timer),this.timer=-1}startLoad(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t){const i=t==null?void 0:t.renditionReports;if(i){let n=-1;for(let r=0;r=0&&l>t.partTarget&&(o+=1)}return new ss(a,o>=0?o:void 0,jt.No)}}}loadPlaylist(e){this.requestScheduled===-1&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}shouldReloadPlaylist(e){return this.timer===-1&&this.requestScheduled===-1&&this.shouldLoadPlaylist(e)}playlistLoaded(e,t,i){const{details:n,stats:r}=t,a=self.performance.now(),o=r.loading.first?Math.max(0,a-r.loading.first):0;if(n.advancedDateTime=Date.now()-o,n.live||i!=null&&i.live){if(n.reloaded(i),i&&this.log(`live playlist ${e} ${n.advanced?"REFRESHED "+n.lastPartSn+"-"+n.lastPartIndex:"MISSED"}`),i&&n.fragments.length>0&&Zl(i,n),!this.canLoad||!n.live)return;let l,c,u;if(n.canBlockReload&&n.endSN&&n.advanced){const A=this.hls.config.lowLatencyMode,T=n.lastPartSn,x=n.endSN,_=n.lastPartIndex,P=_!==-1,L=T===x,G=A?0:_;P?(c=L?x+1:T,u=L?G:_+1):c=x+1;const O=n.age,B=O+n.ageHeader;let k=Math.min(B-n.partTarget,n.targetduration*1.5);if(k>0){if(i&&k>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${k} with playlist age: ${n.age}`),k=0;else{const E=Math.floor(k/n.targetduration);if(c+=E,u!==void 0){const N=Math.round(k%n.targetduration/n.partTarget);u+=N}this.log(`CDN Tune-in age: ${n.ageHeader}s last advanced ${O.toFixed(2)}s goal: ${k} skip sn ${E} to part ${u}`)}n.tuneInGoal=k}if(l=this.getDeliveryDirectives(n,t.deliveryDirectives,c,u),A||!L){this.loadPlaylist(l);return}}else n.canBlockReload&&(l=this.getDeliveryDirectives(n,t.deliveryDirectives,c,u));const h=this.hls.mainForwardBufferInfo,d=h?h.end-h.len:0,f=(n.edge-d)*1e3,g=ic(n,f);n.updated&&a>this.requestScheduled+g&&(this.requestScheduled=r.loading.start),c!==void 0&&n.canBlockReload?this.requestScheduled=r.loading.first+g-(n.partTarget*1e3||1e3):this.requestScheduled===-1||this.requestScheduled+gthis.loadPlaylist(l),v)}else this.clearTimer()}getDeliveryDirectives(e,t,i,n){let r=Ql(e,i);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,n=t.part,r=jt.No),new ss(i,n,r)}checkRetry(e){const t=e.details,i=fi(e),n=e.errorAction,{action:r,retryCount:a=0,retryConfig:o}=n||{},l=!!n&&!!o&&(r===xe.RetryRequest||!n.resolved&&r===xe.SendAlternateToPenaltyBox);if(l){var c;if(this.requestScheduled=-1,a>=o.maxNumRetry)return!1;if(i&&(c=e.context)!=null&&c.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const u=un(o,a);this.timer=self.setTimeout(()=>this.loadPlaylist(),u),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${u}ms`)}e.levelRetry=!0,n.resolved=!0}return l}}let fn;class hc extends dn{constructor(e,t){super(e,"[level-controller]"),this._levels=[],this._firstLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(y.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(y.FRAG_LOADED,this.onFragLoaded,this),e.on(y.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(y.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(y.FRAG_LOADED,this.onFragLoaded,this),e.off(y.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}startLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.startLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[]}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const i=[],n={};let r;t.levels.forEach(a=>{var o;const l=a.attrs;((o=a.audioCodec)==null?void 0:o.indexOf("mp4a.40.34"))!==-1&&(fn||(fn=/chrome|firefox/i.test(navigator.userAgent)),fn&&(a.audioCodec=void 0));const{AUDIO:c,CODECS:u,"FRAME-RATE":h,"PATHWAY-ID":d,RESOLUTION:f,SUBTITLES:g}=l,A=`${`${d||"."}-`}${a.bitrate}-${f}-${h}-${u}`;r=n[A],r?r.addFallback(a):(r=new qt(a),n[A]=r,i.push(r)),pi(r,"audio",c),pi(r,"text",g)}),this.filterAndSortMediaOptions(i,t)}filterAndSortMediaOptions(e,t){let i=[],n=[],r=!1,a=!1,o=!1,l=e.filter(({audioCodec:f,videoCodec:g,width:v,height:A,unknownCodecs:T})=>(r||(r=!!(v&&A)),a||(a=!!g),o||(o=!!f),!(T!=null&&T.length)&&(!f||tn(f,"audio"))&&(!g||tn(g,"video"))));if((r||a)&&o&&(l=l.filter(({videoCodec:f,width:g,height:v})=>!!f||!!(g&&v))),l.length===0){Promise.resolve().then(()=>{if(this.hls){const f=new Error("no level with compatible codecs found in manifest");this.hls.trigger(y.ERROR,{type:J.MEDIA_ERROR,details:w.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:f,reason:f.message})}});return}t.audioTracks&&(i=t.audioTracks.filter(f=>!f.audioCodec||tn(f.audioCodec,"audio")),fs(i)),t.subtitles&&(n=t.subtitles,fs(n));const c=l.slice(0);l.sort((f,g)=>f.attrs["HDCP-LEVEL"]!==g.attrs["HDCP-LEVEL"]?(f.attrs["HDCP-LEVEL"]||"")>(g.attrs["HDCP-LEVEL"]||"")?1:-1:f.bitrate!==g.bitrate?f.bitrate-g.bitrate:f.attrs["FRAME-RATE"]!==g.attrs["FRAME-RATE"]?f.attrs.decimalFloatingPoint("FRAME-RATE")-g.attrs.decimalFloatingPoint("FRAME-RATE"):f.attrs.SCORE!==g.attrs.SCORE?f.attrs.decimalFloatingPoint("SCORE")-g.attrs.decimalFloatingPoint("SCORE"):r&&f.height!==g.height?f.height-g.height:0);let u=c[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==c.length)){for(let f=0;f!!f.url)};this.hls.trigger(y.MANIFEST_PARSED,d),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return this._levels.length===0?null:this._levels}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const u=new Error("invalid level idx"),h=e<0;if(this.hls.trigger(y.ERROR,{type:J.OTHER_ERROR,details:w.LEVEL_SWITCH_ERROR,level:e,fatal:h,error:u,reason:u.message}),h)return;e=Math.min(e,t.length-1)}const i=this.currentLevelIndex,n=this.currentLevel,r=n?n.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,i===e&&a.details&&n&&r===o)return;this.log(`Switching to level ${e}${o?" with Pathway "+o:""} from level ${i}${r?" with Pathway "+r:""}`);const l=Te({},a,{level:e,maxBitrate:a.maxBitrate,attrs:a.attrs,uri:a.uri,urlId:a.urlId});delete l._attrs,delete l._urlId,this.hls.trigger(y.LEVEL_SWITCHING,l);const c=a.details;if(!c||c.live){const u=this.switchParams(a.uri,n==null?void 0:n.details);this.loadPlaylist(u)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this._firstLevel}else return this._startLevel}set startLevel(e){this._startLevel=e}onError(e,t){t.fatal||!t.context||t.context.type===le.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragLoaded(e,{frag:t}){if(t!==void 0&&t.type===ee.MAIN){const i=this._levels[t.level];i!==void 0&&(i.loadError=0)}}onLevelLoaded(e,t){var i;const{level:n,details:r}=t,a=this._levels[n];if(!a){var o;this.warn(`Invalid level index ${n}`),(o=t.deliveryDirectives)!=null&&o.skip&&(r.deltaUpdateFailed=!0);return}n===this.currentLevelIndex?(a.fragmentError===0&&(a.loadError=0),this.playlistLoaded(n,t,a.details)):(i=t.deliveryDirectives)!=null&&i.skip&&(r.deltaUpdateFailed=!0)}onAudioTrackSwitched(e,t){const i=this.currentLevel;if(!i)return;const n=this.hls.audioTracks[t.id].groupId;if(i.audioGroupIds&&i.audioGroupId!==n){let r=-1;for(let a=0;aa!==t,n=this._levels.filter((r,a)=>a!==e?!0:r.url.length>1&&t!==void 0?(r.url=r.url.filter(i),r.audioGroupIds&&(r.audioGroupIds=r.audioGroupIds.filter(i)),r.textGroupIds&&(r.textGroupIds=r.textGroupIds.filter(i)),r.urlId=0,!0):(this.steering&&this.steering.removeLevel(r),!1));this.hls.trigger(y.LEVELS_UPDATED,{levels:n})}onLevelsUpdated(e,{levels:t}){t.forEach((i,n)=>{const{details:r}=i;r!=null&&r.fragments&&r.fragments.forEach(a=>{a.level=n})}),this._levels=t}}function pi(s,e,t){t&&(e==="audio"?(s.audioGroupIds||(s.audioGroupIds=[]),s.audioGroupIds[s.url.length-1]=t):e==="text"&&(s.textGroupIds||(s.textGroupIds=[]),s.textGroupIds[s.url.length-1]=t))}function fs(s){const e={};s.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}var be={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class dc{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(y.BUFFER_APPENDED,this.onBufferAppended,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this),e.on(y.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(y.BUFFER_APPENDED,this.onBufferAppended,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this),e.off(y.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const i=this.activePartLists[t];if(i)for(let n=i.length;n--;){const r=i[n];if(!r)break;const a=r.end;if(r.start<=e&&a!==null&&e<=a)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){const{fragments:i}=this,n=Object.keys(i);for(let r=n.length;r--;){const a=i[n[r]];if((a==null?void 0:a.body.type)===t&&a.buffered){const o=a.body;if(o.start<=e&&e<=o.end)return o}}return null}detectEvictedFragments(e,t,i,n){this.timeRanges&&(this.timeRanges[e]=t);const r=(n==null?void 0:n.fragment.sn)||-1;Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o||r>=o.body.sn)return;if(!o.buffered&&!o.loaded){o.body.type===i&&this.removeFragment(o.body);return}const l=o.range[e];l&&l.time.some(c=>{const u=!this.isTimeBuffered(c.startPTS,c.endPTS,t);return u&&this.removeFragment(o.body),u})})}detectPartialFragments(e){const t=this.timeRanges,{frag:i,part:n}=e;if(!t||i.sn==="initSegment")return;const r=Mt(i),a=this.fragments[r];if(!a||a.buffered&&i.gap)return;const o=!i.relurl;Object.keys(t).forEach(l=>{const c=i.elementaryStreams[l];if(!c)return;const u=t[l],h=o||c.partial===!0;a.range[l]=this.getBufferedTimes(i,n,h,u)}),a.loaded=null,Object.keys(a.range).length?(a.buffered=!0,a.body.endList&&(this.endListFragments[a.body.type]=a),mi(a)||this.removeParts(i.sn-1,i.type)):this.removeFragment(a.body)}removeParts(e,t){const i=this.activePartLists[t];i&&(this.activePartLists[t]=i.filter(n=>n.fragment.sn>=e))}fragBuffered(e,t){const i=Mt(e);let n=this.fragments[i];!n&&t&&(n=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),n&&(n.loaded=null,n.buffered=!0)}getBufferedTimes(e,t,i,n){const r={time:[],partial:i},a=e.start,o=e.end,l=e.minEndPTS||o,c=e.maxStartPTS||a;for(let u=0;u=h&&l<=d){r.time.push({startPTS:Math.max(a,n.start(u)),endPTS:Math.min(o,n.end(u))});break}else if(ah)r.partial=!0,r.time.push({startPTS:Math.max(a,n.start(u)),endPTS:Math.min(o,n.end(u))});else if(o<=h)break}return r}getPartialFragment(e){let t=null,i,n,r,a=0;const{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(c=>{const u=l[c];u&&mi(u)&&(n=u.body.start-o,r=u.body.end+o,e>=n&&e<=r&&(i=Math.min(e-n,r-e),a<=i&&(t=u.body,a=i)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||mi(t))}getState(e){const t=Mt(e),i=this.fragments[t];return i?i.buffered?mi(i)?be.PARTIAL:be.OK:be.APPENDING:be.NOT_LOADED}isTimeBuffered(e,t,i){let n,r;for(let a=0;a=n&&t<=r)return!0;if(t<=n)return!1}return!1}onFragLoaded(e,t){const{frag:i,part:n}=t;if(i.sn==="initSegment"||i.bitrateTest)return;const r=n?null:t,a=Mt(i);this.fragments[a]={body:i,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:i,part:n,timeRanges:r}=t;if(i.sn==="initSegment")return;const a=i.type;if(n){let o=this.activePartLists[a];o||(this.activePartLists[a]=o=[]),o.push(n)}this.timeRanges=r,Object.keys(r).forEach(o=>{const l=r[o];this.detectEvictedFragments(o,l,a,n)})}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Mt(e);return!!this.fragments[t]}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,i,n,r){n&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o)return;const l=o.body;l.type!==i||n&&!l.gap||l.starte&&(o.buffered||r)&&this.removeFragment(l)})}removeFragment(e){const t=Mt(e);e.stats.loaded=0,e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const n=e.sn;this.activePartLists[e.type]=i.filter(r=>r.fragment.sn!==n)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}}function mi(s){var e,t,i;return s.buffered&&(s.body.gap||((e=s.range.video)==null?void 0:e.partial)||((t=s.range.audio)==null?void 0:t.partial)||((i=s.range.audiovideo)==null?void 0:i.partial))}function Mt(s){return`${s.type}_${s.level}_${s.urlId}_${s.sn}`}const gs=Math.pow(2,17);class fc{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const i=e.url;if(!i)return Promise.reject(new lt({type:J.NETWORK_ERROR,details:w.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();const n=this.config,r=n.fLoader,a=n.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(f=>f[0]==="GAP")){l(ms(e));return}else e.gap=!1;const c=this.loader=e.loader=r?new r(n):new a(n),u=ps(e),h=hs(n.fragLoadPolicy.default),d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:gs};e.stats=c.stats,c.load(u,d,{onSuccess:(f,g,v,A)=>{this.resetLoader(e,c);let T=f.data;v.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(T.slice(0,16)),T=T.slice(16)),o({frag:e,part:null,payload:T,networkDetails:A})},onError:(f,g,v,A)=>{this.resetLoader(e,c),l(new lt({type:J.NETWORK_ERROR,details:w.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Re({url:i,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:v,stats:A}))},onAbort:(f,g,v)=>{this.resetLoader(e,c),l(new lt({type:J.NETWORK_ERROR,details:w.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:v,stats:f}))},onTimeout:(f,g,v)=>{this.resetLoader(e,c),l(new lt({type:J.NETWORK_ERROR,details:w.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:v,stats:f}))},onProgress:(f,g,v,A)=>{t&&t({frag:e,part:null,payload:v,networkDetails:A})}})})}loadPart(e,t,i){this.abort();const n=this.config,r=n.fLoader,a=n.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(ms(e,t));return}const c=this.loader=e.loader=r?new r(n):new a(n),u=ps(e,t),h=hs(n.fragLoadPolicy.default),d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:gs};t.stats=c.stats,c.load(u,d,{onSuccess:(f,g,v,A)=>{this.resetLoader(e,c),this.updateStatsFromPart(e,t);const T={frag:e,part:t,payload:f.data,networkDetails:A};i(T),o(T)},onError:(f,g,v,A)=>{this.resetLoader(e,c),l(new lt({type:J.NETWORK_ERROR,details:w.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Re({url:u.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:v,stats:A}))},onAbort:(f,g,v)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,c),l(new lt({type:J.NETWORK_ERROR,details:w.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:v,stats:f}))},onTimeout:(f,g,v)=>{this.resetLoader(e,c),l(new lt({type:J.NETWORK_ERROR,details:w.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:v,stats:f}))}})})}updateStatsFromPart(e,t){const i=e.stats,n=t.stats,r=n.total;if(i.loaded+=n.loaded,r){const l=Math.round(e.duration/t.duration),c=Math.min(Math.round(i.loaded/r),l),h=(l-c)*Math.round(i.loaded/c);i.total=i.loaded+h}else i.total=Math.max(i.loaded,i.total);const a=i.loading,o=n.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function ps(s,e=null){const t=e||s,i={frag:s,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},n=t.byteRangeStartOffset,r=t.byteRangeEndOffset;if(Z(n)&&Z(r)){var a;let o=n,l=r;if(s.sn==="initSegment"&&((a=s.decryptdata)==null?void 0:a.method)==="AES-128"){const c=r-n;c%16&&(l=r+(16-c%16)),n!==0&&(i.resetIV=!0,o=n-16)}i.rangeStart=o,i.rangeEnd=l}return i}function ms(s,e){const t=new Error(`GAP ${s.gap?"tag":"attribute"} found`),i={type:J.MEDIA_ERROR,details:w.FRAG_GAP,fatal:!1,frag:s,error:t,networkDetails:null};return e&&(i.part=e),(e||s).stats.aborted=!0,new lt(i)}class lt extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class gc{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const t in this.keyUriToKeyInfo){const i=this.keyUriToKeyInfo[t].loader;if(i){if(e&&e!==i.context.frag.type)return;i.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=w.KEY_LOAD_ERROR,i,n,r){return new lt({type:J.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:i,networkDetails:n})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:i,cc:n}=e;for(let r=0;r{a.setKeyFormat(o)});break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,n;t&&e.setKeyFormat(t);const r=e.decryptdata;if(!r){const c=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,w.KEY_LOAD_ERROR,c))}const a=r.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,w.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));let o=this.keyUriToKeyInfo[a];if((i=o)!=null&&i.decryptdata.key)return r.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if((n=o)!=null&&n.keyLoadPromise){var l;switch((l=o.mediaKeySessionContext)==null?void 0:l.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return o.keyLoadPromise.then(c=>(r.key=c.keyInfo.decryptdata.key,{frag:e,keyInfo:o}))}}switch(o=this.keyUriToKeyInfo[a]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return r.keyFormat==="identity"?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,w.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){const i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const n=this.emeController.loadKey(i);if(n)return(e.keyLoadPromise=n.then(r=>(e.mediaKeySessionContext=r,i))).catch(r=>{throw e.keyLoadPromise=null,r})}return Promise.resolve(i)}loadKeyHTTP(e,t){const i=this.config,n=i.loader,r=new n(i);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise((a,o)=>{const l={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},c=i.keyLoadPolicy.default,u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(d,f,g,v)=>{const{frag:A,keyInfo:T,url:x}=g;if(!A.decryptdata||T!==this.keyUriToKeyInfo[x])return o(this.createKeyLoadError(A,w.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),v));T.decryptdata.key=A.decryptdata.key=new Uint8Array(d.data),A.keyLoader=null,T.loader=null,a({frag:A,keyInfo:T})},onError:(d,f,g,v)=>{this.resetLoader(f),o(this.createKeyLoadError(t,w.KEY_LOAD_ERROR,new Error(`HTTP Error ${d.code} loading key ${d.text}`),g,Re({url:l.url,data:void 0},d)))},onTimeout:(d,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,w.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),g))},onAbort:(d,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,w.INTERNAL_ABORTED,new Error("key loading aborted"),g))}};r.load(l,u,h)})}resetLoader(e){const{frag:t,keyInfo:i,url:n}=e,r=i.loader;t.keyLoader===r&&(t.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[n],r&&r.destroy()}}class pc{constructor(){this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}const mc={length:0,start:()=>0,end:()=>0};class ge{static isBuffered(e,t){try{if(e){const i=ge.getBuffered(e);for(let n=0;n=i.start(n)&&t<=i.end(n))return!0}}catch{}return!1}static bufferInfo(e,t,i){try{if(e){const n=ge.getBuffered(e),r=[];let a;for(a=0;ah&&(n[u-1].end=e[c].end):n.push(e[c])}else n.push(e[c])}else n=e;let r=0,a,o=t,l=t;for(let c=0;c=u&&tt.startCC||s&&s.cc>>8^T&255^99,e[g]=T,t[T]=g;const x=f[g],_=f[x],P=f[_];let L=f[T]*257^T*16843008;n[g]=L<<24|L>>>8,r[g]=L<<16|L>>>16,a[g]=L<<8|L>>>24,o[g]=L,L=P*16843009^_*65537^x*257^g*16843008,c[T]=L<<24|L>>>8,u[T]=L<<16|L>>>16,h[T]=L<<8|L>>>24,d[T]=L,g?(g=x^f[f[f[P^x]]],v^=f[f[v]]):g=v=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let i=!0,n=0;for(;nn?(this.logOnce("WebCrypto AES decrypt"),new bc(n,new Uint8Array(i)).decrypt(e.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(C.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,i)))}onWebCryptoError(e,t,i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i);const n=this.flush();if(n)return n.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%xc;return i!==e.length&&(t=St(e,0,i),this.remainderData=St(e,i)),t}logOnce(e){this.logEnabled&&(C.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Cc={toString:function(s){let e="";const t=s.length;for(let i=0;io.end){const h=a>u;(a{if(this.fragContextChanged(e)){this.warn(`Fragment ${e.sn}${r.part?" p: "+r.part.index:""} of level ${e.level} was dropped during download.`),this.fragmentTracker.removeFragment(e);return}e.stats.chunkCount++,this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,i,n).then(r=>{if(!r)return;const a=this.state;if(this.fragContextChanged(e)){(a===F.FRAG_LOADING||!this.fragCurrent&&a===F.PARSING)&&(this.fragmentTracker.removeFragment(e),this.state=F.IDLE);return}"payload"in r&&(this.log(`Loaded fragment ${e.sn} of level ${e.level}`),this.hls.trigger(y.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===F.STOPPED||this.state===F.ERROR||(this.warn(r),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===be.APPENDING){const r=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,r),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength);this.reduceMaxBufferLength(o)&&i.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===be.PARTIAL&&i.removeFragment(e))}flushMainBuffer(e,t,i=null){if(!(e-t))return;const n={startOffset:e,endOffset:t,type:i};this.hls.trigger(y.BUFFER_FLUSHING,n)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(i=>{if(!i||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return i}).then(i=>{const{hls:n}=this,{payload:r}=i,a=e.decryptdata;if(r&&r.byteLength>0&&a&&a.key&&a.iv&&a.method==="AES-128"){const o=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),a.key.buffer,a.iv.buffer).catch(l=>{throw n.trigger(y.ERROR,{type:J.MEDIA_ERROR,details:w.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:e}),l}).then(l=>{const c=self.performance.now();return n.trigger(y.FRAG_DECRYPTED,{frag:e,payload:l,stats:{tstart:o,tdecrypt:c}}),i.payload=l,i})}return i}).then(i=>{const{fragCurrent:n,hls:r,levels:a}=this;if(!a)throw new Error("init load aborted, missing levels");const o=e.stats;this.state=F.IDLE,t.fragmentError=0,e.data=new Uint8Array(i.payload),o.parsing.start=o.buffering.start=self.performance.now(),o.parsing.end=o.buffering.end=self.performance.now(),i.frag===n&&r.trigger(y.FRAG_BUFFERED,{stats:o,frag:n,part:null,id:e.type}),this.tick()}).catch(i=>{this.state===F.STOPPED||this.state===F.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.level!==t.level||e.sn!==t.sn||e.urlId!==t.urlId}fragBufferedComplete(e,t){var i,n,r,a;const o=this.mediaBuffer?this.mediaBuffer:this.media;this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.playlistType===ee.MAIN?"level":"track"} ${e.level} (frag:[${((i=e.startPTS)!=null?i:NaN).toFixed(3)}-${((n=e.endPTS)!=null?n:NaN).toFixed(3)}] > buffer:${o?Cc.toString(ge.getBuffered(o)):"(detached)"})`),this.state=F.IDLE,o&&(!this.loadedmetadata&&e.type==ee.MAIN&&o.buffered.length&&((r=this.fragCurrent)==null?void 0:r.sn)===((a=this.fragPrevious)==null?void 0:a.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:n,partsLoaded:r}=e,a=!r||r.length===0||r.some(l=>!l),o=new gn(i.level,i.sn,i.stats.chunkCount+1,0,n?n.index:-1,!a);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,n){var r;const a=t==null?void 0:t.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;if(e.encrypted&&!((r=e.decryptdata)!=null&&r.key)?(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.logPrefix==="[stream-controller]"?"level":"track"} ${e.level}`),this.state=F.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(u=>{if(!this.fragContextChanged(u.frag))return this.hls.trigger(y.KEY_LOADED,u),this.state===F.KEY_LOADING&&(this.state=F.IDLE),u}),this.hls.trigger(y.KEY_LOADING,{frag:e}),this.fragCurrent===null&&(o=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))):!e.encrypted&&a.encryptedFragments.length&&this.keyLoader.loadClear(e,a.encryptedFragments),i=Math.max(e.start,i||0),this.config.lowLatencyMode&&e.sn!=="initSegment"){const u=a.partList;if(u&&n){i>e.end&&a.fragmentHint&&(e=a.fragmentHint);const h=this.getNextPart(u,e,i);if(h>-1){const d=u[h];this.log(`Loading part sn: ${e.sn} p: ${d.index} cc: ${e.cc} of playlist [${a.startSN}-${a.endSN}] parts [0-${h}-${u.length-1}] ${this.logPrefix==="[stream-controller]"?"level":"track"}: ${e.level}, target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=d.start+d.duration,this.state=F.FRAG_LOADING;let f;return o?f=o.then(g=>!g||this.fragContextChanged(g.frag)?null:this.doFragPartsLoad(e,d,t,n)).catch(g=>this.handleFragLoadError(g)):f=this.doFragPartsLoad(e,d,t,n).catch(g=>this.handleFragLoadError(g)),this.hls.trigger(y.FRAG_LOADING,{frag:e,part:d,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):f}else if(!e.url||this.loadedEndOfParts(u,i))return Promise.resolve(null)}}this.log(`Loading fragment ${e.sn} cc: ${e.cc} ${a?"of ["+a.startSN+"-"+a.endSN+"] ":""}${this.logPrefix==="[stream-controller]"?"level":"track"}: ${e.level}, target: ${parseFloat(i.toFixed(3))}`),Z(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=F.FRAG_LOADING;const l=this.config.progressive;let c;return l&&o?c=o.then(u=>!u||this.fragContextChanged(u==null?void 0:u.frag)?null:this.fragmentLoader.load(e,n)).catch(u=>this.handleFragLoadError(u)):c=Promise.all([this.fragmentLoader.load(e,l?n:void 0),o]).then(([u])=>(!l&&u&&n&&n(u),u)).catch(u=>this.handleFragLoadError(u)),this.hls.trigger(y.FRAG_LOADING,{frag:e,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):c}doFragPartsLoad(e,t,i,n){return new Promise((r,a)=>{var o;const l=[],c=(o=i.details)==null?void 0:o.partList,u=h=>{this.fragmentLoader.loadPart(e,h,n).then(d=>{l[h.index]=d;const f=d.part;this.hls.trigger(y.FRAG_LOADED,d);const g=ls(i,e.sn,h.index+1)||cs(c,e.sn,h.index+1);if(g)u(g);else return r({frag:e,part:f,partsLoaded:l})}).catch(a)};u(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===w.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(y.ERROR,t)}else this.hls.trigger(y.ERROR,{type:J.OTHER_ERROR,details:w.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==F.PARSING){!this.fragCurrent&&this.state!==F.STOPPED&&this.state!==F.ERROR&&(this.state=F.IDLE);return}const{frag:i,part:n,level:r}=t,a=self.performance.now();i.stats.parsing.end=a,n&&(n.stats.parsing.end=a),this.updateLevelTiming(i,n,r,e.partial)}getCurrentContext(e){const{levels:t,fragCurrent:i}=this,{level:n,sn:r,part:a}=e;if(!(t!=null&&t[n]))return this.warn(`Levels object was unset while buffering fragment ${r} of level ${n}. The current chunk will not be buffered.`),null;const o=t[n],l=a>-1?ls(o,r,a):null,c=l?l.fragment:nc(o,r,i);return c?(i&&i!==c&&(c.stats=i.stats),{frag:c,part:l,level:o}):null}bufferFragmentData(e,t,i,n,r){var a;if(!e||this.state!==F.PARSING)return;const{data1:o,data2:l}=e;let c=o;if(o&&l&&(c=_t(o,l)),!((a=c)!=null&&a.length))return;const u={type:e.type,frag:t,part:i,chunkMeta:n,parent:t.type,data:c};if(this.hls.trigger(y.BUFFER_APPENDING,u),e.dropped&&e.independent&&!i){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!ge.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const i=t.currentTime,n=ge.bufferInfo(t,i,0),r=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),o=Math.max(Math.min(e.start-a,n.end-a),i+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){const i=this.getLoadPosition();return Z(i)?this.getFwdBufferInfoAtPos(e,i,t):null}getFwdBufferInfoAtPos(e,t,i){const{config:{maxBufferHole:n}}=this,r=ge.bufferInfo(e,t,n);if(r.len===0&&r.nextStart!==void 0){const a=this.fragmentTracker.getBufferedFrag(t,i);if(a&&r.nextStart=i?(t.maxMaxBufferLength/=2,this.warn(`Reduce max buffer length to ${t.maxMaxBufferLength}s`),!0):!1}getAppendedFrag(e,t=ee.MAIN){const i=this.fragmentTracker.getAppendedFrag(e,ee.MAIN);return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){const i=t.fragments,n=i.length;if(!n)return null;const{config:r}=this,a=i[0].start;let o;if(t.live){const l=r.initialLiveManifestSize;if(nt}getNextFragmentLoopLoading(e,t,i,n,r){const a=e.gap,o=this.getNextFragment(this.nextLoadPosition,t);if(o===null)return o;if(e=o,a&&e&&!e.gap&&i.nextStart){const l=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,n);if(l!==null&&i.len+l.len>=r)return this.log(`buffer full after gaps in "${n}" playlist starting at sn: ${e.sn}`),null}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!(e!=null&&e.initSegment.data)&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,i){let n=-1,r=!1,a=!0;for(let o=0,l=e.length;o-1&&ii.start&&i.loaded}getInitialLiveFragment(e,t){const i=this.fragPrevious;let n=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),n=sc(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!n){const r=i.sn+1;if(r>=e.startSN&&r<=e.endSN){const a=t[r-e.startSN];i.cc===a.cc&&(n=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${n.sn}`))}n||(n=oc(t,i.cc),n&&this.log(`Live playlist, switching playlist, load frag with same CC: ${n.sn}`))}}else{const r=this.hls.liveSyncPosition;r!==null&&(n=this.getFragmentAtPosition(r,this.bitrateTest?e.fragmentEnd:e.edge,e))}return n}getFragmentAtPosition(e,t,i){const{config:n}=this;let{fragPrevious:r}=this,{fragments:a,endSN:o}=i;const{fragmentHint:l}=i,c=n.maxFragLookUpTolerance,u=i.partList,h=!!(n.lowLatencyMode&&u!=null&&u.length&&l);h&&l&&!this.bitrateTest&&(a=a.concat(l),o=l.sn);let d;if(et-c?0:c;d=Xt(r,a,e,f)}else d=a[a.length-1];if(d){const f=d.sn-i.startSN,g=this.fragmentTracker.getState(d);if((g===be.OK||g===be.PARTIAL&&d.gap)&&(r=d),r&&d.sn===r.sn&&(!h||u[0].fragment.sn>d.sn)&&r&&d.level===r.level){const A=a[f+1];d.sn=a-t.maxFragLookUpTolerance&&r<=o;if(n!==null&&i.duration>n&&(r${e.startSN} prev-sn: ${r?r.sn:"na"} fragments: ${o}`),h}return l}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let i=this.startPosition;if(i ${(n=this.fragCurrent)==null?void 0:n.url}`);return}const r=t.details===w.FRAG_GAP;r&&this.fragmentTracker.fragBuffered(i,!0);const a=t.errorAction,{action:o,retryCount:l=0,retryConfig:c}=a||{};if(a&&o===xe.RetryRequest&&c){var u;this.resetStartWhenNotLoaded((u=this.levelLastLoaded)!=null?u:i.level);const h=un(c,l);this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${l+1}/${c.maxNumRetry} in ${h}ms`),a.resolved=!0,this.retryDate=self.performance.now()+h,this.state=F.FRAG_LOADING_WAITING_RETRY}else c&&a?(this.resetFragmentErrors(e),l.5;n&&this.reduceMaxBufferLength(i.len);const r=!n;return r&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${t} buffer`),e.frag&&(this.fragmentTracker.removeFragment(e.frag),this.nextLoadPosition=e.frag.start),this.resetLoadingState(),r}return!1}resetFragmentErrors(e){e===ee.AUDIO&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==F.STOPPED&&(this.state=F.IDLE)}afterBufferFlushed(e,t,i){if(!e)return;const n=ge.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,n,i),this.state===F.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=F.IDLE}resetStartWhenNotLoaded(e){if(!this.loadedmetadata){this.startFragRequested=!1;const t=this.levels?this.levels[e].details:null;t!=null&&t.live?(this.startPosition=-1,this.setStartPosition(t,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){var t;this.warn(`The loading context changed while buffering fragment ${e.sn} of level ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded((t=this.levelLastLoaded)!=null?t:e.level),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,n){var r;const a=i.details;if(!a){this.warn("level.details undefined");return}if(Object.keys(e.elementaryStreams).reduce((l,c)=>{const u=e.elementaryStreams[c];if(u){const h=u.endPTS-u.startPTS;if(h<=0)return this.warn(`Could not parse fragment ${e.sn} ${c} duration reliably (${h})`),l||!1;const d=n?0:as(a,e,u.startPTS,u.endPTS,u.startDTS,u.endDTS);return this.hls.trigger(y.LEVEL_PTS_UPDATED,{details:a,level:i,drift:d,type:c,frag:e,start:u.startPTS,end:u.endPTS}),!0}return l},!1))i.fragmentError=0;else if(((r=this.transmuxer)==null?void 0:r.error)===null){const l=new Error(`Found no media in fragment ${e.sn} of level ${e.level} resetting transmuxer to fallback to playlist timing`);if(i.fragmentError===0&&(i.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)),this.warn(l.message),this.hls.trigger(y.ERROR,{type:J.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of level "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=F.PARSED,this.hls.trigger(y.FRAG_PARSED,{frag:e,part:t})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(e){if(e.event==="demuxerWorker"){var t,i,n;this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded((t=(i=this.levelLastLoaded)!=null?i:(n=this.fragCurrent)==null?void 0:n.level)!=null?t:0),this.resetLoadingState()}}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function Es(){return self.SourceBuffer||self.WebKitSourceBuffer}function Lc(){const s=hi();if(!s)return!1;const e=Es(),t=s&&typeof s.isTypeSupported=="function"&&s.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'),i=!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function";return!!t&&!!i}function Ic(){var s;const e=Es();return typeof(e==null||(s=e.prototype)==null?void 0:s.changeType)=="function"}function Rc(){return typeof __HLS_WORKER_BUNDLE__=="function"}function Dc(){const s=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),e=self.URL.createObjectURL(s);return{worker:new self.Worker(e),objectURL:e}}function wc(s){const e=new self.URL(s,self.location.href).href;return{worker:new self.Worker(e),scriptURL:e}}function tt(s="",e=9e4){return{type:s,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Ts{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,i,n){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,i){}demux(e,t){this.cachedData&&(e=_t(this.cachedData,e),this.cachedData=null);let i=oi(e,0),n=i?i.length:0,r;const a=this._audioTrack,o=this._id3Track,l=i?gl(i):void 0,c=e.length;for((this.basePTS===null||this.frameIndex===0&&Z(l))&&(this.basePTS=Pc(l,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),i&&i.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:je.audioId3,duration:Number.POSITIVE_INFINITY});n{if(Z(s))return s*90;const i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i};function Oc(s,e,t,i){let n,r,a,o;const l=navigator.userAgent.toLowerCase(),c=i,u=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];n=((e[t+2]&192)>>>6)+1;const h=(e[t+2]&60)>>>2;if(h>u.length-1){s.trigger(y.ERROR,{type:J.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,fatal:!0,reason:`invalid ADTS sampling index:${h}`});return}return a=(e[t+2]&1)<<2,a|=(e[t+3]&192)>>>6,C.log(`manifest codec:${i}, ADTS type:${n}, samplingIndex:${h}`),/firefox/i.test(l)?h>=6?(n=5,o=new Array(4),r=h-3):(n=2,o=new Array(2),r=h):l.indexOf("android")!==-1?(n=2,o=new Array(2),r=h):(n=5,o=new Array(4),i&&(i.indexOf("mp4a.40.29")!==-1||i.indexOf("mp4a.40.5")!==-1)||!i&&h>=6?r=h-3:((i&&i.indexOf("mp4a.40.2")!==-1&&(h>=6&&a===1||/vivaldi/i.test(l))||!i&&a===1)&&(n=2,o=new Array(2)),r=h)),o[0]=n<<3,o[0]|=(h&14)>>1,o[1]|=(h&1)<<7,o[1]|=a<<3,n===5&&(o[1]|=(r&14)>>1,o[2]=(r&1)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:u[h],channelCount:a,codec:"mp4a.40."+n,manifestCodec:c}}function bs(s,e){return s[e]===255&&(s[e+1]&246)===240}function Ss(s,e){return s[e+1]&1?7:9}function vn(s,e){return(s[e+3]&3)<<11|s[e+4]<<3|(s[e+5]&224)>>>5}function Nc(s,e){return e+5=s.length)return!1;const i=vn(s,e);if(i<=t)return!1;const n=e+i;return n===s.length||vi(s,n)}return!1}function _s(s,e,t,i,n){if(!s.samplerate){const r=Oc(e,t,i,n);if(!r)return;s.config=r.config,s.samplerate=r.samplerate,s.channelCount=r.channelCount,s.codec=r.codec,s.manifestCodec=r.manifestCodec,C.log(`parsed codec:${s.codec}, rate:${r.samplerate}, channels:${r.channelCount}`)}}function ks(s){return 1024*9e4/s}function Bc(s,e){const t=Ss(s,e);if(e+t<=s.length){const i=vn(s,e)-t;if(i>0)return{headerLength:t,frameLength:i}}}function xs(s,e,t,i,n){const r=ks(s.samplerate),a=i+n*r,o=Bc(e,t);let l;if(o){const{frameLength:h,headerLength:d}=o,f=d+h,g=Math.max(0,t+f-e.length);g?(l=new Uint8Array(f-d),l.set(e.subarray(t+d,e.length),0)):l=e.subarray(t+d,t+f);const v={unit:l,pts:a};return g||s.samples.push(v),{sample:v,length:f,missing:g}}const c=e.length-t;return l=new Uint8Array(c),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:a},length:c,missing:-1}}class Uc extends Ts{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,i,n){super.resetInitSegment(e,t,i,n),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let i=(oi(e,0)||[]).length;for(let n=e.length;i16384?e.subarray(0,16384):e,oe(e,["moof"]).length>0}demux(e,t){this.timeOffset=t;let i=e;const n=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=_t(this.remainderData,e));const o=Il(i);this.remainderData=o.remainder,n.samples=o.valid||new Uint8Array}else n.samples=i;const a=this.extractID3Track(n,t);return r.samples=$r(t,n),{videoTrack:n,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const n=this.extractID3Track(t,this.timeOffset);return i.samples=$r(e,t),{videoTrack:t,audioTrack:tt(),id3Track:n,textTrack:tt()}}extractID3Track(e,t){const i=this.id3Track;if(e.samples.length){const n=oe(e.samples,["emsg"]);n&&n.forEach(r=>{const a=wl(r);if($c.test(a.schemeIdUri)){const o=Z(a.presentationTime)?a.presentationTime/a.timeScale:t+a.presentationTimeDelta/a.timeScale;let l=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const c=a.payload;i.samples.push({data:c,len:c.byteLength,dts:o,pts:o,type:je.emsg,duration:l})}})}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}}let Ai=null;const Gc=[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],Kc=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Hc=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Yc=[0,1,1,4];function Cs(s,e,t,i,n){if(t+24>e.length)return;const r=Ls(e,t);if(r&&t+r.frameLength<=e.length){const a=r.samplesPerFrame*9e4/r.sampleRate,o=i+n*a,l={unit:e.subarray(t,t+r.frameLength),pts:o,dts:o};return s.config=[],s.channelCount=r.channelCount,s.samplerate=r.sampleRate,s.samples.push(l),{sample:l,length:r.frameLength,missing:0}}}function Ls(s,e){const t=s[e+1]>>3&3,i=s[e+1]>>1&3,n=s[e+2]>>4&15,r=s[e+2]>>2&3;if(t!==1&&n!==0&&n!==15&&r!==3){const a=s[e+2]>>1&1,o=s[e+3]>>6,l=t===3?3-i:i===3?3:4,c=Gc[l*14+n-1]*1e3,h=Kc[(t===3?0:t===2?1:2)*3+r],d=o===3?1:2,f=Hc[t][i],g=Yc[i],v=f*8*g,A=Math.floor(f*c/h+a)*g;if(Ai===null){const _=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ai=_?parseInt(_[1]):0}return!!Ai&&Ai<=87&&i===2&&c>=224e3&&o===0&&(s[e+3]=s[e+3]|128),{sampleRate:h,channelCount:d,frameLength:A,samplesPerFrame:v}}}function An(s,e){return s[e]===255&&(s[e+1]&224)===224&&(s[e+1]&6)!==0}function Is(s,e){return e+1e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const i=this.word>>>32-t;if(e>32&&C.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?i<>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}skipScalingList(e){let t=8,i=8,n;for(let r=0;r{const l=new Uint8Array(o);n.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)})}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length){i();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,i=new Int8Array(t);let n=0;for(let r=32;r{r.data=this.getAvcDecryptedUnit(a,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,n)})}decryptAvcSamples(e,t,i,n){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){n();return}const r=e[t].units;for(;!(i>=r.length);i++){const a=r[i];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,i,n,a),!this.decrypter.isSync()))return}}}}const Ce=188;class pt{constructor(e,t,i){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._avcTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.observer=e,this.config=t,this.typeSupported=i}static probe(e){const t=pt.syncOffset(e);return t>0&&C.warn(`MPEG2-TS detected but first sync word found @ offset ${t}`),t!==-1}static syncOffset(e){const t=e.length;let i=Math.min(Ce*5,e.length-Ce)+1,n=0;for(;n1&&(a===0&&o>2||l+Ce>i))return a}else{if(o)return-1;break}n++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:Nr[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,i,n){this.pmtParsed=!1,this._pmtId=-1,this._avcTrack=pt.createTrack("video"),this._audioTrack=pt.createTrack("audio",n),this._id3Track=pt.createTrack("id3"),this._txtTrack=pt.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i,this._duration=n}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_avcTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.avcSample=null,this.remainderData=null}demux(e,t,i=!1,n=!1){i||(this.sampleAes=null);let r;const a=this._avcTrack,o=this._audioTrack,l=this._id3Track,c=this._txtTrack;let u=a.pid,h=a.pesData,d=o.pid,f=l.pid,g=o.pesData,v=l.pesData,A=null,T=this.pmtParsed,x=this._pmtId,_=e.length;if(this.remainderData&&(e=_t(this.remainderData,e),_=e.length,this.remainderData=null),_>4;let N;if(E>1){if(N=O+5+e[O+4],N===O+Ce)continue}else N=O+4;switch(k){case u:B&&(h&&(r=Bt(h))&&this.parseAVCPES(a,c,r,!1),h={data:[],size:0}),h&&(h.data.push(e.subarray(N,O+Ce)),h.size+=O+Ce-N);break;case d:if(B){if(g&&(r=Bt(g)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,r);break;case"mp3":this.parseMPEGPES(o,r);break}g={data:[],size:0}}g&&(g.data.push(e.subarray(N,O+Ce)),g.size+=O+Ce-N);break;case f:B&&(v&&(r=Bt(v))&&this.parseID3PES(l,r),v={data:[],size:0}),v&&(v.data.push(e.subarray(N,O+Ce)),v.size+=O+Ce-N);break;case 0:B&&(N+=e[N]+1),x=this._pmtId=qc(e,N);break;case x:{B&&(N+=e[N]+1);const S=Xc(e,N,this.typeSupported,i);u=S.avc,u>0&&(a.pid=u),d=S.audio,d>0&&(o.pid=d,o.segmentCodec=S.segmentCodec),f=S.id3,f>0&&(l.pid=f),A!==null&&!T&&(C.warn(`MPEG-TS PMT found at ${O} after unknown PID '${A}'. Backtracking to sync byte @${P} to parse all TS packets.`),A=null,O=P-188),T=this.pmtParsed=!0;break}case 17:case 8191:break;default:A=k;break}}else L++;if(L>0){const O=new Error(`Found ${L} TS packet/s that do not start with 0x47`);this.observer.emit(y.ERROR,y.ERROR,{type:J.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,fatal:!1,error:O,reason:O.message})}a.pesData=h,o.pesData=g,l.pesData=v;const G={audioTrack:o,videoTrack:a,id3Track:l,textTrack:c};return n&&this.extractRemainingSamples(G),G}flush(){const{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._avcTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:i,id3Track:n,textTrack:r}=e,a=i.pesData,o=t.pesData,l=n.pesData;let c;if(a&&(c=Bt(a))?(this.parseAVCPES(i,r,c,!0),i.pesData=null):i.pesData=a,o&&(c=Bt(o))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,c);break;case"mp3":this.parseMPEGPES(t,c);break}t.pesData=null}else o!=null&&o.size&&C.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;l&&(c=Bt(l))?(this.parseID3PES(n,c),n.pesData=null):n.pesData=l}demuxSampleAes(e,t,i){const n=this.demux(e,i,!0,!this.config.progressive),r=this.sampleAes=new jc(this.observer,this.config,t);return this.decrypt(n,r)}decrypt(e,t){return new Promise(i=>{const{audioTrack:n,videoTrack:r}=e;n.samples&&n.segmentCodec==="aac"?t.decryptAacSamples(n.samples,0,()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,()=>{i(e)}):i(e)}):r.samples&&t.decryptAvcSamples(r.samples,0,0,()=>{i(e)})})}destroy(){this._duration=0}parseAVCPES(e,t,i,n){const r=this.parseAVCNALu(e,i.data);let a=this.avcSample,o,l=!1;i.data=null,a&&r.length&&!e.audFound&&(Qt(a,e),a=this.avcSample=Ei(!1,i.pts,i.dts,"")),r.forEach(c=>{var u;switch(c.type){case 1:{let d=!1;o=!0;const f=c.data;if(l&&f.length>4){const g=new Rs(f).readSliceType();(g===2||g===4||g===7||g===9)&&(d=!0)}if(d){var h;(h=a)!=null&&h.frame&&!a.key&&(Qt(a,e),a=this.avcSample=null)}a||(a=this.avcSample=Ei(!0,i.pts,i.dts,"")),a.frame=!0,a.key=d;break}case 5:o=!0,(u=a)!=null&&u.frame&&!a.key&&(Qt(a,e),a=this.avcSample=null),a||(a=this.avcSample=Ei(!0,i.pts,i.dts,"")),a.key=!0,a.frame=!0;break;case 6:{o=!0,Vr(c.data,1,i.pts,t.samples);break}case 7:if(o=!0,l=!0,!e.sps){const d=c.data,g=new Rs(d).readSPS();e.width=g.width,e.height=g.height,e.pixelRatio=g.pixelRatio,e.sps=[d],e.duration=this._duration;const v=d.subarray(1,4);let A="avc1.";for(let T=0;T<3;T++){let x=v[T].toString(16);x.length<2&&(x="0"+x),A+=x}e.codec=A}break;case 8:o=!0,e.pps||(e.pps=[c.data]);break;case 9:o=!1,e.audFound=!0,a&&Qt(a,e),a=this.avcSample=Ei(!1,i.pts,i.dts,"");break;case 12:o=!0;break;default:o=!1,a&&(a.debug+="unknown NAL "+c.type+" ");break}a&&o&&a.units.push(c)}),n&&a&&(Qt(a,e),this.avcSample=null)}getLastNalUnit(e){var t;let i=this.avcSample,n;if((!i||i.units.length===0)&&(i=e[e.length-1]),(t=i)!=null&&t.units){const r=i.units;n=r[r.length-1]}return n}parseAVCNALu(e,t){const i=t.byteLength;let n=e.naluState||0;const r=n,a=[];let o=0,l,c,u,h=-1,d=0;for(n===-1&&(h=0,d=t[0]&31,n=0,o=1);o=0){const f={data:t.subarray(h,o-n-1),type:d};a.push(f)}else{const f=this.getLastNalUnit(e.samples);if(f&&(r&&o<=4-r&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-r)),c=o-n-1,c>0)){const g=new Uint8Array(f.data.byteLength+c);g.set(f.data,0),g.set(t.subarray(0,c),f.data.byteLength),f.data=g,f.state=0}}o=0&&n>=0){const f={data:t.subarray(h,i),type:d,state:n};a.push(f)}if(a.length===0){const f=this.getLastNalUnit(e.samples);if(f){const g=new Uint8Array(f.data.byteLength+t.byteLength);g.set(f.data,0),g.set(t,f.data.byteLength),f.data=g}}return e.naluState=n,a}parseAACPES(e,t){let i=0;const n=this.aacOverFlow;let r=t.data;if(n){this.aacOverFlow=null;const h=n.missing,d=n.sample.unit.byteLength;if(h===-1){const f=new Uint8Array(d+r.byteLength);f.set(n.sample.unit,0),f.set(r,d),r=f}else{const f=d-h;n.sample.unit.set(r.subarray(0,h),f),e.samples.push(n.sample),i=n.missing}}let a,o;for(a=i,o=r.length;a1;){const c=new Uint8Array(o[0].length+o[1].length);c.set(o[0]),c.set(o[1],o[0].length),o[0]=c,o.splice(1,1)}if(t=o[0],(t[0]<<16)+(t[1]<<8)+t[2]===1){if(i=(t[4]<<8)+t[5],i&&i>s.size-6)return null;const c=t[7];c&192&&(r=(t[9]&14)*536870912+(t[10]&255)*4194304+(t[11]&254)*16384+(t[12]&255)*128+(t[13]&254)/2,c&64?(a=(t[14]&14)*536870912+(t[15]&255)*4194304+(t[16]&254)*16384+(t[17]&255)*128+(t[18]&254)/2,r-a>60*9e4&&(C.warn(`${Math.round((r-a)/9e4)}s delta between PTS and DTS, align them`),r=a)):a=r),n=t[8];let u=n+9;if(s.size<=u)return null;s.size-=u;const h=new Uint8Array(s.size);for(let d=0,f=o.length;dg){u-=g;continue}else t=t.subarray(u),g-=u,u=0;h.set(t,e),e+=g}return i&&(i-=n+3),{data:h,pts:r,dts:a,len:i}}return null}function Qt(s,e){if(s.units.length&&s.frame){if(s.pts===void 0){const t=e.samples,i=t.length;if(i){const n=t[i-1];s.pts=n.pts,s.dts=n.dts}else{e.dropped++;return}}e.samples.push(s)}s.debug.length&&C.log(s.pts+"/"+s.dts+":"+s.debug)}class Qc extends Ts{resetInitSegment(e,t,i,n){super.resetInitSegment(e,t,i,n),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let i=(oi(e,0)||[]).length;for(let n=e.length;i>24&255,a[1]=i>>16&255,a[2]=i>>8&255,a[3]=i&255,a.set(e,4),n=0,i=8;n>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,n>>24,n>>16&255,n>>8&255,n&255,85,196,0,0]))}static mdia(e){return R.box(R.types.mdia,R.mdhd(e.timescale,e.duration),R.hdlr(e.type),R.minf(e))}static mfhd(e){return R.box(R.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?R.box(R.types.minf,R.box(R.types.smhd,R.SMHD),R.DINF,R.stbl(e)):R.box(R.types.minf,R.box(R.types.vmhd,R.VMHD),R.DINF,R.stbl(e))}static moof(e,t,i){return R.box(R.types.moof,R.mfhd(e),R.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=R.trak(e[t]);return R.box.apply(null,[R.types.moov,R.mvhd(e[0].timescale,e[0].duration)].concat(i).concat(R.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=R.trex(e[t]);return R.box.apply(null,[R.types.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(mt+1)),n=Math.floor(t%(mt+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,n>>24,n>>16&255,n>>8&255,n&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return R.box(R.types.mvhd,r)}static sdtp(e){const t=e.samples||[],i=new Uint8Array(4+t.length);let n,r;for(n=0;n>>8&255),t.push(a&255),t=t.concat(Array.prototype.slice.call(r));for(n=0;n>>8&255),i.push(a&255),i=i.concat(Array.prototype.slice.call(r));const o=R.box(R.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(i))),l=e.width,c=e.height,u=e.pixelRatio[0],h=e.pixelRatio[1];return R.box(R.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&255,c>>8&255,c&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,R.box(R.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),R.box(R.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,h>>24,h>>16&255,h>>8&255,h&255])))}static esds(e){const t=e.config.length;return new Uint8Array([0,0,0,0,3,23+t,0,1,0,4,15+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([t]).concat(e.config).concat([6,1,2]))}static mp4a(e){const t=e.samplerate;return R.box(R.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,t&255,0,0]),R.box(R.types.esds,R.esds(e)))}static mp3(e){const t=e.samplerate;return R.box(R.types[".mp3"],new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,t&255,0,0]))}static stsd(e){return e.type==="audio"?e.segmentCodec==="mp3"&&e.codec==="mp3"?R.box(R.types.stsd,R.STSD,R.mp3(e)):R.box(R.types.stsd,R.STSD,R.mp4a(e)):R.box(R.types.stsd,R.STSD,R.avc1(e))}static tkhd(e){const t=e.id,i=e.duration*e.timescale,n=e.width,r=e.height,a=Math.floor(i/(mt+1)),o=Math.floor(i%(mt+1));return R.box(R.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,n>>8&255,n&255,0,0,r>>8&255,r&255,0,0]))}static traf(e,t){const i=R.sdtp(e),n=e.id,r=Math.floor(t/(mt+1)),a=Math.floor(t%(mt+1));return R.box(R.types.traf,R.box(R.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255])),R.box(R.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,a>>24,a>>16&255,a>>8&255,a&255])),R.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,R.box(R.types.trak,R.tkhd(e),R.mdia(e))}static trex(e){const t=e.id;return R.box(R.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const i=e.samples||[],n=i.length,r=12+16*n,a=new Uint8Array(r);let o,l,c,u,h,d;for(t+=8+r,a.set([e.type==="video"?1:0,0,15,1,n>>>24&255,n>>>16&255,n>>>8&255,n&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o>>24&255,c>>>16&255,c>>>8&255,c&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,h.degradPrio&61440,h.degradPrio&15,d>>>24&255,d>>>16&255,d>>>8&255,d&255],12+16*o);return R.box(R.types.trun,a)}static initSegment(e){R.types||R.init();const t=R.moov(e),i=new Uint8Array(R.FTYP.byteLength+t.byteLength);return i.set(R.FTYP),i.set(t,R.FTYP.byteLength),i}}R.types=void 0,R.HDLR_TYPES=void 0,R.STTS=void 0,R.STSC=void 0,R.STCO=void 0,R.STSZ=void 0,R.VMHD=void 0,R.SMHD=void 0,R.STSD=void 0,R.FTYP=void 0,R.DINF=void 0;const ws=9e4;function Tn(s,e,t=1,i=!1){const n=s*e*t;return i?Math.round(n):n}function Zc(s,e,t=1,i=!1){return Tn(s,e,1/t,i)}function Zt(s,e=!1){return Tn(s,1e3,1/ws,e)}function Jc(s,e=1){return Tn(s,ws,1/e)}const eu=10*1e3,Ps=1024,tu=1152;let Ti=null,bn=null;class Sn{constructor(e,t,i,n=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1,Ti===null){const a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ti=a?parseInt(a[1]):0}if(bn===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);bn=r?parseInt(r[1]):0}}destroy(){}resetTimeStamp(e){C.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){C.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){C.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1}getVideoStartPts(e){let t=!1;const i=e.reduce((n,r)=>{const a=r.pts-n;return a<-4294967296?(t=!0,He(n,r.pts)):a>0?n:r.pts},e[0].pts);return t&&C.debug("PTS rollover detected"),i}remux(e,t,i,n,r,a,o,l){let c,u,h,d,f,g,v=r,A=r;const T=e.pid>-1,x=t.pid>-1,_=t.samples.length,P=e.samples.length>0,L=o&&_>0||_>1;if((!T||P)&&(!x||L)||this.ISGenerated||o){this.ISGenerated||(h=this.generateIS(e,t,r,a));const O=this.isVideoContiguous;let B=-1,k;if(L&&(B=iu(t.samples),!O&&this.config.forceKeyFrameOnDiscontinuity))if(g=!0,B>0){C.warn(`[mp4-remuxer]: Dropped ${B} out of ${_} video samples due to a missing keyframe`);const E=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(B),t.dropped+=B,A+=(t.samples[0].pts-E)/t.inputTimeScale,k=A}else B===-1&&(C.warn(`[mp4-remuxer]: No keyframe found out of ${_} video samples`),g=!1);if(this.ISGenerated){if(P&&L){const E=this.getVideoStartPts(t.samples),S=(He(e.samples[0].pts,E)-E)/t.inputTimeScale;v+=Math.max(0,S),A+=Math.max(0,-S)}if(P){if(e.samplerate||(C.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),h=this.generateIS(e,t,r,a)),u=this.remuxAudio(e,v,this.isAudioContiguous,a,x||L||l===ee.AUDIO?A:void 0),L){const E=u?u.endPTS-u.startPTS:0;t.inputTimeScale||(C.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),h=this.generateIS(e,t,r,a)),c=this.remuxVideo(t,A,O,E)}}else L&&(c=this.remuxVideo(t,A,O,0));c&&(c.firstKeyFrame=B,c.independent=B!==-1,c.firstKeyFramePTS=k)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(f=Os(i,r,this._initPTS,this._initDTS)),n.samples.length&&(d=Ns(n,r,this._initPTS))),{audio:u,video:c,initSegment:h,independent:g,text:d,id3:f}}generateIS(e,t,i,n){const r=e.samples,a=t.samples,o=this.typeSupported,l={},c=this._initPTS;let u=!c||n,h="audio/mp4",d,f,g;if(u&&(d=f=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(h="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break}l.audio={id:"audio",container:h,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):R.initSegment([e]),metadata:{channelCount:e.channelCount}},u&&(g=e.inputTimeScale,!c||g!==c.timescale?d=f=r[0].pts-Math.round(g*i):u=!1)}if(t.sps&&t.pps&&a.length&&(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:R.initSegment([t]),metadata:{width:t.width,height:t.height}},u))if(g=t.inputTimeScale,!c||g!==c.timescale){const v=this.getVideoStartPts(a),A=Math.round(g*i);f=Math.min(f,He(a[0].dts,v)-A),d=Math.min(d,v-A)}else u=!1;if(Object.keys(l).length)return this.ISGenerated=!0,u?(this._initPTS={baseTime:d,timescale:g},this._initDTS={baseTime:f,timescale:g}):d=g=void 0,{tracks:l,initPTS:d,timescale:g}}remuxVideo(e,t,i,n){const r=e.inputTimeScale,a=e.samples,o=[],l=a.length,c=this._initPTS;let u=this.nextAvcDts,h=8,d=this.videoSampleDuration,f,g,v=Number.POSITIVE_INFINITY,A=Number.NEGATIVE_INFINITY,T=!1;if(!i||u===null){const U=t*r,$=a[0].pts-He(a[0].dts,a[0].pts);u=U-$}const x=c.baseTime*r/c.timescale;for(let U=0;U0?U-1:U].dts&&(T=!0)}T&&a.sort(function(U,$){const j=U.dts-$.dts,X=U.pts-$.pts;return j||X}),f=a[0].dts,g=a[a.length-1].dts;const _=g-f,P=_?Math.round(_/(l-1)):d||e.inputTimeScale/30;if(i){const U=f-u,$=U>P,j=U<-1;if(($||j)&&($?C.warn(`AVC: ${Zt(U,!0)} ms (${U}dts) hole between fragments detected, filling it`):C.warn(`AVC: ${Zt(-U,!0)} ms (${U}dts) overlapping between fragments detected`),!j||u>=a[0].pts)){f=u;const X=a[0].pts-U;a[0].dts=f,a[0].pts=X,C.log(`Video: First PTS/DTS adjusted: ${Zt(X,!0)}/${Zt(f,!0)}, delta: ${Zt(U,!0)} ms`)}}f=Math.max(0,f);let L=0,G=0;for(let U=0;U0?$.dts-a[U-1].dts:P;if(ne=U>0?$.pts-a[U-1].pts:P,Le.stretchShortVideoTrack&&this.nextAudioPts!==null){const ke=Math.floor(Le.maxBufferHole*r),pe=(n?v+n*r:this.nextAudioPts)-$.pts;pe>ke?(d=pe-Ee,d<0?d=Ee:E=!0,C.log(`[mp4-remuxer]: It is approximately ${pe/90} ms to the next segment; using duration ${d/90} ms for the last video frame.`)):d=Ee}else d=Ee}const q=Math.round($.pts-$.dts);N=Math.min(N,d),I=Math.max(I,d),S=Math.min(S,ne),M=Math.max(M,ne),o.push(new Fs($.key,d,X,q))}if(o.length){if(Ti){if(Ti<70){const U=o[0].flags;U.dependsOn=2,U.isNonSync=0}}else if(bn&&M-S0&&(n&&Math.abs(x-T)<9e3||Math.abs(He(v[0].pts-_,x)-T)<20*u),v.forEach(function(H){H.pts=He(H.pts-_,x)}),!i||T<0){if(v=v.filter(H=>H.pts>=0),!v.length)return;r===0?T=0:n&&!g?T=Math.max(0,x):T=v[0].pts}if(e.segmentCodec==="aac"){const H=this.config.maxAudioFramesDrift;for(let W=0,U=T;W=H*u&&ne0){O+=A;try{G=new Uint8Array(O)}catch(ne){this.observer.emit(y.ERROR,y.ERROR,{type:J.MUX_ERROR,details:w.REMUX_ALLOC_ERROR,fatal:!1,error:ne,bytes:O,reason:`fail allocating audio mdat ${O}`});return}d||(new DataView(G.buffer).setUint32(0,O),G.set(R.types.mdat,4))}else return;G.set($,A);const X=$.byteLength;A+=X,f.push(new Fs(!0,c,X,0)),L=j}const k=f.length;if(!k)return;const E=f[f.length-1];this.nextAudioPts=T=L+l*E.duration;const N=d?new Uint8Array(0):R.moof(e.sequenceNumber++,P/l,Te({},e,{samples:f}));e.samples=[];const S=P/a,I=T/a,K={data1:N,data2:G,startPTS:S,endPTS:I,startDTS:S,endDTS:I,type:"audio",hasAudio:!0,hasVideo:!1,nb:k};return this.isAudioContiguous=!0,K}remuxEmptyAudio(e,t,i,n){const r=e.inputTimeScale,a=e.samplerate?e.samplerate:r,o=r/a,l=this.nextAudioPts,c=this._initDTS,u=c.baseTime*9e4/c.timescale,h=(l!==null?l:n.startDTS*r)+u,d=n.endDTS*r+u,f=o*Ps,g=Math.ceil((d-h)/f),v=Ds.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(C.warn("[mp4-remuxer]: remux empty Audio"),!v){C.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");return}const A=[];for(let T=0;T4294967296;)s+=t;return s}function iu(s){for(let e=0;ea.pts-o.pts);const r=s.samples;return s.samples=[],{samples:r}}class Fs{constructor(e,t,i,n){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=t,this.size=i,this.cts=n,this.flags=new nu(e)}}class nu{constructor(e){this.isLeading=0,this.isDependedOn=0,this.hasRedundancy=0,this.degradPrio=0,this.dependsOn=1,this.isNonSync=1,this.dependsOn=e?2:1,this.isNonSync=e?0:1}}class ru{constructor(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,t,i,n){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(_l(e,n)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:i}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const n=this.initData=Br(e);t||(t=Ms(n.audio,fe.AUDIO)),i||(i=Ms(n.video,fe.VIDEO));const r={};n.audio&&n.video?r.audiovideo={container:"video/mp4",codec:t+","+i,initSegment:e,id:"main"}:n.audio?r.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:n.video?r.video={container:"video/mp4",codec:i,initSegment:e,id:"main"}:C.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=r}remux(e,t,i,n,r,a){var o,l;let{initPTS:c,lastEndTime:u}=this;const h={audio:void 0,video:void 0,text:n,id3:i,initSegment:void 0};Z(u)||(u=this.lastEndTime=r||0);const d=t.samples;if(!(d!=null&&d.length))return h;const f={initPTS:void 0,timescale:1};let g=this.initData;if((o=g)!=null&&o.length||(this.generateInitSegment(d),g=this.initData),!((l=g)!=null&&l.length))return C.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),h;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const v=xl(d,g),A=kl(g,d),T=A===null?r:A;(su(c,T,r,v)||f.timescale!==c.timescale&&a)&&(f.initPTS=T-r,c&&c.timescale===1&&C.warn(`Adjusting initPTS by ${f.initPTS-c.baseTime}`),this.initPTS=c={baseTime:f.initPTS,timescale:1});const x=e?T-c.baseTime/c.timescale:u,_=x+v;Ll(g,d,c.baseTime/c.timescale),v>0?this.lastEndTime=_:(C.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const P=!!g.audio,L=!!g.video;let G="";P&&(G+="audio"),L&&(G+="video");const O={data1:d,startPTS:x,startDTS:x,endPTS:_,endDTS:_,type:G,hasAudio:P,hasVideo:L,nb:1,dropped:0};return h.audio=O.type==="audio"?O:void 0,h.video=O.type!=="audio"?O:void 0,h.initSegment=f,h.id3=Os(i,r,c,c),n.samples.length&&(h.text=Ns(n,r,c)),h}}function su(s,e,t,i){if(s===null)return!0;const n=Math.max(i,1),r=e-s.baseTime/s.timescale;return Math.abs(r-t)>n}function Ms(s,e){const t=s==null?void 0:s.codec;return t&&t.length>4?t:t==="hvc1"||t==="hev1"?"hvc1.1.6.L120.90":t==="av01"?"av01.0.04M.08":t==="avc1"||e===fe.VIDEO?"avc1.42e01e":"mp4a.40.5"}let ct;try{ct=self.performance.now.bind(self.performance)}catch{C.debug("Unable to use Performance API on this environment"),ct=typeof self<"u"&&self.Date.now}const _n=[{demux:Vc,remux:ru},{demux:pt,remux:Sn},{demux:Uc,remux:Sn},{demux:Qc,remux:Sn}];class Bs{constructor(e,t,i,n,r){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.vendor=n,this.id=r}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,n){const r=i.transmuxing;r.executeStart=ct();let a=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:l}=this;n&&(this.currentTransmuxState=n);const{contiguous:c,discontinuity:u,trackSwitch:h,accurateTimeOffset:d,timeOffset:f,initSegmentChange:g}=n||o,{audioCodec:v,videoCodec:A,defaultInitPts:T,duration:x,initSegmentData:_}=l,P=au(a,t);if(P&&P.method==="AES-128"){const B=this.getDecrypter();if(B.isSync()){let k=B.softwareDecrypt(a,P.key.buffer,P.iv.buffer);if(i.part>-1&&(k=B.flush()),!k)return r.executeEnd=ct(),kn(i);a=new Uint8Array(k)}else return this.decryptionPromise=B.webCryptoDecrypt(a,P.key.buffer,P.iv.buffer).then(k=>{const E=this.push(k,null,i);return this.decryptionPromise=null,E}),this.decryptionPromise}const L=this.needsProbing(u,h);if(L){const B=this.configureTransmuxer(a);if(B)return C.warn(`[transmuxer] ${B.message}`),this.observer.emit(y.ERROR,y.ERROR,{type:J.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,fatal:!1,error:B,reason:B.message}),r.executeEnd=ct(),kn(i)}(u||h||g||L)&&this.resetInitSegment(_,v,A,x,t),(u||g||L)&&this.resetInitialTimestamp(T),c||this.resetContiguity();const G=this.transmux(a,P,f,d,i),O=this.currentTransmuxState;return O.contiguous=!0,O.discontinuity=!1,O.trackSwitch=!1,r.executeEnd=ct(),G}flush(e){const t=e.transmuxing;t.executeStart=ct();const{decrypter:i,currentTransmuxState:n,decryptionPromise:r}=this;if(r)return r.then(()=>this.flush(e));const a=[],{timeOffset:o}=n;if(i){const h=i.flush();h&&a.push(this.push(h,null,e))}const{demuxer:l,remuxer:c}=this;if(!l||!c)return t.executeEnd=ct(),[kn(e)];const u=l.flush(o);return bi(u)?u.then(h=>(this.flushRemux(a,h,e),a)):(this.flushRemux(a,u,e),a)}flushRemux(e,t,i){const{audioTrack:n,videoTrack:r,id3Track:a,textTrack:o}=t,{accurateTimeOffset:l,timeOffset:c}=this.currentTransmuxState;C.log(`[transmuxer.ts]: Flushed fragment ${i.sn}${i.part>-1?" p: "+i.part:""} of level ${i.level}`);const u=this.remuxer.remux(n,r,a,o,c,l,!0,this.id);e.push({remuxResult:u,chunkMeta:i}),i.transmuxing.executeEnd=ct()}resetInitialTimestamp(e){const{demuxer:t,remuxer:i}=this;!t||!i||(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,n,r){const{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(e,t,i,n),o.resetInitSegment(e,t,i,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,n,r){let a;return t&&t.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,i,n,r):a=this.transmuxUnencrypted(e,i,n,r),a}transmuxUnencrypted(e,t,i,n){const{audioTrack:r,videoTrack:a,id3Track:o,textTrack:l}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,a,o,l,t,i,!1,this.id),chunkMeta:n}}transmuxSampleAes(e,t,i,n,r){return this.demuxer.demuxSampleAes(e,t,i).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,i,n,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:n,vendor:r}=this;let a;for(let h=0,d=_n.length;h0&&e!=null&&e.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const kn=s=>({remuxResult:{},chunkMeta:s});function bi(s){return"then"in s&&s.then instanceof Function}class ou{constructor(e,t,i,n,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=n,this.defaultInitPts=r||null}}class lu{constructor(e,t,i,n,r,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=n,this.timeOffset=r,this.initSegmentChange=a}}var Us={exports:{}};(function(s){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function n(l,c,u){this.fn=l,this.context=c,this.once=u||!1}function r(l,c,u,h,d){if(typeof u!="function")throw new TypeError("The listener must be a function");var f=new n(u,h||l,d),g=t?t+c:c;return l._events[g]?l._events[g].fn?l._events[g]=[l._events[g],f]:l._events[g].push(f):(l._events[g]=f,l._eventsCount++),l}function a(l,c){--l._eventsCount===0?l._events=new i:delete l._events[c]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],u,h;if(this._eventsCount===0)return c;for(h in u=this._events)e.call(u,h)&&c.push(t?h.slice(1):h);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(u)):c},o.prototype.listeners=function(c){var u=t?t+c:c,h=this._events[u];if(!h)return[];if(h.fn)return[h.fn];for(var d=0,f=h.length,g=new Array(f);d!1};class $s{constructor(e,t,i,n){this.error=null,this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0;const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=i,this.onFlush=n;const a=(c,u)=>{u=u||{},u.frag=this.frag,u.id=this.id,c===y.ERROR&&(this.error=u.error),this.hls.trigger(c,u)};this.observer=new xn,this.observer.on(y.FRAG_DECRYPTED,a),this.observer.on(y.ERROR,a);const o={mp4:Cn.isTypeSupported("video/mp4"),mpeg:Cn.isTypeSupported("audio/mpeg"),mp3:Cn.isTypeSupported('audio/mp4; codecs="mp3"')},l=navigator.vendor;if(this.useWorker&&typeof Worker<"u"&&(r.workerPath||Rc())){try{r.workerPath?(C.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=wc(r.workerPath)):(C.log(`injecting Web Worker for "${t}"`),this.workerContext=Dc()),this.onwmsg=h=>this.onWorkerMessage(h);const{worker:u}=this.workerContext;u.addEventListener("message",this.onwmsg),u.onerror=h=>{const d=new Error(`${h.message} (${h.filename}:${h.lineno})`);r.enableWorker=!1,C.warn(`Error in "${t}" Web Worker, fallback to inline`),this.hls.trigger(y.ERROR,{type:J.OTHER_ERROR,details:w.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:d})},u.postMessage({cmd:"init",typeSupported:o,vendor:l,id:t,config:JSON.stringify(r)})}catch(u){C.warn(`Error setting up "${t}" Web Worker, fallback to inline`,u),this.resetWorker(),this.error=null,this.transmuxer=new Bs(this.observer,o,r,l,t)}return}this.transmuxer=new Bs(this.observer,o,r,l,t)}resetWorker(){if(this.workerContext){const{worker:e,objectURL:t}=this.workerContext;t&&self.URL.revokeObjectURL(t),e.removeEventListener("message",this.onwmsg),e.onerror=null,e.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(e,t,i,n,r,a,o,l,c,u){var h,d;c.transmuxing.start=self.performance.now();const{transmuxer:f}=this,g=a?a.start:r.start,v=r.decryptdata,A=this.frag,T=!(A&&r.cc===A.cc),x=!(A&&c.level===A.level),_=A?c.sn-A.sn:-1,P=this.part?c.part-this.part.index:-1,L=_===0&&c.id>1&&c.id===(A==null?void 0:A.stats.chunkCount),G=!x&&(_===1||_===0&&(P===1||L&&P<=0)),O=self.performance.now();(x||_||r.stats.parsing.start===0)&&(r.stats.parsing.start=O),a&&(P||!G)&&(a.stats.parsing.start=O);const B=!(A&&((h=r.initSegment)==null?void 0:h.url)===((d=A.initSegment)==null?void 0:d.url)),k=new lu(T,G,l,x,g,B);if(!G||T||B){C.log(`[transmuxer-interface, ${r.type}]: Starting new transmux session for sn: ${c.sn} p: ${c.part} level: ${c.level} id: ${c.id} discontinuity: ${T} trackSwitch: ${x} contiguous: ${G} accurateTimeOffset: ${l} timeOffset: ${g} initSegmentChange: ${B}`);const E=new ou(i,n,t,o,u);this.configureTransmuxer(E)}if(this.frag=r,this.part=a,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:e,decryptdata:v,chunkMeta:c,state:k},e instanceof ArrayBuffer?[e]:[]);else if(f){const E=f.push(e,v,c,k);bi(E)?(f.async=!0,E.then(N=>{this.handleTransmuxComplete(N)}).catch(N=>{this.transmuxerError(N,c,"transmuxer-interface push error")})):(f.async=!1,this.handleTransmuxComplete(E))}}flush(e){e.transmuxing.start=self.performance.now();const{transmuxer:t}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:e});else if(t){let i=t.flush(e);bi(i)||t.async?(bi(i)||(i=Promise.resolve(i)),i.then(r=>{this.handleFlushResult(r,e)}).catch(r=>{this.transmuxerError(r,e,"transmuxer-interface flush error")})):this.handleFlushResult(i,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(y.ERROR,{type:J.MEDIA_ERROR,details:w.FRAG_PARSING_ERROR,chunkMeta:t,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(i=>{this.handleTransmuxComplete(i)}),this.onFlush(t)}onWorkerMessage(e){const t=e.data,i=this.hls;switch(t.event){case"init":{var n;const r=(n=this.workerContext)==null?void 0:n.objectURL;r&&self.URL.revokeObjectURL(r);break}case"transmuxComplete":{this.handleTransmuxComplete(t.data);break}case"flush":{this.onFlush(t.data);break}case"workerLog":C[t.data.logType]&&C[t.data.logType](t.data.message);break;default:{t.data=t.data||{},t.data.frag=this.frag,t.data.id=this.id,i.trigger(t.event,t.data);break}}}configureTransmuxer(e){const{transmuxer:t}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:e}):t&&t.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const uu=250,Ln=2,hu=.1,du=.05;class fu{constructor(e,t,i,n){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=e,this.media=t,this.fragmentTracker=i,this.hls=n}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,t){const{config:i,media:n,stalled:r}=this;if(n===null)return;const{currentTime:a,seeking:o}=n,l=this.seeking&&!o,c=!this.seeking&&o;if(this.seeking=o,a!==e){if(this.moved=!0,r!==null){if(this.stallReported){const T=self.performance.now()-r;C.warn(`playback not stuck anymore @${a}, after ${Math.round(T)}ms`),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}return}if(c||l){this.stalled=null;return}if(n.paused&&!o||n.ended||n.playbackRate===0||!ge.getBuffered(n).length)return;const u=ge.bufferInfo(n,a,0),h=u.len>0,d=u.nextStart||0;if(!h&&!d)return;if(o){const T=u.len>Ln,x=!d||t&&t.start<=a||d-a>Ln&&!this.fragmentTracker.getPartialFragment(a);if(T||x)return;this.moved=!1}if(!this.moved&&this.stalled!==null){var f;const T=Math.max(d,u.start||0)-a,x=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,P=(x==null||(f=x.details)==null?void 0:f.live)?x.details.targetduration*2:Ln,L=this.fragmentTracker.getPartialFragment(a);if(T>0&&(T<=P||L)){this._trySkipBufferHole(L);return}}const g=self.performance.now();if(r===null){this.stalled=g;return}const v=g-r;if(!o&&v>=uu&&(this._reportStall(u),!this.media))return;const A=ge.bufferInfo(n,a,i.maxBufferHole);this._tryFixBufferStall(A,v)}_tryFixBufferStall(e,t){const{config:i,fragmentTracker:n,media:r}=this;if(r===null)return;const a=r.currentTime,o=n.getPartialFragment(a);o&&(this._trySkipBufferHole(o)||!this.media)||(e.len>i.maxBufferHole||e.nextStart&&e.nextStart-ai.highBufferWatchdogPeriod*1e3&&(C.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){const{hls:t,media:i,stallReported:n}=this;if(!n&&i){this.stallReported=!0;const r=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${JSON.stringify(e)})`);C.warn(r.message),t.trigger(y.ERROR,{type:J.MEDIA_ERROR,details:w.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:e.len})}}_trySkipBufferHole(e){const{config:t,hls:i,media:n}=this;if(n===null)return 0;const r=n.currentTime,a=ge.bufferInfo(n,r,0),o=r0&&a.len<1&&n.readyState<3,u=o-r;if(u>0&&(l||c)){if(u>t.maxBufferHole){const{fragmentTracker:d}=this;let f=!1;if(r===0){const g=d.getAppendedFrag(0,ee.MAIN);g&&o1?(n=0,this.bitrateTest=!0):n=i.nextAutoLevel),this.level=i.nextLoadLevel=n,this.loadedmetadata=!1}t>0&&e===-1&&(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t),this.state=F.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=F.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case F.WAITING_LEVEL:{var e;const{levels:i,level:n}=this,r=i==null||(e=i[n])==null?void 0:e.details;if(r&&(!r.live||this.levelLastLoaded===this.level)){if(this.waitForCdnTuneIn(r))break;this.state=F.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=F.IDLE;break}break}case F.FRAG_LOADING_WAITING_RETRY:{var t;const i=self.performance.now(),n=this.retryDate;(!n||i>=n||(t=this.media)!=null&&t.seeking)&&(this.resetStartWhenNotLoaded(this.level),this.state=F.IDLE)}break}this.state===F.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:i,media:n}=this,{config:r,nextLoadLevel:a}=e;if(t===null||!n&&(this.startFragRequested||!r.startFragPrefetch)||this.altAudio&&this.audioOnly||!(i!=null&&i[a]))return;const o=i[a],l=this.getMainFwdBufferInfo();if(l===null)return;const c=this.getLevelDetails();if(c&&this._streamEnded(l,c)){const A={};this.altAudio&&(A.type="video"),this.hls.trigger(y.BUFFER_EOS,A),this.state=F.ENDED;return}e.loadLevel!==a&&e.manualLevel===-1&&this.log(`Adapting to level ${a} from level ${this.level}`),this.level=e.nextLoadLevel=a;const u=o.details;if(!u||this.state===F.WAITING_LEVEL||u.live&&this.levelLastLoaded!==a){this.level=a,this.state=F.WAITING_LEVEL;return}const h=l.len,d=this.getMaxBufferLength(o.maxBitrate);if(h>=d)return;this.backtrackFragment&&this.backtrackFragment.start>l.end&&(this.backtrackFragment=null);const f=this.backtrackFragment?this.backtrackFragment.start:l.end;let g=this.getNextFragment(f,u);if(this.couldBacktrack&&!this.fragPrevious&&g&&g.sn!=="initSegment"&&this.fragmentTracker.getState(g)!==be.OK){var v;const T=((v=this.backtrackFragment)!=null?v:g).sn-u.startSN,x=u.fragments[T-1];x&&g.cc===x.cc&&(g=x,this.fragmentTracker.removeFragment(x))}else this.backtrackFragment&&l.len&&(this.backtrackFragment=null);if(g&&this.isLoopLoading(g,f)){if(!g.gap){const T=this.audioOnly&&!this.altAudio?fe.AUDIO:fe.VIDEO,x=(T===fe.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;x&&this.afterBufferFlushed(x,T,ee.MAIN)}g=this.getNextFragmentLoopLoading(g,u,l,ee.MAIN,d)}g&&(g.initSegment&&!g.initSegment.data&&!this.bitrateTest&&(g=g.initSegment),this.loadFragment(g,o,f))}loadFragment(e,t,i){const n=this.fragmentTracker.getState(e);this.fragCurrent=e,n===be.NOT_LOADED||n===be.PARTIAL?e.sn==="initSegment"?this._loadInitSegment(e,t):this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):(this.startFragRequested=!0,super.loadFragment(e,t,i)):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,ee.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let i;const n=this.getAppendedFrag(t.currentTime);n&&n.start>1&&this.flushMainBuffer(0,n.start-1);const r=this.getLevelDetails();if(r!=null&&r.live){const o=this.getMainFwdBufferInfo();if(!o||o.len{r=a.audioCodec,r&&(r.indexOf("mp4a.40.2")!==-1&&(i=!0),r.indexOf("mp4a.40.5")!==-1&&(n=!0))}),this.audioCodecSwitch=i&&n&&!Ic(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:i}=this;if(!i||this.state!==F.IDLE)return;const n=i[t.level];(!n.details||n.details.live&&this.levelLastLoaded!==t.level||this.waitForCdnTuneIn(n.details))&&(this.state=F.WAITING_LEVEL)}onLevelLoaded(e,t){var i;const{levels:n}=this,r=t.level,a=t.details,o=a.totalduration;if(!n){this.warn(`Levels were reset while loading level ${r}`);return}this.log(`Level ${r} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=n[r],c=this.fragCurrent;c&&(this.state===F.FRAG_LOADING||this.state===F.FRAG_LOADING_WAITING_RETRY)&&(c.level!==t.level||c.urlId!==l.urlId)&&c.loader&&this.abortCurrentFrag();let u=0;if(a.live||(i=l.details)!=null&&i.live){if(a.fragments[0]||(a.deltaUpdateFailed=!0),a.deltaUpdateFailed)return;u=this.alignPlaylists(a,l.details)}if(l.details=a,this.levelLastLoaded=r,this.hls.trigger(y.LEVEL_UPDATED,{details:a,level:r}),this.state===F.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=F.IDLE}this.startFragRequested?a.live&&this.synchronizeToLiveEdge(a):this.setStartPosition(a,u),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:i,part:n,payload:r}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const o=a[i.level],l=o.details;if(!l){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}const c=o.videoCodec,u=l.PTSKnown||!l.live,h=(t=i.initSegment)==null?void 0:t.data,d=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new $s(this.hls,ee.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=n?n.index:-1,v=g!==-1,A=new gn(i.level,i.sn,i.stats.chunkCount,r.byteLength,g,v),T=this.initPTS[i.cc];f.push(r,h,d,c,i,n,l.totalduration,u,A,T)}onAudioTrackSwitching(e,t){const i=this.altAudio;if(!!!t.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const r=this.hls;i&&(r.trigger(y.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),r.trigger(y.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=t.id,n=!!this.hls.audioTracks[i].url;if(n){const r=this.videoBuffer;r&&this.mediaBuffer!==r&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=r)}this.altAudio=n,this.tick()}onBufferCreated(e,t){const i=t.tracks;let n,r,a=!1;for(const o in i){const l=i[o];if(l.id==="main"){if(r=o,n=l,o==="video"){const c=i[o];c&&(this.videoBuffer=c.buffer)}}else a=!0}a&&n?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=n.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:i,part:n}=t;if(i&&i.type!==ee.MAIN)return;if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${n?" p: "+n.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===F.PARSED&&(this.state=F.IDLE);return}const r=n?n.stats:i.stats;this.fragLastKbps=Math.round(8*r.total/(r.buffering.end-r.loading.first)),i.sn!=="initSegment"&&(this.fragPrevious=i),this.fragBufferedComplete(i,n)}onError(e,t){var i;if(t.fatal){this.state=F.ERROR;return}switch(t.details){case w.FRAG_GAP:case w.FRAG_PARSING_ERROR:case w.FRAG_DECRYPT_ERROR:case w.FRAG_LOAD_ERROR:case w.FRAG_LOAD_TIMEOUT:case w.KEY_LOAD_ERROR:case w.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(ee.MAIN,t);break;case w.LEVEL_LOAD_ERROR:case w.LEVEL_LOAD_TIMEOUT:case w.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===F.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===le.LEVEL&&(this.state=F.IDLE);break;case w.BUFFER_FULL_ERROR:if(!t.parent||t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case w.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}checkBuffer(){const{media:e,gapController:t}=this;if(!(!e||!t||!e.readyState)){if(this.loadedmetadata||!ge.getBuffered(e).length){const i=this.state!==F.IDLE?this.fragCurrent:null;t.poll(this.lastCurrentTime,i)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=F.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==fe.AUDIO||this.audioOnly&&!this.altAudio){const i=(t===fe.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,t,ee.MAIN)}}onLevelsUpdated(e,t){this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let i=this.startPosition;if(i>=0&&t0&&(a{const{hls:n}=this;if(!i||this.fragContextChanged(e))return;t.fragmentError=0,this.state=F.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const r=e.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),n.trigger(y.FRAG_LOADED,i),e.bitrateTest=!1})}_handleTransmuxComplete(e){var t;const i="main",{hls:n}=this,{remuxResult:r,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:c,level:u}=o,{video:h,text:d,id3:f,initSegment:g}=r,{details:v}=u,A=this.altAudio?void 0:r.audio;if(this.fragContextChanged(l)){this.fragmentTracker.removeFragment(l);return}if(this.state=F.PARSING,g){if(g!=null&&g.tracks){const _=l.initSegment||l;this._bufferInitSegment(u,g.tracks,_,a),n.trigger(y.FRAG_PARSING_INIT_SEGMENT,{frag:_,id:i,tracks:g.tracks})}const T=g.initPTS,x=g.timescale;Z(T)&&(this.initPTS[l.cc]={baseTime:T,timescale:x},n.trigger(y.INIT_PTS_FOUND,{frag:l,id:i,initPTS:T,timescale:x}))}if(h&&v&&l.sn!=="initSegment"){const T=v.fragments[l.sn-1-v.startSN],x=l.sn===v.startSN,_=!T||l.cc>T.cc;if(r.independent!==!1){const{startPTS:P,endPTS:L,startDTS:G,endDTS:O}=h;if(c)c.elementaryStreams[h.type]={startPTS:P,endPTS:L,startDTS:G,endDTS:O};else if(h.firstKeyFrame&&h.independent&&a.id===1&&!_&&(this.couldBacktrack=!0),h.dropped&&h.independent){const B=this.getMainFwdBufferInfo(),k=(B?B.end:this.getLoadPosition())+this.config.maxBufferHole,E=h.firstKeyFramePTS?h.firstKeyFramePTS:P;if(!x&&k{const u=t[l].initSegment;u!=null&&u.byteLength&&this.hls.trigger(y.BUFFER_APPENDING,{type:l,data:u,frag:i,part:null,chunkMeta:n,parent:i.type})}),this.tick()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,ee.MAIN)}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=F.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const i=e.currentTime;if(ge.isBuffered(e,i)?t=this.getAppendedFrag(i):ge.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;const n=this.fragPlaying,r=t.level;(!n||t.sn!==n.sn||n.level!==r||t.urlId!==n.urlId)&&(this.fragPlaying=t,this.hls.trigger(y.FRAG_CHANGED,{frag:t}),(!n||n.level!==r)&&this.hls.trigger(y.LEVEL_SWITCHED,{level:r}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){const e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}get currentProgramDateTime(){const e=this.media;if(e){const t=e.currentTime,i=this.currentFrag;if(i&&Z(t)&&Z(i.programDateTime)){const n=i.programDateTime+(t-i.start)*1e3;return new Date(n)}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class Ut{constructor(e,t=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=i}sample(e,t){const i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class mu{constructor(e,t,i,n=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Ut(e),this.fast_=new Ut(t),this.defaultTTFB_=n,this.ttfb_=new Ut(e)}update(e,t){const{slow_:i,fast_:n,ttfb_:r}=this;i.halfLife!==e&&(this.slow_=new Ut(e,i.getEstimate(),i.getTotalWeight())),n.halfLife!==t&&(this.fast_=new Ut(t,n.getEstimate(),n.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new Ut(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const i=8*t,n=e/1e3,r=i/n;this.fast_.sample(n,r),this.slow_.sample(n,r)}sampleTTFB(e){const t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}destroy(){}}class yu{constructor(e){this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=0,this._nextAutoLevel=-1,this.timer=-1,this.onCheck=this._abandonRulesCheck.bind(this),this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this.hls=e;const t=e.config;this.bwEstimator=new mu(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate),this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(y.FRAG_LOADING,this.onFragLoading,this),e.on(y.FRAG_LOADED,this.onFragLoaded,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this),e.on(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(y.LEVEL_LOADED,this.onLevelLoaded,this)}unregisterListeners(){const{hls:e}=this;e.off(y.FRAG_LOADING,this.onFragLoading,this),e.off(y.FRAG_LOADED,this.onFragLoaded,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this),e.off(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this)}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this.onCheck=null,this.fragCurrent=this.partCurrent=null}onFragLoading(e,t){var i;const n=t.frag;this.ignoreFragment(n)||(this.fragCurrent=n,this.partCurrent=(i=t.part)!=null?i:null,this.clearTimer(),this.timer=self.setInterval(this.onCheck,100))}onLevelSwitching(e,t){this.clearTimer()}getTimeToLoadFrag(e,t,i,n){const r=e+i/t,a=n?this.lastLevelLoadSec:0;return r+a}onLevelLoaded(e,t){const i=this.hls.config,{total:n,bwEstimate:r}=t.stats;Z(n)&&Z(r)&&(this.lastLevelLoadSec=8*n/r),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD)}_abandonRulesCheck(){const{fragCurrent:e,partCurrent:t,hls:i}=this,{autoLevelEnabled:n,media:r}=i;if(!e||!r)return;const a=performance.now(),o=t?t.stats:e.stats,l=t?t.duration:e.duration,c=a-o.loading.start;if(o.aborted||o.loaded&&o.loaded===o.total||e.level===0){this.clearTimer(),this._nextAutoLevel=-1;return}if(!n||r.paused||!r.playbackRate||!r.readyState)return;const u=i.mainForwardBufferInfo;if(u===null)return;const h=this.bwEstimator.getEstimateTTFB(),d=Math.abs(r.playbackRate);if(c<=Math.max(h,1e3*(l/(d*2))))return;const f=u.len/d;if(f>=2*l/d)return;const g=o.loading.first?o.loading.first-o.loading.start:-1,v=o.loaded&&g>-1,A=this.bwEstimator.getEstimate(),{levels:T,minAutoLevel:x}=i,_=T[e.level],P=o.total||Math.max(o.loaded,Math.round(l*_.maxBitrate/8));let L=c-g;L<1&&v&&(L=Math.min(c,o.loaded*8/A));const G=v?o.loaded*1e3/L:0,O=G?(P-o.loaded)/G:P*8/A+h/1e3;if(O<=f)return;const B=G?G*8:A;let k=Number.POSITIVE_INFINITY,E;for(E=e.level-1;E>x;E--){const N=T[E].maxBitrate;if(k=this.getTimeToLoadFrag(h/1e3,B,l*N,!T[E].details),k=O||k>l*10||(i.nextLoadLevel=E,v?this.bwEstimator.sample(c-Math.min(h,g),o.loaded):this.bwEstimator.sampleTTFB(c),this.clearTimer(),C.warn(`[abr] Fragment ${e.sn}${t?" part "+t.index:""} of level ${e.level} is loading too slowly; Time to underbuffer: ${f.toFixed(3)} s Estimated load time for current fragment: ${O.toFixed(3)} s Estimated load time for down switch fragment: ${k.toFixed(3)} s TTFB estimate: ${g} Current BW estimate: ${Z(A)?(A/1024).toFixed(3):"Unknown"} Kb/s New BW estimate: ${(this.bwEstimator.getEstimate()/1024).toFixed(3)} Kb/s Aborting and switching to level ${E}`),e.loader&&(this.fragCurrent=this.partCurrent=null,e.abortRequests()),i.trigger(y.FRAG_LOAD_EMERGENCY_ABORTED,{frag:e,part:t,stats:o}))}onFragLoaded(e,{frag:t,part:i}){const n=i?i.stats:t.stats;if(t.type===ee.MAIN&&this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),this.lastLoadedFragLevel=t.level,this._nextAutoLevel=-1,this.hls.config.abrMaxWithRealBitrate){const r=i?i.duration:t.duration,a=this.hls.levels[t.level],o=(a.loaded?a.loaded.bytes:0)+n.loaded,l=(a.loaded?a.loaded.duration:0)+r;a.loaded={bytes:o,duration:l},a.realBitrate=Math.round(8*o/l)}if(t.bitrateTest){const r={stats:n,frag:t,part:i,id:t.type};this.onFragBuffered(y.FRAG_BUFFERED,r),t.bitrateTest=!1}}}onFragBuffered(e,t){const{frag:i,part:n}=t,r=n!=null&&n.stats.loaded?n.stats:i.stats;if(r.aborted||this.ignoreFragment(i))return;const a=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,r.loaded),r.bwEstimate=this.bwEstimator.getEstimate(),i.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==ee.MAIN||e.sn==="initSegment"}clearTimer(){self.clearInterval(this.timer)}get nextAutoLevel(){const e=this._nextAutoLevel,t=this.bwEstimator;if(e!==-1&&!t.canEstimate())return e;let i=this.getNextABRAutoLevel();if(e!==-1){const n=this.hls.levels;if(n.length>Math.max(e,i)&&n[e].loadError<=n[i].loadError)return e}return e!==-1&&(i=Math.min(e,i)),i}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:i}=this,{maxAutoLevel:n,config:r,minAutoLevel:a,media:o}=i,l=t?t.duration:e?e.duration:0,c=o&&o.playbackRate!==0?Math.abs(o.playbackRate):1,u=this.bwEstimator?this.bwEstimator.getEstimate():r.abrEwmaDefaultEstimate,h=i.mainForwardBufferInfo,d=(h?h.len:0)/c;let f=this.findBestLevel(u,a,n,d,r.abrBandWidthFactor,r.abrBandWidthUpFactor);if(f>=0)return f;C.trace(`[abr] ${d?"rebuffering expected":"buffer is empty"}, finding optimal quality level`);let g=l?Math.min(l,r.maxStarvationDelay):r.maxStarvationDelay,v=r.abrBandWidthFactor,A=r.abrBandWidthUpFactor;if(!d){const T=this.bitrateTestDelay;T&&(g=(l?Math.min(l,r.maxLoadingDelay):r.maxLoadingDelay)-T,C.trace(`[abr] bitrate test took ${Math.round(1e3*T)}ms, set first fragment max fetchDuration to ${Math.round(1e3*g)} ms`),v=A=1)}return f=this.findBestLevel(u,a,n,d+g,v,A),Math.max(f,0)}findBestLevel(e,t,i,n,r,a){var o;const{fragCurrent:l,partCurrent:c,lastLoadedFragLevel:u}=this,{levels:h}=this.hls,d=h[u],f=!!(d!=null&&(o=d.details)!=null&&o.live),g=d==null?void 0:d.codecSet,v=c?c.duration:l?l.duration:0,A=this.bwEstimator.getEstimateTTFB()/1e3;let T=t,x=-1;for(let _=i;_>=t;_--){const P=h[_];if(!P||g&&P.codecSet!==g){P&&(T=Math.min(_,T),x=Math.max(_,x));continue}x!==-1&&C.trace(`[abr] Skipped level(s) ${T}-${x} with CODECS:"${h[x].attrs.CODECS}"; not compatible with "${d.attrs.CODECS}"`);const L=P.details,G=(c?L==null?void 0:L.partTarget:L==null?void 0:L.averagetargetduration)||v;let O;_<=u?O=r*e:O=a*e;const B=h[_].maxBitrate,k=this.getTimeToLoadFrag(A,O,B*G,L===void 0);if(C.trace(`[abr] level:${_} adjustedbw-bitrate:${Math.round(O-B)} avgDuration:${G.toFixed(1)} maxFetchDuration:${n.toFixed(1)} fetchDuration:${k.toFixed(1)}`),O>B&&(k===0||!Z(k)||f&&!this.bitrateTestDelay||k0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t,this.state=F.IDLE):(this.loadedmetadata=!1,this.state=F.WAITING_TRACK),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}doTick(){switch(this.state){case F.IDLE:this.doTickIdle();break;case F.WAITING_TRACK:{var e;const{levels:i,trackId:n}=this,r=i==null||(e=i[n])==null?void 0:e.details;if(r){if(this.waitForCdnTuneIn(r))break;this.state=F.WAITING_INIT_PTS}break}case F.FRAG_LOADING_WAITING_RETRY:{var t;const i=performance.now(),n=this.retryDate;(!n||i>=n||(t=this.media)!=null&&t.seeking)&&(this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded(this.trackId),this.state=F.IDLE);break}case F.WAITING_INIT_PTS:{const i=this.waitingData;if(i){const{frag:n,part:r,cache:a,complete:o}=i;if(this.initPTS[n.cc]!==void 0){this.waitingData=null,this.waitingVideoCC=-1,this.state=F.FRAG_LOADING;const l=a.flush(),c={frag:n,part:r,payload:l,networkDetails:null};this._handleFragmentLoadProgress(c),o&&super._handleFragmentLoadComplete(c)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${n.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const l=this.getLoadPosition(),c=ge.bufferInfo(this.mediaBuffer,l,this.config.maxBufferHole);hn(c.end,this.config.maxFragLookUpTolerance,n)<0&&(this.log(`Waiting fragment cc (${n.cc}) @ ${n.start} cancelled because another fragment at ${c.end} is needed`),this.clearWaitingFragment())}}else this.state=F.IDLE}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=F.IDLE)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){const{hls:e,levels:t,media:i,trackId:n}=this,r=e.config;if(!(t!=null&&t[n])||!i&&(this.startFragRequested||!r.startFragPrefetch))return;const a=t[n],o=a.details;if(!o||o.live&&this.levelLastLoaded!==n||this.waitForCdnTuneIn(o)){this.state=F.WAITING_TRACK;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,fe.AUDIO,ee.AUDIO));const c=this.getFwdBufferInfo(l,ee.AUDIO);if(c===null)return;const{bufferedTrack:u,switchingTrack:h}=this;if(!h&&this._streamEnded(c,o)){e.trigger(y.BUFFER_EOS,{type:"audio"}),this.state=F.ENDED;return}const d=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,ee.MAIN),f=c.len,g=this.getMaxBufferLength(d==null?void 0:d.len);if(f>=g&&!h)return;const A=o.fragments[0].start;let T=c.end;if(h&&i){const L=this.getLoadPosition();u&&h.attrs!==u.attrs&&(T=L),o.PTSKnown&&LA||c.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=A+.05)}let x=this.getNextFragment(T,o),_=!1;if(x&&this.isLoopLoading(x,T)&&(_=!!x.gap,x=this.getNextFragmentLoopLoading(x,o,c,ee.MAIN,g)),!x){this.bufferFlushed=!0;return}const P=d&&x.start>d.end+o.targetduration;if(P||!(d!=null&&d.len)&&c.len){const L=this.getAppendedFrag(x.start,ee.MAIN);if(L===null||(_||(_=!!L.gap||!!P&&d.len===0),P&&!_||_&&c.nextStart&&c.nextStartnew qt(i))}onAudioTrackSwitching(e,t){const i=!!t.url;this.trackId=t.id;const{fragCurrent:n}=this;n&&(n.abortRequests(),this.removeUnbufferedFrags(n.start)),this.resetLoadingState(),i?this.setInterval(Gs):this.resetTransmuxer(),i?(this.switchingTrack=t,this.state=F.IDLE):(this.switchingTrack=null,this.bufferedTrack=t,this.state=F.STOPPED),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}onLevelLoaded(e,t){this.mainDetails=t.details,this.cachedTrackLoadedData!==null&&(this.hls.trigger(y.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(e,t){var i;if(this.mainDetails==null){this.cachedTrackLoadedData=t;return}const{levels:n}=this,{details:r,id:a}=t;if(!n){this.warn(`Audio tracks were reset while loading level ${a}`);return}this.log(`Track ${a} loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const o=n[a];let l=0;if(r.live||(i=o.details)!=null&&i.live){const c=this.mainDetails;if(r.fragments[0]||(r.deltaUpdateFailed=!0),r.deltaUpdateFailed||!c)return;!o.details&&r.hasProgramDateTime&&c.hasProgramDateTime?(As(r,c),l=r.fragments[0].start):l=this.alignPlaylists(r,o.details)}o.details=r,this.levelLastLoaded=a,!this.startFragRequested&&(this.mainDetails||!r.live)&&this.setStartPosition(o.details,l),this.state===F.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=F.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:i,part:n,payload:r}=e,{config:a,trackId:o,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const c=l[o];if(!c){this.warn("Audio track is undefined on fragment load progress");return}const u=c.details;if(!u){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}const h=a.defaultAudioCodec||c.audioCodec||"mp4a.40.2";let d=this.transmuxer;d||(d=this.transmuxer=new $s(this.hls,ee.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[i.cc],g=(t=i.initSegment)==null?void 0:t.data;if(f!==void 0){const A=n?n.index:-1,T=A!==-1,x=new gn(i.level,i.sn,i.stats.chunkCount,r.byteLength,A,T);d.push(r,g,h,"",i,n,u.totalduration,!1,x,f)}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 ${o}`);const{cache:v}=this.waitingData=this.waitingData||{frag:i,part:n,cache:new Vs,complete:!1};v.push(new Uint8Array(r)),this.waitingVideoCC=this.videoTrackCC,this.state=F.WAITING_INIT_PTS}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(e,t){const i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null),t.tracks.video&&(this.videoBuffer=t.tracks.video.buffer||null)}onFragBuffered(e,t){const{frag:i,part:n}=t;if(i.type!==ee.AUDIO){if(!this.loadedmetadata&&i.type===ee.MAIN){const r=this.videoBuffer||this.media;r&&ge.getBuffered(r).length&&(this.loadedmetadata=!0)}return}if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${n?" p: "+n.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(i.sn!=="initSegment"){this.fragPrevious=i;const r=this.switchingTrack;r&&(this.bufferedTrack=r,this.switchingTrack=null,this.hls.trigger(y.AUDIO_TRACK_SWITCHED,Re({},r)))}this.fragBufferedComplete(i,n)}onError(e,t){var i;if(t.fatal){this.state=F.ERROR;return}switch(t.details){case w.FRAG_GAP:case w.FRAG_PARSING_ERROR:case w.FRAG_DECRYPT_ERROR:case w.FRAG_LOAD_ERROR:case w.FRAG_LOAD_TIMEOUT:case w.KEY_LOAD_ERROR:case w.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(ee.AUDIO,t);break;case w.AUDIO_TRACK_LOAD_ERROR:case w.AUDIO_TRACK_LOAD_TIMEOUT:case w.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===F.WAITING_TRACK&&((i=t.context)==null?void 0:i.type)===le.AUDIO_TRACK&&(this.state=F.IDLE);break;case w.BUFFER_FULL_ERROR:if(!t.parent||t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case w.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushed(e,{type:t}){t===fe.AUDIO&&(this.bufferFlushed=!0,this.state===F.ENDED&&(this.state=F.IDLE))}_handleTransmuxComplete(e){var t;const i="audio",{hls:n}=this,{remuxResult:r,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:c,level:u}=o,{details:h}=u,{audio:d,text:f,id3:g,initSegment:v}=r;if(this.fragContextChanged(l)||!h){this.fragmentTracker.removeFragment(l);return}if(this.state=F.PARSING,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),v!=null&&v.tracks){const A=l.initSegment||l;this._bufferInitSegment(v.tracks,A,a),n.trigger(y.FRAG_PARSING_INIT_SEGMENT,{frag:A,id:i,tracks:v.tracks})}if(d){const{startPTS:A,endPTS:T,startDTS:x,endDTS:_}=d;c&&(c.elementaryStreams[fe.AUDIO]={startPTS:A,endPTS:T,startDTS:x,endDTS:_}),l.setElementaryStreamInfo(fe.AUDIO,A,T,x,_),this.bufferFragmentData(d,l,c,a)}if(g!=null&&(t=g.samples)!=null&&t.length){const A=Te({id:i,frag:l,details:h},g);n.trigger(y.FRAG_PARSING_METADATA,A)}if(f){const A=Te({id:i,frag:l,details:h},f);n.trigger(y.FRAG_PARSING_USERDATA,A)}}_bufferInitSegment(e,t,i){if(this.state!==F.PARSING)return;e.video&&delete e.video;const n=e.audio;if(!n)return;n.levelCodec=n.codec,n.id="audio",this.log(`Init audio buffer, container:${n.container}, codecs[parsed]=[${n.codec}]`),this.hls.trigger(y.BUFFER_CODECS,e);const r=n.initSegment;if(r!=null&&r.byteLength){const a={type:"audio",frag:t,part:null,chunkMeta:i,parent:t.type,data:r};this.hls.trigger(y.BUFFER_APPENDING,a)}this.tick()}loadFragment(e,t,i){const n=this.fragmentTracker.getState(e);if(this.fragCurrent=e,this.switchingTrack||n===be.NOT_LOADED||n===be.PARTIAL){var r;e.sn==="initSegment"?this._loadInitSegment(e,t):(r=t.details)!=null&&r.live&&!this.initPTS[e.cc]?(this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=F.WAITING_INIT_PTS):(this.startFragRequested=!0,super.loadFragment(e,t,i))}else this.clearTrackerIfNeeded(e)}completeAudioSwitch(e){const{hls:t,media:i,bufferedTrack:n}=this,r=n==null?void 0:n.attrs,a=e.attrs;i&&r&&(r.CHANNELS!==a.CHANNELS||r.NAME!==a.NAME||r.LANGUAGE!==a.LANGUAGE)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(y.AUDIO_TRACK_SWITCHED,Re({},e))}}class Eu extends dn{constructor(e){super(e,"[audio-track-controller]"),this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.LEVEL_LOADING,this.onLevelLoading,this),e.on(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.LEVEL_LOADING,this.onLevelLoading,this),e.off(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(y.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(y.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:i,groupId:n,details:r}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==n){this.warn(`Track with id:${i} and group:${n} not found in active group ${a.groupId}`);return}const o=a.details;a.details=t.details,this.log(`audio-track ${i} "${a.name}" lang:${a.lang} group:${n} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!(t!=null&&t.audioGroupIds))return;const i=t.audioGroupIds[t.urlId];if(this.groupId!==i){this.groupId=i||null;const n=this.tracks.filter(a=>!i||a.groupId===i);this.selectDefaultTrack&&!n.some(a=>a.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=n;const r={audioTracks:n};this.log(`Updating audio tracks, ${n.length} track(s) found in group:${i}`),this.hls.trigger(y.AUDIO_TRACKS_UPDATED,r),this.selectInitialTrack()}else this.shouldReloadPlaylist(this.currentTrack)&&this.setAudioTrack(this.trackId)}onError(e,t){t.fatal||!t.context||t.context.type===le.AUDIO_TRACK&&t.context.id===this.trackId&&t.context.groupId===this.groupId&&(this.requestScheduled=-1,this.checkRetry(t))}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn("Invalid id passed to audio-track controller");return}this.clearTimer();const i=this.currentTrack;t[this.trackId];const n=t[e],{groupId:r,name:a}=n;if(this.log(`Switching to audio-track ${e} "${a}" lang:${n.lang} group:${r}`),this.trackId=e,this.currentTrack=n,this.selectDefaultTrack=!1,this.hls.trigger(y.AUDIO_TRACK_SWITCHING,Re({},n)),n.details&&!n.details.live)return;const o=this.switchParams(n.url,i==null?void 0:i.details);this.loadPlaylist(o)}selectInitialTrack(){const e=this.tracksInGroup,t=this.findTrackId(this.currentTrack)|this.findTrackId(null);if(t!==-1)this.setAudioTrack(t);else{const i=new Error(`No track found for running audio group-ID: ${this.groupId} track count: ${e.length}`);this.warn(i.message),this.hls.trigger(y.ERROR,{type:J.MEDIA_ERROR,details:w.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:i})}}findTrackId(e){const t=this.tracksInGroup;for(let i=0;is[i]!==e[i])}const Hs=500;class bu extends yn{constructor(e,t,i){super(e,t,i,"[subtitle-stream-controller]",ee.SUBTITLE),this.levels=[],this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null}_registerListeners(){const{hls:e}=this;e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.LEVEL_LOADED,this.onLevelLoaded,this),e.on(y.ERROR,this.onError,this),e.on(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(y.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(y.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(y.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.LEVEL_LOADED,this.onLevelLoaded,this),e.off(y.ERROR,this.onError,this),e.off(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(y.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(y.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(y.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(e){this.stopLoad(),this.state=F.IDLE,this.setInterval(Hs),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:i,success:n}=t;if(this.fragPrevious=i,this.state=F.IDLE,!n)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let a;const o=i.start;for(let c=0;c=r[c].start&&o<=r[c].end){a=r[c];break}const l=i.start+i.duration;a?a.end=l:(a={start:o,end:l},r.push(a)),this.fragmentTracker.fragBuffered(i)}onBufferFlushing(e,t){const{startOffset:i,endOffset:n}=t;if(i===0&&n!==Number.POSITIVE_INFINITY){const r=n-1;if(r<=0)return;t.endOffsetSubtitles=Math.max(0,r),this.tracksBuffered.forEach(a=>{for(let o=0;onew qt(i));return}this.tracksBuffered=[],this.levels=t.map(i=>{const n=new qt(i);return this.tracksBuffered[n.id]=[],n}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,ee.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){if(this.currentTrackId=t.id,!this.levels.length||this.currentTrackId===-1){this.clearInterval();return}const i=this.levels[this.currentTrackId];i!=null&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.setInterval(Hs)}onSubtitleTrackLoaded(e,t){var i;const{details:n,id:r}=t,{currentTrackId:a,levels:o}=this;if(!o.length)return;const l=o[a];if(r>=o.length||r!==a||!l)return;this.mediaBuffer=this.mediaBufferTimeRanges;let c=0;if(n.live||(i=l.details)!=null&&i.live){const u=this.mainDetails;if(n.deltaUpdateFailed||!u)return;const h=u.fragments[0];l.details?(c=this.alignPlaylists(n,l.details),c===0&&h&&(c=h.start,cn(n,c))):n.hasProgramDateTime&&u.hasProgramDateTime?(As(n,u),c=n.fragments[0].start):h&&(c=h.start,cn(n,c))}l.details=n,this.levelLastLoaded=r,!this.startFragRequested&&(this.mainDetails||!n.live)&&this.setStartPosition(l.details,c),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===F.IDLE&&(Xt(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0))}_handleFragmentLoadComplete(e){const{frag:t,payload:i}=e,n=t.decryptdata,r=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&n&&n.key&&n.iv&&n.method==="AES-128"){const a=performance.now();this.decrypter.decrypt(new Uint8Array(i),n.key.buffer,n.iv.buffer).catch(o=>{throw r.trigger(y.ERROR,{type:J.MEDIA_ERROR,details:w.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:t}),o}).then(o=>{const l=performance.now();r.trigger(y.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:a,tdecrypt:l}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=F.IDLE})}}doTick(){if(!this.media){this.state=F.IDLE;return}if(this.state===F.IDLE){const{currentTrackId:e,levels:t}=this,i=t[e];if(!t.length||!i||!i.details)return;const{config:n}=this,r=this.getLoadPosition(),a=ge.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,n.maxBufferHole),{end:o,len:l}=a,c=this.getFwdBufferInfo(this.media,ee.MAIN),u=i.details,h=this.getMaxBufferLength(c==null?void 0:c.len)+u.levelTargetDuration;if(l>h)return;const d=u.fragments,f=d.length,g=u.edge;let v=null;const A=this.fragPrevious;if(og-T?0:T;v=Xt(A,d,Math.max(d[0].start,o),x),!v&&A&&A.start{if(n=n>>>0,n>r-1)throw new DOMException(`Failed to execute '${i}' on 'TimeRanges': The index provided (${n}) is greater than the maximum bound (${r})`);return e[n][i]};this.buffered={get length(){return e.length},end(i){return t("end",i,e.length)},start(i){return t("start",i,e.length)}}}}class _u extends dn{constructor(e){super(e,"[subtitle-track-controller]"),this.media=null,this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.trackChangeListener=()=>this.onTextTracksChanged(),this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.trackChangeListener=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes(this.trackId)}registerListeners(){const{hls:e}=this;e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.LEVEL_LOADING,this.onLevelLoading,this),e.on(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(y.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.LEVEL_LOADING,this.onLevelLoading,this),e.off(y.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(y.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(y.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.trackChangeListener,e)}onMediaDetaching(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),In(this.media.textTracks).forEach(t=>{Ft(t)}),this.subtitleTrack=-1,this.media=null}onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:i,details:n}=t,{trackId:r}=this,a=this.tracksInGroup[r];if(!a){this.warn(`Invalid subtitle track id ${i}`);return}const o=a.details;a.details=t.details,this.log(`subtitle track ${i} loaded [${n.startSN}-${n.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!(t!=null&&t.textGroupIds))return;const i=t.textGroupIds[t.urlId],n=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;if(this.groupId!==i){const r=this.tracks.filter(l=>!i||l.groupId===i);this.tracksInGroup=r;const a=this.findTrackId(n==null?void 0:n.name)||this.findTrackId();this.groupId=i||null;const o={subtitleTracks:r};this.log(`Updating subtitle tracks, ${r.length} track(s) found in "${i}" group-id`),this.hls.trigger(y.SUBTITLE_TRACKS_UPDATED,o),a!==-1&&this.setSubtitleTrack(a,n)}else this.shouldReloadPlaylist(n)&&this.setSubtitleTrack(this.trackId,n)}findTrackId(e){const t=this.tracksInGroup;for(let i=0;io.groupId===this.groupId);if(e===-1)[].slice.call(n).forEach(o=>{o.mode="disabled"});else{const o=r[i];o&&(o.mode="disabled")}const a=r[e];a&&(a.mode=this.subtitleDisplay?"showing":"hidden")}setSubtitleTrack(e,t){var i;const n=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(this.trackId!==e&&this.toggleTrackModes(e),this.trackId===e&&(e===-1||(i=n[e])!=null&&i.details)||e<-1||e>=n.length)return;this.clearTimer();const r=n[e];if(this.log(`Switching to subtitle-track ${e}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:"")),this.trackId=e,r){const{id:a,groupId:o="",name:l,type:c,url:u}=r;this.hls.trigger(y.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:c,url:u});const h=this.switchParams(r.url,t==null?void 0:t.details);this.loadPlaylist(h)}else this.hls.trigger(y.SUBTITLE_TRACK_SWITCH,{id:e})}onTextTracksChanged(){if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=-1;const t=In(this.media.textTracks);for(let i=0;i{t=r}),n={execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(n,e),i}executeNext(e){const{buffers:t,queues:i}=this,n=t[e],r=i[e];if(r.length){const a=r[0];try{a.execute()}catch(o){C.warn("[buffer-operation-queue]: Unhandled exception executing the current operation"),a.onError(o),n!=null&&n.updating||(r.shift(),this.executeNext(e))}}}shiftAndExecuteNext(e){this.queues[e].shift(),this.executeNext(e)}current(e){return this.queues[e][0]}}const Ys=hi(),Ws=/([ha]vc.)(?:\.[^.,]+)+/;class xu{constructor(e){this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendError=0,this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this._onMediaSourceOpen=()=>{const{media:t,mediaSource:i}=this;C.log("[buffer-controller]: Media source opened"),t&&(t.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(y.MEDIA_ATTACHED,{media:t})),i&&i.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{C.log("[buffer-controller]: Media source closed")},this._onMediaSourceEnded=()=>{C.log("[buffer-controller]: Media source ended")},this._onMediaEmptied=()=>{const{media:t,_objectUrl:i}=this;t&&t.src!==i&&C.error(`Media element src was set while attaching MediaSource (${i} > ${t.src})`)},this.hls=e,this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null}registerListeners(){const{hls:e}=this;e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_PARSED,this.onManifestParsed,this),e.on(y.BUFFER_RESET,this.onBufferReset,this),e.on(y.BUFFER_APPENDING,this.onBufferAppending,this),e.on(y.BUFFER_CODECS,this.onBufferCodecs,this),e.on(y.BUFFER_EOS,this.onBufferEos,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(y.FRAG_PARSED,this.onFragParsed,this),e.on(y.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:e}=this;e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_PARSED,this.onManifestParsed,this),e.off(y.BUFFER_RESET,this.onBufferReset,this),e.off(y.BUFFER_APPENDING,this.onBufferAppending,this),e.off(y.BUFFER_CODECS,this.onBufferCodecs,this),e.off(y.BUFFER_EOS,this.onBufferEos,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(y.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(y.FRAG_PARSED,this.onFragParsed,this),e.off(y.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new ku(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=i,C.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(e,t){const i=this.media=t.media;if(i&&Ys){const n=this.mediaSource=new Ys;n.addEventListener("sourceopen",this._onMediaSourceOpen),n.addEventListener("sourceended",this._onMediaSourceEnded),n.addEventListener("sourceclose",this._onMediaSourceClose),i.src=self.URL.createObjectURL(n),this._objectUrl=i.src,i.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:e,mediaSource:t,_objectUrl:i}=this;if(t){if(C.log("[buffer-controller]: media source detaching"),t.readyState==="open")try{t.endOfStream()}catch(n){C.warn(`[buffer-controller]: onMediaDetaching: ${n.message} while calling endOfStream`)}this.onBufferReset(),t.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("sourceended",this._onMediaSourceEnded),t.removeEventListener("sourceclose",this._onMediaSourceClose),e&&(e.removeEventListener("emptied",this._onMediaEmptied),i&&self.URL.revokeObjectURL(i),e.src===i?(e.removeAttribute("src"),e.load()):C.warn("[buffer-controller]: media.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(y.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach(e=>{const t=this.sourceBuffer[e];try{t&&(this.removeBufferListeners(e),this.mediaSource&&this.mediaSource.removeSourceBuffer(t),this.sourceBuffer[e]=void 0)}catch(i){C.warn(`[buffer-controller]: Failed to reset the ${e} buffer`,i)}}),this._initSourceBuffer()}onBufferCodecs(e,t){const i=this.getSourceBufferTypes().length;Object.keys(t).forEach(n=>{if(i){const r=this.tracks[n];if(r&&typeof r.buffer.changeType=="function"){const{id:a,codec:o,levelCodec:l,container:c,metadata:u}=t[n],h=(r.levelCodec||r.codec).replace(Ws,"$1"),d=(l||o).replace(Ws,"$1");if(h!==d){const f=`${c};codecs=${l||o}`;this.appendChangeType(n,f),C.log(`[buffer-controller]: switching codec ${h} to ${d}`),this.tracks[n]={buffer:r.buffer,codec:o,container:c,levelCodec:l,metadata:u,id:a}}}}else this.pendingTracks[n]=t[n]}),!i&&(this.bufferCodecEventsExpected=Math.max(this.bufferCodecEventsExpected-1,0),this.mediaSource&&this.mediaSource.readyState==="open"&&this.checkPendingTracks())}appendChangeType(e,t){const{operationQueue:i}=this,n={execute:()=>{const r=this.sourceBuffer[e];r&&(C.log(`[buffer-controller]: changing ${e} sourceBuffer type to ${t}`),r.changeType(t)),i.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:r=>{C.warn(`[buffer-controller]: Failed to change ${e} SourceBuffer type`,r)}};i.append(n,e)}onBufferAppending(e,t){const{hls:i,operationQueue:n,tracks:r}=this,{data:a,type:o,frag:l,part:c,chunkMeta:u}=t,h=u.buffering[o],d=self.performance.now();h.start=d;const f=l.stats.buffering,g=c?c.stats.buffering:null;f.start===0&&(f.start=d),g&&g.start===0&&(g.start=d);const v=r.audio;let A=!1;o==="audio"&&(v==null?void 0:v.container)==="audio/mpeg"&&(A=!this.lastMpegAudioChunk||u.id===1||this.lastMpegAudioChunk.sn!==u.sn,this.lastMpegAudioChunk=u);const T=l.start,x={execute:()=>{if(h.executeStart=self.performance.now(),A){const _=this.sourceBuffer[o];if(_){const P=T-_.timestampOffset;Math.abs(P)>=.1&&(C.log(`[buffer-controller]: Updating audio SourceBuffer timestampOffset to ${T} (delta: ${P}) sn: ${l.sn})`),_.timestampOffset=T)}}this.appendExecutor(a,o)},onStart:()=>{},onComplete:()=>{const _=self.performance.now();h.executeEnd=h.end=_,f.first===0&&(f.first=_),g&&g.first===0&&(g.first=_);const{sourceBuffer:P}=this,L={};for(const G in P)L[G]=ge.getBuffered(P[G]);this.appendError=0,this.hls.trigger(y.BUFFER_APPENDED,{type:o,frag:l,part:c,chunkMeta:u,parent:l.type,timeRanges:L})},onError:_=>{C.error(`[buffer-controller]: Error encountered while trying to append to the ${o} SourceBuffer`,_);const P={type:J.MEDIA_ERROR,parent:l.type,details:w.BUFFER_APPEND_ERROR,frag:l,part:c,chunkMeta:u,error:_,err:_,fatal:!1};_.code===DOMException.QUOTA_EXCEEDED_ERR?P.details=w.BUFFER_FULL_ERROR:(this.appendError++,P.details=w.BUFFER_APPEND_ERROR,this.appendError>i.config.appendErrorMaxRetry&&(C.error(`[buffer-controller]: Failed ${i.config.appendErrorMaxRetry} times to append segment in sourceBuffer`),P.fatal=!0)),i.trigger(y.ERROR,P)}};n.append(x,o)}onBufferFlushing(e,t){const{operationQueue:i}=this,n=r=>({execute:this.removeExecutor.bind(this,r,t.startOffset,t.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(y.BUFFER_FLUSHED,{type:r})},onError:a=>{C.warn(`[buffer-controller]: Failed to remove from ${r} SourceBuffer`,a)}});t.type?i.append(n(t.type),t.type):this.getSourceBufferTypes().forEach(r=>{i.append(n(r),r)})}onFragParsed(e,t){const{frag:i,part:n}=t,r=[],a=n?n.elementaryStreams:i.elementaryStreams;a[fe.AUDIOVIDEO]?r.push("audiovideo"):(a[fe.AUDIO]&&r.push("audio"),a[fe.VIDEO]&&r.push("video"));const o=()=>{const l=self.performance.now();i.stats.buffering.end=l,n&&(n.stats.buffering.end=l);const c=n?n.stats:i.stats;this.hls.trigger(y.FRAG_BUFFERED,{frag:i,part:n,stats:c,id:i.type})};r.length===0&&C.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(o,r)}onFragChanged(e,t){this.flushBackBuffer()}onBufferEos(e,t){this.getSourceBufferTypes().reduce((n,r)=>{const a=this.sourceBuffer[r];return a&&(!t.type||t.type===r)&&(a.ending=!0,a.ended||(a.ended=!0,C.log(`[buffer-controller]: ${r} sourceBuffer now EOS`))),n&&!!(!a||a.ended)},!0)&&(C.log("[buffer-controller]: Queueing mediaSource.endOfStream()"),this.blockBuffers(()=>{this.getSourceBufferTypes().forEach(r=>{const a=this.sourceBuffer[r];a&&(a.ending=!1)});const{mediaSource:n}=this;if(!n||n.readyState!=="open"){n&&C.info(`[buffer-controller]: Could not call mediaSource.endOfStream(). mediaSource.readyState: ${n.readyState}`);return}C.log("[buffer-controller]: Calling mediaSource.endOfStream()"),n.endOfStream()}))}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}flushBackBuffer(){const{hls:e,details:t,media:i,sourceBuffer:n}=this;if(!i||t===null)return;const r=this.getSourceBufferTypes();if(!r.length)return;const a=t.live&&e.config.liveBackBufferLength!==null?e.config.liveBackBufferLength:e.config.backBufferLength;if(!Z(a)||a<0)return;const o=i.currentTime,l=t.levelTargetDuration,c=Math.max(a,l),u=Math.floor(o/l)*l-c;r.forEach(h=>{const d=n[h];if(d){const f=ge.getBuffered(d);if(f.length>0&&u>f.start(0)){if(e.trigger(y.BACK_BUFFER_REACHED,{bufferEnd:u}),t.live)e.trigger(y.LIVE_BACK_BUFFER_REACHED,{bufferEnd:u});else if(d.ended&&f.end(f.length-1)-oo&&r>a||!Z(a))&&(C.log(`[buffer-controller]: Updating Media Source duration to ${r.toFixed(3)}`),n.duration=r)}updateSeekableRange(e){const t=this.mediaSource,i=e.fragments;if(i.length&&e.live&&t!=null&&t.setLiveSeekableRange){const r=Math.max(0,i[0].start),a=Math.max(r,r+e.totalduration);t.setLiveSeekableRange(r,a)}}checkPendingTracks(){const{bufferCodecEventsExpected:e,operationQueue:t,pendingTracks:i}=this,n=Object.keys(i).length;if(n&&!e||n===2){this.createSourceBuffers(i),this.pendingTracks={};const r=this.getSourceBufferTypes();if(r.length)this.hls.trigger(y.BUFFER_CREATED,{tracks:this.tracks}),r.forEach(a=>{t.executeNext(a)});else{const a=new Error("could not create source buffer for media codec(s)");this.hls.trigger(y.ERROR,{type:J.MEDIA_ERROR,details:w.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:a,reason:a.message})}}}createSourceBuffers(e){const{sourceBuffer:t,mediaSource:i}=this;if(!i)throw Error("createSourceBuffers called when mediaSource was null");for(const n in e)if(!t[n]){const r=e[n];if(!r)throw Error(`source buffer exists for track ${n}, however track does not`);const a=r.levelCodec||r.codec,o=`${r.container};codecs=${a}`;C.log(`[buffer-controller]: creating sourceBuffer(${o})`);try{const l=t[n]=i.addSourceBuffer(o),c=n;this.addBufferListener(c,"updatestart",this._onSBUpdateStart),this.addBufferListener(c,"updateend",this._onSBUpdateEnd),this.addBufferListener(c,"error",this._onSBUpdateError),this.tracks[n]={buffer:l,codec:a,container:r.container,levelCodec:r.levelCodec,metadata:r.metadata,id:r.id}}catch(l){C.error(`[buffer-controller]: error while trying to add sourceBuffer: ${l.message}`),this.hls.trigger(y.ERROR,{type:J.MEDIA_ERROR,details:w.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:l,mimeType:o})}}}_onSBUpdateStart(e){const{operationQueue:t}=this;t.current(e).onStart()}_onSBUpdateEnd(e){const{operationQueue:t}=this;t.current(e).onComplete(),t.shiftAndExecuteNext(e)}_onSBUpdateError(e,t){const i=new Error(`${e} SourceBuffer error`);C.error(`[buffer-controller]: ${i}`,t),this.hls.trigger(y.ERROR,{type:J.MEDIA_ERROR,details:w.BUFFER_APPENDING_ERROR,error:i,fatal:!1});const n=this.operationQueue.current(e);n&&n.onError(t)}removeExecutor(e,t,i){const{media:n,mediaSource:r,operationQueue:a,sourceBuffer:o}=this,l=o[e];if(!n||!r||!l){C.warn(`[buffer-controller]: Attempting to remove from the ${e} SourceBuffer, but it does not exist`),a.shiftAndExecuteNext(e);return}const c=Z(n.duration)?n.duration:1/0,u=Z(r.duration)?r.duration:1/0,h=Math.max(0,t),d=Math.min(i,c,u);d>h&&!l.ending?(l.ended=!1,C.log(`[buffer-controller]: Removing [${h},${d}] from the ${e} SourceBuffer`),l.remove(h,d)):a.shiftAndExecuteNext(e)}appendExecutor(e,t){const{operationQueue:i,sourceBuffer:n}=this,r=n[t];if(!r){C.warn(`[buffer-controller]: Attempting to append to the ${t} SourceBuffer, but it does not exist`),i.shiftAndExecuteNext(t);return}r.ended=!1,r.appendBuffer(e)}blockBuffers(e,t=this.getSourceBufferTypes()){if(!t.length){C.log("[buffer-controller]: Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);return}const{operationQueue:i}=this,n=t.map(r=>i.appendBlocker(r));Promise.all(n).then(()=>{e(),t.forEach(r=>{const a=this.sourceBuffer[r];a!=null&&a.updating||i.shiftAndExecuteNext(r)})})}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(e,t,i){const n=this.sourceBuffer[e];if(!n)return;const r=i.bind(this,e);this.listeners[e].push({event:t,listener:r}),n.addEventListener(t,r)}removeBufferListeners(e){const t=this.sourceBuffer[e];t&&this.listeners[e].forEach(i=>{t.removeEventListener(i.event,i.listener)})}}const zs={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},js=function(e){let t=e;return zs.hasOwnProperty(e)&&(t=zs[e]),String.fromCharCode(t)},qe=15,ut=100,Cu={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Lu={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Iu={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Ru={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Du=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class wu{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const i=typeof t=="function"?t():t;C.log(`${this.time} [${e}] ${i}`)}}}const kt=function(e){const t=[];for(let i=0;iut&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=ut)}moveCursor(e){const t=this.pos+e;if(e>1)for(let i=this.pos+1;i=144&&this.backSpace();const t=js(e);if(this.pos>=ut){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t"pacData = "+JSON.stringify(e));let t=e.row-1;if(this.nrRollUpRows&&t"bkgData = "+JSON.stringify(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let i="",n=-1;for(let r=0;r0&&(e?i="["+t.join(" | ")+"]":i=t.join(` `)),i}getTextAndFormat(){return this.rows}}class Xs{constructor(e,t,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=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new Rn(i),this.nonDisplayedMemory=new Rn(i),this.lastOutputScreen=new Rn(i),this.currRollUpRow=this.displayedMemory.rows[qe-1],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[qe-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let i=0;it+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{const i=Math.floor(e/2)-16,n=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=n[i]}this.logger.log(2,"MIDROW: "+JSON.stringify(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class Qs{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=void 0,this.logger=void 0;const n=new wu;this.channels=[null,new Xs(e,t,n),new Xs(e+1,i,n)],this.cmdHistory=Js(),this.logger=n}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){let i,n,r,a=!1;this.logger.time=e;for(let o=0;o ("+kt([n,r])+")"),i=this.parseCmd(n,r),i||(i=this.parseMidrow(n,r)),i||(i=this.parsePAC(n,r)),i||(i=this.parseBackgroundAttributes(n,r)),!i&&(a=this.parseChars(n,r),a)){const l=this.currentChannel;l&&l>0?this.channels[l].insertChars(a):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!i&&!a&&this.logger.log(2,"Couldn't parse cleaned data "+kt([n,r])+" orig: "+kt([t[o],t[o+1]]))}}parseCmd(e,t){const{cmdHistory:i}=this,n=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,r=(e===23||e===31)&&t>=33&&t<=35;if(!(n||r))return!1;if(Zs(e,t,i))return $t(null,null,i),this.logger.log(3,"Repeated command ("+kt([e,t])+") is dropped"),!0;const a=e===20||e===21||e===23?1:2,o=this.channels[a];return e===20||e===21||e===28||e===29?t===32?o.ccRCL():t===33?o.ccBS():t===34?o.ccAOF():t===35?o.ccAON():t===36?o.ccDER():t===37?o.ccRU(2):t===38?o.ccRU(3):t===39?o.ccRU(4):t===40?o.ccFON():t===41?o.ccRDC():t===42?o.ccTR():t===43?o.ccRTD():t===44?o.ccEDM():t===45?o.ccCR():t===46?o.ccENM():t===47&&o.ccEOC():o.ccTO(t-32),$t(e,t,i),this.currentChannel=a,!0}parseMidrow(e,t){let i=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?i=1:i=2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const n=this.channels[i];return n?(n.ccMIDROW(t),this.logger.log(3,"MIDROW ("+kt([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let i;const n=this.cmdHistory,r=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,a=(e===16||e===24)&&t>=64&&t<=95;if(!(r||a))return!1;if(Zs(e,t,n))return $t(null,null,n),!0;const o=e<=23?1:2;t>=64&&t<=95?i=o===1?Cu[e]:Iu[e]:i=o===1?Lu[e]:Ru[e];const l=this.channels[o];return l?(l.setPAC(this.interpretPAC(i,t)),$t(e,t,n),this.currentChannel=o,!0):!1}interpretPAC(e,t){let i;const n={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?i=t-96:i=t-64,n.underline=(i&1)===1,i<=13?n.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(n.italics=!0,n.color="white"):n.indent=Math.floor((i-16)/2)*4,n}parseChars(e,t){let i,n=null,r=null;if(e>=25?(i=2,r=e-8):(i=1,r=e),r>=17&&r<=19){let a;r===17?a=t+80:r===18?a=t+112:a=t+144,this.logger.log(2,"Special char '"+js(a)+"' in channel "+i),n=[a]}else e>=32&&e<=127&&(n=t===0?[e]:[e,t]);if(n){const a=kt(n);this.logger.log(3,"Char codes = "+a.join(",")),$t(e,t,this.cmdHistory)}return n}parseBackgroundAttributes(e,t){const i=(e===16||e===24)&&t>=32&&t<=47,n=(e===23||e===31)&&t>=45&&t<=47;if(!(i||n))return!1;let r;const a={};e===16||e===24?(r=Math.floor((t-32)/2),a.background=Du[r],t%2===1&&(a.background=a.background+"_semi")):t===45?a.background="transparent":(a.foreground="black",t===47&&(a.underline=!0));const o=e<=23?1:2;return this.channels[o].setBkgData(a),$t(e,t,this.cmdHistory),!0}reset(){for(let e=0;ee)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var Dn=function(){if(typeof self<"u"&&self.VTTCue)return self.VTTCue;const s=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,l){if(typeof l!="string"||!Array.isArray(o))return!1;const c=l.toLowerCase();return~o.indexOf(c)?c:!1}function i(o){return t(s,o)}function n(o){return t(e,o)}function r(o,...l){let c=1;for(;c100)throw new Error("Position must be between 0 and 100.");G=E,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",r({},h,{get:function(){return O},set:function(E){const N=n(E);if(!N)throw new SyntaxError("An invalid or illegal string was specified.");O=N,this.hasBeenReset=!0}})),Object.defineProperty(u,"size",r({},h,{get:function(){return B},set:function(E){if(E<0||E>100)throw new Error("Size must be between 0 and 100.");B=E,this.hasBeenReset=!0}})),Object.defineProperty(u,"align",r({},h,{get:function(){return k},set:function(E){const N=n(E);if(!N)throw new SyntaxError("An invalid or illegal string was specified.");k=N,this.hasBeenReset=!0}})),u.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}();class Nu{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function ea(s){function e(i,n,r,a){return(i|0)*3600+(n|0)*60+(r|0)+parseFloat(a||0)}const t=s.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}class Fu{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,i){for(let n=0;n=0&&i<=100)return this.set(e,i),!0}return!1}}function ta(s,e,t,i){const n=i?s.split(i):[s];for(const r in n){if(typeof n[r]!="string")continue;const a=n[r].split(t);if(a.length!==2)continue;const o=a[0],l=a[1];e(o,l)}}const wn=new Dn(0,0,""),_i=wn.align==="middle"?"middle":"center";function Mu(s,e,t){const i=s;function n(){const o=ea(s);if(o===null)throw new Error("Malformed timestamp: "+i);return s=s.replace(/^[^\sa-zA-Z-]+/,""),o}function r(o,l){const c=new Fu;ta(o,function(d,f){let g;switch(d){case"region":for(let v=t.length-1;v>=0;v--)if(t[v].id===f){c.set(d,t[v].region);break}break;case"vertical":c.alt(d,f,["rl","lr"]);break;case"line":g=f.split(","),c.integer(d,g[0]),c.percent(d,g[0])&&c.set("snapToLines",!1),c.alt(d,g[0],["auto"]),g.length===2&&c.alt("lineAlign",g[1],["start",_i,"end"]);break;case"position":g=f.split(","),c.percent(d,g[0]),g.length===2&&c.alt("positionAlign",g[1],["start",_i,"end","line-left","line-right","auto"]);break;case"size":c.percent(d,f);break;case"align":c.alt(d,f,["start",_i,"end","left","right"]);break}},/:/,/\s/),l.region=c.get("region",null),l.vertical=c.get("vertical","");let u=c.get("line","auto");u==="auto"&&wn.line===-1&&(u=-1),l.line=u,l.lineAlign=c.get("lineAlign","start"),l.snapToLines=c.get("snapToLines",!0),l.size=c.get("size",100),l.align=c.get("align",_i);let h=c.get("position","auto");h==="auto"&&wn.position===50&&(h=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=h}function a(){s=s.replace(/^\s+/,"")}if(a(),e.startTime=n(),a(),s.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+i);s=s.slice(3),a(),e.endTime=n(),a(),r(s,e)}function ia(s){return s.replace(//gi,` `)}class Bu{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Nu,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function i(){let r=t.buffer,a=0;for(r=ia(r);a")===-1){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{Mu(r,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const o=r.indexOf("-->")!==-1;if(!r||o&&(a=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=` `),t.cue.text+=r}continue;case"BADCUE":r||(t.state="ID")}}}catch{t.state==="CUETEXT"&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=` `,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const Uu=/\r\n|\n\r|\n|\r/g,Pn=function(e,t,i=0){return e.slice(i,i+t.length)===t},$u=function(e){let t=parseInt(e.slice(-3));const i=parseInt(e.slice(-6,-4)),n=parseInt(e.slice(-9,-7)),r=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!Z(t)||!Z(i)||!Z(n)||!Z(r))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=60*1e3*n,t+=60*60*1e3*r,t},On=function(e){let t=5381,i=e.length;for(;i;)t=t*33^e.charCodeAt(--i);return(t>>>0).toString()};function Nn(s,e,t){return On(s.toString())+On(e.toString())+On(t)}const Vu=function(e,t,i){let n=e[t],r=e[n.prevCC];if(!r||!r.new&&n.new){e.ccOffset=e.presentationOffset=n.start,n.new=!1;return}for(;(a=r)!=null&&a.new;){var a;e.ccOffset+=n.start-r.start,n.new=!1,n=r,r=e[n.prevCC]}e.presentationOffset=i};function Gu(s,e,t,i,n,r,a){const o=new Bu,l=Je(new Uint8Array(s)).trim().replace(Uu,` `).split(` `),c=[],u=e?Jc(e.baseTime,e.timescale):0;let h="00:00.000",d=0,f=0,g,v=!0;o.oncue=function(A){const T=t[i];let x=t.ccOffset;const _=(d-u)/9e4;if(T!=null&&T.new&&(f!==void 0?x=t.ccOffset=T.start:Vu(t,i,_)),_){if(!e){g=new Error("Missing initPTS for VTT MPEGTS");return}x=_-t.presentationOffset}const P=A.endTime-A.startTime,L=He((A.startTime+x-f)*9e4,n*9e4)/9e4;A.startTime=Math.max(L,0),A.endTime=Math.max(L+P,0);const G=A.text.trim();A.text=decodeURIComponent(encodeURIComponent(G)),A.id||(A.id=Nn(A.startTime,A.endTime,G)),A.endTime>0&&c.push(A)},o.onparsingerror=function(A){g=A},o.onflush=function(){if(g){a(g);return}r(c)},l.forEach(A=>{if(v)if(Pn(A,"X-TIMESTAMP-MAP=")){v=!1,A.slice(16).split(",").forEach(T=>{Pn(T,"LOCAL:")?h=T.slice(6):Pn(T,"MPEGTS:")&&(d=parseInt(T.slice(7)))});try{f=$u(h)/1e3}catch(T){g=T}return}else A===""&&(v=!1);o.parse(A+` `)}),o.flush()}const Fn="stpp.ttml.im1t",na=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,ra=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Ku={left:"start",center:"center",right:"end",start:"start",end:"end"};function sa(s,e,t,i){const n=oe(new Uint8Array(s),["mdat"]);if(n.length===0){i(new Error("Could not parse IMSC1 mdat"));return}const r=n.map(o=>Je(o)),a=Zc(e.baseTime,1,e.timescale);try{r.forEach(o=>t(Hu(o,a)))}catch(o){i(o)}}function Hu(s,e){const n=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("tt")[0];if(!n)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(r).reduce((h,d)=>(h[d]=n.getAttribute(`ttp:${d}`)||r[d],h),{}),o=n.getAttribute("xml:space")!=="preserve",l=aa(Mn(n,"styling","style")),c=aa(Mn(n,"layout","region")),u=Mn(n,"body","[begin]");return[].map.call(u,h=>{const d=oa(h,o);if(!d||!h.hasAttribute("begin"))return null;const f=Un(h.getAttribute("begin"),a),g=Un(h.getAttribute("dur"),a);let v=Un(h.getAttribute("end"),a);if(f===null)throw la(h);if(v===null){if(g===null)throw la(h);v=f+g}const A=new Dn(f-e,v-e,d);A.id=Nn(A.startTime,A.endTime,A.text);const T=c[h.getAttribute("region")],x=l[h.getAttribute("style")],_=Yu(T,x,l),{textAlign:P}=_;if(P){const L=Ku[P];L&&(A.lineAlign=L),A.align=P}return Te(A,_),A}).filter(h=>h!==null)}function Mn(s,e,t){const i=s.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(t)):[]}function aa(s){return s.reduce((e,t)=>{const i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function oa(s,e){return[].slice.call(s.childNodes).reduce((t,i,n)=>{var r;return i.nodeName==="br"&&n?t+` `:(r=i.childNodes)!=null&&r.length?oa(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function Yu(s,e,t){const i="http://www.w3.org/ns/ttml#styling";let n=null;const r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=s!=null&&s.hasAttribute("style")?s.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(n=t[a]),r.reduce((o,l)=>{const c=Bn(e,i,l)||Bn(s,i,l)||Bn(n,i,l);return c&&(o[l]=c),o},{})}function Bn(s,e,t){return s&&s.hasAttributeNS(e,t)?s.getAttributeNS(e,t):null}function la(s){return new Error(`Could not parse ttml timestamp ${s}`)}function Un(s,e){if(!s)return null;let t=ea(s);return t===null&&(na.test(s)?t=Wu(s,e):ra.test(s)&&(t=zu(s,e))),t}function Wu(s,e){const t=na.exec(s),i=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+i/e.frameRate}function zu(s,e){const t=ra.exec(s),i=Number(t[1]);switch(t[2]){case"h":return i*3600;case"m":return i*60;case"ms":return i*1e3;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}class ju{constructor(e){if(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.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=ca(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},this.config.enableCEA708Captions){const t=new Si(this,"textTrack1"),i=new Si(this,"textTrack2"),n=new Si(this,"textTrack3"),r=new Si(this,"textTrack4");this.cea608Parser1=new Qs(1,t,i),this.cea608Parser2=new Qs(3,n,r)}e.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(y.MANIFEST_LOADING,this.onManifestLoading,this),e.on(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(y.FRAG_LOADING,this.onFragLoading,this),e.on(y.FRAG_LOADED,this.onFragLoaded,this),e.on(y.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(y.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(y.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(y.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(y.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(y.MANIFEST_LOADING,this.onManifestLoading,this),e.off(y.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(y.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(y.FRAG_LOADING,this.onFragLoading,this),e.off(y.FRAG_LOADED,this.onFragLoaded,this),e.off(y.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(y.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(y.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(y.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(y.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.cea608Parser1=this.cea608Parser2=null}addCues(e,t,i,n,r){let a=!1;for(let o=r.length;o--;){const l=r[o],c=Xu(l[0],l[1],t,i);if(c>=0&&(l[0]=Math.min(l[0],t),l[1]=Math.max(l[1],i),a=!0,c/(i-t)>.5))return}if(a||r.push([t,i]),this.config.renderTextTracksNatively){const o=this.captionsTracks[e];this.Cues.newCue(o,t,i,n)}else{const o=this.Cues.newCue(null,t,i,n);this.hls.trigger(y.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:n,timescale:r}){const{unparsedVttFrags:a}=this;i==="main"&&(this.initPTS[t.cc]={baseTime:n,timescale:r}),a.length&&(this.unparsedVttFrags=[],a.forEach(o=>{this.onFragLoaded(y.FRAG_LOADED,o)}))}getExistingTrack(e){const{media:t}=this;if(t)for(let i=0;i{Ft(e[t]),delete e[t]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=ca(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let i=0;ir.textCodec===Fn);if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if(Ks(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const a=this.media?this.media.textTracks:null;this.tracks.forEach((o,l)=>{let c;if(a&&l({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(y.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}_captionsOrSubtitlesFromCharacteristics(e){if(e.attrs.CHARACTERISTICS){const t=/transcribes-spoken-dialog/gi.test(e.attrs.CHARACTERISTICS),i=/describes-music-and-sound/gi.test(e.attrs.CHARACTERISTICS);if(t&&i)return"captions"}return"subtitles"}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(i=>{const n=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!n)return;const r=`textTrack${n[1]}`,a=this.captionsProperties[r];a&&(a.label=i.name,i.lang&&(a.languageCode=i.lang),a.media=i)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){const{cea608Parser1:i,cea608Parser2:n,lastSn:r,lastPartIndex:a}=this;if(!(!this.enabled||!(i&&n))&&t.frag.type===ee.MAIN){var o,l;const c=t.frag.sn,u=(o=t==null||(l=t.part)==null?void 0:l.index)!=null?o:-1;c===r+1||c===r&&u===a+1||(i.reset(),n.reset()),this.lastSn=c,this.lastPartIndex=u}}onFragLoaded(e,t){const{frag:i,payload:n}=t;if(i.type===ee.SUBTITLE)if(n.byteLength){const r=i.decryptdata,a="stats"in t;if(r==null||!r.encrypted||a){const o=this.tracks[i.level],l=this.vttCCs;l[i.cc]||(l[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),o&&o.textCodec===Fn?this._parseIMSC1(i,n):this._parseVTTs(t)}}else this.hls.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const i=this.hls;sa(t,this.initPTS[e.cc],n=>{this._appendCues(n,e.level),i.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},n=>{C.log(`Failed to parse IMSC1: ${n}`),i.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:n})})}_parseVTTs(e){var t;const{frag:i,payload:n}=e,{initPTS:r,unparsedVttFrags:a}=this,o=r.length-1;if(!r[i.cc]&&o===-1){a.push(e);return}const l=this.hls,c=(t=i.initSegment)!=null&&t.data?_t(i.initSegment.data,new Uint8Array(n)):n;Gu(c,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,u=>{this._appendCues(u,i.level),l.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},u=>{const h=u.message==="Missing initPTS for VTT MPEGTS";h?a.push(e):this._fallbackToIMSC1(i,n),C.log(`Failed to parse VTT cue: ${u}`),!(h&&o>i.cc)&&l.trigger(y.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:u})})}_fallbackToIMSC1(e,t){const i=this.tracks[e.level];i.textCodec||sa(t,this.initPTS[e.cc],()=>{i.textCodec=Fn,this._parseIMSC1(e,t)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){const i=this.hls;if(this.config.renderTextTracksNatively){const n=this.textTracks[t];if(!n||n.mode==="disabled")return;e.forEach(r=>rs(n,r))}else{const n=this.tracks[t];if(!n)return;const r=n.default?"default":"subtitles"+t;i.trigger(y.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){const{frag:i}=t;i.type===ee.SUBTITLE&&this.onFragLoaded(y.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){const{cea608Parser1:i,cea608Parser2:n}=this;if(!this.enabled||!(i&&n))return;const{frag:r,samples:a}=t;if(!(r.type===ee.MAIN&&this.closedCaptionsForLevel(r)==="NONE"))for(let o=0;orn(o[l],t,i))}if(this.config.renderTextTracksNatively&&t===0&&n!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(l=>rn(o[l],t,n))}}}extractCea608Data(e){const t=[[],[]],i=e[0]&31;let n=2;for(let r=0;r0&&this.mediaWidth>0){const e=this.hls.levels;if(e.length){const t=this.hls;t.autoLevelCapping=this.getMaxLevel(e.length-1),t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const i=t.filter((n,r)=>this.isLevelAllowed(n)&&r<=e);return this.clientRect=null,$n.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,this.hls.firstLevel=this.getMaxLevel(this.firstLevel),self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,!t.width&&!t.height&&(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return e}isLevelAllowed(e){return!this.restrictedLevels.some(i=>e.bitrate===i.bitrate&&e.width===i.width&&e.height===i.height)}static getMaxLevelByMediaSize(e,t,i){if(!(e!=null&&e.length))return-1;const n=(a,o)=>o?a.width!==o.width||a.height!==o.height:!0;let r=e.length-1;for(let a=0;a=t||o.height>=i)&&n(o,e[a+1])){r=a;break}}return r}}class Qu{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(y.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(y.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const i=this.hls.config;if(i.capLevelOnFPSDrop){const n=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=n,n&&typeof n.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}checkFPS(e,t,i){const n=performance.now();if(t){if(this.lastTime){const r=n-this.lastTime,a=i-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*a/r,c=this.hls;if(c.trigger(y.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:i}),l>0&&a>c.config.fpsDroppedMonitoringThreshold*o){let u=c.currentLevel;C.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(c.autoLevelCapping===-1||c.autoLevelCapping>=u)&&(u=u-1,c.trigger(y.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:c.currentLevel}),c.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=n,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}const ki="[eme]";class Vt{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=Vt.CDMCleanupPromise?[Vt.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=C.debug.bind(C,ki),this.log=C.log.bind(C,ki),this.warn=C.warn.bind(C,ki),this.error=C.error.bind(C,ki),this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(y.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(y.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(y.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(y.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(y.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(y.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:i}=this.config,n=t[e];if(n)return n.licenseUrl;if(e===ye.WIDEVINE&&i)return i;throw new Error(`no license server URL configured for key-system "${e}"`)}getServerCertificateUrl(e){const{drmSystems:t}=this.config,i=t[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,i=(a,o,l)=>!!a&&l.indexOf(a)===o,n=t.map(a=>a.audioCodec).filter(i),r=t.map(a=>a.videoCodec).filter(i);return n.length+r.length===0&&r.push("avc1.42e01e"),new Promise((a,o)=>{const l=c=>{const u=c.shift();this.getMediaKeysPromise(u,n,r).then(h=>a({keySystem:u,mediaKeys:h})).catch(h=>{c.length?l(c):h instanceof Ye?o(h):o(new Ye({type:J.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_ACCESS,error:h,fatal:!0},h.message))})};l(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let n=`Configured requestMediaKeySystemAccess is not a function ${i}`;return Dr===null&&self.location.protocol==="http:"&&(n=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(n))}return i(e,t)}getMediaKeysPromise(e,t,i){const n=hl(e,t,i,this.config.drmSystemOptions),r=this.keySystemAccessPromises[e];let a=r==null?void 0:r.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${JSON.stringify(n)}`),a=this.requestMediaKeySystemAccess(e,n);const o=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),a.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const c=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),o.mediaKeys=l.createMediaKeys().then(u=>(this.log(`Media-keys created for "${e}"`),c.then(h=>h?this.setMediaKeysServerCertificate(u,e,h):u))),o.mediaKeys.catch(u=>{this.error(`Failed to create media-keys for "${e}"}: ${u}`)}),o.mediaKeys})}return a.then(()=>r.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${et.hexDump(e.keyId||[])}`);const n=i.createSession(),r={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:n,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const i=this.createMediaKeySessionContext(e),n=this.getKeyIdString(t),r="cenc";this.keyIdToKeySessionPromise[n]=this.generateRequestWithPreferredKeySession(i,r,t.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(e.keyId===null)throw new Error("keyId is null");return et.hexDump(e.keyId)}updateKeySession(e,t){var i;const n=e.mediaKeysSession;return this.log(`Updating key-session "${n.sessionId}" for keyID ${et.hexDump(((i=e.decryptdata)==null?void 0:i.keyId)||[])} } (data length: ${t&&t.byteLength})`),n.update(t)}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise((t,i)=>{const n=Xi(this.config),r=e.map(Lr).filter(a=>!!a&&n.indexOf(a)!==-1);return this.getKeySystemSelectionPromise(r).then(({keySystem:a})=>{const o=Rr(a);o?t(o):i(new Error(`Unable to find format for key-system "${a}"`))}).catch(i)})}loadKey(e){const t=e.keyInfo.decryptdata,i=this.getKeyIdString(t),n=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${n}`);let r=this.keyIdToKeySessionPromise[i];return r||(r=this.keyIdToKeySessionPromise[i]=this.getKeySystemForKeyPromise(t).then(({keySystem:a,mediaKeys:o})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${n}`),this.attemptSetMediaKeys(a,o).then(()=>{this.throwIfDestroyed();const l=this.createMediaKeySessionContext({keySystem:a,mediaKeys:o,decryptdata:t}),c="cenc";return this.generateRequestWithPreferredKeySession(l,c,t.pssh,"playlist-key")}))),r.catch(a=>this.handleError(a))),r}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof Ye?this.hls.trigger(y.ERROR,e.data):this.hls.trigger(y.ERROR,{type:J.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),i=this.keyIdToKeySessionPromise[t];if(!i){const n=Lr(e.keyFormat),r=n?[n]:Xi(this.config);return this.attemptKeySystemAccess(r)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=Xi(this.config)),e.length===0)throw new Ye({type:J.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}_onMediaEncrypted(e){const{initDataType:t,initData:i}=e;if(this.debug(`"${e.type}" event: init data type: "${t}"`),i===null)return;let n,r;if(t==="sinf"&&this.config.drmSystems[ye.FAIRPLAY]){const u=_e(new Uint8Array(i));try{const h=qi(JSON.parse(u).sinf),d=Ur(new Uint8Array(h));if(!d)return;n=d.subarray(8,24),r=ye.FAIRPLAY}catch{this.warn('Failed to parse sinf "encrypted" event message initData');return}}else{const u=Nl(i);if(u===null)return;u.version===0&&u.systemId===Ir.WIDEVINE&&u.data&&(n=u.data.subarray(8,24)),r=ul(u.systemId)}if(!r||!n)return;const a=et.hexDump(n),{keyIdToKeySessionPromise:o,mediaKeySessions:l}=this;let c=o[a];for(let u=0;uthis.generateRequestWithPreferredKeySession(h,t,i,"encrypted-event-key-match"));break}}c||(c=o[a]=this.getKeySystemSelectionPromise([r]).then(({keySystem:u,mediaKeys:h})=>{var d;this.throwIfDestroyed();const f=new zt("ISO-23001-7",a,(d=Rr(u))!=null?d:"");return f.pssh=new Uint8Array(i),f.keyId=n,this.attemptSetMediaKeys(u,h).then(()=>{this.throwIfDestroyed();const g=this.createMediaKeySessionContext({decryptdata:f,keySystem:u,mediaKeys:h});return this.generateRequestWithPreferredKeySession(g,t,i,"encrypted-event-no-match")})})),c.catch(u=>this.handleError(u))}_onWaitingForKey(e){this.log(`"${e.type}" event`)}attemptSetMediaKeys(e,t){const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const n=Promise.all(i).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)});return this.setMediaKeysQueue.push(n),n.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(n),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(r=>i.indexOf(r)===-1)})}generateRequestWithPreferredKeySession(e,t,i,n){var r,a;const o=(r=this.config.drmSystems)==null||(a=r[e.keySystem])==null?void 0:a.generateRequest;if(o)try{const d=o.call(this.hls,t,i,e);if(!d)throw new Error("Invalid response from configured generateRequest filter");t=d.initDataType,i=e.decryptdata.pssh=d.initData?new Uint8Array(d.initData):null}catch(d){var l;if(this.warn(d.message),(l=this.hls)!=null&&l.config.debug)throw d}if(i===null)return this.log(`Skipping key-session request for "${n}" (no initData)`),Promise.resolve(e);const c=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${n}": ${c} (init data type: ${t} length: ${i?i.byteLength:null})`);const u=new xn;e.mediaKeysSession.onmessage=d=>{const f=e.mediaKeysSession;if(!f){u.emit("error",new Error("invalid state"));return}const{messageType:g,message:v}=d;this.log(`"${g}" message event for session "${f.sessionId}" message size: ${v.byteLength}`),g==="license-request"||g==="license-renewal"?this.renewLicense(e,v).catch(A=>{this.handleError(A),u.emit("error",A)}):g==="license-release"?e.keySystem===ye.FAIRPLAY&&(this.updateKeySession(e,Cr("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${g}"`)},e.mediaKeysSession.onkeystatuseschange=d=>{if(!e.mediaKeysSession){u.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(e);const g=e.keyStatus;u.emit("keyStatus",g),g==="expired"&&(this.warn(`${e.keySystem} expired for key ${c}`),this.renewKeySession(e))};const h=new Promise((d,f)=>{u.on("error",f),u.on("keyStatus",g=>{g.startsWith("usable")?d():g==="output-restricted"?f(new Ye({type:J.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):g==="internal-error"?f(new Ye({type:J.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${g}"`)):g==="expired"?f(new Error("key expired while generating request")):this.warn(`unhandled key status change "${g}"`)})});return e.mediaKeysSession.generateRequest(t,i).then(()=>{var d;this.log(`Request generated for key-session "${(d=e.mediaKeysSession)==null?void 0:d.sessionId}" keyId: ${c}`)}).catch(d=>{throw new Ye({type:J.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_NO_SESSION,error:d,fatal:!1},`Error generating key-session request: ${d}`)}).then(()=>h).catch(d=>{throw u.removeAllListeners(),this.removeSession(e),d}).then(()=>(u.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((t,i)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${et.hexDump("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${et.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t})}fetchServerCertificate(e){const t=this.config,i=t.loader,n=new i(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching serverCertificate for "${e}"`),new Promise((a,o)=>{const l={responseType:"arraybuffer",url:r},c=t.certLoadPolicy.default,u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(d,f,g,v)=>{a(d.data)},onError:(d,f,g,v)=>{o(new Ye({type:J.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:Re({url:l.url,data:void 0},d)},`"${e}" certificate request failed (${r}). Status: ${d.code} (${d.text})`))},onTimeout:(d,f,g)=>{o(new Ye({type:J.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(d,f,g)=>{o(new Error("aborted"))}};n.load(l,u,h)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((n,r)=>{e.setServerCertificate(i).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${i==null?void 0:i.byteLength}) on "${t}"`),n(e)}).catch(a=>{r(new Ye({type:J.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(i=>this.updateKeySession(e,new Uint8Array(i)).catch(n=>{throw new Ye({type:J.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:n,fatal:!0},n.message)}))}setupLicenseXHR(e,t,i,n){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return r.call(this.hls,e,t,i,n)}).catch(a=>{if(!i.decryptdata)throw a;return e.open("POST",t,!0),r.call(this.hls,e,t,i,n)}).then(a=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:a||n})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:n}))}requestLicense(e,t){const i=this.config.keyLoadPolicy.default;return new Promise((n,r)=>{const a=this.getLicenseServerUrl(e.keySystem);this.log(`Sending license request to URL: ${a}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let l=o.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);const c=this.config.licenseResponseCallback;if(c)try{l=c.call(this.hls,o,a,e)}catch(u){this.error(u)}n(l)}else{const l=i.errorRetry,c=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>c||o.status>=400&&o.status<500)r(new Ye({type:J.KEY_SYSTEM_ERROR,details:w.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{const u=c-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${u} attempts left`),this.requestLicense(e,t).then(n,r)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,t).then(({xhr:l,licenseChallenge:c})=>{l.send(c)})})}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const i=t.media;this.media=i,i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media,t=this.mediaKeySessions;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},zt.clearKeyUriToKeyIdMap();const i=t.length;Vt.CDMCleanupPromise=Promise.all(t.map(n=>this.removeSession(n)).concat(e==null?void 0:e.setMediaKeys(null).catch(n=>{this.log(`Could not clear media keys: ${n}. media.src: ${e==null?void 0:e.src}`)}))).then(()=>{i&&(this.log("finished closing key sessions and clearing media keys"),t.length=0)}).catch(n=>{this.log(`Could not close sessions and clear media keys: ${n}. media.src: ${e==null?void 0:e.src}`)})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const i=t.reduce((n,r)=>(n.indexOf(r.keyFormat)===-1&&n.push(r.keyFormat),n),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:i}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),t.onmessage=null,t.onkeystatuseschange=null,i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const n=this.mediaKeySessions.indexOf(e);return n>-1&&this.mediaKeySessions.splice(n,1),t.remove().catch(r=>{this.log(`Could not remove session: ${r}`)}).then(()=>t.close()).catch(r=>{this.log(`Could not close session: ${r}`)})}}}Vt.CDMCleanupPromise=void 0;class Ye extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}const Zu=1;var Pe={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"};const Ju="h";class yt{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.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=n=>{try{this.apply(n,{ot:Pe.MANIFEST,su:!this.initialized})}catch(r){C.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=n=>{try{const r=n.frag,a=this.hls.levels[r.level],o=this.getObjectType(r),l={d:r.duration*1e3,ot:o};(o===Pe.VIDEO||o===Pe.AUDIO||o==Pe.MUXED)&&(l.br=a.bitrate/1e3,l.tb=this.getTopBandwidth(o)/1e3,l.bl=this.getBufferLength(o)),this.apply(n,l)}catch(r){C.warn("Could not generate segment CMCD data.",r)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;i!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||yt.uuid(),this.cid=i.contentId,this.useHeaders=i.useHeaders===!0,this.registerListeners())}registerListeners(){const e=this.hls;e.on(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(y.MEDIA_DETACHED,this.onMediaDetached,this),e.on(y.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(y.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(y.MEDIA_DETACHED,this.onMediaDetached,this),e.off(y.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var i,n;this.audioBuffer=(i=t.tracks.audio)==null?void 0:i.buffer,this.videoBuffer=(n=t.tracks.video)==null?void 0:n.buffer}createData(){var e;return{v:Zu,sf:Ju,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){Te(t,this.createData());const i=t.ot===Pe.INIT||t.ot===Pe.VIDEO||t.ot===Pe.MUXED;if(this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering),this.useHeaders){const n=yt.toHeaders(t);if(!Object.keys(n).length)return;e.headers||(e.headers={}),Te(e.headers,n)}else{const n=yt.toQuery(t);if(!n)return;e.url=yt.appendQueryToUri(e.url,n)}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return Pe.TIMED_TEXT;if(e.sn==="initSegment")return Pe.INIT;if(t==="audio")return Pe.AUDIO;if(t==="main")return this.hls.audioTracks.length?Pe.VIDEO:Pe.MUXED}getTopBandwidth(e){let t=0,i;const n=this.hls;if(e===Pe.AUDIO)i=n.audioTracks;else{const r=n.maxAutoLevel,a=r>-1?r+1:n.levels.length;i=n.levels.slice(0,a)}for(const r of i)r.bitrate>t&&(t=r.bitrate);return t>0?t:NaN}getBufferLength(e){const t=this.hls.media,i=e===Pe.AUDIO?this.audioBuffer:this.videoBuffer;return!i||!t?NaN:ge.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new i(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,a,o){t(r),this.loader.load(r,a,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new i(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,a,o){t(r),this.loader.load(r,a,o)}}}static uuid(){const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}static serialize(e){const t=[],i=c=>!Number.isNaN(c)&&c!=null&&c!==""&&c!==!1,n=c=>Math.round(c),r=c=>n(c/100)*100,o={br:n,d:n,bl:r,dl:r,mtp:r,nor:c=>encodeURIComponent(c),rtp:r,tb:n},l=Object.keys(e||{}).sort();for(const c of l){let u=e[c];if(!i(u)||c==="v"&&u===1||c=="pr"&&u===1)continue;const h=o[c];h&&(u=h(u));const d=typeof u;let f;c==="ot"||c==="sf"||c==="st"?f=`${c}=${u}`:d==="boolean"?f=c:d==="number"?f=`${c}=${u}`:f=`${c}=${JSON.stringify(u)}`,t.push(f)}return t.join(",")}static toHeaders(e){const t=Object.keys(e),i={},n=["Object","Request","Session","Status"],r=[{},{},{},{}],a={br:0,d:0,ot:0,tb:0,bl:1,dl:1,mtp:1,nor:1,nrr:1,su:1,cid:2,pr:2,sf:2,sid:2,st:2,v:2,bs:3,rtp:3};for(const o of t){const l=a[o]!=null?a[o]:1;r[l][o]=e[o]}for(let o=0;oi!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:i}=t;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:i}=t;if((i==null?void 0:i.action)===xe.SendAlternateToPenaltyBox&&i.flags===Ke.MoveAllAlternatesMatchingHost){let n=this.pathwayPriority;const r=this.pathwayId;this.penalizedPathways[r]||(this.penalizedPathways[r]=performance.now()),!n&&this.levels&&(n=this.levels.reduce((a,o)=>(a.indexOf(o.pathwayId)===-1&&a.push(o.pathwayId),a),[])),n&&n.length>1&&(this.updatePathwayPriority(n),i.resolved=this.pathwayId!==r)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length?(this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t):e}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this.pathwayPriority=e;let t;const i=this.penalizedPathways,n=performance.now();Object.keys(i).forEach(r=>{n-i[r]>eh&&delete i[r]});for(let r=0;r0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,this.hls.trigger(y.LEVELS_UPDATED,{levels:t});const c=this.hls.levels[o];l&&c&&this.levels&&(c.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&c.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${c.bitrate}`),this.hls.nextLoadLevel=o);break}}}clonePathways(e){const t=this.levels;if(!t)return;const i={},n={};e.forEach(r=>{const{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=r;if(t.some(u=>u.pathwayId===a))return;const c=this.getLevelsForPathway(o).map(u=>{const h=Te({},u);h.details=void 0,h.url=ha(u.uri,u.attrs["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l);const d=new me(u.attrs);d["PATHWAY-ID"]=a;const f=d.AUDIO&&`${d.AUDIO}_clone_${a}`,g=d.SUBTITLES&&`${d.SUBTITLES}_clone_${a}`;f&&(i[d.AUDIO]=f,d.AUDIO=f),g&&(n[d.SUBTITLES]=g,d.SUBTITLES=g),h.attrs=d;const v=new qt(h);return pi(v,"audio",f),pi(v,"text",g),v});t.push(...c),ua(this.audioTracks,i,l,a),ua(this.subtitleTracks,n,l,a)})}loadSteeringManifest(e){const t=this.hls.config,i=t.loader;this.loader&&this.loader.destroy(),this.loader=new i(t);let n;try{n=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(n.protocol!=="data:"){const u=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;n.searchParams.set("_HLS_pathway",this.pathwayId),n.searchParams.set("_HLS_throughput",""+u)}const r={responseType:"json",url:n.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},c={onSuccess:(u,h,d,f)=>{this.log(`Loaded steering manifest: "${n}"`);const g=u.data;if(g.VERSION!==1){this.log(`Steering VERSION ${g.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=g.TTL;const{"RELOAD-URI":v,"PATHWAY-CLONES":A,"PATHWAY-PRIORITY":T}=g;if(v)try{this.uri=new self.URL(v,n).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${v}`);return}this.scheduleRefresh(this.uri||d.url),A&&this.clonePathways(A),T&&this.updatePathwayPriority(T)},onError:(u,h,d,f)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${h.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${h.url} no longer available`);return}let g=this.timeToLoad*1e3;if(u.code===429){const v=this.loader;if(typeof(v==null?void 0:v.getResponseHeader)=="function"){const A=v.getResponseHeader("Retry-After");A&&(g=parseFloat(A)*1e3)}this.log(`Steering manifest ${h.url} rate limited`);return}this.scheduleRefresh(this.uri||h.url,g)},onTimeout:(u,h,d)=>{this.log(`Timeout loading steering manifest (${h.url})`),this.scheduleRefresh(this.uri||h.url)}};this.log(`Requesting steering manifest: ${n}`),this.loader.load(r,l,c)}scheduleRefresh(e,t=this.timeToLoad*1e3){self.clearTimeout(this.reloadTimer),this.reloadTimer=self.setTimeout(()=>{this.loadSteeringManifest(e)},t)}}function ua(s,e,t,i){s&&Object.keys(e).forEach(n=>{const r=s.filter(a=>a.groupId===n).map(a=>{const o=Te({},a);return o.details=void 0,o.attrs=new me(o.attrs),o.url=o.attrs.URI=ha(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[n],o.attrs["PATHWAY-ID"]=i,o});s.push(...r)})}function ha(s,e,t,i){const{HOST:n,PARAMS:r,[t]:a}=i;let o;e&&(o=a==null?void 0:a[e],o&&(s=o));const l=new self.URL(s);return n&&!o&&(l.host=n),r&&Object.keys(r).sort().forEach(c=>{c&&l.searchParams.set(c,r[c])}),l.href}const ih=/^age:\s*[\d.]+\s*$/im;class da{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=void 0,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new ai,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,i){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e)return;const i=this.loader=new self.XMLHttpRequest,n=this.stats;n.loading.first=0,n.loaded=0,n.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!this.stats.aborted)return r(i,t.url)}).catch(a=>(i.open("GET",t.url,!0),r(i,t.url))).then(()=>{this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(a=>{this.callbacks.onError({code:i.status,text:a.message},t,i,n)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);const n=this.context.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:a}=i.loadPolicy;if(n)for(const o in n)e.setRequestHeader(o,n[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=r&&Z(r)?r:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:i}=this;if(!e||!t)return;const n=t.readyState,r=this.config;if(!i.aborted&&n>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),n===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const a=t.status,o=t.responseType!=="text";if(a>=200&&a<300&&(o&&t.response||t.responseText!==null)){i.loading.end=Math.max(self.performance.now(),i.loading.first);const l=o?t.response:t.responseText,c=t.responseType==="arraybuffer"?l.byteLength:l.length;if(i.loaded=i.total=c,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first),!this.callbacks)return;const u=this.callbacks.onProgress;if(u&&u(i,e,l,t),!this.callbacks)return;const h={url:t.responseURL,data:l,code:a};this.callbacks.onSuccess(h,i,e,t)}else{const l=r.loadPolicy.errorRetry,c=i.retry;gi(l,c,!1,a)?this.retry(l):(C.error(`${a} while loading ${e.url}`),this.callbacks.onError({code:a,text:t.statusText},e,t,i))}}}loadtimeout(){var e;const t=(e=this.config)==null?void 0:e.loadPolicy.timeoutRetry,i=this.stats.retry;if(gi(t,i,!0))this.retry(t);else{C.warn(`timeout while loading ${this.context.url}`);const n=this.callbacks;n&&(this.abortInternal(),n.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=un(e,i.retry),i.retry++,C.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&ih.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}function nh(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const rh=/(\d+)-(\d+)\/(\d+)/;class fa{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=void 0,this.response=void 0,this.controller=void 0,this.context=void 0,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||lh,this.controller=new self.AbortController,this.stats=new ai}destroy(){this.loader=this.callbacks=null,this.abortInternal()}abortInternal(){const e=this.response;e!=null&&e.ok||(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,i){const n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now();const r=sh(e,this.controller.signal),a=i.onProgress,o=e.responseType==="arraybuffer",l=o?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:u}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=c&&Z(c)?c:u,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(n,e,this.response)},t.timeout),self.fetch(this.request).then(h=>{this.response=this.loader=h;const d=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=u,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(n,e,this.response)},u-(d-n.loading.start)),!h.ok){const{status:f,statusText:g}=h;throw new ch(g||"fetch, bad network response",f,h)}return n.loading.first=d,n.total=oh(h.headers)||n.total,a&&Z(t.highWaterMark)?this.loadProgressively(h,n,e,t.highWaterMark,a):o?h.arrayBuffer():e.responseType==="json"?h.json():h.text()}).then(h=>{const{response:d}=this;self.clearTimeout(this.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);const f=h[l];f&&(n.loaded=n.total=f);const g={url:d.url,data:h,code:d.status};a&&!Z(t.highWaterMark)&&a(n,e,h,d),i.onSuccess(g,n,e,d)}).catch(h=>{if(self.clearTimeout(this.requestTimeout),n.aborted)return;const d=h&&h.code||0,f=h?h.message:null;i.onError({code:d,text:f},e,h?h.details:null,n)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,n=0,r){const a=new Vs,o=e.body.getReader(),l=()=>o.read().then(c=>{if(c.done)return a.dataLength&&r(t,i,a.flush(),e),Promise.resolve(new ArrayBuffer(0));const u=c.value,h=u.length;return t.loaded+=h,h=n&&r(t,i,a.flush(),e)):r(t,i,u,e),l()}).catch(()=>Promise.reject());return l()}}function sh(s,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(Te({},s.headers))};return s.rangeEnd&&t.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),t}function ah(s){const e=rh.exec(s);if(e)return parseInt(e[2])-parseInt(e[1])+1}function oh(s){const e=s.get("Content-Range");if(e){const i=ah(e);if(Z(i))return i}const t=s.get("Content-Length");if(t)return parseInt(t)}function lh(s,e){return new self.Request(s.url,e)}class ch extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const uh=/\s/,hh={newCue(s,e,t,i){const n=[];let r,a,o,l,c;const u=self.VTTCue||self.TextTrackCue;for(let d=0;d=16?l--:l++;const f=ia(c.trim()),g=Nn(e,t,f);s!=null&&(h=s.cues)!=null&&h.getCueById(g)||(a=new u(e,t,f),a.id=g,a.line=d+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),n.push(a))}return s&&n.length&&(n.sort((d,f)=>d.line==="auto"||f.line==="auto"?0:d.line>8&&f.line>8?f.line-d.line:d.line-f.line),n.forEach(d=>rs(s,d))),n}},dh={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},fh=Re(Re({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,maxBufferSize:60*1e3*1e3,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:da,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:yu,bufferController:xu,capLevelController:$n,errorController:cc,fpsController:Qu,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Dr,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,certLoadPolicy:{default:dh},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},gh()),{},{subtitleStreamController:bu,subtitleTrackController:_u,timelineController:ju,audioStreamController:Au,audioTrackController:Eu,emeController:Vt,cmcdController:yt,contentSteeringController:th});function gh(){return{cueHandler:hh,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function ph(s,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const t=Vn(s),i=["manifest","level","frag"],n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(r=>{const a=`${r==="level"?"playlist":r}LoadPolicy`,o=e[a]===void 0,l=[];n.forEach(c=>{const u=`${r}Loading${c}`,h=e[u];if(h!==void 0&&o){l.push(u);const d=t[a].default;switch(e[a]={default:d},c){case"TimeOut":d.maxLoadTimeMs=h,d.maxTimeToFirstByteMs=h;break;case"MaxRetry":d.errorRetry.maxNumRetry=h,d.timeoutRetry.maxNumRetry=h;break;case"RetryDelay":d.errorRetry.retryDelayMs=h,d.timeoutRetry.retryDelayMs=h;break;case"MaxRetryTimeout":d.errorRetry.maxRetryDelayMs=h,d.timeoutRetry.maxRetryDelayMs=h;break}}}),l.length&&C.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${a}": ${JSON.stringify(e[a])}`)}),Re(Re({},t),e)}function Vn(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(Vn):Object.keys(s).reduce((e,t)=>(e[t]=Vn(s[t]),e),{}):s}function mh(s){const e=s.loader;e!==fa&&e!==da?(C.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=!1):nh()&&(s.loader=fa,s.progressive=!0,s.enableSoftwareAES=!0,C.log("[config]: Progressive streaming enabled, using FetchLoader"))}class ce{static get version(){return"1.4.10"}static isSupported(){return Lc()}static get Events(){return y}static get ErrorTypes(){return J}static get ErrorDetails(){return w}static get DefaultConfig(){return ce.defaultConfig?ce.defaultConfig:fh}static set DefaultConfig(e){ce.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new xn,this._autoLevelCapping=void 0,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,el(e.debug||!1,"Hls instance");const t=this.config=ph(ce.DefaultConfig,e);this.userConfig=e,this._autoLevelCapping=-1,t.progressive&&mh(t);const{abrController:i,bufferController:n,capLevelController:r,errorController:a,fpsController:o}=t,l=new a(this),c=this.abrController=new i(this),u=this.bufferController=new n(this),h=this.capLevelController=new r(this),d=new o(this),f=new Hl(this),g=new ql(this),v=t.contentSteeringController,A=v?new v(this):null,T=this.levelController=new hc(this,A),x=new dc(this),_=new gc(this.config),P=this.streamController=new pu(this,x,_);h.setStreamController(P),d.setStreamController(P);const L=[f,T,P];A&&L.splice(1,0,A),this.networkControllers=L;const G=[c,u,h,d,g,x];this.audioTrackController=this.createController(t.audioTrackController,L);const O=t.audioStreamController;O&&L.push(new O(this,x,_)),this.subtitleTrackController=this.createController(t.subtitleTrackController,L);const B=t.subtitleStreamController;B&&L.push(new B(this,x,_)),this.createController(t.timelineController,G),_.emeController=this.emeController=this.createController(t.emeController,G),this.cmcdController=this.createController(t.cmcdController,G),this.latencyController=this.createController(Xl,G),this.coreComponents=G,L.push(l);const k=l.onErrorOut;typeof k=="function"&&this.on(y.ERROR,k,l)}createController(e,t){if(e){const i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,n){this._emitter.off(e,t,i,n)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(i){C.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),this.trigger(y.ERROR,{type:J.OTHER_ERROR,details:w.INTERNAL_EXCEPTION,fatal:!1,event:e,error:i})}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){C.log("destroy"),this.trigger(y.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 e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){C.log("attachMedia"),this._media=e,this.trigger(y.MEDIA_ATTACHING,{media:e})}detachMedia(){C.log("detachMedia"),this.trigger(y.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();const t=this.media,i=this.url,n=this.url=Wi.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});C.log(`loadSource:${n}`),t&&i&&(i!==n||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(y.MANIFEST_LOADING,{url:e})}startLoad(e=-1){C.log(`startLoad(${e})`),this.networkControllers.forEach(t=>{t.startLoad(e)})}stopLoad(){C.log("stopLoad"),this.networkControllers.forEach(e=>{e.stopLoad()})}swapAudioCodec(){C.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){C.log("recoverMediaError");const e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e,t=0){this.levelController.removeLevel(e,t)}get levels(){const e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){C.log(`set currentLevel:${e}`),this.loadLevel=e,this.abrController.clearTimer(),this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){C.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){C.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){C.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){return this.levelController.startLevel}set startLevel(e){C.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(C.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e)}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){on.indexOf(e)>-1&&(this._maxHdcpLevel=e)}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const i=e.length;for(let n=0;n=t)return n;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this;let n;if(t===-1&&e&&e.length?n=e.length-1:n=t,i)for(let r=n;r--;){const a=e[r].attrs["HDCP-LEVEL"];if(a&&a<=i)return r}return n}get nextAutoLevel(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)}set nextAutoLevel(e){this.abrController.nextAutoLevel=Math.max(this.minAutoLevel,e)}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}ce.defaultConfig=void 0;var yh=rt.now,vh=rt.listContainsIgnoreCase,Ah=-1,Eh=16;p.register("PLAYBACK_FRAGMENT_CHANGED"),p.register("PLAYBACK_FRAGMENT_PARSING_METADATA");var ga=function(s){Fo(t,s);var e=$o(t);function t(){var i;Po(this,t);for(var n=arguments.length,r=new Array(n),a=0;a"u"?60:this.options.hlsMinimumDvrSize,this._extrapolatedWindowNumSegments=!this.options.playback||typeof this.options.playback.extrapolatedWindowNumSegments>"u"?2:this.options.playback.extrapolatedWindowNumSegments,this._playbackType=se.VOD,this._lastTimeUpdate={current:0,total:0},this._lastDuration=null,this._playableRegionStartTime=0,this._localStartTimeCorrelation=null,this._localEndTimeCorrelation=null,this._playableRegionDuration=0,this._programDateTime=0,this._durationExcludesAfterLiveSyncPoint=!1,this._segmentTargetDuration=null,this._playlistType=null,this._recoverAttemptsRemaining=this.options.hlsRecoverAttempts||Eh}},{key:"_setup",value:function(){this._destroyHLSInstance(),this._createHLSInstance(),this._listenHLSEvents(),this._attachHLSMedia()}},{key:"_destroyHLSInstance",value:function(){this._hls&&(this._manifestParsed=!1,this._ccIsSetup=!1,this._ccTracksUpdated=!1,this._setInitialState(),this._hls.destroy(),this._hls=null)}},{key:"_createHLSInstance",value:function(){var n=Ki({},this.options.playback.hlsjsConfig);this._hls=new ce(n)}},{key:"_attachHLSMedia",value:function(){this._hls&&this._hls.attachMedia(this.el)}},{key:"_listenHLSEvents",value:function(){var n=this;this._hls&&(this._hls.once(ce.Events.MEDIA_ATTACHED,function(){n.options.hlsPlayback.preload&&n._hls.loadSource(n.options.src)}),this._hls.on(ce.Events.MANIFEST_PARSED,function(){return n._manifestParsed=!0}),this._hls.on(ce.Events.LEVEL_LOADED,function(r,a){return n._updatePlaybackType(r,a)}),this._hls.on(ce.Events.LEVEL_UPDATED,function(r,a){return n._onLevelUpdated(r,a)}),this._hls.on(ce.Events.LEVEL_SWITCHING,function(r,a){return n._onLevelSwitch(r,a)}),this._hls.on(ce.Events.FRAG_CHANGED,function(r,a){return n._onFragmentChanged(r,a)}),this._hls.on(ce.Events.FRAG_LOADED,function(r,a){return n._onFragmentLoaded(r,a)}),this._hls.on(ce.Events.FRAG_PARSING_METADATA,function(r,a){return n._onFragmentParsingMetadata(r,a)}),this._hls.on(ce.Events.ERROR,function(r,a){return n._onHLSJSError(r,a)}),this._hls.on(ce.Events.SUBTITLE_TRACK_LOADED,function(r,a){return n._onSubtitleLoaded(r,a)}),this._hls.on(ce.Events.SUBTITLE_TRACKS_UPDATED,function(){return n._ccTracksUpdated=!0}),this.bindCustomListeners())}},{key:"bindCustomListeners",value:function(){var n=this;this.customListeners.forEach(function(r){var a=r.eventName,o=r.once?"once":"on";a&&n._hls["".concat(o)](a,r.callback)})}},{key:"unbindCustomListeners",value:function(){var n=this;this.customListeners.forEach(function(r){var a=r.eventName;a&&n._hls.off(a,r.callback)})}},{key:"_onFragmentParsingMetadata",value:function(n,r){this.trigger(p.Custom.PLAYBACK_FRAGMENT_PARSING_METADATA,{evt:n,data:r})}},{key:"render",value:function(){return this._ready(),gt(Ze(t.prototype),"render",this).call(this)}},{key:"_ready",value:function(){this._isReadyState||(!this._hls&&this._setup(),this._isReadyState=!0,this.trigger(p.PLAYBACK_READY,this.name))}},{key:"_recover",value:function(n,r,a){if(!this._recoveredDecodingError)this._recoveredDecodingError=!0,this._hls.recoverMediaError();else if(!this._recoveredAudioCodecError)this._recoveredAudioCodecError=!0,this._hls.swapAudioCodec(),this._hls.recoverMediaError();else{ae.error("hlsjs: failed to recover",{evt:n,data:r}),a.level=Ve.Levels.FATAL;var o=this.createError(a);this.trigger(p.PLAYBACK_ERROR,o),this.stop()}}},{key:"_setupSrc",value:function(n){}},{key:"_startTimeUpdateTimer",value:function(){var n=this;this._timeUpdateTimer||(this._timeUpdateTimer=setInterval(function(){n._onDurationChange(),n._onTimeUpdate()},100))}},{key:"_stopTimeUpdateTimer",value:function(){this._timeUpdateTimer&&(clearInterval(this._timeUpdateTimer),this._timeUpdateTimer=null)}},{key:"getProgramDateTime",value:function(){return this._programDateTime}},{key:"getDuration",value:function(){return this._duration}},{key:"getCurrentTime",value:function(){return Math.max(0,this.el.currentTime-this._startTime)}},{key:"getStartTimeOffset",value:function(){return this._startTime}},{key:"seekPercentage",value:function(n){var r=n>0?this._duration*(n/100):this._duration;this.seek(r)}},{key:"seek",value:function(n){n<0&&(ae.warn("Attempt to seek to a negative time. Resetting to live point. Use seekToLivePoint() to seek to the live point."),n=this.getDuration()),this.dvrEnabled&&this._updateDvr(n0)switch(this._recoverAttemptsRemaining-=1,r.type){case ce.ErrorTypes.NETWORK_ERROR:switch(r.details){case ce.ErrorDetails.MANIFEST_LOAD_ERROR:case ce.ErrorDetails.MANIFEST_LOAD_TIMEOUT:case ce.ErrorDetails.MANIFEST_PARSING_ERROR:case ce.ErrorDetails.LEVEL_LOAD_ERROR:case ce.ErrorDetails.LEVEL_LOAD_TIMEOUT:ae.error("hlsjs: unrecoverable network fatal error.",{evt:n,data:r}),o=this.createError(a),this.trigger(p.PLAYBACK_ERROR,o),this.stop();break;default:ae.warn("hlsjs: trying to recover from network error.",{evt:n,data:r}),a.level=Ve.Levels.WARN,this._hls.startLoad();break}break;case ce.ErrorTypes.MEDIA_ERROR:ae.warn("hlsjs: trying to recover from media error.",{evt:n,data:r}),a.level=Ve.Levels.WARN,this._recover(n,r,a);break;default:ae.error("hlsjs: could not recover from error.",{evt:n,data:r}),o=this.createError(a),this.trigger(p.PLAYBACK_ERROR,o),this.stop();break}else ae.error("hlsjs: could not recover from error after maximum number of attempts.",{evt:n,data:r}),o=this.createError(a),this.trigger(p.PLAYBACK_ERROR,o),this.stop();else{if(this.options.playback.triggerFatalErrorOnResourceDenied&&this._keyIsDenied(r)){ae.error("hlsjs: could not load decrypt key.",{evt:n,data:r}),o=this.createError(a),this.trigger(p.PLAYBACK_ERROR,o),this.stop();return}a.level=Ve.Levels.WARN,ae.warn("hlsjs: non-fatal error occurred",{evt:n,data:r})}}},{key:"_keyIsDenied",value:function(n){return n.type===ce.ErrorTypes.NETWORK_ERROR&&n.details===ce.ErrorDetails.KEY_LOAD_ERROR&&n.response&&n.response.code>=400}},{key:"_onTimeUpdate",value:function(){var n={current:this.getCurrentTime(),total:this.getDuration(),firstFragDateTime:this.getProgramDateTime()},r=this._lastTimeUpdate&&n.current===this._lastTimeUpdate.current&&n.total===this._lastTimeUpdate.total;r||(this._lastTimeUpdate=n,this.trigger(p.PLAYBACK_TIMEUPDATE,n,this.name))}},{key:"_onDurationChange",value:function(){var n=this.getDuration();this._lastDuration!==n&&(this._lastDuration=n,gt(Ze(t.prototype),"_onDurationChange",this).call(this))}},{key:"_onProgress",value:function(){if(this.el.buffered.length){for(var n=[],r=0,a=0;a=n[a].start&&this.el.currentTime<=n[a].end&&(r=a);var o={start:n[r].start,current:n[r].end,total:this.getDuration()};this.trigger(p.PLAYBACK_PROGRESS,o,n)}}},{key:"load",value:function(n){this._stopTimeUpdateTimer(),this.options.src=n,this._setup()}},{key:"play",value:function(){!this._hls&&this._setup(),!this._manifestParsed&&!this.options.hlsPlayback.preload&&this._hls.loadSource(this.options.src),gt(Ze(t.prototype),"play",this).call(this),this._startTimeUpdateTimer()}},{key:"pause",value:function(){this._hls&&(this.el.pause(),this.dvrEnabled&&this._updateDvr(!0))}},{key:"stop",value:function(){this._stopTimeUpdateTimer(),this._hls&>(Ze(t.prototype),"stop",this).call(this),this._destroyHLSInstance()}},{key:"destroy",value:function(){this._stopTimeUpdateTimer(),this._destroyHLSInstance(),gt(Ze(t.prototype),"destroy",this).call(this)}},{key:"_updatePlaybackType",value:function(n,r){this._playbackType=r.details.live?se.LIVE:se.VOD,this._onLevelUpdated(n,r),this._ccTracksUpdated&&this._playbackType===se.LIVE&&this.hasClosedCaptionsTracks&&this._onSubtitleLoaded()}},{key:"_fillLevels",value:function(){this._levels=this._hls.levels.map(function(n,r){return{id:r,level:n,label:"".concat(n.bitrate/1e3,"Kbps")}}),this.trigger(p.PLAYBACK_LEVELS_AVAILABLE,this._levels)}},{key:"_onLevelUpdated",value:function(n,r){this._segmentTargetDuration=r.details.targetduration,this._playlistType=r.details.type||null;var a=!1,o=!1,l=r.details.fragments,c=this._playableRegionStartTime,u=this._playableRegionDuration;if(l.length!==0){if(l[0].rawProgramDateTime&&(this._programDateTime=l[0].rawProgramDateTime),this._playableRegionStartTime!==l[0].start&&(a=!0,this._playableRegionStartTime=l[0].start),a)if(!this._localStartTimeCorrelation)this._localStartTimeCorrelation={local:this._now,remote:(l[0].start+this._extrapolatedWindowDuration/2)*1e3};else{var h=this._localStartTimeCorrelation,d=this._now-h.local,f=(h.remote+d)/1e3;fc+this._extrapolatedWindowDuration&&(this._localStartTimeCorrelation={local:this._now,remote:Math.max(l[0].start,c+this._extrapolatedWindowDuration)*1e3})}var g=r.details.totalduration;if(this._playbackType===se.LIVE){var v=r.details.targetduration,A=this.options.playback.hlsjsConfig||{},T=A.liveSyncDurationCount||ce.DefaultConfig.liveSyncDurationCount,x=v*T;x<=g?(g-=x,this._durationExcludesAfterLiveSyncPoint=!0):this._durationExcludesAfterLiveSyncPoint=!1}g!==this._playableRegionDuration&&(o=!0,this._playableRegionDuration=g);var _=l[0].start+g,P=c+u,L=_!==P;if(L)if(!this._localEndTimeCorrelation)this._localEndTimeCorrelation={local:this._now,remote:_*1e3};else{var G=this._localEndTimeCorrelation,O=this._now-G.local,B=(G.remote+O)/1e3;B>_?this._localEndTimeCorrelation={local:this._now,remote:_*1e3}:B<_-this._extrapolatedWindowDuration?this._localEndTimeCorrelation={local:this._now,remote:(_-this._extrapolatedWindowDuration)*1e3}:B>P&&(this._localEndTimeCorrelation={local:this._now,remote:P*1e3})}o&&this._onDurationChange(),a&&this._onProgress()}}},{key:"_onFragmentChanged",value:function(n,r){this.trigger(p.Custom.PLAYBACK_FRAGMENT_CHANGED,r)}},{key:"_onFragmentLoaded",value:function(n,r){this.trigger(p.PLAYBACK_FRAGMENT_LOADED,r)}},{key:"_onSubtitleLoaded",value:function(){if(!this._ccIsSetup){this.trigger(p.PLAYBACK_SUBTITLE_AVAILABLE);var n=this._playbackType===se.LIVE?-1:this.closedCaptionsTrackId;this.closedCaptionsTrackId=n,this._ccIsSetup=!0}}},{key:"_onLevelSwitch",value:function(n,r){this.levels.length||this._fillLevels(),this.trigger(p.PLAYBACK_LEVEL_SWITCH_END),this.trigger(p.PLAYBACK_LEVEL_SWITCH,r);var a=this._hls.levels[r.level];a&&(this.highDefinition=a.height>=720||a.bitrate/1e3>=2e3,this.trigger(p.PLAYBACK_HIGHDEFINITIONUPDATE,this.highDefinition),this.trigger(p.PLAYBACK_BITRATE,{height:a.height,width:a.width,bandwidth:a.bitrate,bitrate:a.bitrate,level:r.level}))}},{key:"dvrEnabled",get:function(){return this._durationExcludesAfterLiveSyncPoint&&this._duration>=this._minDvrSize&&this.getPlaybackType()===se.LIVE}},{key:"getPlaybackType",value:function(){return this._playbackType}},{key:"isSeekEnabled",value:function(){return this._playbackType===se.VOD||this.dvrEnabled}}],[{key:"HLSJS",get:function(){return ce}}]),t}(Ge);ga.canPlay=function(s,e){var t=s.split("?")[0].match(/.*\.(.*)$/)||[],i=t.length>1&&t[1].toLowerCase()==="m3u8"||vh(e,["application/vnd.apple.mpegurl","application/x-mpegURL"]);return!!(ce.isSupported()&&i)};function Fe(s,e){if(!(s instanceof e))throw new TypeError("Cannot call a class as a function")}function pa(s,e){for(var t=0;t"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function bh(s){if(s===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return s}function ma(s,e){if(e&&(typeof e=="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return bh(s)}function Ue(s){var e=Th();return function(){var i=vt(s),n;if(e){var r=vt(this).constructor;n=Reflect.construct(i,arguments,r)}else n=i.apply(this,arguments);return ma(this,n)}}function Sh(s,e){for(;!Object.prototype.hasOwnProperty.call(s,e)&&(s=vt(s),s!==null););return s}function Gt(){return typeof Reflect<"u"&&Reflect.get?Gt=Reflect.get.bind():Gt=function(e,t,i){var n=Sh(e,t);if(n){var r=Object.getOwnPropertyDescriptor(n,t);return r.get?r.get.call(arguments.length<3?e:i):r.value}},Gt.apply(this,arguments)}function _h(s,e){if(typeof s!="object"||s===null)return s;var t=s[Symbol.toPrimitive];if(t!==void 0){var i=t.call(s,e||"default");if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(s)}function kh(s){var e=_h(s,"string");return typeof e=="symbol"?e:String(e)}var xh=function(s){Be(t,s);var e=Ue(t);function t(i){return Fe(this,t),e.call(this,i)}return Me(t,[{key:"name",get:function(){return"click_to_pause"}},{key:"supportedVersion",get:function(){return{min:"0.4.27"}}},{key:"config",get:function(){return this.container.options.clickToPauseConfig||{}}},{key:"bindEvents",value:function(){this.listenTo(this.container,p.CONTAINER_CLICK,this.click),this.listenTo(this.container,p.CONTAINER_SETTINGSUPDATE,this.settingsUpdate)}},{key:"click",value:function(){var n=this.config.onClickPayload;(this.container.getPlaybackType()!==se.LIVE||this.container.isDvrEnabled())&&(this.container.isPlaying()?this.container.pause(n):this.container.play(n))}},{key:"settingsUpdate",value:function(){var n=this.container.getPlaybackType()!==se.LIVE||this.container.isDvrEnabled();if(n!==this.pointerEnabled){var r=n?"addClass":"removeClass";this.container.$el[r]("pointer-enabled"),this.pointerEnabled=n}}}]),t}(at),Ch=` `,Lh=` `,Ih=`.cc-controls[data-cc-controls] { float: right; position: relative; display: none; } .cc-controls[data-cc-controls].available { display: block; } .cc-controls[data-cc-controls] .cc-button { padding: 6px !important; } .cc-controls[data-cc-controls] .cc-button.enabled { display: block; opacity: 1.0; } .cc-controls[data-cc-controls] .cc-button.enabled:hover { opacity: 1.0; text-shadow: none; } .cc-controls[data-cc-controls] > ul { list-style-type: none; position: absolute; bottom: 25px; border: 1px solid black; display: none; background-color: #e6e6e6; } .cc-controls[data-cc-controls] li { font-size: 10px; } .cc-controls[data-cc-controls] li[data-title] { background-color: #c3c2c2; padding: 5px; } .cc-controls[data-cc-controls] li a { color: #444; padding: 2px 10px; display: block; text-decoration: none; } .cc-controls[data-cc-controls] li a:hover { background-color: #555; color: white; } .cc-controls[data-cc-controls] li a:hover a { color: white; text-decoration: none; } .cc-controls[data-cc-controls] li.current a { color: #f00; } `,Rh=function(s){Be(t,s);var e=Ue(t);function t(i){var n;Fe(this,t),n=e.call(this,i);var r=i.options.closedCaptionsConfig;return n._title=r&&r.title?r.title:null,n._ariaLabel=r&&r.ariaLabel?r.ariaLabel:"cc-button",n._labelCb=r&&r.labelCallback&&typeof r.labelCallback=="function"?r.labelCallback:function(a){return a.name},n}return Me(t,[{key:"name",get:function(){return"closed_captions"}},{key:"supportedVersion",get:function(){return{min:"0.4.27"}}},{key:"template",get:function(){return Ie(Lh)}},{key:"events",get:function(){return{"click [data-cc-button]":"toggleContextMenu","click [data-cc-select]":"onTrackSelect"}}},{key:"attributes",get:function(){return{class:"cc-controls","data-cc-controls":""}}},{key:"bindEvents",value:function(){this.listenTo(this.core,p.CORE_ACTIVE_CONTAINER_CHANGED,this.containerChanged),this.listenTo(this.core.mediaControl,p.MEDIACONTROL_RENDERED,this.render),this.listenTo(this.core.mediaControl,p.MEDIACONTROL_HIDE,this.hideContextMenu),this.bindContainerEvents()}},{key:"bindContainerEvents",value:function(){this.container=this.core.activeContainer,this.container&&(this.listenTo(this.container,p.CONTAINER_SUBTITLE_AVAILABLE,this.onSubtitleAvailable),this.listenTo(this.container,p.CONTAINER_SUBTITLE_CHANGED,this.onSubtitleChanged),this.listenTo(this.container,p.CONTAINER_STOP,this.onContainerStop))}},{key:"onContainerStop",value:function(){this.ccAvailable(!1)}},{key:"containerChanged",value:function(){this.ccAvailable(!1),this.stopListening(),this.bindEvents()}},{key:"onSubtitleAvailable",value:function(){this.renderCcButton(),this.ccAvailable(!0)}},{key:"onSubtitleChanged",value:function(n){this.setCurrentContextMenuElement(n.id)}},{key:"onTrackSelect",value:function(n){var r=parseInt(n.target.dataset.ccSelect,10);return this.container.closedCaptionsTrackId=r,this.hideContextMenu(),n.stopPropagation(),!1}},{key:"ccAvailable",value:function(n){var r=n?"addClass":"removeClass";this.$el[r]("available")}},{key:"toggleContextMenu",value:function(){this.$el.find("ul").toggle()}},{key:"hideContextMenu",value:function(){this.$el.find("ul").hide()}},{key:"contextMenuElement",value:function(n){return this.$el.find("ul a"+(isNaN(n)?"":'[data-cc-select="'+n+'"]')).parent()}},{key:"setCurrentContextMenuElement",value:function(n){if(this._trackId!==n){this.contextMenuElement().removeClass("current"),this.contextMenuElement(n).addClass("current");var r=n>-1?"addClass":"removeClass";this.$ccButton[r]("enabled"),this._trackId=n}}},{key:"renderCcButton",value:function(){for(var n=this.container?this.container.closedCaptionsTracks:[],r=0;r<%= live %>
`,wh=`.dvr-controls[data-dvr-controls] { display: inline-block; float: left; color: #fff; line-height: 32px; font-size: 10px; font-weight: bold; margin-left: 6px; } .dvr-controls[data-dvr-controls] .live-info { cursor: default; font-family: "Roboto", "Open Sans", Arial, sans-serif; text-transform: uppercase; } .dvr-controls[data-dvr-controls] .live-info:before { content: ""; display: inline-block; position: relative; width: 7px; height: 7px; border-radius: 3.5px; margin-right: 3.5px; background-color: #ff0101; } .dvr-controls[data-dvr-controls] .live-info.disabled { opacity: 0.3; } .dvr-controls[data-dvr-controls] .live-info.disabled:before { background-color: #fff; } .dvr-controls[data-dvr-controls] .live-button { cursor: pointer; outline: none; display: none; border: 0; color: #fff; background-color: transparent; height: 32px; padding: 0; opacity: 0.7; font-family: "Roboto", "Open Sans", Arial, sans-serif; text-transform: uppercase; transition: all 0.1s ease; } .dvr-controls[data-dvr-controls] .live-button:before { content: ""; display: inline-block; position: relative; width: 7px; height: 7px; border-radius: 3.5px; margin-right: 3.5px; background-color: #fff; } .dvr-controls[data-dvr-controls] .live-button:hover { opacity: 1; text-shadow: rgba(255, 255, 255, 0.75) 0 0 5px; } .dvr .dvr-controls[data-dvr-controls] .live-info { display: none; } .dvr .dvr-controls[data-dvr-controls] .live-button { display: block; } .dvr.media-control.live[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar] { background-color: #005aff; } .media-control.live[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar] { background-color: #ff0101; } `,Ph=function(s){Be(t,s);var e=Ue(t);function t(i){var n;return Fe(this,t),n=e.call(this,i),n.settingsUpdate(),n}return Me(t,[{key:"template",get:function(){return Ie(Dh)}},{key:"name",get:function(){return"dvr_controls"}},{key:"supportedVersion",get:function(){return{min:"0.4.27"}}},{key:"events",get:function(){return{"click .live-button":"click"}}},{key:"attributes",get:function(){return{class:"dvr-controls","data-dvr-controls":""}}},{key:"bindEvents",value:function(){this.bindCoreEvents(),this.bindContainerEvents()}},{key:"bindCoreEvents",value:function(){var n=this;this.core.mediaControl.settings?(this.listenTo(this.core.mediaControl,p.MEDIACONTROL_CONTAINERCHANGED,this.containerChanged),this.listenTo(this.core.mediaControl,p.MEDIACONTROL_RENDERED,this.settingsUpdate),this.listenTo(this.core,p.CORE_OPTIONS_CHANGE,this.render)):setTimeout(function(){return n.bindCoreEvents()},100)}},{key:"bindContainerEvents",value:function(){this.core.activeContainer&&(this.listenToOnce(this.core.activeContainer,p.CONTAINER_TIMEUPDATE,this.render),this.listenTo(this.core.activeContainer,p.CONTAINER_PLAYBACKDVRSTATECHANGED,this.dvrChanged))}},{key:"containerChanged",value:function(){this.stopListening(),this.bindEvents()}},{key:"dvrChanged",value:function(n){this.core.getPlaybackType()===se.LIVE&&(this.settingsUpdate(),this.core.mediaControl.$el.addClass("live"),n?(this.core.mediaControl.$el.addClass("dvr"),this.core.mediaControl.$el.find(".media-control-indicator[data-position], .media-control-indicator[data-duration]").hide()):this.core.mediaControl.$el.removeClass("dvr"))}},{key:"click",value:function(){var n=this.core.mediaControl,r=n.container;r.isPlaying()||r.play(),n.$el.hasClass("dvr")&&r.seek(r.getDuration())}},{key:"settingsUpdate",value:function(){var n=this;this.stopListening(),this.core.mediaControl.$el.removeClass("live"),this.shouldRender()&&(this.render(),this.$el.click(function(){return n.click()})),this.bindEvents()}},{key:"shouldRender",value:function(){var n=this.core.options.useDvrControls===void 0||!!this.core.options.useDvrControls;return n&&this.core.getPlaybackType()===se.LIVE}},{key:"render",value:function(){var n=Se.getStyleFor(wh,{baseUrl:this.options.baseUrl});return this.$el.html(this.template({live:this.core.i18n.t("live"),backToLive:this.core.i18n.t("back_to_live")})),this.$el.append(n[0]),this.shouldRender()&&(this.core.mediaControl.$el.addClass("live"),this.core.mediaControl.$(".media-control-left-panel[data-media-control]").append(this.$el)),this}}]),t}(Ne),Oh=function(s){Be(t,s);var e=Ue(t);function t(){return Fe(this,t),e.apply(this,arguments)}return Me(t,[{key:"name",get:function(){return"end_video"}},{key:"supportedVersion",get:function(){return{min:"0.4.27"}}},{key:"bindEvents",value:function(){this.listenTo(this.core,p.CORE_ACTIVE_CONTAINER_CHANGED,this.containerChanged);var n=this.core.activeContainer;n&&(this.listenTo(n,p.CONTAINER_ENDED,this.ended),this.listenTo(n,p.CONTAINER_STOP,this.ended))}},{key:"containerChanged",value:function(){this.stopListening(),this.bindEvents()}},{key:"ended",value:function(){var n=typeof this.core.options.exitFullscreenOnEnd>"u"||this.core.options.exitFullscreenOnEnd;n&&this.core.isFullscreen()&&this.core.toggleFullscreen()}}]),t}(ot),Nh=` `,Fh=`
<% if (icon) { %>
<%= icon %>
<% } %>
<%= title %>
<%= message %>
Error code: <%= code %>
<%= reloadIcon %>
`,Mh=`[data-player] .player-error-screen { -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; color: #CCCACA; position: absolute; top: 0; height: 100%; width: 100%; background-color: rgba(0, 0, 0, 0.7); z-index: 2000; display: flex; flex-direction: column; justify-content: center; } [data-player] .player-error-screen__content[data-error-screen] { font-size: 14px; color: #CCCACA; margin-top: 45px; } [data-player] .player-error-screen__title[data-error-screen] { font-weight: bold; line-height: 30px; font-size: 18px; } [data-player] .player-error-screen__message[data-error-screen] { width: 90%; margin: 0 auto; } [data-player] .player-error-screen__code[data-error-screen] { font-size: 13px; margin-top: 15px; } [data-player] .player-error-screen__reload { cursor: pointer; width: 30px; margin: 15px auto 0 !important; } `,Bh=function(s){Be(t,s);var e=Ue(t);function t(i){var n;return Fe(this,t),n=e.call(this,i),n.options.disableErrorScreen?ma(n,n.disable()):n}return Me(t,[{key:"name",get:function(){return"error_screen"}},{key:"supportedVersion",get:function(){return{min:"0.4.27"}}},{key:"template",get:function(){return Ie(Fh)}},{key:"container",get:function(){return this.core.getCurrentContainer()}},{key:"attributes",get:function(){return{class:"player-error-screen","data-error-screen":""}}},{key:"bindEvents",value:function(){this.listenTo(this.core,p.ERROR,this.onError),this.listenTo(this.core,p.CORE_ACTIVE_CONTAINER_CHANGED,this.onContainerChanged)}},{key:"bindReload",value:function(){this.reloadButton=this.$el.find(".player-error-screen__reload"),this.reloadButton&&this.reloadButton.on("click",this.reload.bind(this))}},{key:"reload",value:function(){var n=this;this.listenToOnce(this.core,p.CORE_READY,function(){return n.container.play()}),this.core.load(this.options.sources,this.options.mimeType),this.unbindReload()}},{key:"unbindReload",value:function(){this.reloadButton&&this.reloadButton.off("click")}},{key:"onContainerChanged",value:function(){this.err=null,this.unbindReload(),this.hide()}},{key:"onError",value:function(){var n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};n.level===Ve.Levels.FATAL&&(this.err=n,this.container.disableMediaControl(),this.container.stop(),this.show())}},{key:"show",value:function(){this.render(),this.$el.show()}},{key:"hide",value:function(){this.$el.hide()}},{key:"render",value:function(){if(this.err){var n=Se.getStyleFor(Mh,{baseUrl:this.options.baseUrl});return this.$el.html(this.template({title:this.err.UI.title,message:this.err.UI.message,code:this.err.code,icon:this.err.UI.icon||"",reloadIcon:Nh})),this.$el.append(n[0]),this.core.$el.append(this.el),this.bindReload(),this}}}]),t}(Ne),xt=` `,Kn=` `,Uh=Q('link[rel="shortcut icon"]'),$h=function(s){Be(t,s);var e=Ue(t);function t(i){var n;return Fe(this,t),n=e.call(this,i),n._container=null,n.configure(),n}return Me(t,[{key:"name",get:function(){return"favicon"}},{key:"supportedVersion",get:function(){return{min:"0.4.27"}}},{key:"oldIcon",get:function(){return Uh}},{key:"configure",value:function(){this.core.options.changeFavicon?this.enabled||(this.stopListening(this.core,p.CORE_OPTIONS_CHANGE),this.enable()):this.enabled&&(this.disable(),this.listenTo(this.core,p.CORE_OPTIONS_CHANGE,this.configure))}},{key:"bindEvents",value:function(){this.listenTo(this.core,p.CORE_OPTIONS_CHANGE,this.configure),this.listenTo(this.core,p.CORE_ACTIVE_CONTAINER_CHANGED,this.containerChanged),this.core.activeContainer&&this.containerChanged()}},{key:"containerChanged",value:function(){this._container&&this.stopListening(this._container),this._container=this.core.activeContainer,this.listenTo(this._container,p.CONTAINER_PLAY,this.setPlayIcon),this.listenTo(this._container,p.CONTAINER_PAUSE,this.setPauseIcon),this.listenTo(this._container,p.CONTAINER_STOP,this.resetIcon),this.listenTo(this._container,p.CONTAINER_ENDED,this.resetIcon),this.listenTo(this._container,p.CONTAINER_ERROR,this.resetIcon),this.resetIcon()}},{key:"disable",value:function(){Gt(vt(t.prototype),"disable",this).call(this),this.resetIcon()}},{key:"destroy",value:function(){Gt(vt(t.prototype),"destroy",this).call(this),this.resetIcon()}},{key:"createIcon",value:function(n){var r=Q("");r[0].width=16,r[0].height=16;var a=r[0].getContext("2d");a.fillStyle="#000";var o=Q(n).find("path").attr("d"),l=new Path2D(o);a.fill(l);var c=Q('');return c.attr("href",r[0].toDataURL("image/png")),c}},{key:"setPlayIcon",value:function(){this.playIcon||(this.playIcon=this.createIcon(xt)),this.changeIcon(this.playIcon)}},{key:"setPauseIcon",value:function(){this.pauseIcon||(this.pauseIcon=this.createIcon(Kn)),this.changeIcon(this.pauseIcon)}},{key:"resetIcon",value:function(){Q('link[rel="shortcut icon"]').remove(),Q("head").append(this.oldIcon)}},{key:"changeIcon",value:function(n){n&&(Q('link[rel="shortcut icon"]').remove(),Q("head").append(n))}}]),t}(ot),Vh=function(s){Be(t,s);var e=Ue(t);function t(i){var n;return Fe(this,t),n=e.call(this,i),n.container.options.gaAccount&&(n.account=n.container.options.gaAccount,n.trackerName=n.container.options.gaTrackerName?n.container.options.gaTrackerName+".":"Clappr.",n.domainName=n.container.options.gaDomainName,n.currentHDState=void 0,n.embedScript()),n}return Me(t,[{key:"name",get:function(){return"google_analytics"}},{key:"supportedVersion",get:function(){return{min:"0.4.27"}}},{key:"embedScript",value:function(){var n=this;if(window._gat)this.addEventListeners();else{var r=document.createElement("script");r.setAttribute("type","text/javascript"),r.setAttribute("async","async"),r.setAttribute("src","//www.google-analytics.com/ga.js"),r.onload=function(){return n.addEventListeners()},document.body.appendChild(r)}}},{key:"addEventListeners",value:function(){var n=this;this.container&&(this.listenTo(this.container,p.CONTAINER_READY,this.onReady),this.listenTo(this.container,p.CONTAINER_PLAY,this.onPlay),this.listenTo(this.container,p.CONTAINER_STOP,this.onStop),this.listenTo(this.container,p.CONTAINER_PAUSE,this.onPause),this.listenTo(this.container,p.CONTAINER_ENDED,this.onEnded),this.listenTo(this.container,p.CONTAINER_STATE_BUFFERING,this.onBuffering),this.listenTo(this.container,p.CONTAINER_STATE_BUFFERFULL,this.onBufferFull),this.listenTo(this.container,p.CONTAINER_ERROR,this.onError),this.listenTo(this.container,p.CONTAINER_PLAYBACKSTATE,this.onPlaybackChanged),this.listenTo(this.container,p.CONTAINER_VOLUME,function(r){return n.onVolumeChanged(r)}),this.listenTo(this.container,p.CONTAINER_SEEK,function(r){return n.onSeek(r)}),this.listenTo(this.container,p.CONTAINER_FULL_SCREEN,this.onFullscreen),this.listenTo(this.container,p.CONTAINER_HIGHDEFINITIONUPDATE,this.onHD),this.listenTo(this.container,p.CONTAINER_PLAYBACKDVRSTATECHANGED,this.onDVR)),_gaq.push([this.trackerName+"_setAccount",this.account]),this.domainName&&_gaq.push([this.trackerName+"_setDomainName",this.domainName])}},{key:"onReady",value:function(){this.push(["Video","Playback",this.container.playback.name])}},{key:"onPlay",value:function(){this.push(["Video","Play",this.container.playback.src])}},{key:"onStop",value:function(){this.push(["Video","Stop",this.container.playback.src])}},{key:"onEnded",value:function(){this.push(["Video","Ended",this.container.playback.src])}},{key:"onBuffering",value:function(){this.push(["Video","Buffering",this.container.playback.src])}},{key:"onBufferFull",value:function(){this.push(["Video","Bufferfull",this.container.playback.src])}},{key:"onError",value:function(){this.push(["Video","Error",this.container.playback.src])}},{key:"onHD",value:function(n){var r=n?"ON":"OFF";r!==this.currentHDState&&(this.currentHDState=r,this.push(["Video","HD - "+r,this.container.playback.src]))}},{key:"onPlaybackChanged",value:function(n){n.type!==null&&this.push(["Video","Playback Type - "+n.type,this.container.playback.src])}},{key:"onDVR",value:function(n){var r=n?"ON":"OFF";this.push(["Interaction","DVR - "+r,this.container.playback.src])}},{key:"onPause",value:function(){this.push(["Video","Pause",this.container.playback.src])}},{key:"onSeek",value:function(){this.push(["Video","Seek",this.container.playback.src])}},{key:"onVolumeChanged",value:function(){this.push(["Interaction","Volume",this.container.playback.src])}},{key:"onFullscreen",value:function(){this.push(["Interaction","Fullscreen",this.container.playback.src])}},{key:"push",value:function(n){var r=[this.trackerName+"_trackEvent"].concat(n);_gaq.push(r)}}]),t}(at),Y=function(e){this.element=e||window.document,this.initialize()};Y.KEY_NAMES_BY_CODE={8:"backspace",9:"tab",13:"enter",16:"shift",17:"ctrl",18:"alt",20:"caps_lock",27:"esc",32:"space",37:"left",38:"up",39:"right",40:"down",48:"0",49:"1",50:"2",51:"3",52:"4",53:"5",54:"6",55:"7",56:"8",57:"9",65:"a",66:"b",67:"c",68:"d",69:"e",70:"f",71:"g",72:"h",73:"i",74:"j",75:"k",76:"l",77:"m",78:"n",79:"o",80:"p",81:"q",82:"r",83:"s",84:"t",85:"u",86:"v",87:"w",88:"x",89:"y",90:"z",112:"f1",113:"f2",114:"f3",115:"f4",116:"f5",117:"f6",118:"f7",119:"f8",120:"f9",121:"f10",122:"f11",123:"f12"},Y.KEY_CODES_BY_NAME={},function(){for(var s in Y.KEY_NAMES_BY_CODE)Object.prototype.hasOwnProperty.call(Y.KEY_NAMES_BY_CODE,s)&&(Y.KEY_CODES_BY_NAME[Y.KEY_NAMES_BY_CODE[s]]=+s)}(),Y.MODIFIERS=["shift","ctrl","alt"],Y.registerEvent=function(){if(document.addEventListener)return function(s,e,t){s.addEventListener(e,t,!1)};if(document.attachEvent)return function(s,e,t){s.attachEvent("on"+e,t)}}(),Y.unregisterEvent=function(){if(document.removeEventListener)return function(s,e,t){s.removeEventListener(e,t,!1)};if(document.detachEvent)return function(s,e,t){s.detachEvent("on"+e,t)}}(),Y.stringContains=function(s,e){return s.indexOf(e)!==-1},Y.neatString=function(s){return s.replace(/^\s+|\s+$/g,"").replace(/\s+/g," ")},Y.capitalize=function(s){return s.toLowerCase().replace(/^./,function(e){return e.toUpperCase()})},Y.isString=function(s){return Y.stringContains(Object.prototype.toString.call(s),"String")},Y.arrayIncludes=function(){return Array.prototype.indexOf?function(s,e){return s.indexOf(e)!==-1}:function(s,e){for(var t=0;t
<% var renderBar = function(name) { %>
>
>
>
>
>
>
>
<% }; %> <% var renderSegmentedBar = function(name, segments) { segments = segments || 10; %>
> <% for (var i = 0; i < segments; i++) { %>
>
<% } %>
<% }; %> <% var renderDrawer = function(name, renderContent) { %>
>
>
>
>
<% renderContent(name); %>
<% }; %> <% var renderIndicator = function(name) { %>
>
<% }; %> <% var renderButton = function(name) { %> <% }; %> <% var templates = { bar: renderBar, segmentedBar: renderSegmentedBar, }; var render = function(settingsList) { settingsList.forEach(function(setting) { if(setting === "seekbar") { renderBar(setting); } else if (setting === "volume") { renderDrawer(setting, settings.volumeBarTemplate ? templates[settings.volumeBarTemplate] : function(name) { return renderSegmentedBar(name); }); } else if (setting === "duration" || setting === "position") { renderIndicator(setting); } else { renderButton(setting); } }); }; %> <% if (settings.default && settings.default.length) { %>
<% render(settings.default); %>
<% } %> <% if (settings.left && settings.left.length) { %>
<% render(settings.left); %>
<% } %> <% if (settings.right && settings.right.length) { %>
<% render(settings.right); %>
<% } %>
`,ya=` `,va=` `,Hh=` `,Aa=` `,Yh=` `,Wh=` `,Ea=rt.Config,Ta=rt.Fullscreen,ba=rt.formatTime,zh=rt.extend,Hn=rt.removeArrayItem,Yn=function(s){Be(t,s);var e=Ue(t);function t(i){var n;return Fe(this,t),n=e.call(this,i),n.persistConfig=n.options.persistConfig,n.currentPositionValue=null,n.currentDurationValue=null,n.keepVisible=!1,n.fullScreenOnVideoTagSupported=null,n.setInitialVolume(),n.settings={left:["play","stop","pause"],right:["volume"],default:["position","seekbar","duration"]},n.kibo=new Y(n.options.focusElement),n.bindKeyEvents(),n.container?Q.isEmptyObject(n.container.settings)||(n.settings=Q.extend({},n.container.settings)):n.settings={},n.userDisabled=!1,(n.container&&n.container.mediaControlDisabled||n.options.chromeless)&&n.disable(),n.stopDragHandler=function(r){return n.stopDrag(r)},n.updateDragHandler=function(r){return n.updateDrag(r)},Q(document).bind("mouseup",n.stopDragHandler),Q(document).bind("mousemove",n.updateDragHandler),n}return Me(t,[{key:"name",get:function(){return"media_control"}},{key:"supportedVersion",get:function(){return{min:"0.4.27"}}},{key:"disabled",get:function(){var n=this.container&&this.container.getPlaybackType()===se.NO_OP;return this.userDisabled||n}},{key:"container",get:function(){return this.core&&this.core.activeContainer}},{key:"playback",get:function(){return this.core&&this.core.activePlayback}},{key:"attributes",get:function(){return{class:"media-control","data-media-control":""}}},{key:"events",get:function(){return{"click [data-play]":"play","click [data-pause]":"pause","click [data-playpause]":"togglePlayPause","click [data-stop]":"stop","click [data-playstop]":"togglePlayStop","click [data-fullscreen]":"toggleFullscreen","click .bar-container[data-seekbar]":"seek","click .bar-container[data-volume]":"onVolumeClick","click .drawer-icon[data-volume]":"toggleMute","mouseenter .drawer-container[data-volume]":"showVolumeBar","mouseleave .drawer-container[data-volume]":"hideVolumeBar","mousedown .bar-container[data-volume]":"startVolumeDrag","mousemove .bar-container[data-volume]":"mousemoveOnVolumeBar","mousedown .bar-scrubber[data-seekbar]":"startSeekDrag","mousemove .bar-container[data-seekbar]":"mousemoveOnSeekBar","mouseleave .bar-container[data-seekbar]":"mouseleaveOnSeekBar","mouseenter .media-control-layer[data-controls]":"setUserKeepVisible","mouseleave .media-control-layer[data-controls]":"resetUserKeepVisible"}}},{key:"template",get:function(){return Ie(Kh)}},{key:"volume",get:function(){return this.container&&this.container.isReady?this.container.volume:this.intendedVolume}},{key:"muted",get:function(){return this.volume===0}},{key:"getExternalInterface",value:function(){var n=this;return{setVolume:this.setVolume,getVolume:function(){return n.volume}}}},{key:"bindEvents",value:function(){var n=this;this.stopListening(),this.listenTo(this.core,p.CORE_ACTIVE_CONTAINER_CHANGED,this.onActiveContainerChanged),this.listenTo(this.core,p.CORE_MOUSE_MOVE,this.show),this.listenTo(this.core,p.CORE_MOUSE_LEAVE,function(){return n.hide(n.options.hideMediaControlDelay)}),this.listenTo(this.core,p.CORE_FULLSCREEN,this.show),this.listenTo(this.core,p.CORE_OPTIONS_CHANGE,this.configure),this.listenTo(this.core,p.CORE_RESIZE,this.playerResize),this.bindContainerEvents()}},{key:"bindContainerEvents",value:function(){this.container&&(this.listenTo(this.container,p.CONTAINER_PLAY,this.changeTogglePlay),this.listenTo(this.container,p.CONTAINER_PAUSE,this.changeTogglePlay),this.listenTo(this.container,p.CONTAINER_STOP,this.changeTogglePlay),this.listenTo(this.container,p.CONTAINER_DBLCLICK,this.toggleFullscreen),this.listenTo(this.container,p.CONTAINER_TIMEUPDATE,this.onTimeUpdate),this.listenTo(this.container,p.CONTAINER_PROGRESS,this.updateProgressBar),this.listenTo(this.container,p.CONTAINER_SETTINGSUPDATE,this.settingsUpdate),this.listenTo(this.container,p.CONTAINER_PLAYBACKDVRSTATECHANGED,this.settingsUpdate),this.listenTo(this.container,p.CONTAINER_HIGHDEFINITIONUPDATE,this.highDefinitionUpdate),this.listenTo(this.container,p.CONTAINER_MEDIACONTROL_DISABLE,this.disable),this.listenTo(this.container,p.CONTAINER_MEDIACONTROL_ENABLE,this.enable),this.listenTo(this.container,p.CONTAINER_ENDED,this.ended),this.listenTo(this.container,p.CONTAINER_VOLUME,this.onVolumeChanged),this.listenTo(this.container,p.CONTAINER_OPTIONS_CHANGE,this.setInitialVolume),this.container.playback.el.nodeName.toLowerCase()==="video"&&this.listenToOnce(this.container,p.CONTAINER_LOADEDMETADATA,this.onLoadedMetadataOnVideoTag))}},{key:"disable",value:function(){this.userDisabled=!0,this.hide(),this.unbindKeyEvents(),this.$el.hide()}},{key:"enable",value:function(){this.options.chromeless||(this.userDisabled=!1,this.bindKeyEvents(),this.show())}},{key:"play",value:function(){this.container&&this.container.play()}},{key:"pause",value:function(){this.container&&this.container.pause()}},{key:"stop",value:function(){this.container&&this.container.stop()}},{key:"setInitialVolume",value:function(){var n=this.persistConfig?Ea.restore("volume"):100,r=this.container&&this.container.options||this.options;this.setVolume(r.mute?0:n,!0)}},{key:"onVolumeChanged",value:function(){this.updateVolumeUI()}},{key:"onLoadedMetadataOnVideoTag",value:function(){var n=this.playback&&this.playback.el;!Ta.fullscreenEnabled()&&n.webkitSupportsFullscreen&&(this.fullScreenOnVideoTagSupported=!0,this.settingsUpdate())}},{key:"updateVolumeUI",value:function(){if(this.rendered){this.$volumeBarContainer.find(".bar-fill-2").css({});var n=this.$volumeBarContainer.width(),r=this.$volumeBarBackground.width(),a=(n-r)/2,o=r*this.volume/100+a;this.$volumeBarFill.css({width:"".concat(this.volume,"%")}),this.$volumeBarScrubber.css({left:o}),this.$volumeBarContainer.find(".segmented-bar-element").removeClass("fill");var l=Math.ceil(this.volume/10);this.$volumeBarContainer.find(".segmented-bar-element").slice(0,l).addClass("fill"),this.$volumeIcon.html(""),this.$volumeIcon.removeClass("muted"),this.muted?(this.$volumeIcon.append(Hh),this.$volumeIcon.addClass("muted")):this.$volumeIcon.append(va),this.applyButtonStyle(this.$volumeIcon)}}},{key:"changeTogglePlay",value:function(){this.$playPauseToggle.html(""),this.$playStopToggle.html(""),this.container&&this.container.isPlaying()?(this.$playPauseToggle.append(Kn),this.$playStopToggle.append(ya),this.trigger(p.MEDIACONTROL_PLAYING)):(this.$playPauseToggle.append(xt),this.$playStopToggle.append(xt),this.trigger(p.MEDIACONTROL_NOTPLAYING),z.isMobile&&this.show()),this.applyButtonStyle(this.$playPauseToggle),this.applyButtonStyle(this.$playStopToggle)}},{key:"mousemoveOnSeekBar",value:function(n){if(this.settings.seekEnabled){var r=n.pageX-this.$seekBarContainer.offset().left-this.$seekBarHover.width()/2;this.$seekBarHover.css({left:r})}this.trigger(p.MEDIACONTROL_MOUSEMOVE_SEEKBAR,n)}},{key:"mouseleaveOnSeekBar",value:function(n){this.trigger(p.MEDIACONTROL_MOUSELEAVE_SEEKBAR,n)}},{key:"onVolumeClick",value:function(n){this.setVolume(this.getVolumeFromUIEvent(n))}},{key:"mousemoveOnVolumeBar",value:function(n){this.draggingVolumeBar&&this.setVolume(this.getVolumeFromUIEvent(n))}},{key:"playerResize",value:function(n){this.$fullscreenToggle.html("");var r=this.core.isFullscreen()?Yh:Aa;this.$fullscreenToggle.append(r),this.applyButtonStyle(this.$fullscreenToggle),this.$el.find(".media-control").length!==0&&this.$el.removeClass("w320"),(n.width<=320||this.options.hideVolumeBar)&&this.$el.addClass("w320")}},{key:"togglePlayPause",value:function(){return this.container.isPlaying()?this.container.pause():this.container.play(),!1}},{key:"togglePlayStop",value:function(){this.container.isPlaying()?this.container.stop():this.container.play()}},{key:"startSeekDrag",value:function(n){this.settings.seekEnabled&&(this.draggingSeekBar=!0,this.$el.addClass("dragging"),this.$seekBarLoaded.addClass("media-control-notransition"),this.$seekBarPosition.addClass("media-control-notransition"),this.$seekBarScrubber.addClass("media-control-notransition"),n&&n.preventDefault())}},{key:"startVolumeDrag",value:function(n){this.draggingVolumeBar=!0,this.$el.addClass("dragging"),n&&n.preventDefault()}},{key:"stopDrag",value:function(n){this.draggingSeekBar&&this.seek(n),this.$el.removeClass("dragging"),this.$seekBarLoaded.removeClass("media-control-notransition"),this.$seekBarPosition.removeClass("media-control-notransition"),this.$seekBarScrubber.removeClass("media-control-notransition dragging"),this.draggingSeekBar=!1,this.draggingVolumeBar=!1}},{key:"updateDrag",value:function(n){if(this.draggingSeekBar){n.preventDefault();var r=n.pageX-this.$seekBarContainer.offset().left,a=r/this.$seekBarContainer.width()*100;a=Math.min(100,Math.max(a,0)),this.setSeekPercentage(a)}else this.draggingVolumeBar&&(n.preventDefault(),this.setVolume(this.getVolumeFromUIEvent(n)))}},{key:"getVolumeFromUIEvent",value:function(n){var r=n.pageX-this.$volumeBarContainer.offset().left,a=r/this.$volumeBarContainer.width()*100;return a}},{key:"toggleMute",value:function(){this.setVolume(this.muted?100:0)}},{key:"setVolume",value:function(n){var r=this,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;n=Math.min(100,Math.max(n,0)),this.intendedVolume=n,this.persistConfig&&!a&&Ea.persist("volume",n);var o=function(){r.container&&r.container.isReady?r.container.setVolume(n):r.listenToOnce(r.container,p.CONTAINER_READY,function(){r.container.setVolume(n)})};this.container?o():this.listenToOnce(this,p.MEDIACONTROL_CONTAINERCHANGED,function(){return o()})}},{key:"toggleFullscreen",value:function(){this.trigger(p.MEDIACONTROL_FULLSCREEN,this.name),this.container.fullscreen(),this.core.toggleFullscreen(),this.resetUserKeepVisible()}},{key:"onActiveContainerChanged",value:function(){this.fullScreenOnVideoTagSupported=null,this.bindEvents(),this.setInitialVolume(),this.changeTogglePlay(),this.bindContainerEvents(),this.settingsUpdate(),this.container&&this.container.trigger(p.CONTAINER_PLAYBACKDVRSTATECHANGED,this.container.isDvrInUse()),this.container&&this.container.mediaControlDisabled&&this.disable(),this.trigger(p.MEDIACONTROL_CONTAINERCHANGED)}},{key:"showVolumeBar",value:function(){this.hideVolumeId&&clearTimeout(this.hideVolumeId),this.$volumeBarContainer.removeClass("volume-bar-hide")}},{key:"hideVolumeBar",value:function(){var n=this,r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:400;this.$volumeBarContainer&&(this.draggingVolumeBar?this.hideVolumeId=setTimeout(function(){return n.hideVolumeBar()},r):(this.hideVolumeId&&clearTimeout(this.hideVolumeId),this.hideVolumeId=setTimeout(function(){return n.$volumeBarContainer.addClass("volume-bar-hide")},r)))}},{key:"ended",value:function(){this.changeTogglePlay()}},{key:"updateProgressBar",value:function(n){var r=n.start/n.total*100,a=n.current/n.total*100;this.$seekBarLoaded.css({left:"".concat(r,"%"),width:"".concat(a-r,"%")})}},{key:"onTimeUpdate",value:function(n){if(!this.draggingSeekBar){var r=n.current<0?n.total:n.current;this.currentPositionValue=r,this.currentDurationValue=n.total,this.renderSeekBar()}}},{key:"renderSeekBar",value:function(){if(!(this.currentPositionValue===null||this.currentDurationValue===null)){this.currentSeekBarPercentage=100,this.container&&(this.container.getPlaybackType()!==se.LIVE||this.container.isDvrInUse())&&(this.currentSeekBarPercentage=this.currentPositionValue/this.currentDurationValue*100),this.setSeekPercentage(this.currentSeekBarPercentage);var n=ba(this.currentPositionValue),r=ba(this.currentDurationValue);n!==this.displayedPosition&&(this.$position.text(n),this.displayedPosition=n),r!==this.displayedDuration&&(this.$duration.text(r),this.displayedDuration=r)}}},{key:"seek",value:function(n){if(this.settings.seekEnabled){var r=n.pageX-this.$seekBarContainer.offset().left,a=r/this.$seekBarContainer.width()*100;return a=Math.min(100,Math.max(a,0)),this.container&&this.container.seekPercentage(a),this.setSeekPercentage(a),!1}}},{key:"setKeepVisible",value:function(){this.keepVisible=!0}},{key:"resetKeepVisible",value:function(){this.keepVisible=!1}},{key:"setUserKeepVisible",value:function(){this.userKeepVisible=!0}},{key:"resetUserKeepVisible",value:function(){this.userKeepVisible=!1}},{key:"isVisible",value:function(){return!this.$el.hasClass("media-control-hide")}},{key:"show",value:function(n){var r=this;if(!this.disabled){var a=2e3,o=n&&n.clientX!==this.lastMouseX&&n.clientY!==this.lastMouseY;(!n||o||navigator.userAgent.match(/firefox/i))&&(clearTimeout(this.hideId),this.$el.show(),this.trigger(p.MEDIACONTROL_SHOW,this.name),this.container&&this.container.trigger(p.CONTAINER_MEDIACONTROL_SHOW,this.name),this.$el.removeClass("media-control-hide"),this.hideId=setTimeout(function(){return r.hide()},a),n&&(this.lastMouseX=n.clientX,this.lastMouseY=n.clientY));var l=!0;this.updateCursorStyle(l)}}},{key:"hide",value:function(){var n=this,r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;if(this.isVisible()){var a=r||2e3;if(clearTimeout(this.hideId),!(!this.disabled&&this.options.hideMediaControl===!1)){var o=this.userKeepVisible||this.keepVisible,l=this.draggingSeekBar||this.draggingVolumeBar;if(!this.disabled&&(r||o||l))this.hideId=setTimeout(function(){return n.hide()},a);else{this.trigger(p.MEDIACONTROL_HIDE,this.name),this.container&&this.container.trigger(p.CONTAINER_MEDIACONTROL_HIDE,this.name),this.$el.addClass("media-control-hide"),this.hideVolumeBar(0);var c=!1;this.updateCursorStyle(c)}}}}},{key:"updateCursorStyle",value:function(n){n?this.core.$el.removeClass("nocursor"):this.core.isFullscreen()&&this.core.$el.addClass("nocursor")}},{key:"settingsUpdate",value:function(){var n=this.getSettings();n&&!this.fullScreenOnVideoTagSupported&&!Ta.fullscreenEnabled()&&(n.default&&Hn(n.default,"fullscreen"),n.left&&Hn(n.left,"fullscreen"),n.right&&Hn(n.right,"fullscreen"));var r=JSON.stringify(this.settings)!==JSON.stringify(n);r&&(this.settings=n,this.render())}},{key:"getSettings",value:function(){return Q.extend(!0,{},this.container&&this.container.settings)}},{key:"highDefinitionUpdate",value:function(n){this.isHD=n;var r=n?"addClass":"removeClass";this.$hdIndicator[r]("enabled")}},{key:"createCachedElements",value:function(){var n=this.$el.find(".media-control-layer");this.$duration=n.find(".media-control-indicator[data-duration]"),this.$fullscreenToggle=n.find("button.media-control-button[data-fullscreen]"),this.$playPauseToggle=n.find("button.media-control-button[data-playpause]"),this.$playStopToggle=n.find("button.media-control-button[data-playstop]"),this.$position=n.find(".media-control-indicator[data-position]"),this.$seekBarContainer=n.find(".bar-container[data-seekbar]"),this.$seekBarHover=n.find(".bar-hover[data-seekbar]"),this.$seekBarLoaded=n.find(".bar-fill-1[data-seekbar]"),this.$seekBarPosition=n.find(".bar-fill-2[data-seekbar]"),this.$seekBarScrubber=n.find(".bar-scrubber[data-seekbar]"),this.$volumeBarContainer=n.find(".bar-container[data-volume]"),this.$volumeContainer=n.find(".drawer-container[data-volume]"),this.$volumeIcon=n.find(".drawer-icon[data-volume]"),this.$volumeBarBackground=this.$el.find(".bar-background[data-volume]"),this.$volumeBarFill=this.$el.find(".bar-fill-1[data-volume]"),this.$volumeBarScrubber=this.$el.find(".bar-scrubber[data-volume]"),this.$hdIndicator=this.$el.find("button.media-control-button[data-hd-indicator]"),this.resetIndicators(),this.initializeIcons()}},{key:"resetIndicators",value:function(){this.displayedPosition=this.$position.text(),this.displayedDuration=this.$duration.text()}},{key:"initializeIcons",value:function(){var n=this.$el.find(".media-control-layer");n.find("button.media-control-button[data-play]").append(xt),n.find("button.media-control-button[data-pause]").append(Kn),n.find("button.media-control-button[data-stop]").append(ya),this.$playPauseToggle.append(xt),this.$playStopToggle.append(xt),this.$volumeIcon.append(va),this.$fullscreenToggle.append(Aa),this.$hdIndicator.append(Wh)}},{key:"setSeekPercentage",value:function(n){n=Math.max(Math.min(n,100),0),this.displayedSeekBarPercentage!==n&&(this.displayedSeekBarPercentage=n,this.$seekBarPosition.removeClass("media-control-notransition"),this.$seekBarScrubber.removeClass("media-control-notransition"),this.$seekBarPosition.css({width:"".concat(n,"%")}),this.$seekBarScrubber.css({left:"".concat(n,"%")}))}},{key:"seekRelative",value:function(n){if(this.settings.seekEnabled){var r=this.container.getCurrentTime(),a=this.container.getDuration(),o=Math.min(Math.max(r+n,0),a);o=Math.min(o*100/a,100),this.container.seekPercentage(o)}}},{key:"bindKeyAndShow",value:function(n,r){var a=this;this.kibo.down(n,function(){return a.show(),r()})}},{key:"bindKeyEvents",value:function(){var n=this;if(!(z.isMobile||this.options.disableKeyboardShortcuts)){this.unbindKeyEvents(),this.kibo=new Y(this.options.focusElement||this.options.parentElement),this.bindKeyAndShow("space",function(){return n.togglePlayPause()}),this.bindKeyAndShow("left",function(){return n.seekRelative(-5)}),this.bindKeyAndShow("right",function(){return n.seekRelative(5)}),this.bindKeyAndShow("shift left",function(){return n.seekRelative(-10)}),this.bindKeyAndShow("shift right",function(){return n.seekRelative(10)}),this.bindKeyAndShow("shift ctrl left",function(){return n.seekRelative(-15)}),this.bindKeyAndShow("shift ctrl right",function(){return n.seekRelative(15)});var r=["1","2","3","4","5","6","7","8","9","0"];r.forEach(function(a){n.bindKeyAndShow(a,function(){n.settings.seekEnabled&&n.container&&n.container.seekPercentage(a*10)})})}}},{key:"unbindKeyEvents",value:function(){this.kibo&&(this.kibo.off("space"),this.kibo.off("left"),this.kibo.off("right"),this.kibo.off("shift left"),this.kibo.off("shift right"),this.kibo.off("shift ctrl left"),this.kibo.off("shift ctrl right"),this.kibo.off(["1","2","3","4","5","6","7","8","9","0"]))}},{key:"parseColors",value:function(){if(this.options.mediacontrol){this.buttonsColor=this.options.mediacontrol.buttons;var n=this.options.mediacontrol.seekbar;this.$el.find(".bar-fill-2[data-seekbar]").css("background-color",n),this.$el.find(".media-control-icon svg path").css("fill",this.buttonsColor),this.$el.find(".segmented-bar-element[data-volume]").css("boxShadow","inset 2px 0 0 "+this.buttonsColor)}}},{key:"applyButtonStyle",value:function(n){this.buttonsColor&&n&&Q(n).find("svg path").css("fill",this.buttonsColor)}},{key:"destroy",value:function(){Q(document).unbind("mouseup",this.stopDragHandler),Q(document).unbind("mousemove",this.updateDragHandler),this.unbindKeyEvents(),this.stopListening(),Gt(vt(t.prototype),"destroy",this).call(this)}},{key:"configure",value:function(n){this.options.chromeless||n.source||n.sources?this.disable():this.enable(),this.trigger(p.MEDIACONTROL_OPTIONS_CHANGE)}},{key:"render",value:function(){var n=this,r=this.options.hideMediaControlDelay||2e3;this.settings&&this.$el.html(this.template({settings:this.settings}));var a=Se.getStyleFor(Gh,{baseUrl:this.options.baseUrl});this.$el.append(a[0]),this.createCachedElements(),this.$playPauseToggle.addClass("paused"),this.$playStopToggle.addClass("stopped"),this.changeTogglePlay(),this.container&&(this.hideId=setTimeout(function(){return n.hide()},r),this.disabled&&this.hide()),z.isSafari&&z.isMobile&&(z.version<10?this.$volumeContainer.css("display","none"):this.$volumeBarContainer.css("display","none")),this.$seekBarPosition.addClass("media-control-notransition"),this.$seekBarScrubber.addClass("media-control-notransition");var o=0;return this.displayedSeekBarPercentage&&(o=this.displayedSeekBarPercentage),this.displayedSeekBarPercentage=null,this.setSeekPercentage(o),setTimeout(function(){!n.settings.seekEnabled&&n.$seekBarContainer.addClass("seek-disabled"),!z.isMobile&&!n.options.disableKeyboardShortcuts&&n.bindKeyEvents(),n.playerResize({width:n.options.width,height:n.options.height}),n.hideVolumeBar(0)},0),this.parseColors(),this.highDefinitionUpdate(this.isHD),this.core.$el.append(this.el),this.rendered=!0,this.updateVolumeUI(),this.trigger(p.MEDIACONTROL_RENDERED),this}}]),t}(Ne);Yn.extend=function(s){return zh(Yn,s)};var jh=`
`,qh=`.player-poster[data-poster] { display: flex; justify-content: center; align-items: center; position: absolute; height: 100%; width: 100%; z-index: 998; top: 0; left: 0; background-color: transparent; background-size: cover; background-repeat: no-repeat; background-position: 50% 50%; } .player-poster[data-poster].clickable { cursor: pointer; } .player-poster[data-poster]:hover .play-wrapper[data-poster] { opacity: 1; } .player-poster[data-poster] .play-wrapper[data-poster] { width: 100%; height: 25%; margin: 0 auto; opacity: 0.75; transition: opacity 0.1s ease; } .player-poster[data-poster] .play-wrapper[data-poster] svg { height: 100%; } .player-poster[data-poster] .play-wrapper[data-poster] svg path { fill: #fff; } `,Xh=function(s){Be(t,s);var e=Ue(t);function t(i){var n;return Fe(this,t),n=e.call(this,i),n.hasStartedPlaying=!1,n.playRequested=!1,n.render(),setTimeout(function(){return n.update()},0),n}return Me(t,[{key:"name",get:function(){return"poster"}},{key:"supportedVersion",get:function(){return{min:"0.4.27"}}},{key:"template",get:function(){return Ie(jh)}},{key:"shouldRender",get:function(){var n=!!(this.options.poster&&this.options.poster.showForNoOp);return this.container.playback.name!=="html_img"&&(this.container.playback.getPlaybackType()!==se.NO_OP||n)}},{key:"attributes",get:function(){return{class:"player-poster","data-poster":""}}},{key:"events",get:function(){return{click:"clicked"}}},{key:"showOnVideoEnd",get:function(){return!this.options.poster||this.options.poster.showOnVideoEnd||this.options.poster.showOnVideoEnd===void 0}},{key:"bindEvents",value:function(){this.listenTo(this.container,p.CONTAINER_STOP,this.onStop),this.listenTo(this.container,p.CONTAINER_PLAY,this.onPlay),this.listenTo(this.container,p.CONTAINER_STATE_BUFFERING,this.update),this.listenTo(this.container,p.CONTAINER_STATE_BUFFERFULL,this.update),this.listenTo(this.container,p.CONTAINER_OPTIONS_CHANGE,this.render),this.listenTo(this.container,p.CONTAINER_ERROR,this.onError),this.showOnVideoEnd&&this.listenTo(this.container,p.CONTAINER_ENDED,this.onStop)}},{key:"onError",value:function(n){this.hasFatalError=n.level===Ve.Levels.FATAL,this.hasFatalError&&(this.hasStartedPlaying=!1,this.playRequested=!1,this.showPlayButton())}},{key:"onPlay",value:function(){this.hasStartedPlaying=!0,this.update()}},{key:"onStop",value:function(){this.hasStartedPlaying=!1,this.playRequested=!1,this.update()}},{key:"updatePlayButton",value:function(n){n&&(!this.options.chromeless||this.options.allowUserInteraction)?this.showPlayButton():this.hidePlayButton()}},{key:"showPlayButton",value:function(){this.hasFatalError&&!this.options.disableErrorScreen||(this.$playButton.show(),this.$el.addClass("clickable"))}},{key:"hidePlayButton",value:function(){this.$playButton.hide(),this.$el.removeClass("clickable")}},{key:"clicked",value:function(){if(!this.hasStartedPlaying)return(!this.options.chromeless||this.options.allowUserInteraction)&&(this.playRequested=!0,this.update(),this.container.playback&&(this.container.playback._consented=!0),this.container.play()),!1}},{key:"shouldHideOnPlay",value:function(){return!this.container.playback.isAudioOnly}},{key:"update",value:function(){if(this.shouldRender){var n=!this.playRequested&&!this.hasStartedPlaying&&!this.container.buffering;this.updatePlayButton(n),this.updatePoster()}}},{key:"updatePoster",value:function(){this.hasStartedPlaying?this.hidePoster():this.showPoster()}},{key:"showPoster",value:function(){this.container.disableMediaControl(),this.$el.show()}},{key:"hidePoster",value:function(){this.container.enableMediaControl(),this.shouldHideOnPlay()&&this.$el.hide()}},{key:"render",value:function(){if(this.shouldRender){var n=Se.getStyleFor(qh,{baseUrl:this.options.baseUrl});this.$el.html(this.template()),this.$el.append(n[0]);var r=this.options.poster&&this.options.poster.custom===void 0;if(r){var a=this.options.poster.url||this.options.poster;this.$el.css({"background-image":"url("+a+")"}),this.removeVideoElementPoster()}else this.options.poster&&(this.$el.css({background:this.options.poster.custom}),this.removeVideoElementPoster());this.container.$el.append(this.el),this.$playWrapper=this.$el.find(".play-wrapper"),this.$playWrapper.append(xt),this.$playButton=this.$playWrapper.find("svg"),this.$playButton.addClass("poster-icon"),this.$playButton.attr("data-poster","");var o=this.options.mediacontrol&&this.options.mediacontrol.buttons;return o&&this.$el.find("svg path").css("fill",o),this.options.mediacontrol&&this.options.mediacontrol.buttons&&(o=this.options.mediacontrol.buttons,this.$playButton.css("color",o)),this.update(),this}}},{key:"removeVideoElementPoster",value:function(){this.container.playback&&this.container.playback.$el&&this.container.playback.$el[0]&&this.container.playback.$el[0].removeAttribute&&this.container.playback.$el[0].removeAttribute("poster")}}]),t}(ft),Qh=` `,Zh=`.seek-time[data-seek-time] { position: absolute; white-space: nowrap; height: 20px; line-height: 20px; font-size: 0; left: -100%; bottom: 55px; background-color: rgba(2, 2, 2, 0.5); z-index: 9999; transition: opacity 0.1s ease; } .seek-time[data-seek-time].hidden[data-seek-time] { opacity: 0; } .seek-time[data-seek-time] [data-seek-time] { display: inline-block; color: white; font-size: 10px; padding-left: 7px; padding-right: 7px; vertical-align: top; } .seek-time[data-seek-time] [data-duration] { display: inline-block; color: rgba(255, 255, 255, 0.5); font-size: 10px; padding-right: 7px; vertical-align: top; } .seek-time[data-seek-time] [data-duration]:before { content: "|"; margin-right: 7px; } `,Sa=rt.formatTime,Jh=function(s){Be(t,s);var e=Ue(t);function t(i){var n;return Fe(this,t),n=e.call(this,i),n.hoveringOverSeekBar=!1,n.hoverPosition=null,n.duration=null,n.firstFragDateTime=null,n.actualLiveTime=!!n.mediaControl.options.actualLiveTime,n.actualLiveTime&&(n.mediaControl.options.actualLiveServerTime?n.actualLiveServerTimeDiff=new Date().getTime()-new Date(n.mediaControl.options.actualLiveServerTime).getTime():n.actualLiveServerTimeDiff=0),n}return Me(t,[{key:"name",get:function(){return"seek_time"}},{key:"supportedVersion",get:function(){return{min:"0.4.27"}}},{key:"template",get:function(){return Ie(Qh)}},{key:"attributes",get:function(){return{class:"seek-time","data-seek-time":""}}},{key:"mediaControl",get:function(){return this.core.mediaControl}},{key:"mediaControlContainer",get:function(){return this.mediaControl.container}},{key:"isLiveStreamWithDvr",get:function(){return this.mediaControlContainer&&this.mediaControlContainer.getPlaybackType()===se.LIVE&&this.mediaControlContainer.isDvrEnabled()}},{key:"durationShown",get:function(){return this.isLiveStreamWithDvr&&!this.actualLiveTime}},{key:"useActualLiveTime",get:function(){return this.actualLiveTime&&this.isLiveStreamWithDvr}},{key:"bindEvents",value:function(){this.listenTo(this.mediaControl,p.MEDIACONTROL_RENDERED,this.render),this.listenTo(this.mediaControl,p.MEDIACONTROL_MOUSEMOVE_SEEKBAR,this.showTime),this.listenTo(this.mediaControl,p.MEDIACONTROL_MOUSELEAVE_SEEKBAR,this.hideTime),this.listenTo(this.mediaControl,p.MEDIACONTROL_CONTAINERCHANGED,this.onContainerChanged),this.mediaControlContainer&&(this.listenTo(this.mediaControlContainer,p.CONTAINER_PLAYBACKDVRSTATECHANGED,this.update),this.listenTo(this.mediaControlContainer,p.CONTAINER_TIMEUPDATE,this.updateDuration))}},{key:"onContainerChanged",value:function(){this.stopListening(),this.bindEvents()}},{key:"updateDuration",value:function(n){this.duration=n.total,this.firstFragDateTime=n.firstFragDateTime,this.update()}},{key:"showTime",value:function(n){this.hoveringOverSeekBar=!0,this.calculateHoverPosition(n),this.update()}},{key:"hideTime",value:function(){this.hoveringOverSeekBar=!1,this.update()}},{key:"calculateHoverPosition",value:function(n){var r=n.pageX-this.mediaControl.$seekBarContainer.offset().left;this.hoverPosition=Math.min(1,Math.max(r/this.mediaControl.$seekBarContainer.width(),0))}},{key:"getSeekTime",value:function(){var n,r,a,o;return this.useActualLiveTime?(this.firstFragDateTime?(o=new Date(this.firstFragDateTime),a=new Date(this.firstFragDateTime),a.setHours(0,0,0,0),r=(o.getTime()-a.getTime())/1e3+this.duration):(a=new Date(new Date().getTime()-this.actualLiveServerTimeDiff),o=new Date(a),r=(o-a.setHours(0,0,0,0))/1e3),n=r-this.duration+this.hoverPosition*this.duration,n<0&&(n+=86400)):n=this.hoverPosition*this.duration,{seekTime:n,secondsSinceMidnight:r}}},{key:"update",value:function(){if(this.rendered)if(!this.shouldBeVisible())this.$el.hide(),this.$el.css("left","-100%");else{var n=this.getSeekTime(),r=Sa(n.seekTime,this.useActualLiveTime);if(r!==this.displayedSeekTime&&(this.$seekTimeEl.text(r),this.displayedSeekTime=r),this.durationShown){this.$durationEl.show();var a=Sa(this.actualLiveTime?n.secondsSinceMidnight:this.duration,this.actualLiveTime);a!==this.displayedDuration&&(this.$durationEl.text(a),this.displayedDuration=a)}else this.$durationEl.hide();this.$el.show();var o=this.mediaControl.$seekBarContainer.width(),l=this.$el.width(),c=this.hoverPosition*o;c-=l/2,c=Math.max(0,Math.min(c,o-l)),this.$el.css("left",c)}}},{key:"shouldBeVisible",value:function(){return this.mediaControlContainer&&this.mediaControlContainer.settings.seekEnabled&&this.hoveringOverSeekBar&&this.hoverPosition!==null&&this.duration!==null}},{key:"render",value:function(){var n=Se.getStyleFor(Zh,{baseUrl:this.options.baseUrl});this.rendered=!0,this.displayedDuration=null,this.displayedSeekTime=null,this.$el.html(this.template()),this.$el.append(n[0]),this.$el.hide(),this.mediaControl.$el.append(this.el),this.$seekTimeEl=this.$el.find("[data-seek-time]"),this.$durationEl=this.$el.find("[data-duration]"),this.$durationEl.hide(),this.update()}}]),t}(Ne),ed=`
`,td=`.spinner-three-bounce[data-spinner] { position: absolute; margin: 0 auto; width: 70px; text-align: center; z-index: 999; left: 0; right: 0; margin-left: auto; margin-right: auto; /* center vertically */ top: 50%; transform: translateY(-50%); } .spinner-three-bounce[data-spinner] > div { width: 18px; height: 18px; background-color: #FFFFFF; border-radius: 100%; display: inline-block; animation: bouncedelay 1.4s infinite ease-in-out; /* Prevent first frame from flickering when animation starts */ animation-fill-mode: both; } .spinner-three-bounce[data-spinner] [data-bounce1] { animation-delay: -0.32s; } .spinner-three-bounce[data-spinner] [data-bounce2] { animation-delay: -0.16s; } @keyframes bouncedelay { 0%, 80%, 100% { transform: scale(0); } 40% { transform: scale(1); } } `,id=function(s){Be(t,s);var e=Ue(t);function t(i){var n;return Fe(this,t),n=e.call(this,i),n.template=Ie(ed),n.showTimeout=null,n.listenTo(n.container,p.CONTAINER_STATE_BUFFERING,n.onBuffering),n.listenTo(n.container,p.CONTAINER_STATE_BUFFERFULL,n.onBufferFull),n.listenTo(n.container,p.CONTAINER_STOP,n.onStop),n.listenTo(n.container,p.CONTAINER_ENDED,n.onStop),n.listenTo(n.container,p.CONTAINER_ERROR,n.onStop),n.render(),n}return Me(t,[{key:"name",get:function(){return"spinner"}},{key:"supportedVersion",get:function(){return{min:"0.4.27"}}},{key:"attributes",get:function(){return{"data-spinner":"",class:"spinner-three-bounce"}}},{key:"onBuffering",value:function(){this.show()}},{key:"onBufferFull",value:function(){this.hide()}},{key:"onStop",value:function(){this.hide()}},{key:"show",value:function(){var n=this;this.showTimeout===null&&(this.showTimeout=setTimeout(function(){return n.$el.show()},300))}},{key:"hide",value:function(){this.showTimeout!==null&&(clearTimeout(this.showTimeout),this.showTimeout=null),this.$el.hide()}},{key:"render",value:function(){var n=Se.getStyleFor(td,{baseUrl:this.options.baseUrl});return this.$el.html(this.template()),this.$el.append(n[0]),this.container.$el.append(this.$el),this.$el.hide(),this.container.buffering&&this.onBuffering(),this}}]),t}(ft),nd=function(s){Be(t,s);var e=Ue(t);function t(i){var n;return Fe(this,t),n=e.call(this,i),n.setInitialAttrs(),n.reportInterval=n.options.reportInterval||5e3,n.state="IDLE",n}return Me(t,[{key:"name",get:function(){return"stats"}},{key:"supportedVersion",get:function(){return{min:"0.4.27"}}},{key:"bindEvents",value:function(){this.listenTo(this.container.playback,p.PLAYBACK_PLAY,this.onPlay),this.listenTo(this.container,p.CONTAINER_STOP,this.onStop),this.listenTo(this.container,p.CONTAINER_ENDED,this.onStop),this.listenTo(this.container,p.CONTAINER_DESTROYED,this.onStop),this.listenTo(this.container,p.CONTAINER_STATE_BUFFERING,this.onBuffering),this.listenTo(this.container,p.CONTAINER_STATE_BUFFERFULL,this.onBufferFull),this.listenTo(this.container,p.CONTAINER_STATS_ADD,this.onStatsAdd),this.listenTo(this.container,p.CONTAINER_BITRATE,this.onStatsAdd),this.listenTo(this.container.playback,p.PLAYBACK_STATS_ADD,this.onStatsAdd)}},{key:"setInitialAttrs",value:function(){this.firstPlay=!0,this.startupTime=0,this.rebufferingTime=0,this.watchingTime=0,this.rebuffers=0,this.externalMetrics={}}},{key:"onPlay",value:function(){this.state="PLAYING",this.watchingTimeInit=Date.now(),this.intervalId||(this.intervalId=setInterval(this.report.bind(this),this.reportInterval))}},{key:"onStop",value:function(){clearInterval(this.intervalId),this.report(),this.intervalId=void 0,this.state="STOPPED"}},{key:"onBuffering",value:function(){this.firstPlay?this.startupTimeInit=Date.now():this.rebufferingTimeInit=Date.now(),this.state="BUFFERING",this.rebuffers++}},{key:"onBufferFull",value:function(){this.firstPlay&&this.startupTimeInit?(this.firstPlay=!1,this.startupTime=Date.now()-this.startupTimeInit,this.watchingTimeInit=Date.now()):this.rebufferingTimeInit&&(this.rebufferingTime+=this.getRebufferingTime()),this.rebufferingTimeInit=void 0,this.state="PLAYING"}},{key:"getRebufferingTime",value:function(){return Date.now()-this.rebufferingTimeInit}},{key:"getWatchingTime",value:function(){var n=Date.now()-this.watchingTimeInit;return n-this.rebufferingTime}},{key:"isRebuffering",value:function(){return!!this.rebufferingTimeInit}},{key:"onStatsAdd",value:function(n){Q.extend(this.externalMetrics,n)}},{key:"getStats",value:function(){var n={startupTime:this.startupTime,rebuffers:this.rebuffers,rebufferingTime:this.isRebuffering()?this.rebufferingTime+this.getRebufferingTime():this.rebufferingTime,watchingTime:this.isRebuffering()?this.getWatchingTime()-this.getRebufferingTime():this.getWatchingTime()};return Q.extend(n,this.externalMetrics),n}},{key:"report",value:function(){this.container.statsReport(this.getStats())}}]),t}(at),rd=`
> <% if(typeof imageLink !== 'undefined') { %> <% } %> <% if(typeof imageLink !== 'undefined') { %> <% } %>
`,sd=`.clappr-watermark[data-watermark] { position: absolute; min-width: 70px; max-width: 200px; width: 12%; text-align: center; z-index: 10; } .clappr-watermark[data-watermark] a { outline: none; cursor: pointer; } .clappr-watermark[data-watermark] img { max-width: 100%; } .clappr-watermark[data-watermark-bottom-left] { bottom: 10px; left: 10px; } .clappr-watermark[data-watermark-bottom-right] { bottom: 10px; right: 42px; } .clappr-watermark[data-watermark-top-left] { top: 10px; left: 10px; } .clappr-watermark[data-watermark-top-right] { top: 10px; right: 37px; } `,ad=function(s){Be(t,s);var e=Ue(t);function t(i){var n;return Fe(this,t),n=e.call(this,i),n.configure(),n}return Me(t,[{key:"name",get:function(){return"watermark"}},{key:"supportedVersion",get:function(){return{min:"0.4.27"}}},{key:"template",get:function(){return Ie(rd)}},{key:"bindEvents",value:function(){this.listenTo(this.container,p.CONTAINER_PLAY,this.onPlay),this.listenTo(this.container,p.CONTAINER_STOP,this.onStop),this.listenTo(this.container,p.CONTAINER_OPTIONS_CHANGE,this.configure)}},{key:"configure",value:function(){this.position=this.options.position||"bottom-right",this.options.watermark?(this.imageUrl=this.options.watermark,this.imageLink=this.options.watermarkLink,this.render()):this.$el.remove()}},{key:"onPlay",value:function(){this.hidden||this.$el.show()}},{key:"onStop",value:function(){this.$el.hide()}},{key:"render",value:function(){this.$el.hide();var n=Se.getStyleFor(sd,{baseUrl:this.options.baseUrl}),r={position:this.position,imageUrl:this.imageUrl,imageLink:this.imageLink};return this.$el.html(this.template(r)),this.$el.append(n[0]),this.container.$el.append(this.$el),this}}]),t}(ft),od={ClickToPause:xh,ClosedCaptions:Rh,DVRControls:Ph,EndVideo:Oh,ErrorScreen:Bh,Favicon:$h,GoogleAnalytics:Vh,MediaControl:Yn,Poster:Xh,SeekTime:Jh,SpinnerThreeBounce:id,Stats:nd,WaterMark:ad};class ld extends at{static get version(){return"1.0.0"}get name(){return"error_plugin"}get background(){return"data:image/svg+xml;utf8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22100%22%20height%3D%22100%22%20viewBox%3D%220%200%2026.458318%2026.458333%22%3E%3Cpath%20d%3D%22M13.23.302C6.07.302.264%206.107.264%2013.267a12.965%2012.965%200%200%200%20.847%204.595c.19-.497.408-.982.682-1.438.14-.232.294-.457.396-.707.103-.25.15-.533.072-.792a1.362%201.362%200%200%200-.22-.404c-.092-.123-.192-.24-.275-.37a1.662%201.662%200%200%201-.255-1.12%201.5%201.5%200%200%201%20.58-.987c.28-.208.635-.3.985-.288a1.757%201.757%200%200%201%20.346.048c.452.11.852.393%201.148.75.368.447.584%201.01.637%201.586a3.574%203.574%200%200%201-.275%201.693c-.4.955-1.15%201.725-1.565%202.673-.338.775-.435%201.638-.39%202.483.007.077.018.155.025.234a12.965%2012.965%200%200%200%203.62%203.18%2017.63%2017.63%200%200%201-.13-2.11c.002-.56.03-1.12.085-1.675-.34-.236-.65-.51-.87-.86-.392-.62-.466-1.408-.305-2.124.16-.717.54-1.37.997-1.945a7.833%207.833%200%200%201%202.835-2.223%2010.305%2010.305%200%200%201-.09-.126%204.854%204.854%200%200%201-.702-2.176c-.06-.777.064-1.554.115-2.33.037-.543.04-1.085.07-1.627.038-.627.114-1.255.29-1.858a2.36%202.36%200%200%201%20.266-.63%201.4%201.4%200%200%201%20.594-.514c.274-.108.51-.132.776-.087.22.046.425.156.604.294.18.138.335.304.48.477a7.298%207.298%200%200%201%201.04%201.617%203.57%203.57%200%200%201%201.09%200%207.287%207.287%200%200%201%201.04-1.616%203.21%203.21%200%200%201%20.48-.476c.18-.14.383-.248.604-.295a1.268%201.268%200%200%201%20.78.086%201.402%201.402%200%200%201%20.595.517c.124.19.202.408.266.626.175.602.252%201.23.29%201.856.03.543.033%201.087.07%201.628.05.777.175%201.554.116%202.33a4.855%204.855%200%200%201-.705%202.178c-.03.05-.07.096-.103.145.247.278.598.513.898.614a1.956%201.956%200%200%200%201.05.044%201.65%201.65%200%200%200%20.533-.226%201.253%201.253%200%200%200%20.397-.418c.118-.21.166-.45.192-.687.067-.61%200-1.224-.05-1.835-.034-.396-.062-.8.027-1.187.06-.26.177-.518.373-.7a1.106%201.106%200%200%201%20.465-.255%201.312%201.312%200%200%201%20.53-.03c.38.057.736.274.948.594.12.18.194.39.238.604.044.213.06.43.072.648.04.76.04%201.522.018%202.284-.018.665-.055%201.348-.32%201.957-.343.782-1.032%201.366-1.775%201.786a7.052%207.052%200%200%201-1.588.647c.482%201.54.733%203.24.733%204.968a17.6%2017.6%200%200%201-.135%202.125%2012.964%2012.964%200%200%200%206.384-11.152c0-7.16-5.806-12.965-12.965-12.965zM9.602%2016.284v1.483a1.88%201.88%200%200%201%201.083.362%201.738%201.738%200%200%201%20.556.68c.122.27.166.576.116.868a1.493%201.493%200%200%201-.332.708%201.647%201.647%200%200%201-.635.458%201.738%201.738%200%200%201-.787.122v3.73l7.762-4.208-7.762-4.204z%22%20fill%3D%22%23999%22%2F%3E%3C%2Fsvg%3E"}constructor(...e){super(...e),this.timeout=1,this.max_timeout=10}bindEvents(){this.listenTo(this.container,p.CONTAINER_ERROR,this.onError)}hide(){this._err&&this._err.remove()}show(e){this.hide();const t=e&&e.title||"Oh no, we encountered an error",i=e&&e.subtitle||"Please reload the page";this._err=Q("
").css({position:"absolute","z-index":"999",width:"100%",height:"100%","background-image":"url("+this.background+")","background-size":"18%","background-repeat":"no-repeat","background-color":"black","background-position":"center","text-align":"center","font-weight":"bold",color:"#eee"});const n=Q("
").css({position:"absolute",width:"100%","padding-bottom":"5%",bottom:0}).append(Q("

").text(t).css({"font-size":"2em"})).append(Q("

").text(i).css({"font-size":"1.2em",margin:"15px"}));this._err.append(n),this.container&&this.container.$el.prepend(this._err)}onError(e){if(!this.container)return;const t=()=>{this.hide(),this.container.getPlugin("click_to_pause").enable()},i=this.options.errorPlugin.onError;let n=null;i&&typeof i=="function"&&(n=i(e,t)),this.show(n),this.container.getPlugin("click_to_pause").disable()}}const cd=`

    <% if (title) { %>
  • <%= title %>
  • <% }; %> <% languages.forEach((language) => { %>
  • <%= language %>
  • <% }); %>
`,ud=".audio_track_selector[data-audio-track-selector]{float:right;height:100%;position:relative}.audio_track_selector[data-audio-track-selector] button{background-color:transparent;color:#fff;font-family:Roboto,Open Sans,Arial,sans-serif;-webkit-font-smoothing:antialiased;border:none;font-size:12px;height:100%}.audio_track_selector[data-audio-track-selector] button:hover{color:#c9c9c9}.audio_track_selector[data-audio-track-selector] button.changing{-webkit-animation:pulse .5s infinite alternate;animation:pulse .5s infinite alternate}.audio_track_selector[data-audio-track-selector]>ul{overflow-x:hidden;overflow-y:auto;list-style-type:none;position:absolute;bottom:100%;display:none;background-color:#1c1c1ce6;white-space:nowrap}.audio_track_selector[data-audio-track-selector] li{font-size:12px;color:#eee}.audio_track_selector[data-audio-track-selector] li[data-title]{background-color:#333;padding:8px 25px}.audio_track_selector[data-audio-track-selector] li a{color:#eee;padding:5px 18px;display:block;text-decoration:none}.audio_track_selector[data-audio-track-selector] li a:hover{background-color:#ffffff1a;color:#fff}.audio_track_selector[data-audio-track-selector] li a:hover a{color:#fff;text-decoration:none}.audio_track_selector[data-audio-track-selector] li.current a{color:#2ecc71}@-webkit-keyframes pulse{0%{color:#fff}50%{color:#ff0101}to{color:#b80000}}@keyframes pulse{0%{color:#fff}50%{color:#ff0101}to{color:#b80000}}";class hd extends Ne{static get version(){return"0.1.0"}get name(){return"audio_track_selector"}get template(){return Ie(cd)}get attributes(){return{class:this.name,"data-audio-track-selector":""}}get events(){return{"click [data-audio-track-selector-lang]":"handleLanguageSelect","click [data-audio-track-selector-button]":"handleAudioTrackSelectorClick"}}get container(){return this.core.activeContainer?this.core.activeContainer:this.core.mediaControl.container}get playback(){return this.core.activePlayback?this.core.activePlayback:this.core.getCurrentPlayback()}bindEvents(){p.CORE_ACTIVE_CONTAINER_CHANGED?this.listenTo(this.core,p.CORE_ACTIVE_CONTAINER_CHANGED,this.reload):this.listenTo(this.core.mediaControl,p.MEDIACONTROL_CONTAINERCHANGED,this.reload),this.listenTo(this.core,p.CORE_READY,this.bindPlaybackEvents),this.listenTo(this.core.mediaControl,p.MEDIACONTROL_RENDERED,this.render),this.listenTo(this.core.mediaControl,p.MEDIACONTROL_HIDE,this._hideContextMenu)}bindPlaybackEvents(){this.listenTo(this.playback,p.PLAYBACK_LEVELS_AVAILABLE,this._handleLevels),this.listenTo(this.playback,p.PLAYBACK_BITRATE,this._handleAdaptation),this.listenTo(this.playback,p.PLAYBACK_PLAY,this._handlePlay)}reload(){this.stopListening(),this.bindEvents(),this.bindPlaybackEvents()}shouldRender(){if(!this.container||!this.playback)return!1;var e=!!(this.languages&&this.languages.size>1);return e}render(){if(this.shouldRender()){var e=Se.getStyleFor(ud,{baseUrl:this.core.options.baseUrl});this.$el.html(this.template({title:this._getTitle(),languages:this.languages})),this.$el.append(e),this.core.mediaControl.$(".media-control-right-panel").append(this.el),this._highlightCurrentElement()}return this}_setLanguage(e){if(console.log("setLanguage",e),this.playback.selectAudioLanguage)this.nextLanguage=e,this.playback.selectAudioLanguage(e);else if(this.playback._hls){const t=this.playback._hls.audioTracks.find(i=>i.lang==e||i.name===e);if(!t)return;this.playback._hls.audioTrack=t.id,this.activeLanguage=e,this._highlightCurrentElement()}else if(this.playback.el.audioTracks){const i=[...this.playback.el.audioTracks].find(n=>n.language==e||n.label===e);if(!i)return;i.enabled=!0,this.activeLanguage=e,this._highlightCurrentElement()}}_fillLanguages(){if(this.playback.audioLanguages)this.languages=new Set(this.playback.audioLanguages);else if(this.playback._hls){const e=this.playback._hls.audioTracks,t=this.playback._hls.audioTrack,i=e.find(n=>n.id==t);this.languages=new Set(e.map(n=>n.lang||n.name)),i&&(this.activeLanguage=i.lang||i.name)}else if(this.playback.el.audioTracks){const e=[...this.playback.el.audioTracks],t=e.find(i=>i.enabled);this.languages=new Set(e.map(i=>i.language||i.label)),t&&(this.activeLanguage=t.language||t.label)}this.render()}handleLanguageSelect(e){e.preventDefault(),e.stopPropagation();const t=e.target.dataset.audioTrackSelectorLang;return this.activeLanguage==t||(this._setLanguage(t),this._toggleContextMenu()),!1}_handleAdaptation(e){e.language&&(this.activeLanguage=e.language,this._highlightCurrentElement())}_handleLevels(){this._fillLanguages()}_handlePlay(){(this.playback._hls||this.playback instanceof Ge)&&this._fillLanguages()}handleAudioTrackSelectorClick(e){this._toggleContextMenu()}_toggleContextMenu(){this.$(".audio_track_selector ul").toggle()}_hideContextMenu(){this.$(".audio_track_selector ul").hide()}_getLanguageElement(e=null){return e?this.$('.audio_track_selector a[data-audio-track-selector-lang="'+e+'"]').parent():this.$(".audio_track_selector a").parent()}_getButtonElement(){return this.$(".audio_track_selector button")}_getTitle(){return(this.core.options.audioTrackSelectorConfig||{}).title}_highlightCurrentElement(){this.activeLanguage&&(this._getLanguageElement().removeClass("current"),this._getLanguageElement(this.activeLanguage).addClass("current"),this._getButtonElement().text(this.activeLanguage))}}const dd=` `,fd=".level_selector[data-level-selector]{float:right;height:100%;position:relative}.level_selector[data-level-selector] button{background-color:transparent;color:#fff;font-family:Roboto,Open Sans,Arial,sans-serif;-webkit-font-smoothing:antialiased;border:none;font-size:12px;height:100%}.level_selector[data-level-selector] button:hover{color:#c9c9c9}.level_selector[data-level-selector] button.changing{-webkit-animation:pulse .5s infinite alternate;animation:pulse .5s infinite alternate}.level_selector[data-level-selector]>ul{overflow-x:hidden;overflow-y:auto;list-style-type:none;position:absolute;bottom:100%;display:none;background-color:#1c1c1ce6;white-space:nowrap}.level_selector[data-level-selector] li{font-size:12px;color:#eee}.level_selector[data-level-selector] li[data-title]{background-color:#333;padding:8px 25px}.level_selector[data-level-selector] li a{color:#eee;padding:5px 18px;display:block;text-decoration:none}.level_selector[data-level-selector] li a:hover{background-color:#ffffff1a;color:#fff}.level_selector[data-level-selector] li a:hover a{color:#fff;text-decoration:none}.level_selector[data-level-selector] li.current a{color:#2ecc71}@-webkit-keyframes pulse{0%{color:#fff}50%{color:#ff0101}to{color:#b80000}}@keyframes pulse{0%{color:#fff}50%{color:#ff0101}to{color:#b80000}}",_a=-1;class gd extends Ne{static get version(){return VERSION}get name(){return"level_selector"}get template(){return Ie(dd)}get attributes(){return{class:this.name,"data-level-selector":""}}get events(){return{"click [data-level-selector-select]":"onLevelSelect","click [data-level-selector-button]":"onShowLevelSelectMenu"}}bindEvents(){this.listenTo(this.core,p.CORE_READY,this.bindPlaybackEvents),this.listenTo(this.core.mediaControl,p.MEDIACONTROL_CONTAINERCHANGED,this.reload),this.listenTo(this.core.mediaControl,p.MEDIACONTROL_RENDERED,this.render),this.listenTo(this.core.mediaControl,p.MEDIACONTROL_HIDE,this.hideSelectLevelMenu)}unBindEvents(){this.stopListening(this.core,p.CORE_READY),this.stopListening(this.core.mediaControl,p.MEDIACONTROL_CONTAINERCHANGED),this.stopListening(this.core.mediaControl,p.MEDIACONTROL_RENDERED),this.stopListening(this.core.mediaControl,p.MEDIACONTROL_HIDE),this.stopListening(this.core.getCurrentPlayback(),p.PLAYBACK_LEVELS_AVAILABLE),this.stopListening(this.core.getCurrentPlayback(),p.PLAYBACK_BITRATE)}bindPlaybackEvents(){var e=this.core.getCurrentPlayback();this.listenTo(e,p.PLAYBACK_LEVELS_AVAILABLE,this.fillLevels),this.listenTo(e,p.PLAYBACK_BITRATE,this.handleAdaptation);var t=e.levels&&e.levels.length>0;t&&this.fillLevels(e.levels)}reload(){this.unBindEvents(),this.bindEvents(),this.bindPlaybackEvents()}shouldRender(){if(!this.core.getCurrentContainer())return!1;var e=this.core.getCurrentPlayback();if(!e)return!1;var t=e.currentLevel!==void 0,i=!!(this.levels&&this.levels.length>1);return t&&i}render(){if(this.shouldRender()){var e=Se.getStyleFor(fd,{baseUrl:this.core.options.baseUrl});this.$el.html(this.template({levels:this.levels,title:this.getTitle()})),this.$el.append(e),this.core.mediaControl.$(".media-control-right-panel").append(this.el),this.highlightCurrentLevel()}return this}fillLevels(e,t=_a){console.log("got levels",e,t),this.selectedLevelId===void 0&&(this.selectedLevelId=t),this.levels=e,this.configureLevelsLabels(),this.render()}configureLevelsLabels(){if(this.levels.forEach(o=>{o.label=`${o.height?o.height:o.level.height}p`}),this.core.options.levelSelectorConfig!==void 0){var e=this.core.options.levelSelectorConfig.labelCallback;if(e&&typeof e!="function")throw new TypeError("labelCallback must be a function");var t=this.core.options.levelSelectorConfig.labels,i=t?this.core.options.levelSelectorConfig.labels:{};if(e||t){var n,r;for(var a in this.levels)n=this.levels[a],r=i[n.id],e?n.label=e(n,r):r&&(n.label=r)}}}findLevelBy(e){var t;return this.levels.forEach(i=>{i.id===e&&(t=i)}),t}onLevelSelect(e){return this.selectedLevelId=parseInt(e.target.dataset.levelSelectorSelect,10),this.core.getCurrentPlayback().currentLevel==this.selectedLevelId||(this.core.getCurrentPlayback().currentLevel=this.selectedLevelId,this.toggleContextMenu(),e.stopPropagation()),!1}onShowLevelSelectMenu(e){this.toggleContextMenu()}hideSelectLevelMenu(){this.$(".level_selector ul").hide()}toggleContextMenu(){this.$(".level_selector ul").toggle()}buttonElement(){return this.$(".level_selector button")}levelElement(e){return this.$(".level_selector ul a"+(isNaN(e)?"":'[data-level-selector-select="'+e+'"]')).parent()}getTitle(){return(this.core.options.levelSelectorConfig||{}).title}updateText(e){e===_a?this.buttonElement().text(this.currentLevel?"AUTO ("+this.currentLevel.label+")":"AUTO"):this.buttonElement().text(this.findLevelBy(e).label)}handleAdaptation(e){var t=this.findLevelBy(e.level);this.currentLevel=t||null,this.highlightCurrentLevel()}highlightCurrentLevel(){this.updateText(this.selectedLevelId),this.levelElement().removeClass("current"),this.currentLevel&&this.levelElement(this.currentLevel.id).addClass("current");var e=this.currentLevel&&this.currentLevel.language;e&&(this.levelElement().removeClass("hidden"),this.levels.forEach(t=>{t.language!=e&&this.levelElement(t.id).addClass("hidden")}))}}const pd=async(s="",e={})=>{await fetch(s,{method:"POST",mode:"cors",cache:"no-cache",credentials:"omit",headers:{"Content-Type":"application/json"},redirect:"follow",referrerPolicy:"no-referrer",body:JSON.stringify(e)})},md=async s=>{const e=new AbortController,t=setTimeout(()=>{console.log("request timeout"),e.abort()},3e3);await fetch(s+`?t=${Date.now()}`,{signal:e.signal,method:"HEAD",mode:"cors",cache:"no-cache",redirect:"follow",referrerPolicy:"no-referrer"}),clearTimeout(t)};function yd(s){let e=[];for(var t in s)s.hasOwnProperty(t)&&s[t]!=null&&e.push(encodeURIComponent(t)+"="+encodeURIComponent(s[t]));return e.join("&")}function vd(s){return new Promise((e,t)=>{const i=new Image;i.onload=()=>{e()},i.onerror=()=>{t()},i.src=s})}const Ad=function(s,e,t={}){new Headers;const i=e.replace(/\s+/g," "),n=yd({query:i,operation:s,variables:JSON.stringify(t)});return fetch(`https://media.ccc.de/graphql?${n}`,{method:"GET",headers:{Accept:"application/json"}}).then(r=>{const a=r.body.getReader();let o="",l=new TextDecoder("utf-8");return a.read().then(function c({done:u,value:h}){return u?JSON.parse(o):(o+=l.decode(h),a.read().then(c))})})};function Ed(s){return Ad("LectureBySlug",` query LectureBySlug($slug: ID!) { lecture: lectureBySlug(slug: $slug) { originalLanguage timelens { thumbnailsUrl, timelineUrl } videos { label, source: url, mimeType } images { posterUrl } relive playerConfig } } `,{slug:s}).then(e=>{if(!e.data.lecture)throw new Error("Lecture could not be found");return e.data.lecture})}const Td="data:image/svg+xml;utf8,%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%20standalone%3D%22no%22%3F%3E%0A%3Csvg%0A%20%20%20xmlns%3Adc%3D%22http%3A%2F%2Fpurl.org%2Fdc%2Felements%2F1.1%2F%22%0A%20%20%20xmlns%3Acc%3D%22http%3A%2F%2Fcreativecommons.org%2Fns%23%22%0A%20%20%20xmlns%3Ardf%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2F02%2F22-rdf-syntax-ns%23%22%0A%20%20%20xmlns%3Asvg%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%0A%20%20%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%0A%20%20%20id%3D%22svg4568%22%0A%20%20%20version%3D%221.1%22%0A%20%20%20viewBox%3D%220%200%2026.458318%2026.458333%22%0A%20%20%20height%3D%22100%22%0A%20%20%20width%3D%22100%22%3E%0A%20%20%3Cmetadata%0A%20%20%20%20%20id%3D%22metadata4574%22%3E%0A%20%20%20%20%3Crdf%3ARDF%3E%0A%20%20%20%20%20%20%3Ccc%3AWork%0A%20%20%20%20%20%20%20%20%20rdf%3Aabout%3D%22%22%3E%0A%20%20%20%20%20%20%20%20%3Cdc%3Aformat%3Eimage%2Fsvg%2Bxml%3C%2Fdc%3Aformat%3E%0A%20%20%20%20%20%20%20%20%3Cdc%3Atype%0A%20%20%20%20%20%20%20%20%20%20%20rdf%3Aresource%3D%22http%3A%2F%2Fpurl.org%2Fdc%2Fdcmitype%2FStillImage%22%20%2F%3E%0A%20%20%20%20%20%20%20%20%3Cdc%3Atitle%3E%3C%2Fdc%3Atitle%3E%0A%20%20%20%20%20%20%3C%2Fcc%3AWork%3E%0A%20%20%20%20%3C%2Frdf%3ARDF%3E%0A%20%20%3C%2Fmetadata%3E%0A%20%20%3Cdefs%0A%20%20%20%20%20id%3D%22defs4572%22%20%2F%3E%0A%20%20%3Cpath%0A%20%20%20%20%20style%3D%22fill%3A%23ffffff%3Bfill-opacity%3A0.8627451%3Bstroke-width%3A0.79176539%22%0A%20%20%20%20%20id%3D%22path4566%22%0A%20%20%20%20%20d%3D%22m%2012.91039%2C7.1445417%20c%20-5.6690402%2C0%20-10.2660306%2C4.5961993%20-10.2660306%2C10.2652403%20a%2010.265238%2C10.265238%200%200%200%200.6706253%2C3.63816%20c%200.1504354%2C-0.393506%200.3230402%2C-0.777512%200.539984%2C-1.138557%200.1108472%2C-0.18369%200.2327789%2C-0.361837%200.313539%2C-0.559779%200.081551%2C-0.197941%200.1187648%2C-0.42201%200.057007%2C-0.627078%20A%201.0783844%2C1.0783844%200%200%200%204.0513264%2C18.402655%20C%203.9784841%2C18.305267%203.8993075%2C18.212631%203.833591%2C18.109702%20A%201.3159141%2C1.3159141%200%200%201%203.6316909%2C17.222924%201.1876481%2C1.1876481%200%200%201%204.0909148%2C16.441452%20c%200.2216944%2C-0.164688%200.5027709%2C-0.23753%200.7798889%2C-0.228028%20a%201.3911318%2C1.3911318%200%200%201%200.2739508%2C0.03801%20c%200.3578779%2C0.08709%200.6745841%2C0.311164%200.9089467%2C0.593824%200.2913696%2C0.353919%200.462391%2C0.799683%200.5043546%2C1.25574%20a%202.8297696%2C2.8297696%200%200%201%20-0.2177355%2C1.34046%20C%206.0236142%2C20.197593%205.42979%2C20.807252%205.1012074%2C21.557847%204.8335907%2C22.171464%204.7567894%2C22.854758%204.7924189%2C23.5238%20c%200.00554%2C0.06096%200.014251%2C0.122723%200.019794%2C0.185272%20a%2010.265238%2C10.265238%200%200%200%202.866191%2C2.517815%2013.958824%2C13.958824%200%200%201%20-0.1029298%2C-1.670626%20c%200.00161%2C-0.443389%200.023751%2C-0.886777%200.067304%2C-1.326206%20C%207.3735785%2C23.043191%207.1281312%2C22.826248%206.9539421%2C22.54913%206.6435705%2C22.058235%206.5849797%2C21.434324%206.712454%2C20.867421%206.8391365%2C20.299724%207.1400069%2C19.782702%207.5018439%2C19.327437%20A%206.2018984%2C6.2018984%200%200%201%209.7464993%2C17.567343%208.1591425%2C8.1591425%200%200%201%209.6752356%2C17.46758%203.8432293%2C3.8432293%200%200%201%209.1194163%2C15.744698%20c%20-0.047503%2C-0.615201%200.050669%2C-1.230403%200.091055%2C-1.844814%200.02929%2C-0.429928%200.031672%2C-0.859064%200.055423%2C-1.288201%200.030084%2C-0.496437%200.090261%2C-0.993667%200.2296124%2C-1.471101%20a%201.8685664%2C1.8685664%200%200%201%200.21061%2C-0.498812%201.1084716%2C1.1084716%200%200%201%200.4703083%2C-0.406968%20c%200.216945%2C-0.0855%200.403801%2C-0.104512%200.614411%2C-0.06888%200.174189%2C0.03642%200.3365%2C0.123516%200.478227%2C0.232779%200.142518%2C0.109264%200.26524%2C0.240698%200.380047%2C0.377673%20a%205.7783039%2C5.7783039%200%200%201%200.823436%2C1.280285%202.8266025%2C2.8266025%200%200%201%200.863024%2C0%205.7695944%2C5.7695944%200%200%201%200.823436%2C-1.279493%202.5415669%2C2.5415669%200%200%201%200.380047%2C-0.376881%20c%200.142518%2C-0.110847%200.303246%2C-0.196358%200.478227%2C-0.23357%20a%201.0039585%2C1.0039585%200%200%201%200.617577%2C0.06809%201.1100551%2C1.1100551%200%200%201%200.4711%2C0.409343%20c%200.09818%2C0.150436%200.159936%2C0.323041%200.21061%2C0.495645%200.138558%2C0.476643%200.199525%2C0.973872%200.229612%2C1.469517%200.02375%2C0.429928%200.02612%2C0.860649%200.05542%2C1.288995%200.0396%2C0.615201%200.138559%2C1.230403%200.09185%2C1.844813%20a%203.844021%2C3.844021%200%200%201%20-0.558194%2C1.724465%20c%20-0.02375%2C0.0396%20-0.05542%2C0.076%20-0.08154%2C0.114805%200.195565%2C0.220111%200.473476%2C0.406176%200.711006%2C0.486144%20a%201.5486932%2C1.5486932%200%200%200%200.831353%2C0.03484%201.3064129%2C1.3064129%200%200%200%200.42201%2C-0.17894%200.99208205%2C0.99208205%200%200%200%200.314331%2C-0.330957%20c%200.09343%2C-0.166272%200.131433%2C-0.356295%200.152019%2C-0.543944%200.05305%2C-0.482977%200%2C-0.96912%20-0.0396%2C-1.452889%20-0.02692%2C-0.313539%20-0.04909%2C-0.633412%200.02138%2C-0.939826%200.0475%2C-0.205858%200.140142%2C-0.410133%200.295328%2C-0.554235%20a%200.87569253%2C0.87569253%200%200%201%200.36817%2C-0.2019%201.0387963%2C1.0387963%200%200%201%200.419637%2C-0.02375%20c%200.30087%2C0.04514%200.582739%2C0.216942%200.750593%2C0.470308%200.09502%2C0.142517%200.153603%2C0.308788%200.18844%2C0.478226%200.03484%2C0.168646%200.0475%2C0.340459%200.05701%2C0.513064%200.03167%2C0.601741%200.03167%2C1.205067%200.01426%2C1.808392%20-0.01426%2C0.526524%20-0.04355%2C1.0673%20-0.253366%2C1.549486%20-0.271575%2C0.619159%20-0.817101%2C1.08155%20-1.405383%2C1.414092%20a%205.5835296%2C5.5835296%200%200%201%20-1.257323%2C0.512272%20c%200.38163%2C1.219319%200.580363%2C2.56532%200.580363%2C3.93349%20a%2013.935071%2C13.935071%200%200%201%20-0.106901%2C1.682498%2010.264446%2C10.264446%200%200%200%205.054631%2C-8.829768%20c%200%2C-5.669041%20-4.59699%2C-10.2652391%20-10.265238%2C-10.2652391%20z%20M%2010.037865%2C19.798537%20v%201.174188%20a%201.488519%2C1.488519%200%200%201%200.857482%2C0.286619%201.3760882%2C1.3760882%200%200%201%200.440222%2C0.538402%20c%200.0966%2C0.213775%200.131432%2C0.456056%200.09184%2C0.687252%20a%201.1821057%2C1.1821057%200%200%201%20-0.262867%2C0.560568%201.3040376%2C1.3040376%200%200%201%20-0.502772%2C0.36263%201.3760882%2C1.3760882%200%200%201%20-0.623119%2C0.0966%20v%202.953287%20l%206.145683%2C-3.33175%20-6.145683%2C-3.328583%20z%22%20%2F%3E%0A%3C%2Fsvg%3E",bd=()=>({width:"100%",height:"100%",hideMediaControlDelay:1e3,position:"top-left",watermark:Td,watermarkLink:"https://c3voc.de",levelSelectorConfig:{labelCallback:function(s){let e="unknown";return s.height?e=s.height:s.level&&s.level.height&&(e=s.level.height),e+"p"},title:"Quality"},audioTrackSelectorConfig:{title:"Language"}}),Sd=(s,e,t,i,n)=>{const r="MediaSource"in window,a={poster:`//cdn.c3voc.de/thumbnail/${s}/poster.jpeg`,levelSelectorConfig:{labelCallback:function(l){var u;if((u=l==null?void 0:l.level)!=null&&u.url){const h=l.level.url[0].split("/");return h[h.length-1].split(".")[0]}var c=l.videoBandwidth||l.level.bitrate;return c<=1e5?"Slides":c<=9e5?"SD":c<=5e6?"HD":"Source"},title:"Quality"},disableErrorScreen:!0,errorPlugin:{onError:n},vocConfigUpdate:l=>{if(document.visibilityState!=="visible"||l.isPlaying())return;const c=`//cdn.c3voc.de/thumbnail/${s}/poster.jpeg?t=${Date.now()}`;vd(c).then(()=>{l.configure({poster:c})})}};return!(navigator.userAgent.indexOf("Firefox")!=-1)&&!t&&r&&MediaSource.isTypeSupported('video/webm; codecs="vp9,opus"')?(a.source={source:`//cdn.c3voc.de/dash/${s}/manifest.mpd`},a.shakaConfiguration={preferredAudioLanguage:i,abr:{defaultBandwidthEstimate:1e6},streaming:{jumpLargeGaps:!0},manifest:{dash:{defaultPresentationDelay:3,ignoreSuggestedPresentationDelay:!0}}}):!e&&(r||document.createElement("video").canPlayType("application/vnd.apple.mpegURL")!="")?a.source={source:`//cdn.c3voc.de/hls/${s}/native_hd.m3u8`,mimeType:"application/vnd.apple.mpegURL"}:e?a.source={source:`//cdn.c3voc.de/${s}_native.mp3`,mimeType:"audio/mp3"}:a.source={source:`//cdn.c3voc.de/${s}_native_hd.webm`,mimeType:"video/webm"},Promise.resolve(a)},_d=function(s,e){return Ed(s).then(t=>{var i,n,r,a;return{sources:t.videos||((i=t.relive)==null?void 0:i.playlistCut)||((n=t.relive)==null?void 0:n.playlist),poster:(r=t.images)==null?void 0:r.posterUrl,timelens:t.timelens,playback:{externalTracks:(a=t.playerConfig)==null?void 0:a.subtitles},levelSelectorConfig:{labelCallback:function(o,l){console.log("labelCallback",arguments);var c=o.videoBandwidth||o.level.bitrate;return c<=1e5?"Slides":c<=9e5?"SD":"HD"},title:"Quality"}}}).catch(t=>(console.log("Failed to fetch media sources",t),{playbackNotSupportedMessage:`${t.message}`}))},ka=5,kd=15,{ClickToPause:xd,ClosedCaptions:Cd,DVRControls:Ld,EndVideo:Id,ErrorScreen:Rd,Favicon:Dd,MediaControl:wd,Poster:Pd,SeekTime:Od,SpinnerThreeBounce:Nd,Stats:Fd,WaterMark:Md}=od;Qe.registerPlayback(ga);for(let s of[xd,Cd,Ld,Id,Rd,Dd,wd,Pd,Od,Nd,Fd,Md,ld,hd,gd])Qe.registerPlugin(s);const xa=(s,e)=>s.origin=="dash_shaka_playback"&&(s.raw.code==e||s.raw.detail&&s.raw.detail.code==e),Ca=(s,e)=>s.origin=="hls"&&s.raw.response.code==e,Bd=s=>new Promise(e=>setTimeout(e,s));class Ud extends st{constructor(e){super(),this.timeout=ka,this.maxTimeout=kd,this._events=[],this._buffering=!1,this._lastSeek=0,this._vocStream=e.vocStream,this._playerPromise=this._getConfig(e).then(t=>(this._options=t,this._player=new mr(this._options),this._player.core&&this._player.core.isReady?this._addEventListeners():this.listenToOnce(this._player,p.PLAYER_READY,this._addEventListeners.bind(this)),t.vocConfigUpdate&&setInterval(()=>t.vocConfigUpdate(this._player),3e4),this._player))}attachTo(){console.log("will attach",...arguments),this._playerPromise.then(e=>{console.log("attach",...arguments),e.attachTo.apply(e,arguments)})}_getConfig(e){let t=Promise.resolve({});return e.vocStream?t=Sd(e.vocStream,e.audioOnly,e.h264Only,e.preferredAudioLanguage,this._handleError.bind(this)):e.vocLecture&&(t=_d(e.vocLecture)),t.then(i=>Object.assign(bd(),i,e))}_containerChanged(){this.stopListening(),this._addEventListeners()}_addEventListeners(){const e=this._player.core;this._container=e.activeContainer,this.listenTo(this._player,p.PLAYER_PLAY,this._handlePlay),this.listenTo(this._player,p.PLAYER_STOP,this._handleStop),this.listenTo(this._player,p.PLAYER_SEEK,this._handleSeek),this.listenTo(e,p.CORE_ACTIVE_CONTAINER_CHANGED,this._containerChanged),this.listenTo(this._container,p.CONTAINER_STATE_BUFFERFULL,this._handleBufferFull),this.listenTo(this._container,p.CONTAINER_MEDIACONTROL_HIDE,this._handleMediaControlHide),this.listenTo(this._container,p.CONTAINER_MEDIACONTROL_SHOW,this._handleMediaControlShow),this.listenTo(e.getCurrentPlayback(),p.PLAYBACK_BUFFERING,this._handleBuffering),this.listenTo(e.getCurrentPlayback(),p.PLAYBACK_BITRATE,this._handleBitrate);const t=e.getCurrentPlayback();t._hls&&t._hls.on("hlsManifestLoaded",(i,n)=>{if(!n.url)return;const r=new URL(n.url);this._relay=r.hostname,console.log("got relay",this._relay)})}_handleMediaControlHide(){this._container.$el.find(".clappr-watermark[data-watermark]").addClass("clappr-watermark-hide")}_handleMediaControlShow(){this._container.$el.find(".clappr-watermark[data-watermark]").removeClass("clappr-watermark-hide")}_getTimeout(){const e=.6*this.timeout+.4*this.timeout*Math.random();return this.timeout=Math.min(this.timeout*2,this.maxTimeout),e}_resetTimeout(){this.timeout=ka}_handleError(e,t){if(this._appendEvent({type:"error"}),this._recovery)return;this._player.stop();const i=this._getTimeout();return console.log("got error",e,`retrying in ${Math.round(i)}s`),this._recovery={clearOverlay:t,state:"restarting",timeout:setTimeout(this._waitForMedia.bind(this),i*1e3)},xa(e,1001)||Ca(e,404)?{title:"Stream is offline",subtitle:"We will be right back"}:xa(e,1002)||Ca(0)?{title:"A network error ocurred",subtitle:"Please check your internet connection"}:{title:"Oh no, an unknown error occured",subtitle:"Please try reloading the page"}}_handlePlay(){console.log(this._container.playback),this._recovery&&(console.log("soft recovery: play"),this._recovery.clearOverlay(),clearTimeout(this._recovery.timeout),this._recovery=null,this._appendEvent({type:"recovery"})),this._resetTimeout()}_handleStop(e){this._recovery&&this._container&&(console.log("soft recovery: stop"),this._container.playback.play.call(this._container.playback))}_handleSeek(e){this._lastSeek=Date.now()}_handleBufferFull(){if(this._buffering=!1,!!this._recovery&&(console.log(`recovered? playbackType=${this._container.playback.getPlaybackType()}`),this._container.playback.getPlaybackType()=="live")){console.log("seeking to end for recovery");const e=Math.max(this._player.getDuration()-6,0);this._player.seek(e)}}_handleBuffering(){this._buffering=!0,Date.now()-this._lastSeek>1e3&&this._appendEvent({type:"buffering"})}_handleBitrate(e){if(!this._lastBitrate){this._lastBitrate=e;return}if(!e.bitrate||!this._lastBitrate.bitrate){this._lastBitrate=e;return}if(e.bitrate===this._lastBitrate.bitrate)return;const t=e.bitrate-this._lastBitrate.bitrate>0;this._lastBitrate=e,!this._buffering&&this._appendEvent({type:"quality_switch",isUp:t})}_appendEvent(e){this._container.playback.getPlaybackType()==="live"&&(console.log("player event",e),e.time=Date.now(),this._vocStream&&(e.slug=this._vocStream),this._relay&&(e.relay=this._relay),this._events.push(e),this._sendStats())}async _sendStats(){this._statsTimeout||(this._statsTimeout=setTimeout(this._doSendStats.bind(this),Math.random()*5e3))}async _doSendStats(){let e=3e3;for(;;){try{const t=[],i=Date.now();for(const n of this._events)t.push({...n,offset:(i-n.time)/1e3,time:void 0});await pd("https://cdn.c3voc.de/stats/",t),this._events=[],this._statsTimeout=void 0;return}catch(t){console.error("failed to report stats",t)}await Bd(e*.5+Math.random()*.5*e),e*=2}}async _waitForMedia(){let e=this._player.options.source;if(e&&e.source&&(e=e.source),typeof e!="string"){this.reset();return}console.log("waiting for media",e);try{await md(e),console.log("try playing again, media should be available"),this._player.play()}catch(t){const i=this._getTimeout();console.log(`test for media failed, retrying in ~${Math.round(i)}s`,t),setTimeout(this._waitForMedia.bind(this),i*1e3)}}reset(){console.log("performing hard reset"),this._recovery=null;const e=this._player.getVolume()==0;e||this._player.mute(),this._player.configure({source:this._player.options.source,autoPlay:!0}),e||this._player.unmute()}}console.log("VOC player 1.3.0"),ue.$=Q,ue.BaseObject=st,ue.Browser=z,ue.Container=Ui,ue.ContainerPlugin=at,ue.Core=$i,ue.CorePlugin=ot,ue.Events=p,ue.HTML5Audio=Vi,ue.HTML5Video=Ge,ue.HTMLImg=Gi,ue.Loader=Qe,ue.Log=ae,ue.Playback=se,ue.Player=Ud,ue.PlayerError=Ve,ue.Styler=Se,ue.UIContainerPlugin=ft,ue.UICorePlugin=Ne,ue.UIObject=Ot,ue.Utils=rt,ue.template=Ie,ue.version=wo,Object.defineProperty(ue,Symbol.toStringTag,{value:"Module"})});